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 static cl::opt<unsigned> 146 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, 147 cl::ZeroOrMore, 148 cl::desc("Maximum number of iterations SCEV will " 149 "symbolically execute a constant " 150 "derived loop"), 151 cl::init(100)); 152 153 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean. 154 static cl::opt<bool> VerifySCEV( 155 "verify-scev", cl::Hidden, 156 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)")); 157 static cl::opt<bool> VerifySCEVStrict( 158 "verify-scev-strict", cl::Hidden, 159 cl::desc("Enable stricter verification with -verify-scev is passed")); 160 static cl::opt<bool> 161 VerifySCEVMap("verify-scev-maps", cl::Hidden, 162 cl::desc("Verify no dangling value in ScalarEvolution's " 163 "ExprValueMap (slow)")); 164 165 static cl::opt<bool> VerifyIR( 166 "scev-verify-ir", cl::Hidden, 167 cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"), 168 cl::init(false)); 169 170 static cl::opt<unsigned> MulOpsInlineThreshold( 171 "scev-mulops-inline-threshold", cl::Hidden, 172 cl::desc("Threshold for inlining multiplication operands into a SCEV"), 173 cl::init(32)); 174 175 static cl::opt<unsigned> AddOpsInlineThreshold( 176 "scev-addops-inline-threshold", cl::Hidden, 177 cl::desc("Threshold for inlining addition operands into a SCEV"), 178 cl::init(500)); 179 180 static cl::opt<unsigned> MaxSCEVCompareDepth( 181 "scalar-evolution-max-scev-compare-depth", cl::Hidden, 182 cl::desc("Maximum depth of recursive SCEV complexity comparisons"), 183 cl::init(32)); 184 185 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth( 186 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden, 187 cl::desc("Maximum depth of recursive SCEV operations implication analysis"), 188 cl::init(2)); 189 190 static cl::opt<unsigned> MaxValueCompareDepth( 191 "scalar-evolution-max-value-compare-depth", cl::Hidden, 192 cl::desc("Maximum depth of recursive value complexity comparisons"), 193 cl::init(2)); 194 195 static cl::opt<unsigned> 196 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden, 197 cl::desc("Maximum depth of recursive arithmetics"), 198 cl::init(32)); 199 200 static cl::opt<unsigned> MaxConstantEvolvingDepth( 201 "scalar-evolution-max-constant-evolving-depth", cl::Hidden, 202 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32)); 203 204 static cl::opt<unsigned> 205 MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden, 206 cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"), 207 cl::init(8)); 208 209 static cl::opt<unsigned> 210 MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden, 211 cl::desc("Max coefficients in AddRec during evolving"), 212 cl::init(8)); 213 214 static cl::opt<unsigned> 215 HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden, 216 cl::desc("Size of the expression which is considered huge"), 217 cl::init(4096)); 218 219 static cl::opt<bool> 220 ClassifyExpressions("scalar-evolution-classify-expressions", 221 cl::Hidden, cl::init(true), 222 cl::desc("When printing analysis, include information on every instruction")); 223 224 static cl::opt<bool> UseExpensiveRangeSharpening( 225 "scalar-evolution-use-expensive-range-sharpening", cl::Hidden, 226 cl::init(false), 227 cl::desc("Use more powerful methods of sharpening expression ranges. May " 228 "be costly in terms of compile time")); 229 230 static cl::opt<unsigned> MaxPhiSCCAnalysisSize( 231 "scalar-evolution-max-scc-analysis-depth", cl::Hidden, 232 cl::desc("Maximum amount of nodes to process while searching SCEVUnknown " 233 "Phi strongly connected components"), 234 cl::init(8)); 235 236 static cl::opt<bool> 237 EnableFiniteLoopControl("scalar-evolution-finite-loop", cl::Hidden, 238 cl::desc("Handle <= and >= in finite loops"), 239 cl::init(true)); 240 241 //===----------------------------------------------------------------------===// 242 // SCEV class definitions 243 //===----------------------------------------------------------------------===// 244 245 //===----------------------------------------------------------------------===// 246 // Implementation of the SCEV class. 247 // 248 249 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 250 LLVM_DUMP_METHOD void SCEV::dump() const { 251 print(dbgs()); 252 dbgs() << '\n'; 253 } 254 #endif 255 256 void SCEV::print(raw_ostream &OS) const { 257 switch (getSCEVType()) { 258 case scConstant: 259 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false); 260 return; 261 case scPtrToInt: { 262 const SCEVPtrToIntExpr *PtrToInt = cast<SCEVPtrToIntExpr>(this); 263 const SCEV *Op = PtrToInt->getOperand(); 264 OS << "(ptrtoint " << *Op->getType() << " " << *Op << " to " 265 << *PtrToInt->getType() << ")"; 266 return; 267 } 268 case scTruncate: { 269 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this); 270 const SCEV *Op = Trunc->getOperand(); 271 OS << "(trunc " << *Op->getType() << " " << *Op << " to " 272 << *Trunc->getType() << ")"; 273 return; 274 } 275 case scZeroExtend: { 276 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this); 277 const SCEV *Op = ZExt->getOperand(); 278 OS << "(zext " << *Op->getType() << " " << *Op << " to " 279 << *ZExt->getType() << ")"; 280 return; 281 } 282 case scSignExtend: { 283 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this); 284 const SCEV *Op = SExt->getOperand(); 285 OS << "(sext " << *Op->getType() << " " << *Op << " to " 286 << *SExt->getType() << ")"; 287 return; 288 } 289 case scAddRecExpr: { 290 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this); 291 OS << "{" << *AR->getOperand(0); 292 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i) 293 OS << ",+," << *AR->getOperand(i); 294 OS << "}<"; 295 if (AR->hasNoUnsignedWrap()) 296 OS << "nuw><"; 297 if (AR->hasNoSignedWrap()) 298 OS << "nsw><"; 299 if (AR->hasNoSelfWrap() && 300 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW))) 301 OS << "nw><"; 302 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false); 303 OS << ">"; 304 return; 305 } 306 case scAddExpr: 307 case scMulExpr: 308 case scUMaxExpr: 309 case scSMaxExpr: 310 case scUMinExpr: 311 case scSMinExpr: 312 case scSequentialUMinExpr: { 313 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this); 314 const char *OpStr = nullptr; 315 switch (NAry->getSCEVType()) { 316 case scAddExpr: OpStr = " + "; break; 317 case scMulExpr: OpStr = " * "; break; 318 case scUMaxExpr: OpStr = " umax "; break; 319 case scSMaxExpr: OpStr = " smax "; break; 320 case scUMinExpr: 321 OpStr = " umin "; 322 break; 323 case scSMinExpr: 324 OpStr = " smin "; 325 break; 326 case scSequentialUMinExpr: 327 OpStr = " umin_seq "; 328 break; 329 default: 330 llvm_unreachable("There are no other nary expression types."); 331 } 332 OS << "("; 333 ListSeparator LS(OpStr); 334 for (const SCEV *Op : NAry->operands()) 335 OS << LS << *Op; 336 OS << ")"; 337 switch (NAry->getSCEVType()) { 338 case scAddExpr: 339 case scMulExpr: 340 if (NAry->hasNoUnsignedWrap()) 341 OS << "<nuw>"; 342 if (NAry->hasNoSignedWrap()) 343 OS << "<nsw>"; 344 break; 345 default: 346 // Nothing to print for other nary expressions. 347 break; 348 } 349 return; 350 } 351 case scUDivExpr: { 352 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this); 353 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")"; 354 return; 355 } 356 case scUnknown: { 357 const SCEVUnknown *U = cast<SCEVUnknown>(this); 358 Type *AllocTy; 359 if (U->isSizeOf(AllocTy)) { 360 OS << "sizeof(" << *AllocTy << ")"; 361 return; 362 } 363 if (U->isAlignOf(AllocTy)) { 364 OS << "alignof(" << *AllocTy << ")"; 365 return; 366 } 367 368 Type *CTy; 369 Constant *FieldNo; 370 if (U->isOffsetOf(CTy, FieldNo)) { 371 OS << "offsetof(" << *CTy << ", "; 372 FieldNo->printAsOperand(OS, false); 373 OS << ")"; 374 return; 375 } 376 377 // Otherwise just print it normally. 378 U->getValue()->printAsOperand(OS, false); 379 return; 380 } 381 case scCouldNotCompute: 382 OS << "***COULDNOTCOMPUTE***"; 383 return; 384 } 385 llvm_unreachable("Unknown SCEV kind!"); 386 } 387 388 Type *SCEV::getType() const { 389 switch (getSCEVType()) { 390 case scConstant: 391 return cast<SCEVConstant>(this)->getType(); 392 case scPtrToInt: 393 case scTruncate: 394 case scZeroExtend: 395 case scSignExtend: 396 return cast<SCEVCastExpr>(this)->getType(); 397 case scAddRecExpr: 398 return cast<SCEVAddRecExpr>(this)->getType(); 399 case scMulExpr: 400 return cast<SCEVMulExpr>(this)->getType(); 401 case scUMaxExpr: 402 case scSMaxExpr: 403 case scUMinExpr: 404 case scSMinExpr: 405 return cast<SCEVMinMaxExpr>(this)->getType(); 406 case scSequentialUMinExpr: 407 return cast<SCEVSequentialMinMaxExpr>(this)->getType(); 408 case scAddExpr: 409 return cast<SCEVAddExpr>(this)->getType(); 410 case scUDivExpr: 411 return cast<SCEVUDivExpr>(this)->getType(); 412 case scUnknown: 413 return cast<SCEVUnknown>(this)->getType(); 414 case scCouldNotCompute: 415 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 416 } 417 llvm_unreachable("Unknown SCEV kind!"); 418 } 419 420 bool SCEV::isZero() const { 421 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 422 return SC->getValue()->isZero(); 423 return false; 424 } 425 426 bool SCEV::isOne() const { 427 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 428 return SC->getValue()->isOne(); 429 return false; 430 } 431 432 bool SCEV::isAllOnesValue() const { 433 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 434 return SC->getValue()->isMinusOne(); 435 return false; 436 } 437 438 bool SCEV::isNonConstantNegative() const { 439 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this); 440 if (!Mul) return false; 441 442 // If there is a constant factor, it will be first. 443 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); 444 if (!SC) return false; 445 446 // Return true if the value is negative, this matches things like (-42 * V). 447 return SC->getAPInt().isNegative(); 448 } 449 450 SCEVCouldNotCompute::SCEVCouldNotCompute() : 451 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {} 452 453 bool SCEVCouldNotCompute::classof(const SCEV *S) { 454 return S->getSCEVType() == scCouldNotCompute; 455 } 456 457 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) { 458 FoldingSetNodeID ID; 459 ID.AddInteger(scConstant); 460 ID.AddPointer(V); 461 void *IP = nullptr; 462 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 463 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V); 464 UniqueSCEVs.InsertNode(S, IP); 465 return S; 466 } 467 468 const SCEV *ScalarEvolution::getConstant(const APInt &Val) { 469 return getConstant(ConstantInt::get(getContext(), Val)); 470 } 471 472 const SCEV * 473 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) { 474 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty)); 475 return getConstant(ConstantInt::get(ITy, V, isSigned)); 476 } 477 478 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy, 479 const SCEV *op, Type *ty) 480 : SCEV(ID, SCEVTy, computeExpressionSize(op)), Ty(ty) { 481 Operands[0] = op; 482 } 483 484 SCEVPtrToIntExpr::SCEVPtrToIntExpr(const FoldingSetNodeIDRef ID, const SCEV *Op, 485 Type *ITy) 486 : SCEVCastExpr(ID, scPtrToInt, Op, ITy) { 487 assert(getOperand()->getType()->isPointerTy() && Ty->isIntegerTy() && 488 "Must be a non-bit-width-changing pointer-to-integer cast!"); 489 } 490 491 SCEVIntegralCastExpr::SCEVIntegralCastExpr(const FoldingSetNodeIDRef ID, 492 SCEVTypes SCEVTy, const SCEV *op, 493 Type *ty) 494 : SCEVCastExpr(ID, SCEVTy, op, ty) {} 495 496 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, const SCEV *op, 497 Type *ty) 498 : SCEVIntegralCastExpr(ID, scTruncate, op, ty) { 499 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 500 "Cannot truncate non-integer value!"); 501 } 502 503 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, 504 const SCEV *op, Type *ty) 505 : SCEVIntegralCastExpr(ID, scZeroExtend, op, ty) { 506 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 507 "Cannot zero extend non-integer value!"); 508 } 509 510 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, 511 const SCEV *op, Type *ty) 512 : SCEVIntegralCastExpr(ID, scSignExtend, op, ty) { 513 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 514 "Cannot sign extend non-integer value!"); 515 } 516 517 void SCEVUnknown::deleted() { 518 // Clear this SCEVUnknown from various maps. 519 SE->forgetMemoizedResults(this); 520 521 // Remove this SCEVUnknown from the uniquing map. 522 SE->UniqueSCEVs.RemoveNode(this); 523 524 // Release the value. 525 setValPtr(nullptr); 526 } 527 528 void SCEVUnknown::allUsesReplacedWith(Value *New) { 529 // Remove this SCEVUnknown from the uniquing map. 530 SE->UniqueSCEVs.RemoveNode(this); 531 532 // Update this SCEVUnknown to point to the new value. This is needed 533 // because there may still be outstanding SCEVs which still point to 534 // this SCEVUnknown. 535 setValPtr(New); 536 } 537 538 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const { 539 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 540 if (VCE->getOpcode() == Instruction::PtrToInt) 541 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 542 if (CE->getOpcode() == Instruction::GetElementPtr && 543 CE->getOperand(0)->isNullValue() && 544 CE->getNumOperands() == 2) 545 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1))) 546 if (CI->isOne()) { 547 AllocTy = cast<GEPOperator>(CE)->getSourceElementType(); 548 return true; 549 } 550 551 return false; 552 } 553 554 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const { 555 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 556 if (VCE->getOpcode() == Instruction::PtrToInt) 557 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 558 if (CE->getOpcode() == Instruction::GetElementPtr && 559 CE->getOperand(0)->isNullValue()) { 560 Type *Ty = cast<GEPOperator>(CE)->getSourceElementType(); 561 if (StructType *STy = dyn_cast<StructType>(Ty)) 562 if (!STy->isPacked() && 563 CE->getNumOperands() == 3 && 564 CE->getOperand(1)->isNullValue()) { 565 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2))) 566 if (CI->isOne() && 567 STy->getNumElements() == 2 && 568 STy->getElementType(0)->isIntegerTy(1)) { 569 AllocTy = STy->getElementType(1); 570 return true; 571 } 572 } 573 } 574 575 return false; 576 } 577 578 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const { 579 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 580 if (VCE->getOpcode() == Instruction::PtrToInt) 581 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 582 if (CE->getOpcode() == Instruction::GetElementPtr && 583 CE->getNumOperands() == 3 && 584 CE->getOperand(0)->isNullValue() && 585 CE->getOperand(1)->isNullValue()) { 586 Type *Ty = cast<GEPOperator>(CE)->getSourceElementType(); 587 // Ignore vector types here so that ScalarEvolutionExpander doesn't 588 // emit getelementptrs that index into vectors. 589 if (Ty->isStructTy() || Ty->isArrayTy()) { 590 CTy = Ty; 591 FieldNo = CE->getOperand(2); 592 return true; 593 } 594 } 595 596 return false; 597 } 598 599 //===----------------------------------------------------------------------===// 600 // SCEV Utilities 601 //===----------------------------------------------------------------------===// 602 603 /// Compare the two values \p LV and \p RV in terms of their "complexity" where 604 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order 605 /// operands in SCEV expressions. \p EqCache is a set of pairs of values that 606 /// have been previously deemed to be "equally complex" by this routine. It is 607 /// intended to avoid exponential time complexity in cases like: 608 /// 609 /// %a = f(%x, %y) 610 /// %b = f(%a, %a) 611 /// %c = f(%b, %b) 612 /// 613 /// %d = f(%x, %y) 614 /// %e = f(%d, %d) 615 /// %f = f(%e, %e) 616 /// 617 /// CompareValueComplexity(%f, %c) 618 /// 619 /// Since we do not continue running this routine on expression trees once we 620 /// have seen unequal values, there is no need to track them in the cache. 621 static int 622 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue, 623 const LoopInfo *const LI, Value *LV, Value *RV, 624 unsigned Depth) { 625 if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV)) 626 return 0; 627 628 // Order pointer values after integer values. This helps SCEVExpander form 629 // GEPs. 630 bool LIsPointer = LV->getType()->isPointerTy(), 631 RIsPointer = RV->getType()->isPointerTy(); 632 if (LIsPointer != RIsPointer) 633 return (int)LIsPointer - (int)RIsPointer; 634 635 // Compare getValueID values. 636 unsigned LID = LV->getValueID(), RID = RV->getValueID(); 637 if (LID != RID) 638 return (int)LID - (int)RID; 639 640 // Sort arguments by their position. 641 if (const auto *LA = dyn_cast<Argument>(LV)) { 642 const auto *RA = cast<Argument>(RV); 643 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo(); 644 return (int)LArgNo - (int)RArgNo; 645 } 646 647 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) { 648 const auto *RGV = cast<GlobalValue>(RV); 649 650 const auto IsGVNameSemantic = [&](const GlobalValue *GV) { 651 auto LT = GV->getLinkage(); 652 return !(GlobalValue::isPrivateLinkage(LT) || 653 GlobalValue::isInternalLinkage(LT)); 654 }; 655 656 // Use the names to distinguish the two values, but only if the 657 // names are semantically important. 658 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV)) 659 return LGV->getName().compare(RGV->getName()); 660 } 661 662 // For instructions, compare their loop depth, and their operand count. This 663 // is pretty loose. 664 if (const auto *LInst = dyn_cast<Instruction>(LV)) { 665 const auto *RInst = cast<Instruction>(RV); 666 667 // Compare loop depths. 668 const BasicBlock *LParent = LInst->getParent(), 669 *RParent = RInst->getParent(); 670 if (LParent != RParent) { 671 unsigned LDepth = LI->getLoopDepth(LParent), 672 RDepth = LI->getLoopDepth(RParent); 673 if (LDepth != RDepth) 674 return (int)LDepth - (int)RDepth; 675 } 676 677 // Compare the number of operands. 678 unsigned LNumOps = LInst->getNumOperands(), 679 RNumOps = RInst->getNumOperands(); 680 if (LNumOps != RNumOps) 681 return (int)LNumOps - (int)RNumOps; 682 683 for (unsigned Idx : seq(0u, LNumOps)) { 684 int Result = 685 CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx), 686 RInst->getOperand(Idx), Depth + 1); 687 if (Result != 0) 688 return Result; 689 } 690 } 691 692 EqCacheValue.unionSets(LV, RV); 693 return 0; 694 } 695 696 // Return negative, zero, or positive, if LHS is less than, equal to, or greater 697 // than RHS, respectively. A three-way result allows recursive comparisons to be 698 // more efficient. 699 // If the max analysis depth was reached, return None, assuming we do not know 700 // if they are equivalent for sure. 701 static Optional<int> 702 CompareSCEVComplexity(EquivalenceClasses<const SCEV *> &EqCacheSCEV, 703 EquivalenceClasses<const Value *> &EqCacheValue, 704 const LoopInfo *const LI, const SCEV *LHS, 705 const SCEV *RHS, DominatorTree &DT, unsigned Depth = 0) { 706 // Fast-path: SCEVs are uniqued so we can do a quick equality check. 707 if (LHS == RHS) 708 return 0; 709 710 // Primarily, sort the SCEVs by their getSCEVType(). 711 SCEVTypes LType = LHS->getSCEVType(), RType = RHS->getSCEVType(); 712 if (LType != RType) 713 return (int)LType - (int)RType; 714 715 if (EqCacheSCEV.isEquivalent(LHS, RHS)) 716 return 0; 717 718 if (Depth > MaxSCEVCompareDepth) 719 return None; 720 721 // Aside from the getSCEVType() ordering, the particular ordering 722 // isn't very important except that it's beneficial to be consistent, 723 // so that (a + b) and (b + a) don't end up as different expressions. 724 switch (LType) { 725 case scUnknown: { 726 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS); 727 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); 728 729 int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(), 730 RU->getValue(), Depth + 1); 731 if (X == 0) 732 EqCacheSCEV.unionSets(LHS, RHS); 733 return X; 734 } 735 736 case scConstant: { 737 const SCEVConstant *LC = cast<SCEVConstant>(LHS); 738 const SCEVConstant *RC = cast<SCEVConstant>(RHS); 739 740 // Compare constant values. 741 const APInt &LA = LC->getAPInt(); 742 const APInt &RA = RC->getAPInt(); 743 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth(); 744 if (LBitWidth != RBitWidth) 745 return (int)LBitWidth - (int)RBitWidth; 746 return LA.ult(RA) ? -1 : 1; 747 } 748 749 case scAddRecExpr: { 750 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); 751 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); 752 753 // There is always a dominance between two recs that are used by one SCEV, 754 // so we can safely sort recs by loop header dominance. We require such 755 // order in getAddExpr. 756 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); 757 if (LLoop != RLoop) { 758 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader(); 759 assert(LHead != RHead && "Two loops share the same header?"); 760 if (DT.dominates(LHead, RHead)) 761 return 1; 762 else 763 assert(DT.dominates(RHead, LHead) && 764 "No dominance between recurrences used by one SCEV?"); 765 return -1; 766 } 767 768 // Addrec complexity grows with operand count. 769 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands(); 770 if (LNumOps != RNumOps) 771 return (int)LNumOps - (int)RNumOps; 772 773 // Lexicographically compare. 774 for (unsigned i = 0; i != LNumOps; ++i) { 775 auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 776 LA->getOperand(i), RA->getOperand(i), DT, 777 Depth + 1); 778 if (X != 0) 779 return X; 780 } 781 EqCacheSCEV.unionSets(LHS, RHS); 782 return 0; 783 } 784 785 case scAddExpr: 786 case scMulExpr: 787 case scSMaxExpr: 788 case scUMaxExpr: 789 case scSMinExpr: 790 case scUMinExpr: 791 case scSequentialUMinExpr: { 792 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); 793 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); 794 795 // Lexicographically compare n-ary expressions. 796 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); 797 if (LNumOps != RNumOps) 798 return (int)LNumOps - (int)RNumOps; 799 800 for (unsigned i = 0; i != LNumOps; ++i) { 801 auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 802 LC->getOperand(i), RC->getOperand(i), DT, 803 Depth + 1); 804 if (X != 0) 805 return X; 806 } 807 EqCacheSCEV.unionSets(LHS, RHS); 808 return 0; 809 } 810 811 case scUDivExpr: { 812 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); 813 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); 814 815 // Lexicographically compare udiv expressions. 816 auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(), 817 RC->getLHS(), DT, Depth + 1); 818 if (X != 0) 819 return X; 820 X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(), 821 RC->getRHS(), DT, Depth + 1); 822 if (X == 0) 823 EqCacheSCEV.unionSets(LHS, RHS); 824 return X; 825 } 826 827 case scPtrToInt: 828 case scTruncate: 829 case scZeroExtend: 830 case scSignExtend: { 831 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS); 832 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS); 833 834 // Compare cast expressions by operand. 835 auto X = 836 CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getOperand(), 837 RC->getOperand(), DT, Depth + 1); 838 if (X == 0) 839 EqCacheSCEV.unionSets(LHS, RHS); 840 return X; 841 } 842 843 case scCouldNotCompute: 844 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 845 } 846 llvm_unreachable("Unknown SCEV kind!"); 847 } 848 849 /// Given a list of SCEV objects, order them by their complexity, and group 850 /// objects of the same complexity together by value. When this routine is 851 /// finished, we know that any duplicates in the vector are consecutive and that 852 /// complexity is monotonically increasing. 853 /// 854 /// Note that we go take special precautions to ensure that we get deterministic 855 /// results from this routine. In other words, we don't want the results of 856 /// this to depend on where the addresses of various SCEV objects happened to 857 /// land in memory. 858 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, 859 LoopInfo *LI, DominatorTree &DT) { 860 if (Ops.size() < 2) return; // Noop 861 862 EquivalenceClasses<const SCEV *> EqCacheSCEV; 863 EquivalenceClasses<const Value *> EqCacheValue; 864 865 // Whether LHS has provably less complexity than RHS. 866 auto IsLessComplex = [&](const SCEV *LHS, const SCEV *RHS) { 867 auto Complexity = 868 CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT); 869 return Complexity && *Complexity < 0; 870 }; 871 if (Ops.size() == 2) { 872 // This is the common case, which also happens to be trivially simple. 873 // Special case it. 874 const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; 875 if (IsLessComplex(RHS, LHS)) 876 std::swap(LHS, RHS); 877 return; 878 } 879 880 // Do the rough sort by complexity. 881 llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) { 882 return IsLessComplex(LHS, RHS); 883 }); 884 885 // Now that we are sorted by complexity, group elements of the same 886 // complexity. Note that this is, at worst, N^2, but the vector is likely to 887 // be extremely short in practice. Note that we take this approach because we 888 // do not want to depend on the addresses of the objects we are grouping. 889 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { 890 const SCEV *S = Ops[i]; 891 unsigned Complexity = S->getSCEVType(); 892 893 // If there are any objects of the same complexity and same value as this 894 // one, group them. 895 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { 896 if (Ops[j] == S) { // Found a duplicate. 897 // Move it to immediately after i'th element. 898 std::swap(Ops[i+1], Ops[j]); 899 ++i; // no need to rescan it. 900 if (i == e-2) return; // Done! 901 } 902 } 903 } 904 } 905 906 /// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at 907 /// least HugeExprThreshold nodes). 908 static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) { 909 return any_of(Ops, [](const SCEV *S) { 910 return S->getExpressionSize() >= HugeExprThreshold; 911 }); 912 } 913 914 //===----------------------------------------------------------------------===// 915 // Simple SCEV method implementations 916 //===----------------------------------------------------------------------===// 917 918 /// Compute BC(It, K). The result has width W. Assume, K > 0. 919 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, 920 ScalarEvolution &SE, 921 Type *ResultTy) { 922 // Handle the simplest case efficiently. 923 if (K == 1) 924 return SE.getTruncateOrZeroExtend(It, ResultTy); 925 926 // We are using the following formula for BC(It, K): 927 // 928 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! 929 // 930 // Suppose, W is the bitwidth of the return value. We must be prepared for 931 // overflow. Hence, we must assure that the result of our computation is 932 // equal to the accurate one modulo 2^W. Unfortunately, division isn't 933 // safe in modular arithmetic. 934 // 935 // However, this code doesn't use exactly that formula; the formula it uses 936 // is something like the following, where T is the number of factors of 2 in 937 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is 938 // exponentiation: 939 // 940 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) 941 // 942 // This formula is trivially equivalent to the previous formula. However, 943 // this formula can be implemented much more efficiently. The trick is that 944 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular 945 // arithmetic. To do exact division in modular arithmetic, all we have 946 // to do is multiply by the inverse. Therefore, this step can be done at 947 // width W. 948 // 949 // The next issue is how to safely do the division by 2^T. The way this 950 // is done is by doing the multiplication step at a width of at least W + T 951 // bits. This way, the bottom W+T bits of the product are accurate. Then, 952 // when we perform the division by 2^T (which is equivalent to a right shift 953 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get 954 // truncated out after the division by 2^T. 955 // 956 // In comparison to just directly using the first formula, this technique 957 // is much more efficient; using the first formula requires W * K bits, 958 // but this formula less than W + K bits. Also, the first formula requires 959 // a division step, whereas this formula only requires multiplies and shifts. 960 // 961 // It doesn't matter whether the subtraction step is done in the calculation 962 // width or the input iteration count's width; if the subtraction overflows, 963 // the result must be zero anyway. We prefer here to do it in the width of 964 // the induction variable because it helps a lot for certain cases; CodeGen 965 // isn't smart enough to ignore the overflow, which leads to much less 966 // efficient code if the width of the subtraction is wider than the native 967 // register width. 968 // 969 // (It's possible to not widen at all by pulling out factors of 2 before 970 // the multiplication; for example, K=2 can be calculated as 971 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires 972 // extra arithmetic, so it's not an obvious win, and it gets 973 // much more complicated for K > 3.) 974 975 // Protection from insane SCEVs; this bound is conservative, 976 // but it probably doesn't matter. 977 if (K > 1000) 978 return SE.getCouldNotCompute(); 979 980 unsigned W = SE.getTypeSizeInBits(ResultTy); 981 982 // Calculate K! / 2^T and T; we divide out the factors of two before 983 // multiplying for calculating K! / 2^T to avoid overflow. 984 // Other overflow doesn't matter because we only care about the bottom 985 // W bits of the result. 986 APInt OddFactorial(W, 1); 987 unsigned T = 1; 988 for (unsigned i = 3; i <= K; ++i) { 989 APInt Mult(W, i); 990 unsigned TwoFactors = Mult.countTrailingZeros(); 991 T += TwoFactors; 992 Mult.lshrInPlace(TwoFactors); 993 OddFactorial *= Mult; 994 } 995 996 // We need at least W + T bits for the multiplication step 997 unsigned CalculationBits = W + T; 998 999 // Calculate 2^T, at width T+W. 1000 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T); 1001 1002 // Calculate the multiplicative inverse of K! / 2^T; 1003 // this multiplication factor will perform the exact division by 1004 // K! / 2^T. 1005 APInt Mod = APInt::getSignedMinValue(W+1); 1006 APInt MultiplyFactor = OddFactorial.zext(W+1); 1007 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); 1008 MultiplyFactor = MultiplyFactor.trunc(W); 1009 1010 // Calculate the product, at width T+W 1011 IntegerType *CalculationTy = IntegerType::get(SE.getContext(), 1012 CalculationBits); 1013 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); 1014 for (unsigned i = 1; i != K; ++i) { 1015 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); 1016 Dividend = SE.getMulExpr(Dividend, 1017 SE.getTruncateOrZeroExtend(S, CalculationTy)); 1018 } 1019 1020 // Divide by 2^T 1021 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); 1022 1023 // Truncate the result, and divide by K! / 2^T. 1024 1025 return SE.getMulExpr(SE.getConstant(MultiplyFactor), 1026 SE.getTruncateOrZeroExtend(DivResult, ResultTy)); 1027 } 1028 1029 /// Return the value of this chain of recurrences at the specified iteration 1030 /// number. We can evaluate this recurrence by multiplying each element in the 1031 /// chain by the binomial coefficient corresponding to it. In other words, we 1032 /// can evaluate {A,+,B,+,C,+,D} as: 1033 /// 1034 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) 1035 /// 1036 /// where BC(It, k) stands for binomial coefficient. 1037 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, 1038 ScalarEvolution &SE) const { 1039 return evaluateAtIteration(makeArrayRef(op_begin(), op_end()), It, SE); 1040 } 1041 1042 const SCEV * 1043 SCEVAddRecExpr::evaluateAtIteration(ArrayRef<const SCEV *> Operands, 1044 const SCEV *It, ScalarEvolution &SE) { 1045 assert(Operands.size() > 0); 1046 const SCEV *Result = Operands[0]; 1047 for (unsigned i = 1, e = Operands.size(); i != e; ++i) { 1048 // The computation is correct in the face of overflow provided that the 1049 // multiplication is performed _after_ the evaluation of the binomial 1050 // coefficient. 1051 const SCEV *Coeff = BinomialCoefficient(It, i, SE, Result->getType()); 1052 if (isa<SCEVCouldNotCompute>(Coeff)) 1053 return Coeff; 1054 1055 Result = SE.getAddExpr(Result, SE.getMulExpr(Operands[i], Coeff)); 1056 } 1057 return Result; 1058 } 1059 1060 //===----------------------------------------------------------------------===// 1061 // SCEV Expression folder implementations 1062 //===----------------------------------------------------------------------===// 1063 1064 const SCEV *ScalarEvolution::getLosslessPtrToIntExpr(const SCEV *Op, 1065 unsigned Depth) { 1066 assert(Depth <= 1 && 1067 "getLosslessPtrToIntExpr() should self-recurse at most once."); 1068 1069 // We could be called with an integer-typed operands during SCEV rewrites. 1070 // Since the operand is an integer already, just perform zext/trunc/self cast. 1071 if (!Op->getType()->isPointerTy()) 1072 return Op; 1073 1074 // What would be an ID for such a SCEV cast expression? 1075 FoldingSetNodeID ID; 1076 ID.AddInteger(scPtrToInt); 1077 ID.AddPointer(Op); 1078 1079 void *IP = nullptr; 1080 1081 // Is there already an expression for such a cast? 1082 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 1083 return S; 1084 1085 // It isn't legal for optimizations to construct new ptrtoint expressions 1086 // for non-integral pointers. 1087 if (getDataLayout().isNonIntegralPointerType(Op->getType())) 1088 return getCouldNotCompute(); 1089 1090 Type *IntPtrTy = getDataLayout().getIntPtrType(Op->getType()); 1091 1092 // We can only trivially model ptrtoint if SCEV's effective (integer) type 1093 // is sufficiently wide to represent all possible pointer values. 1094 // We could theoretically teach SCEV to truncate wider pointers, but 1095 // that isn't implemented for now. 1096 if (getDataLayout().getTypeSizeInBits(getEffectiveSCEVType(Op->getType())) != 1097 getDataLayout().getTypeSizeInBits(IntPtrTy)) 1098 return getCouldNotCompute(); 1099 1100 // If not, is this expression something we can't reduce any further? 1101 if (auto *U = dyn_cast<SCEVUnknown>(Op)) { 1102 // Perform some basic constant folding. If the operand of the ptr2int cast 1103 // is a null pointer, don't create a ptr2int SCEV expression (that will be 1104 // left as-is), but produce a zero constant. 1105 // NOTE: We could handle a more general case, but lack motivational cases. 1106 if (isa<ConstantPointerNull>(U->getValue())) 1107 return getZero(IntPtrTy); 1108 1109 // Create an explicit cast node. 1110 // We can reuse the existing insert position since if we get here, 1111 // we won't have made any changes which would invalidate it. 1112 SCEV *S = new (SCEVAllocator) 1113 SCEVPtrToIntExpr(ID.Intern(SCEVAllocator), Op, IntPtrTy); 1114 UniqueSCEVs.InsertNode(S, IP); 1115 registerUser(S, Op); 1116 return S; 1117 } 1118 1119 assert(Depth == 0 && "getLosslessPtrToIntExpr() should not self-recurse for " 1120 "non-SCEVUnknown's."); 1121 1122 // Otherwise, we've got some expression that is more complex than just a 1123 // single SCEVUnknown. But we don't want to have a SCEVPtrToIntExpr of an 1124 // arbitrary expression, we want to have SCEVPtrToIntExpr of an SCEVUnknown 1125 // only, and the expressions must otherwise be integer-typed. 1126 // So sink the cast down to the SCEVUnknown's. 1127 1128 /// The SCEVPtrToIntSinkingRewriter takes a scalar evolution expression, 1129 /// which computes a pointer-typed value, and rewrites the whole expression 1130 /// tree so that *all* the computations are done on integers, and the only 1131 /// pointer-typed operands in the expression are SCEVUnknown. 1132 class SCEVPtrToIntSinkingRewriter 1133 : public SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter> { 1134 using Base = SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter>; 1135 1136 public: 1137 SCEVPtrToIntSinkingRewriter(ScalarEvolution &SE) : SCEVRewriteVisitor(SE) {} 1138 1139 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE) { 1140 SCEVPtrToIntSinkingRewriter Rewriter(SE); 1141 return Rewriter.visit(Scev); 1142 } 1143 1144 const SCEV *visit(const SCEV *S) { 1145 Type *STy = S->getType(); 1146 // If the expression is not pointer-typed, just keep it as-is. 1147 if (!STy->isPointerTy()) 1148 return S; 1149 // Else, recursively sink the cast down into it. 1150 return Base::visit(S); 1151 } 1152 1153 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) { 1154 SmallVector<const SCEV *, 2> Operands; 1155 bool Changed = false; 1156 for (auto *Op : Expr->operands()) { 1157 Operands.push_back(visit(Op)); 1158 Changed |= Op != Operands.back(); 1159 } 1160 return !Changed ? Expr : SE.getAddExpr(Operands, Expr->getNoWrapFlags()); 1161 } 1162 1163 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) { 1164 SmallVector<const SCEV *, 2> Operands; 1165 bool Changed = false; 1166 for (auto *Op : Expr->operands()) { 1167 Operands.push_back(visit(Op)); 1168 Changed |= Op != Operands.back(); 1169 } 1170 return !Changed ? Expr : SE.getMulExpr(Operands, Expr->getNoWrapFlags()); 1171 } 1172 1173 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 1174 assert(Expr->getType()->isPointerTy() && 1175 "Should only reach pointer-typed SCEVUnknown's."); 1176 return SE.getLosslessPtrToIntExpr(Expr, /*Depth=*/1); 1177 } 1178 }; 1179 1180 // And actually perform the cast sinking. 1181 const SCEV *IntOp = SCEVPtrToIntSinkingRewriter::rewrite(Op, *this); 1182 assert(IntOp->getType()->isIntegerTy() && 1183 "We must have succeeded in sinking the cast, " 1184 "and ending up with an integer-typed expression!"); 1185 return IntOp; 1186 } 1187 1188 const SCEV *ScalarEvolution::getPtrToIntExpr(const SCEV *Op, Type *Ty) { 1189 assert(Ty->isIntegerTy() && "Target type must be an integer type!"); 1190 1191 const SCEV *IntOp = getLosslessPtrToIntExpr(Op); 1192 if (isa<SCEVCouldNotCompute>(IntOp)) 1193 return IntOp; 1194 1195 return getTruncateOrZeroExtend(IntOp, Ty); 1196 } 1197 1198 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty, 1199 unsigned Depth) { 1200 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && 1201 "This is not a truncating conversion!"); 1202 assert(isSCEVable(Ty) && 1203 "This is not a conversion to a SCEVable type!"); 1204 assert(!Op->getType()->isPointerTy() && "Can't truncate pointer!"); 1205 Ty = getEffectiveSCEVType(Ty); 1206 1207 FoldingSetNodeID ID; 1208 ID.AddInteger(scTruncate); 1209 ID.AddPointer(Op); 1210 ID.AddPointer(Ty); 1211 void *IP = nullptr; 1212 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1213 1214 // Fold if the operand is constant. 1215 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1216 return getConstant( 1217 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); 1218 1219 // trunc(trunc(x)) --> trunc(x) 1220 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) 1221 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1); 1222 1223 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing 1224 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1225 return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1); 1226 1227 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing 1228 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1229 return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1); 1230 1231 if (Depth > MaxCastDepth) { 1232 SCEV *S = 1233 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty); 1234 UniqueSCEVs.InsertNode(S, IP); 1235 registerUser(S, Op); 1236 return S; 1237 } 1238 1239 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and 1240 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN), 1241 // if after transforming we have at most one truncate, not counting truncates 1242 // that replace other casts. 1243 if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) { 1244 auto *CommOp = cast<SCEVCommutativeExpr>(Op); 1245 SmallVector<const SCEV *, 4> Operands; 1246 unsigned numTruncs = 0; 1247 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2; 1248 ++i) { 1249 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1); 1250 if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) && 1251 isa<SCEVTruncateExpr>(S)) 1252 numTruncs++; 1253 Operands.push_back(S); 1254 } 1255 if (numTruncs < 2) { 1256 if (isa<SCEVAddExpr>(Op)) 1257 return getAddExpr(Operands); 1258 else if (isa<SCEVMulExpr>(Op)) 1259 return getMulExpr(Operands); 1260 else 1261 llvm_unreachable("Unexpected SCEV type for Op."); 1262 } 1263 // Although we checked in the beginning that ID is not in the cache, it is 1264 // possible that during recursion and different modification ID was inserted 1265 // into the cache. So if we find it, just return it. 1266 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 1267 return S; 1268 } 1269 1270 // If the input value is a chrec scev, truncate the chrec's operands. 1271 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 1272 SmallVector<const SCEV *, 4> Operands; 1273 for (const SCEV *Op : AddRec->operands()) 1274 Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1)); 1275 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap); 1276 } 1277 1278 // Return zero if truncating to known zeros. 1279 uint32_t MinTrailingZeros = GetMinTrailingZeros(Op); 1280 if (MinTrailingZeros >= getTypeSizeInBits(Ty)) 1281 return getZero(Ty); 1282 1283 // The cast wasn't folded; create an explicit cast node. We can reuse 1284 // the existing insert position since if we get here, we won't have 1285 // made any changes which would invalidate it. 1286 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), 1287 Op, Ty); 1288 UniqueSCEVs.InsertNode(S, IP); 1289 registerUser(S, Op); 1290 return S; 1291 } 1292 1293 // Get the limit of a recurrence such that incrementing by Step cannot cause 1294 // signed overflow as long as the value of the recurrence within the 1295 // loop does not exceed this limit before incrementing. 1296 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step, 1297 ICmpInst::Predicate *Pred, 1298 ScalarEvolution *SE) { 1299 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1300 if (SE->isKnownPositive(Step)) { 1301 *Pred = ICmpInst::ICMP_SLT; 1302 return SE->getConstant(APInt::getSignedMinValue(BitWidth) - 1303 SE->getSignedRangeMax(Step)); 1304 } 1305 if (SE->isKnownNegative(Step)) { 1306 *Pred = ICmpInst::ICMP_SGT; 1307 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - 1308 SE->getSignedRangeMin(Step)); 1309 } 1310 return nullptr; 1311 } 1312 1313 // Get the limit of a recurrence such that incrementing by Step cannot cause 1314 // unsigned overflow as long as the value of the recurrence within the loop does 1315 // not exceed this limit before incrementing. 1316 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step, 1317 ICmpInst::Predicate *Pred, 1318 ScalarEvolution *SE) { 1319 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1320 *Pred = ICmpInst::ICMP_ULT; 1321 1322 return SE->getConstant(APInt::getMinValue(BitWidth) - 1323 SE->getUnsignedRangeMax(Step)); 1324 } 1325 1326 namespace { 1327 1328 struct ExtendOpTraitsBase { 1329 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *, 1330 unsigned); 1331 }; 1332 1333 // Used to make code generic over signed and unsigned overflow. 1334 template <typename ExtendOp> struct ExtendOpTraits { 1335 // Members present: 1336 // 1337 // static const SCEV::NoWrapFlags WrapType; 1338 // 1339 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr; 1340 // 1341 // static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1342 // ICmpInst::Predicate *Pred, 1343 // ScalarEvolution *SE); 1344 }; 1345 1346 template <> 1347 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase { 1348 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW; 1349 1350 static const GetExtendExprTy GetExtendExpr; 1351 1352 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1353 ICmpInst::Predicate *Pred, 1354 ScalarEvolution *SE) { 1355 return getSignedOverflowLimitForStep(Step, Pred, SE); 1356 } 1357 }; 1358 1359 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1360 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr; 1361 1362 template <> 1363 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase { 1364 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW; 1365 1366 static const GetExtendExprTy GetExtendExpr; 1367 1368 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1369 ICmpInst::Predicate *Pred, 1370 ScalarEvolution *SE) { 1371 return getUnsignedOverflowLimitForStep(Step, Pred, SE); 1372 } 1373 }; 1374 1375 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1376 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr; 1377 1378 } // end anonymous namespace 1379 1380 // The recurrence AR has been shown to have no signed/unsigned wrap or something 1381 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as 1382 // easily prove NSW/NUW for its preincrement or postincrement sibling. This 1383 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step + 1384 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the 1385 // expression "Step + sext/zext(PreIncAR)" is congruent with 1386 // "sext/zext(PostIncAR)" 1387 template <typename ExtendOpTy> 1388 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, 1389 ScalarEvolution *SE, unsigned Depth) { 1390 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1391 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1392 1393 const Loop *L = AR->getLoop(); 1394 const SCEV *Start = AR->getStart(); 1395 const SCEV *Step = AR->getStepRecurrence(*SE); 1396 1397 // Check for a simple looking step prior to loop entry. 1398 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); 1399 if (!SA) 1400 return nullptr; 1401 1402 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV 1403 // subtraction is expensive. For this purpose, perform a quick and dirty 1404 // difference, by checking for Step in the operand list. 1405 SmallVector<const SCEV *, 4> DiffOps; 1406 for (const SCEV *Op : SA->operands()) 1407 if (Op != Step) 1408 DiffOps.push_back(Op); 1409 1410 if (DiffOps.size() == SA->getNumOperands()) 1411 return nullptr; 1412 1413 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` + 1414 // `Step`: 1415 1416 // 1. NSW/NUW flags on the step increment. 1417 auto PreStartFlags = 1418 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW); 1419 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags); 1420 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( 1421 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); 1422 1423 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies 1424 // "S+X does not sign/unsign-overflow". 1425 // 1426 1427 const SCEV *BECount = SE->getBackedgeTakenCount(L); 1428 if (PreAR && PreAR->getNoWrapFlags(WrapType) && 1429 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) 1430 return PreStart; 1431 1432 // 2. Direct overflow check on the step operation's expression. 1433 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); 1434 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); 1435 const SCEV *OperandExtendedStart = 1436 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth), 1437 (SE->*GetExtendExpr)(Step, WideTy, Depth)); 1438 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) { 1439 if (PreAR && AR->getNoWrapFlags(WrapType)) { 1440 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW 1441 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then 1442 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. 1443 SE->setNoWrapFlags(const_cast<SCEVAddRecExpr *>(PreAR), WrapType); 1444 } 1445 return PreStart; 1446 } 1447 1448 // 3. Loop precondition. 1449 ICmpInst::Predicate Pred; 1450 const SCEV *OverflowLimit = 1451 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); 1452 1453 if (OverflowLimit && 1454 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) 1455 return PreStart; 1456 1457 return nullptr; 1458 } 1459 1460 // Get the normalized zero or sign extended expression for this AddRec's Start. 1461 template <typename ExtendOpTy> 1462 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, 1463 ScalarEvolution *SE, 1464 unsigned Depth) { 1465 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1466 1467 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth); 1468 if (!PreStart) 1469 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth); 1470 1471 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty, 1472 Depth), 1473 (SE->*GetExtendExpr)(PreStart, Ty, Depth)); 1474 } 1475 1476 // Try to prove away overflow by looking at "nearby" add recurrences. A 1477 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it 1478 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. 1479 // 1480 // Formally: 1481 // 1482 // {S,+,X} == {S-T,+,X} + T 1483 // => Ext({S,+,X}) == Ext({S-T,+,X} + T) 1484 // 1485 // If ({S-T,+,X} + T) does not overflow ... (1) 1486 // 1487 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) 1488 // 1489 // If {S-T,+,X} does not overflow ... (2) 1490 // 1491 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) 1492 // == {Ext(S-T)+Ext(T),+,Ext(X)} 1493 // 1494 // If (S-T)+T does not overflow ... (3) 1495 // 1496 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} 1497 // == {Ext(S),+,Ext(X)} == LHS 1498 // 1499 // Thus, if (1), (2) and (3) are true for some T, then 1500 // Ext({S,+,X}) == {Ext(S),+,Ext(X)} 1501 // 1502 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) 1503 // does not overflow" restricted to the 0th iteration. Therefore we only need 1504 // to check for (1) and (2). 1505 // 1506 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T 1507 // is `Delta` (defined below). 1508 template <typename ExtendOpTy> 1509 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, 1510 const SCEV *Step, 1511 const Loop *L) { 1512 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1513 1514 // We restrict `Start` to a constant to prevent SCEV from spending too much 1515 // time here. It is correct (but more expensive) to continue with a 1516 // non-constant `Start` and do a general SCEV subtraction to compute 1517 // `PreStart` below. 1518 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); 1519 if (!StartC) 1520 return false; 1521 1522 APInt StartAI = StartC->getAPInt(); 1523 1524 for (unsigned Delta : {-2, -1, 1, 2}) { 1525 const SCEV *PreStart = getConstant(StartAI - Delta); 1526 1527 FoldingSetNodeID ID; 1528 ID.AddInteger(scAddRecExpr); 1529 ID.AddPointer(PreStart); 1530 ID.AddPointer(Step); 1531 ID.AddPointer(L); 1532 void *IP = nullptr; 1533 const auto *PreAR = 1534 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 1535 1536 // Give up if we don't already have the add recurrence we need because 1537 // actually constructing an add recurrence is relatively expensive. 1538 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2) 1539 const SCEV *DeltaS = getConstant(StartC->getType(), Delta); 1540 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; 1541 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep( 1542 DeltaS, &Pred, this); 1543 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1) 1544 return true; 1545 } 1546 } 1547 1548 return false; 1549 } 1550 1551 // Finds an integer D for an expression (C + x + y + ...) such that the top 1552 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or 1553 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is 1554 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and 1555 // the (C + x + y + ...) expression is \p WholeAddExpr. 1556 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1557 const SCEVConstant *ConstantTerm, 1558 const SCEVAddExpr *WholeAddExpr) { 1559 const APInt &C = ConstantTerm->getAPInt(); 1560 const unsigned BitWidth = C.getBitWidth(); 1561 // Find number of trailing zeros of (x + y + ...) w/o the C first: 1562 uint32_t TZ = BitWidth; 1563 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I) 1564 TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I))); 1565 if (TZ) { 1566 // Set D to be as many least significant bits of C as possible while still 1567 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap: 1568 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C; 1569 } 1570 return APInt(BitWidth, 0); 1571 } 1572 1573 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top 1574 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the 1575 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p 1576 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count. 1577 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1578 const APInt &ConstantStart, 1579 const SCEV *Step) { 1580 const unsigned BitWidth = ConstantStart.getBitWidth(); 1581 const uint32_t TZ = SE.GetMinTrailingZeros(Step); 1582 if (TZ) 1583 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth) 1584 : ConstantStart; 1585 return APInt(BitWidth, 0); 1586 } 1587 1588 const SCEV * 1589 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1590 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1591 "This is not an extending conversion!"); 1592 assert(isSCEVable(Ty) && 1593 "This is not a conversion to a SCEVable type!"); 1594 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!"); 1595 Ty = getEffectiveSCEVType(Ty); 1596 1597 // Fold if the operand is constant. 1598 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1599 return getConstant( 1600 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty))); 1601 1602 // zext(zext(x)) --> zext(x) 1603 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1604 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1605 1606 // Before doing any expensive analysis, check to see if we've already 1607 // computed a SCEV for this Op and Ty. 1608 FoldingSetNodeID ID; 1609 ID.AddInteger(scZeroExtend); 1610 ID.AddPointer(Op); 1611 ID.AddPointer(Ty); 1612 void *IP = nullptr; 1613 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1614 if (Depth > MaxCastDepth) { 1615 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1616 Op, Ty); 1617 UniqueSCEVs.InsertNode(S, IP); 1618 registerUser(S, Op); 1619 return S; 1620 } 1621 1622 // zext(trunc(x)) --> zext(x) or x or trunc(x) 1623 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1624 // It's possible the bits taken off by the truncate were all zero bits. If 1625 // so, we should be able to simplify this further. 1626 const SCEV *X = ST->getOperand(); 1627 ConstantRange CR = getUnsignedRange(X); 1628 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1629 unsigned NewBits = getTypeSizeInBits(Ty); 1630 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( 1631 CR.zextOrTrunc(NewBits))) 1632 return getTruncateOrZeroExtend(X, Ty, Depth); 1633 } 1634 1635 // If the input value is a chrec scev, and we can prove that the value 1636 // did not overflow the old, smaller, value, we can zero extend all of the 1637 // operands (often constants). This allows analysis of something like 1638 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } 1639 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1640 if (AR->isAffine()) { 1641 const SCEV *Start = AR->getStart(); 1642 const SCEV *Step = AR->getStepRecurrence(*this); 1643 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1644 const Loop *L = AR->getLoop(); 1645 1646 if (!AR->hasNoUnsignedWrap()) { 1647 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1648 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags); 1649 } 1650 1651 // If we have special knowledge that this addrec won't overflow, 1652 // we don't need to do any further analysis. 1653 if (AR->hasNoUnsignedWrap()) 1654 return getAddRecExpr( 1655 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1656 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1657 1658 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1659 // Note that this serves two purposes: It filters out loops that are 1660 // simply not analyzable, and it covers the case where this code is 1661 // being called from within backedge-taken count analysis, such that 1662 // attempting to ask for the backedge-taken count would likely result 1663 // in infinite recursion. In the later case, the analysis code will 1664 // cope with a conservative value, and it will take care to purge 1665 // that value once it has finished. 1666 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 1667 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1668 // Manually compute the final value for AR, checking for overflow. 1669 1670 // Check whether the backedge-taken count can be losslessly casted to 1671 // the addrec's type. The count is always unsigned. 1672 const SCEV *CastedMaxBECount = 1673 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 1674 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 1675 CastedMaxBECount, MaxBECount->getType(), Depth); 1676 if (MaxBECount == RecastedMaxBECount) { 1677 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1678 // Check whether Start+Step*MaxBECount has no unsigned overflow. 1679 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step, 1680 SCEV::FlagAnyWrap, Depth + 1); 1681 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul, 1682 SCEV::FlagAnyWrap, 1683 Depth + 1), 1684 WideTy, Depth + 1); 1685 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1); 1686 const SCEV *WideMaxBECount = 1687 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 1688 const SCEV *OperandExtendedAdd = 1689 getAddExpr(WideStart, 1690 getMulExpr(WideMaxBECount, 1691 getZeroExtendExpr(Step, WideTy, Depth + 1), 1692 SCEV::FlagAnyWrap, Depth + 1), 1693 SCEV::FlagAnyWrap, Depth + 1); 1694 if (ZAdd == OperandExtendedAdd) { 1695 // Cache knowledge of AR NUW, which is propagated to this AddRec. 1696 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW); 1697 // Return the expression with the addrec on the outside. 1698 return getAddRecExpr( 1699 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1700 Depth + 1), 1701 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1702 AR->getNoWrapFlags()); 1703 } 1704 // Similar to above, only this time treat the step value as signed. 1705 // This covers loops that count down. 1706 OperandExtendedAdd = 1707 getAddExpr(WideStart, 1708 getMulExpr(WideMaxBECount, 1709 getSignExtendExpr(Step, WideTy, Depth + 1), 1710 SCEV::FlagAnyWrap, Depth + 1), 1711 SCEV::FlagAnyWrap, Depth + 1); 1712 if (ZAdd == OperandExtendedAdd) { 1713 // Cache knowledge of AR NW, which is propagated to this AddRec. 1714 // Negative step causes unsigned wrap, but it still can't self-wrap. 1715 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW); 1716 // Return the expression with the addrec on the outside. 1717 return getAddRecExpr( 1718 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1719 Depth + 1), 1720 getSignExtendExpr(Step, Ty, Depth + 1), L, 1721 AR->getNoWrapFlags()); 1722 } 1723 } 1724 } 1725 1726 // Normally, in the cases we can prove no-overflow via a 1727 // backedge guarding condition, we can also compute a backedge 1728 // taken count for the loop. The exceptions are assumptions and 1729 // guards present in the loop -- SCEV is not great at exploiting 1730 // these to compute max backedge taken counts, but can still use 1731 // these to prove lack of overflow. Use this fact to avoid 1732 // doing extra work that may not pay off. 1733 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1734 !AC.assumptions().empty()) { 1735 1736 auto NewFlags = proveNoUnsignedWrapViaInduction(AR); 1737 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags); 1738 if (AR->hasNoUnsignedWrap()) { 1739 // Same as nuw case above - duplicated here to avoid a compile time 1740 // issue. It's not clear that the order of checks does matter, but 1741 // it's one of two issue possible causes for a change which was 1742 // reverted. Be conservative for the moment. 1743 return getAddRecExpr( 1744 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1745 Depth + 1), 1746 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1747 AR->getNoWrapFlags()); 1748 } 1749 1750 // For a negative step, we can extend the operands iff doing so only 1751 // traverses values in the range zext([0,UINT_MAX]). 1752 if (isKnownNegative(Step)) { 1753 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - 1754 getSignedRangeMin(Step)); 1755 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || 1756 isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) { 1757 // Cache knowledge of AR NW, which is propagated to this 1758 // AddRec. Negative step causes unsigned wrap, but it 1759 // still can't self-wrap. 1760 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW); 1761 // Return the expression with the addrec on the outside. 1762 return getAddRecExpr( 1763 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1764 Depth + 1), 1765 getSignExtendExpr(Step, Ty, Depth + 1), L, 1766 AR->getNoWrapFlags()); 1767 } 1768 } 1769 } 1770 1771 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw> 1772 // if D + (C - D + Step * n) could be proven to not unsigned wrap 1773 // where D maximizes the number of trailing zeros of (C - D + Step * n) 1774 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 1775 const APInt &C = SC->getAPInt(); 1776 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 1777 if (D != 0) { 1778 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1779 const SCEV *SResidual = 1780 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 1781 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1782 return getAddExpr(SZExtD, SZExtR, 1783 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1784 Depth + 1); 1785 } 1786 } 1787 1788 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { 1789 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW); 1790 return getAddRecExpr( 1791 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1792 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1793 } 1794 } 1795 1796 // zext(A % B) --> zext(A) % zext(B) 1797 { 1798 const SCEV *LHS; 1799 const SCEV *RHS; 1800 if (matchURem(Op, LHS, RHS)) 1801 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1), 1802 getZeroExtendExpr(RHS, Ty, Depth + 1)); 1803 } 1804 1805 // zext(A / B) --> zext(A) / zext(B). 1806 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op)) 1807 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1), 1808 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1)); 1809 1810 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1811 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> 1812 if (SA->hasNoUnsignedWrap()) { 1813 // If the addition does not unsign overflow then we can, by definition, 1814 // commute the zero extension with the addition operation. 1815 SmallVector<const SCEV *, 4> Ops; 1816 for (const auto *Op : SA->operands()) 1817 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1818 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1); 1819 } 1820 1821 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...)) 1822 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap 1823 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1824 // 1825 // Often address arithmetics contain expressions like 1826 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))). 1827 // This transformation is useful while proving that such expressions are 1828 // equal or differ by a small constant amount, see LoadStoreVectorizer pass. 1829 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1830 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1831 if (D != 0) { 1832 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1833 const SCEV *SResidual = 1834 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 1835 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1836 return getAddExpr(SZExtD, SZExtR, 1837 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1838 Depth + 1); 1839 } 1840 } 1841 } 1842 1843 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) { 1844 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw> 1845 if (SM->hasNoUnsignedWrap()) { 1846 // If the multiply does not unsign overflow then we can, by definition, 1847 // commute the zero extension with the multiply operation. 1848 SmallVector<const SCEV *, 4> Ops; 1849 for (const auto *Op : SM->operands()) 1850 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1851 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1); 1852 } 1853 1854 // zext(2^K * (trunc X to iN)) to iM -> 1855 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw> 1856 // 1857 // Proof: 1858 // 1859 // zext(2^K * (trunc X to iN)) to iM 1860 // = zext((trunc X to iN) << K) to iM 1861 // = zext((trunc X to i{N-K}) << K)<nuw> to iM 1862 // (because shl removes the top K bits) 1863 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM 1864 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>. 1865 // 1866 if (SM->getNumOperands() == 2) 1867 if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0))) 1868 if (MulLHS->getAPInt().isPowerOf2()) 1869 if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) { 1870 int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) - 1871 MulLHS->getAPInt().logBase2(); 1872 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits); 1873 return getMulExpr( 1874 getZeroExtendExpr(MulLHS, Ty), 1875 getZeroExtendExpr( 1876 getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty), 1877 SCEV::FlagNUW, Depth + 1); 1878 } 1879 } 1880 1881 // The cast wasn't folded; create an explicit cast node. 1882 // Recompute the insert position, as it may have been invalidated. 1883 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1884 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1885 Op, Ty); 1886 UniqueSCEVs.InsertNode(S, IP); 1887 registerUser(S, Op); 1888 return S; 1889 } 1890 1891 const SCEV * 1892 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1893 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1894 "This is not an extending conversion!"); 1895 assert(isSCEVable(Ty) && 1896 "This is not a conversion to a SCEVable type!"); 1897 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!"); 1898 Ty = getEffectiveSCEVType(Ty); 1899 1900 // Fold if the operand is constant. 1901 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1902 return getConstant( 1903 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); 1904 1905 // sext(sext(x)) --> sext(x) 1906 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1907 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1); 1908 1909 // sext(zext(x)) --> zext(x) 1910 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1911 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1912 1913 // Before doing any expensive analysis, check to see if we've already 1914 // computed a SCEV for this Op and Ty. 1915 FoldingSetNodeID ID; 1916 ID.AddInteger(scSignExtend); 1917 ID.AddPointer(Op); 1918 ID.AddPointer(Ty); 1919 void *IP = nullptr; 1920 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1921 // Limit recursion depth. 1922 if (Depth > MaxCastDepth) { 1923 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1924 Op, Ty); 1925 UniqueSCEVs.InsertNode(S, IP); 1926 registerUser(S, Op); 1927 return S; 1928 } 1929 1930 // sext(trunc(x)) --> sext(x) or x or trunc(x) 1931 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1932 // It's possible the bits taken off by the truncate were all sign bits. If 1933 // so, we should be able to simplify this further. 1934 const SCEV *X = ST->getOperand(); 1935 ConstantRange CR = getSignedRange(X); 1936 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1937 unsigned NewBits = getTypeSizeInBits(Ty); 1938 if (CR.truncate(TruncBits).signExtend(NewBits).contains( 1939 CR.sextOrTrunc(NewBits))) 1940 return getTruncateOrSignExtend(X, Ty, Depth); 1941 } 1942 1943 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1944 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 1945 if (SA->hasNoSignedWrap()) { 1946 // If the addition does not sign overflow then we can, by definition, 1947 // commute the sign extension with the addition operation. 1948 SmallVector<const SCEV *, 4> Ops; 1949 for (const auto *Op : SA->operands()) 1950 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1)); 1951 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1); 1952 } 1953 1954 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...)) 1955 // if D + (C - D + x + y + ...) could be proven to not signed wrap 1956 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1957 // 1958 // For instance, this will bring two seemingly different expressions: 1959 // 1 + sext(5 + 20 * %x + 24 * %y) and 1960 // sext(6 + 20 * %x + 24 * %y) 1961 // to the same form: 1962 // 2 + sext(4 + 20 * %x + 24 * %y) 1963 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1964 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1965 if (D != 0) { 1966 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 1967 const SCEV *SResidual = 1968 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 1969 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 1970 return getAddExpr(SSExtD, SSExtR, 1971 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1972 Depth + 1); 1973 } 1974 } 1975 } 1976 // If the input value is a chrec scev, and we can prove that the value 1977 // did not overflow the old, smaller, value, we can sign extend all of the 1978 // operands (often constants). This allows analysis of something like 1979 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 1980 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1981 if (AR->isAffine()) { 1982 const SCEV *Start = AR->getStart(); 1983 const SCEV *Step = AR->getStepRecurrence(*this); 1984 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1985 const Loop *L = AR->getLoop(); 1986 1987 if (!AR->hasNoSignedWrap()) { 1988 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1989 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags); 1990 } 1991 1992 // If we have special knowledge that this addrec won't overflow, 1993 // we don't need to do any further analysis. 1994 if (AR->hasNoSignedWrap()) 1995 return getAddRecExpr( 1996 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 1997 getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW); 1998 1999 // Check whether the backedge-taken count is SCEVCouldNotCompute. 2000 // Note that this serves two purposes: It filters out loops that are 2001 // simply not analyzable, and it covers the case where this code is 2002 // being called from within backedge-taken count analysis, such that 2003 // attempting to ask for the backedge-taken count would likely result 2004 // in infinite recursion. In the later case, the analysis code will 2005 // cope with a conservative value, and it will take care to purge 2006 // that value once it has finished. 2007 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 2008 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 2009 // Manually compute the final value for AR, checking for 2010 // overflow. 2011 2012 // Check whether the backedge-taken count can be losslessly casted to 2013 // the addrec's type. The count is always unsigned. 2014 const SCEV *CastedMaxBECount = 2015 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 2016 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 2017 CastedMaxBECount, MaxBECount->getType(), Depth); 2018 if (MaxBECount == RecastedMaxBECount) { 2019 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 2020 // Check whether Start+Step*MaxBECount has no signed overflow. 2021 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step, 2022 SCEV::FlagAnyWrap, Depth + 1); 2023 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul, 2024 SCEV::FlagAnyWrap, 2025 Depth + 1), 2026 WideTy, Depth + 1); 2027 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1); 2028 const SCEV *WideMaxBECount = 2029 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 2030 const SCEV *OperandExtendedAdd = 2031 getAddExpr(WideStart, 2032 getMulExpr(WideMaxBECount, 2033 getSignExtendExpr(Step, WideTy, Depth + 1), 2034 SCEV::FlagAnyWrap, Depth + 1), 2035 SCEV::FlagAnyWrap, Depth + 1); 2036 if (SAdd == OperandExtendedAdd) { 2037 // Cache knowledge of AR NSW, which is propagated to this AddRec. 2038 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW); 2039 // Return the expression with the addrec on the outside. 2040 return getAddRecExpr( 2041 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2042 Depth + 1), 2043 getSignExtendExpr(Step, Ty, Depth + 1), L, 2044 AR->getNoWrapFlags()); 2045 } 2046 // Similar to above, only this time treat the step value as unsigned. 2047 // This covers loops that count up with an unsigned step. 2048 OperandExtendedAdd = 2049 getAddExpr(WideStart, 2050 getMulExpr(WideMaxBECount, 2051 getZeroExtendExpr(Step, WideTy, Depth + 1), 2052 SCEV::FlagAnyWrap, Depth + 1), 2053 SCEV::FlagAnyWrap, Depth + 1); 2054 if (SAdd == OperandExtendedAdd) { 2055 // If AR wraps around then 2056 // 2057 // abs(Step) * MaxBECount > unsigned-max(AR->getType()) 2058 // => SAdd != OperandExtendedAdd 2059 // 2060 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> 2061 // (SAdd == OperandExtendedAdd => AR is NW) 2062 2063 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW); 2064 2065 // Return the expression with the addrec on the outside. 2066 return getAddRecExpr( 2067 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2068 Depth + 1), 2069 getZeroExtendExpr(Step, Ty, Depth + 1), L, 2070 AR->getNoWrapFlags()); 2071 } 2072 } 2073 } 2074 2075 auto NewFlags = proveNoSignedWrapViaInduction(AR); 2076 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags); 2077 if (AR->hasNoSignedWrap()) { 2078 // Same as nsw case above - duplicated here to avoid a compile time 2079 // issue. It's not clear that the order of checks does matter, but 2080 // it's one of two issue possible causes for a change which was 2081 // reverted. Be conservative for the moment. 2082 return getAddRecExpr( 2083 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2084 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2085 } 2086 2087 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw> 2088 // if D + (C - D + Step * n) could be proven to not signed wrap 2089 // where D maximizes the number of trailing zeros of (C - D + Step * n) 2090 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 2091 const APInt &C = SC->getAPInt(); 2092 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 2093 if (D != 0) { 2094 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 2095 const SCEV *SResidual = 2096 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 2097 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 2098 return getAddExpr(SSExtD, SSExtR, 2099 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 2100 Depth + 1); 2101 } 2102 } 2103 2104 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { 2105 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW); 2106 return getAddRecExpr( 2107 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2108 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2109 } 2110 } 2111 2112 // If the input value is provably positive and we could not simplify 2113 // away the sext build a zext instead. 2114 if (isKnownNonNegative(Op)) 2115 return getZeroExtendExpr(Op, Ty, Depth + 1); 2116 2117 // The cast wasn't folded; create an explicit cast node. 2118 // Recompute the insert position, as it may have been invalidated. 2119 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 2120 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 2121 Op, Ty); 2122 UniqueSCEVs.InsertNode(S, IP); 2123 registerUser(S, { Op }); 2124 return S; 2125 } 2126 2127 const SCEV *ScalarEvolution::getCastExpr(SCEVTypes Kind, const SCEV *Op, 2128 Type *Ty) { 2129 switch (Kind) { 2130 case scTruncate: 2131 return getTruncateExpr(Op, Ty); 2132 case scZeroExtend: 2133 return getZeroExtendExpr(Op, Ty); 2134 case scSignExtend: 2135 return getSignExtendExpr(Op, Ty); 2136 case scPtrToInt: 2137 return getPtrToIntExpr(Op, Ty); 2138 default: 2139 llvm_unreachable("Not a SCEV cast expression!"); 2140 } 2141 } 2142 2143 /// getAnyExtendExpr - Return a SCEV for the given operand extended with 2144 /// unspecified bits out to the given type. 2145 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, 2146 Type *Ty) { 2147 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 2148 "This is not an extending conversion!"); 2149 assert(isSCEVable(Ty) && 2150 "This is not a conversion to a SCEVable type!"); 2151 Ty = getEffectiveSCEVType(Ty); 2152 2153 // Sign-extend negative constants. 2154 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 2155 if (SC->getAPInt().isNegative()) 2156 return getSignExtendExpr(Op, Ty); 2157 2158 // Peel off a truncate cast. 2159 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { 2160 const SCEV *NewOp = T->getOperand(); 2161 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) 2162 return getAnyExtendExpr(NewOp, Ty); 2163 return getTruncateOrNoop(NewOp, Ty); 2164 } 2165 2166 // Next try a zext cast. If the cast is folded, use it. 2167 const SCEV *ZExt = getZeroExtendExpr(Op, Ty); 2168 if (!isa<SCEVZeroExtendExpr>(ZExt)) 2169 return ZExt; 2170 2171 // Next try a sext cast. If the cast is folded, use it. 2172 const SCEV *SExt = getSignExtendExpr(Op, Ty); 2173 if (!isa<SCEVSignExtendExpr>(SExt)) 2174 return SExt; 2175 2176 // Force the cast to be folded into the operands of an addrec. 2177 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { 2178 SmallVector<const SCEV *, 4> Ops; 2179 for (const SCEV *Op : AR->operands()) 2180 Ops.push_back(getAnyExtendExpr(Op, Ty)); 2181 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); 2182 } 2183 2184 // If the expression is obviously signed, use the sext cast value. 2185 if (isa<SCEVSMaxExpr>(Op)) 2186 return SExt; 2187 2188 // Absent any other information, use the zext cast value. 2189 return ZExt; 2190 } 2191 2192 /// Process the given Ops list, which is a list of operands to be added under 2193 /// the given scale, update the given map. This is a helper function for 2194 /// getAddRecExpr. As an example of what it does, given a sequence of operands 2195 /// that would form an add expression like this: 2196 /// 2197 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r) 2198 /// 2199 /// where A and B are constants, update the map with these values: 2200 /// 2201 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) 2202 /// 2203 /// and add 13 + A*B*29 to AccumulatedConstant. 2204 /// This will allow getAddRecExpr to produce this: 2205 /// 2206 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) 2207 /// 2208 /// This form often exposes folding opportunities that are hidden in 2209 /// the original operand list. 2210 /// 2211 /// Return true iff it appears that any interesting folding opportunities 2212 /// may be exposed. This helps getAddRecExpr short-circuit extra work in 2213 /// the common case where no interesting opportunities are present, and 2214 /// is also used as a check to avoid infinite recursion. 2215 static bool 2216 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, 2217 SmallVectorImpl<const SCEV *> &NewOps, 2218 APInt &AccumulatedConstant, 2219 const SCEV *const *Ops, size_t NumOperands, 2220 const APInt &Scale, 2221 ScalarEvolution &SE) { 2222 bool Interesting = false; 2223 2224 // Iterate over the add operands. They are sorted, with constants first. 2225 unsigned i = 0; 2226 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2227 ++i; 2228 // Pull a buried constant out to the outside. 2229 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) 2230 Interesting = true; 2231 AccumulatedConstant += Scale * C->getAPInt(); 2232 } 2233 2234 // Next comes everything else. We're especially interested in multiplies 2235 // here, but they're in the middle, so just visit the rest with one loop. 2236 for (; i != NumOperands; ++i) { 2237 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); 2238 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { 2239 APInt NewScale = 2240 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); 2241 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { 2242 // A multiplication of a constant with another add; recurse. 2243 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); 2244 Interesting |= 2245 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2246 Add->op_begin(), Add->getNumOperands(), 2247 NewScale, SE); 2248 } else { 2249 // A multiplication of a constant with some other value. Update 2250 // the map. 2251 SmallVector<const SCEV *, 4> MulOps(drop_begin(Mul->operands())); 2252 const SCEV *Key = SE.getMulExpr(MulOps); 2253 auto Pair = M.insert({Key, NewScale}); 2254 if (Pair.second) { 2255 NewOps.push_back(Pair.first->first); 2256 } else { 2257 Pair.first->second += NewScale; 2258 // The map already had an entry for this value, which may indicate 2259 // a folding opportunity. 2260 Interesting = true; 2261 } 2262 } 2263 } else { 2264 // An ordinary operand. Update the map. 2265 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = 2266 M.insert({Ops[i], Scale}); 2267 if (Pair.second) { 2268 NewOps.push_back(Pair.first->first); 2269 } else { 2270 Pair.first->second += Scale; 2271 // The map already had an entry for this value, which may indicate 2272 // a folding opportunity. 2273 Interesting = true; 2274 } 2275 } 2276 } 2277 2278 return Interesting; 2279 } 2280 2281 bool ScalarEvolution::willNotOverflow(Instruction::BinaryOps BinOp, bool Signed, 2282 const SCEV *LHS, const SCEV *RHS) { 2283 const SCEV *(ScalarEvolution::*Operation)(const SCEV *, const SCEV *, 2284 SCEV::NoWrapFlags, unsigned); 2285 switch (BinOp) { 2286 default: 2287 llvm_unreachable("Unsupported binary op"); 2288 case Instruction::Add: 2289 Operation = &ScalarEvolution::getAddExpr; 2290 break; 2291 case Instruction::Sub: 2292 Operation = &ScalarEvolution::getMinusSCEV; 2293 break; 2294 case Instruction::Mul: 2295 Operation = &ScalarEvolution::getMulExpr; 2296 break; 2297 } 2298 2299 const SCEV *(ScalarEvolution::*Extension)(const SCEV *, Type *, unsigned) = 2300 Signed ? &ScalarEvolution::getSignExtendExpr 2301 : &ScalarEvolution::getZeroExtendExpr; 2302 2303 // Check ext(LHS op RHS) == ext(LHS) op ext(RHS) 2304 auto *NarrowTy = cast<IntegerType>(LHS->getType()); 2305 auto *WideTy = 2306 IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2); 2307 2308 const SCEV *A = (this->*Extension)( 2309 (this->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0), WideTy, 0); 2310 const SCEV *B = (this->*Operation)((this->*Extension)(LHS, WideTy, 0), 2311 (this->*Extension)(RHS, WideTy, 0), 2312 SCEV::FlagAnyWrap, 0); 2313 return A == B; 2314 } 2315 2316 std::pair<SCEV::NoWrapFlags, bool /*Deduced*/> 2317 ScalarEvolution::getStrengthenedNoWrapFlagsFromBinOp( 2318 const OverflowingBinaryOperator *OBO) { 2319 SCEV::NoWrapFlags Flags = SCEV::NoWrapFlags::FlagAnyWrap; 2320 2321 if (OBO->hasNoUnsignedWrap()) 2322 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2323 if (OBO->hasNoSignedWrap()) 2324 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2325 2326 bool Deduced = false; 2327 2328 if (OBO->hasNoUnsignedWrap() && OBO->hasNoSignedWrap()) 2329 return {Flags, Deduced}; 2330 2331 if (OBO->getOpcode() != Instruction::Add && 2332 OBO->getOpcode() != Instruction::Sub && 2333 OBO->getOpcode() != Instruction::Mul) 2334 return {Flags, Deduced}; 2335 2336 const SCEV *LHS = getSCEV(OBO->getOperand(0)); 2337 const SCEV *RHS = getSCEV(OBO->getOperand(1)); 2338 2339 if (!OBO->hasNoUnsignedWrap() && 2340 willNotOverflow((Instruction::BinaryOps)OBO->getOpcode(), 2341 /* Signed */ false, LHS, RHS)) { 2342 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2343 Deduced = true; 2344 } 2345 2346 if (!OBO->hasNoSignedWrap() && 2347 willNotOverflow((Instruction::BinaryOps)OBO->getOpcode(), 2348 /* Signed */ true, LHS, RHS)) { 2349 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2350 Deduced = true; 2351 } 2352 2353 return {Flags, Deduced}; 2354 } 2355 2356 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and 2357 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of 2358 // can't-overflow flags for the operation if possible. 2359 static SCEV::NoWrapFlags 2360 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, 2361 const ArrayRef<const SCEV *> Ops, 2362 SCEV::NoWrapFlags Flags) { 2363 using namespace std::placeholders; 2364 2365 using OBO = OverflowingBinaryOperator; 2366 2367 bool CanAnalyze = 2368 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; 2369 (void)CanAnalyze; 2370 assert(CanAnalyze && "don't call from other places!"); 2371 2372 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 2373 SCEV::NoWrapFlags SignOrUnsignWrap = 2374 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2375 2376 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 2377 auto IsKnownNonNegative = [&](const SCEV *S) { 2378 return SE->isKnownNonNegative(S); 2379 }; 2380 2381 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) 2382 Flags = 2383 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); 2384 2385 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2386 2387 if (SignOrUnsignWrap != SignOrUnsignMask && 2388 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 && 2389 isa<SCEVConstant>(Ops[0])) { 2390 2391 auto Opcode = [&] { 2392 switch (Type) { 2393 case scAddExpr: 2394 return Instruction::Add; 2395 case scMulExpr: 2396 return Instruction::Mul; 2397 default: 2398 llvm_unreachable("Unexpected SCEV op."); 2399 } 2400 }(); 2401 2402 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); 2403 2404 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow. 2405 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { 2406 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2407 Opcode, C, OBO::NoSignedWrap); 2408 if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) 2409 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2410 } 2411 2412 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow. 2413 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { 2414 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2415 Opcode, C, OBO::NoUnsignedWrap); 2416 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) 2417 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2418 } 2419 } 2420 2421 // <0,+,nonnegative><nw> is also nuw 2422 // TODO: Add corresponding nsw case 2423 if (Type == scAddRecExpr && ScalarEvolution::hasFlags(Flags, SCEV::FlagNW) && 2424 !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) && Ops.size() == 2 && 2425 Ops[0]->isZero() && IsKnownNonNegative(Ops[1])) 2426 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2427 2428 // both (udiv X, Y) * Y and Y * (udiv X, Y) are always NUW 2429 if (Type == scMulExpr && !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) && 2430 Ops.size() == 2) { 2431 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[0])) 2432 if (UDiv->getOperand(1) == Ops[1]) 2433 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2434 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[1])) 2435 if (UDiv->getOperand(1) == Ops[0]) 2436 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2437 } 2438 2439 return Flags; 2440 } 2441 2442 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) { 2443 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader()); 2444 } 2445 2446 /// Get a canonical add expression, or something simpler if possible. 2447 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2448 SCEV::NoWrapFlags OrigFlags, 2449 unsigned Depth) { 2450 assert(!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && 2451 "only nuw or nsw allowed"); 2452 assert(!Ops.empty() && "Cannot get empty add!"); 2453 if (Ops.size() == 1) return Ops[0]; 2454 #ifndef NDEBUG 2455 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2456 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2457 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2458 "SCEVAddExpr operand types don't match!"); 2459 unsigned NumPtrs = count_if( 2460 Ops, [](const SCEV *Op) { return Op->getType()->isPointerTy(); }); 2461 assert(NumPtrs <= 1 && "add has at most one pointer operand"); 2462 #endif 2463 2464 // Sort by complexity, this groups all similar expression types together. 2465 GroupByComplexity(Ops, &LI, DT); 2466 2467 // If there are any constants, fold them together. 2468 unsigned Idx = 0; 2469 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2470 ++Idx; 2471 assert(Idx < Ops.size()); 2472 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2473 // We found two constants, fold them together! 2474 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); 2475 if (Ops.size() == 2) return Ops[0]; 2476 Ops.erase(Ops.begin()+1); // Erase the folded element 2477 LHSC = cast<SCEVConstant>(Ops[0]); 2478 } 2479 2480 // If we are left with a constant zero being added, strip it off. 2481 if (LHSC->getValue()->isZero()) { 2482 Ops.erase(Ops.begin()); 2483 --Idx; 2484 } 2485 2486 if (Ops.size() == 1) return Ops[0]; 2487 } 2488 2489 // Delay expensive flag strengthening until necessary. 2490 auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) { 2491 return StrengthenNoWrapFlags(this, scAddExpr, Ops, OrigFlags); 2492 }; 2493 2494 // Limit recursion calls depth. 2495 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 2496 return getOrCreateAddExpr(Ops, ComputeFlags(Ops)); 2497 2498 if (SCEV *S = findExistingSCEVInCache(scAddExpr, Ops)) { 2499 // Don't strengthen flags if we have no new information. 2500 SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S); 2501 if (Add->getNoWrapFlags(OrigFlags) != OrigFlags) 2502 Add->setNoWrapFlags(ComputeFlags(Ops)); 2503 return S; 2504 } 2505 2506 // Okay, check to see if the same value occurs in the operand list more than 2507 // once. If so, merge them together into an multiply expression. Since we 2508 // sorted the list, these values are required to be adjacent. 2509 Type *Ty = Ops[0]->getType(); 2510 bool FoundMatch = false; 2511 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 2512 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 2513 // Scan ahead to count how many equal operands there are. 2514 unsigned Count = 2; 2515 while (i+Count != e && Ops[i+Count] == Ops[i]) 2516 ++Count; 2517 // Merge the values into a multiply. 2518 const SCEV *Scale = getConstant(Ty, Count); 2519 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1); 2520 if (Ops.size() == Count) 2521 return Mul; 2522 Ops[i] = Mul; 2523 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 2524 --i; e -= Count - 1; 2525 FoundMatch = true; 2526 } 2527 if (FoundMatch) 2528 return getAddExpr(Ops, OrigFlags, Depth + 1); 2529 2530 // Check for truncates. If all the operands are truncated from the same 2531 // type, see if factoring out the truncate would permit the result to be 2532 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y) 2533 // if the contents of the resulting outer trunc fold to something simple. 2534 auto FindTruncSrcType = [&]() -> Type * { 2535 // We're ultimately looking to fold an addrec of truncs and muls of only 2536 // constants and truncs, so if we find any other types of SCEV 2537 // as operands of the addrec then we bail and return nullptr here. 2538 // Otherwise, we return the type of the operand of a trunc that we find. 2539 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx])) 2540 return T->getOperand()->getType(); 2541 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2542 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1); 2543 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp)) 2544 return T->getOperand()->getType(); 2545 } 2546 return nullptr; 2547 }; 2548 if (auto *SrcType = FindTruncSrcType()) { 2549 SmallVector<const SCEV *, 8> LargeOps; 2550 bool Ok = true; 2551 // Check all the operands to see if they can be represented in the 2552 // source type of the truncate. 2553 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 2554 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 2555 if (T->getOperand()->getType() != SrcType) { 2556 Ok = false; 2557 break; 2558 } 2559 LargeOps.push_back(T->getOperand()); 2560 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2561 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 2562 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 2563 SmallVector<const SCEV *, 8> LargeMulOps; 2564 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 2565 if (const SCEVTruncateExpr *T = 2566 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 2567 if (T->getOperand()->getType() != SrcType) { 2568 Ok = false; 2569 break; 2570 } 2571 LargeMulOps.push_back(T->getOperand()); 2572 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { 2573 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 2574 } else { 2575 Ok = false; 2576 break; 2577 } 2578 } 2579 if (Ok) 2580 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1)); 2581 } else { 2582 Ok = false; 2583 break; 2584 } 2585 } 2586 if (Ok) { 2587 // Evaluate the expression in the larger type. 2588 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1); 2589 // If it folds to something simple, use it. Otherwise, don't. 2590 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 2591 return getTruncateExpr(Fold, Ty); 2592 } 2593 } 2594 2595 if (Ops.size() == 2) { 2596 // Check if we have an expression of the form ((X + C1) - C2), where C1 and 2597 // C2 can be folded in a way that allows retaining wrapping flags of (X + 2598 // C1). 2599 const SCEV *A = Ops[0]; 2600 const SCEV *B = Ops[1]; 2601 auto *AddExpr = dyn_cast<SCEVAddExpr>(B); 2602 auto *C = dyn_cast<SCEVConstant>(A); 2603 if (AddExpr && C && isa<SCEVConstant>(AddExpr->getOperand(0))) { 2604 auto C1 = cast<SCEVConstant>(AddExpr->getOperand(0))->getAPInt(); 2605 auto C2 = C->getAPInt(); 2606 SCEV::NoWrapFlags PreservedFlags = SCEV::FlagAnyWrap; 2607 2608 APInt ConstAdd = C1 + C2; 2609 auto AddFlags = AddExpr->getNoWrapFlags(); 2610 // Adding a smaller constant is NUW if the original AddExpr was NUW. 2611 if (ScalarEvolution::hasFlags(AddFlags, SCEV::FlagNUW) && 2612 ConstAdd.ule(C1)) { 2613 PreservedFlags = 2614 ScalarEvolution::setFlags(PreservedFlags, SCEV::FlagNUW); 2615 } 2616 2617 // Adding a constant with the same sign and small magnitude is NSW, if the 2618 // original AddExpr was NSW. 2619 if (ScalarEvolution::hasFlags(AddFlags, SCEV::FlagNSW) && 2620 C1.isSignBitSet() == ConstAdd.isSignBitSet() && 2621 ConstAdd.abs().ule(C1.abs())) { 2622 PreservedFlags = 2623 ScalarEvolution::setFlags(PreservedFlags, SCEV::FlagNSW); 2624 } 2625 2626 if (PreservedFlags != SCEV::FlagAnyWrap) { 2627 SmallVector<const SCEV *, 4> NewOps(AddExpr->operands()); 2628 NewOps[0] = getConstant(ConstAdd); 2629 return getAddExpr(NewOps, PreservedFlags); 2630 } 2631 } 2632 } 2633 2634 // Canonicalize (-1 * urem X, Y) + X --> (Y * X/Y) 2635 if (Ops.size() == 2) { 2636 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[0]); 2637 if (Mul && Mul->getNumOperands() == 2 && 2638 Mul->getOperand(0)->isAllOnesValue()) { 2639 const SCEV *X; 2640 const SCEV *Y; 2641 if (matchURem(Mul->getOperand(1), X, Y) && X == Ops[1]) { 2642 return getMulExpr(Y, getUDivExpr(X, Y)); 2643 } 2644 } 2645 } 2646 2647 // Skip past any other cast SCEVs. 2648 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 2649 ++Idx; 2650 2651 // If there are add operands they would be next. 2652 if (Idx < Ops.size()) { 2653 bool DeletedAdd = false; 2654 // If the original flags and all inlined SCEVAddExprs are NUW, use the 2655 // common NUW flag for expression after inlining. Other flags cannot be 2656 // preserved, because they may depend on the original order of operations. 2657 SCEV::NoWrapFlags CommonFlags = maskFlags(OrigFlags, SCEV::FlagNUW); 2658 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2659 if (Ops.size() > AddOpsInlineThreshold || 2660 Add->getNumOperands() > AddOpsInlineThreshold) 2661 break; 2662 // If we have an add, expand the add operands onto the end of the operands 2663 // list. 2664 Ops.erase(Ops.begin()+Idx); 2665 Ops.append(Add->op_begin(), Add->op_end()); 2666 DeletedAdd = true; 2667 CommonFlags = maskFlags(CommonFlags, Add->getNoWrapFlags()); 2668 } 2669 2670 // If we deleted at least one add, we added operands to the end of the list, 2671 // and they are not necessarily sorted. Recurse to resort and resimplify 2672 // any operands we just acquired. 2673 if (DeletedAdd) 2674 return getAddExpr(Ops, CommonFlags, Depth + 1); 2675 } 2676 2677 // Skip over the add expression until we get to a multiply. 2678 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2679 ++Idx; 2680 2681 // Check to see if there are any folding opportunities present with 2682 // operands multiplied by constant values. 2683 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2684 uint64_t BitWidth = getTypeSizeInBits(Ty); 2685 DenseMap<const SCEV *, APInt> M; 2686 SmallVector<const SCEV *, 8> NewOps; 2687 APInt AccumulatedConstant(BitWidth, 0); 2688 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2689 Ops.data(), Ops.size(), 2690 APInt(BitWidth, 1), *this)) { 2691 struct APIntCompare { 2692 bool operator()(const APInt &LHS, const APInt &RHS) const { 2693 return LHS.ult(RHS); 2694 } 2695 }; 2696 2697 // Some interesting folding opportunity is present, so its worthwhile to 2698 // re-generate the operands list. Group the operands by constant scale, 2699 // to avoid multiplying by the same constant scale multiple times. 2700 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2701 for (const SCEV *NewOp : NewOps) 2702 MulOpLists[M.find(NewOp)->second].push_back(NewOp); 2703 // Re-generate the operands list. 2704 Ops.clear(); 2705 if (AccumulatedConstant != 0) 2706 Ops.push_back(getConstant(AccumulatedConstant)); 2707 for (auto &MulOp : MulOpLists) { 2708 if (MulOp.first == 1) { 2709 Ops.push_back(getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1)); 2710 } else if (MulOp.first != 0) { 2711 Ops.push_back(getMulExpr( 2712 getConstant(MulOp.first), 2713 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1), 2714 SCEV::FlagAnyWrap, Depth + 1)); 2715 } 2716 } 2717 if (Ops.empty()) 2718 return getZero(Ty); 2719 if (Ops.size() == 1) 2720 return Ops[0]; 2721 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2722 } 2723 } 2724 2725 // If we are adding something to a multiply expression, make sure the 2726 // something is not already an operand of the multiply. If so, merge it into 2727 // the multiply. 2728 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2729 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2730 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2731 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2732 if (isa<SCEVConstant>(MulOpSCEV)) 2733 continue; 2734 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2735 if (MulOpSCEV == Ops[AddOp]) { 2736 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2737 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2738 if (Mul->getNumOperands() != 2) { 2739 // If the multiply has more than two operands, we must get the 2740 // Y*Z term. 2741 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2742 Mul->op_begin()+MulOp); 2743 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2744 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2745 } 2746 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul}; 2747 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2748 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV, 2749 SCEV::FlagAnyWrap, Depth + 1); 2750 if (Ops.size() == 2) return OuterMul; 2751 if (AddOp < Idx) { 2752 Ops.erase(Ops.begin()+AddOp); 2753 Ops.erase(Ops.begin()+Idx-1); 2754 } else { 2755 Ops.erase(Ops.begin()+Idx); 2756 Ops.erase(Ops.begin()+AddOp-1); 2757 } 2758 Ops.push_back(OuterMul); 2759 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2760 } 2761 2762 // Check this multiply against other multiplies being added together. 2763 for (unsigned OtherMulIdx = Idx+1; 2764 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2765 ++OtherMulIdx) { 2766 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2767 // If MulOp occurs in OtherMul, we can fold the two multiplies 2768 // together. 2769 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2770 OMulOp != e; ++OMulOp) 2771 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2772 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2773 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2774 if (Mul->getNumOperands() != 2) { 2775 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2776 Mul->op_begin()+MulOp); 2777 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2778 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2779 } 2780 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2781 if (OtherMul->getNumOperands() != 2) { 2782 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2783 OtherMul->op_begin()+OMulOp); 2784 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2785 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2786 } 2787 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2}; 2788 const SCEV *InnerMulSum = 2789 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2790 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum, 2791 SCEV::FlagAnyWrap, Depth + 1); 2792 if (Ops.size() == 2) return OuterMul; 2793 Ops.erase(Ops.begin()+Idx); 2794 Ops.erase(Ops.begin()+OtherMulIdx-1); 2795 Ops.push_back(OuterMul); 2796 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2797 } 2798 } 2799 } 2800 } 2801 2802 // If there are any add recurrences in the operands list, see if any other 2803 // added values are loop invariant. If so, we can fold them into the 2804 // recurrence. 2805 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2806 ++Idx; 2807 2808 // Scan over all recurrences, trying to fold loop invariants into them. 2809 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2810 // Scan all of the other operands to this add and add them to the vector if 2811 // they are loop invariant w.r.t. the recurrence. 2812 SmallVector<const SCEV *, 8> LIOps; 2813 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2814 const Loop *AddRecLoop = AddRec->getLoop(); 2815 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2816 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2817 LIOps.push_back(Ops[i]); 2818 Ops.erase(Ops.begin()+i); 2819 --i; --e; 2820 } 2821 2822 // If we found some loop invariants, fold them into the recurrence. 2823 if (!LIOps.empty()) { 2824 // Compute nowrap flags for the addition of the loop-invariant ops and 2825 // the addrec. Temporarily push it as an operand for that purpose. These 2826 // flags are valid in the scope of the addrec only. 2827 LIOps.push_back(AddRec); 2828 SCEV::NoWrapFlags Flags = ComputeFlags(LIOps); 2829 LIOps.pop_back(); 2830 2831 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2832 LIOps.push_back(AddRec->getStart()); 2833 2834 SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands()); 2835 2836 // It is not in general safe to propagate flags valid on an add within 2837 // the addrec scope to one outside it. We must prove that the inner 2838 // scope is guaranteed to execute if the outer one does to be able to 2839 // safely propagate. We know the program is undefined if poison is 2840 // produced on the inner scoped addrec. We also know that *for this use* 2841 // the outer scoped add can't overflow (because of the flags we just 2842 // computed for the inner scoped add) without the program being undefined. 2843 // Proving that entry to the outer scope neccesitates entry to the inner 2844 // scope, thus proves the program undefined if the flags would be violated 2845 // in the outer scope. 2846 SCEV::NoWrapFlags AddFlags = Flags; 2847 if (AddFlags != SCEV::FlagAnyWrap) { 2848 auto *DefI = getDefiningScopeBound(LIOps); 2849 auto *ReachI = &*AddRecLoop->getHeader()->begin(); 2850 if (!isGuaranteedToTransferExecutionTo(DefI, ReachI)) 2851 AddFlags = SCEV::FlagAnyWrap; 2852 } 2853 AddRecOps[0] = getAddExpr(LIOps, AddFlags, Depth + 1); 2854 2855 // Build the new addrec. Propagate the NUW and NSW flags if both the 2856 // outer add and the inner addrec are guaranteed to have no overflow. 2857 // Always propagate NW. 2858 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2859 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2860 2861 // If all of the other operands were loop invariant, we are done. 2862 if (Ops.size() == 1) return NewRec; 2863 2864 // Otherwise, add the folded AddRec by the non-invariant parts. 2865 for (unsigned i = 0;; ++i) 2866 if (Ops[i] == AddRec) { 2867 Ops[i] = NewRec; 2868 break; 2869 } 2870 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2871 } 2872 2873 // Okay, if there weren't any loop invariants to be folded, check to see if 2874 // there are multiple AddRec's with the same loop induction variable being 2875 // added together. If so, we can fold them. 2876 for (unsigned OtherIdx = Idx+1; 2877 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2878 ++OtherIdx) { 2879 // We expect the AddRecExpr's to be sorted in reverse dominance order, 2880 // so that the 1st found AddRecExpr is dominated by all others. 2881 assert(DT.dominates( 2882 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), 2883 AddRec->getLoop()->getHeader()) && 2884 "AddRecExprs are not sorted in reverse dominance order?"); 2885 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2886 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2887 SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands()); 2888 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2889 ++OtherIdx) { 2890 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2891 if (OtherAddRec->getLoop() == AddRecLoop) { 2892 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2893 i != e; ++i) { 2894 if (i >= AddRecOps.size()) { 2895 AddRecOps.append(OtherAddRec->op_begin()+i, 2896 OtherAddRec->op_end()); 2897 break; 2898 } 2899 SmallVector<const SCEV *, 2> TwoOps = { 2900 AddRecOps[i], OtherAddRec->getOperand(i)}; 2901 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2902 } 2903 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2904 } 2905 } 2906 // Step size has changed, so we cannot guarantee no self-wraparound. 2907 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2908 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2909 } 2910 } 2911 2912 // Otherwise couldn't fold anything into this recurrence. Move onto the 2913 // next one. 2914 } 2915 2916 // Okay, it looks like we really DO need an add expr. Check to see if we 2917 // already have one, otherwise create a new one. 2918 return getOrCreateAddExpr(Ops, ComputeFlags(Ops)); 2919 } 2920 2921 const SCEV * 2922 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops, 2923 SCEV::NoWrapFlags Flags) { 2924 FoldingSetNodeID ID; 2925 ID.AddInteger(scAddExpr); 2926 for (const SCEV *Op : Ops) 2927 ID.AddPointer(Op); 2928 void *IP = nullptr; 2929 SCEVAddExpr *S = 2930 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2931 if (!S) { 2932 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2933 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2934 S = new (SCEVAllocator) 2935 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size()); 2936 UniqueSCEVs.InsertNode(S, IP); 2937 registerUser(S, Ops); 2938 } 2939 S->setNoWrapFlags(Flags); 2940 return S; 2941 } 2942 2943 const SCEV * 2944 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops, 2945 const Loop *L, SCEV::NoWrapFlags Flags) { 2946 FoldingSetNodeID ID; 2947 ID.AddInteger(scAddRecExpr); 2948 for (const SCEV *Op : Ops) 2949 ID.AddPointer(Op); 2950 ID.AddPointer(L); 2951 void *IP = nullptr; 2952 SCEVAddRecExpr *S = 2953 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2954 if (!S) { 2955 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2956 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2957 S = new (SCEVAllocator) 2958 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L); 2959 UniqueSCEVs.InsertNode(S, IP); 2960 LoopUsers[L].push_back(S); 2961 registerUser(S, Ops); 2962 } 2963 setNoWrapFlags(S, Flags); 2964 return S; 2965 } 2966 2967 const SCEV * 2968 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops, 2969 SCEV::NoWrapFlags Flags) { 2970 FoldingSetNodeID ID; 2971 ID.AddInteger(scMulExpr); 2972 for (const SCEV *Op : Ops) 2973 ID.AddPointer(Op); 2974 void *IP = nullptr; 2975 SCEVMulExpr *S = 2976 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2977 if (!S) { 2978 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2979 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2980 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2981 O, Ops.size()); 2982 UniqueSCEVs.InsertNode(S, IP); 2983 registerUser(S, Ops); 2984 } 2985 S->setNoWrapFlags(Flags); 2986 return S; 2987 } 2988 2989 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2990 uint64_t k = i*j; 2991 if (j > 1 && k / j != i) Overflow = true; 2992 return k; 2993 } 2994 2995 /// Compute the result of "n choose k", the binomial coefficient. If an 2996 /// intermediate computation overflows, Overflow will be set and the return will 2997 /// be garbage. Overflow is not cleared on absence of overflow. 2998 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 2999 // We use the multiplicative formula: 3000 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 3001 // At each iteration, we take the n-th term of the numeral and divide by the 3002 // (k-n)th term of the denominator. This division will always produce an 3003 // integral result, and helps reduce the chance of overflow in the 3004 // intermediate computations. However, we can still overflow even when the 3005 // final result would fit. 3006 3007 if (n == 0 || n == k) return 1; 3008 if (k > n) return 0; 3009 3010 if (k > n/2) 3011 k = n-k; 3012 3013 uint64_t r = 1; 3014 for (uint64_t i = 1; i <= k; ++i) { 3015 r = umul_ov(r, n-(i-1), Overflow); 3016 r /= i; 3017 } 3018 return r; 3019 } 3020 3021 /// Determine if any of the operands in this SCEV are a constant or if 3022 /// any of the add or multiply expressions in this SCEV contain a constant. 3023 static bool containsConstantInAddMulChain(const SCEV *StartExpr) { 3024 struct FindConstantInAddMulChain { 3025 bool FoundConstant = false; 3026 3027 bool follow(const SCEV *S) { 3028 FoundConstant |= isa<SCEVConstant>(S); 3029 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S); 3030 } 3031 3032 bool isDone() const { 3033 return FoundConstant; 3034 } 3035 }; 3036 3037 FindConstantInAddMulChain F; 3038 SCEVTraversal<FindConstantInAddMulChain> ST(F); 3039 ST.visitAll(StartExpr); 3040 return F.FoundConstant; 3041 } 3042 3043 /// Get a canonical multiply expression, or something simpler if possible. 3044 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 3045 SCEV::NoWrapFlags OrigFlags, 3046 unsigned Depth) { 3047 assert(OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) && 3048 "only nuw or nsw allowed"); 3049 assert(!Ops.empty() && "Cannot get empty mul!"); 3050 if (Ops.size() == 1) return Ops[0]; 3051 #ifndef NDEBUG 3052 Type *ETy = Ops[0]->getType(); 3053 assert(!ETy->isPointerTy()); 3054 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3055 assert(Ops[i]->getType() == ETy && 3056 "SCEVMulExpr operand types don't match!"); 3057 #endif 3058 3059 // Sort by complexity, this groups all similar expression types together. 3060 GroupByComplexity(Ops, &LI, DT); 3061 3062 // If there are any constants, fold them together. 3063 unsigned Idx = 0; 3064 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3065 ++Idx; 3066 assert(Idx < Ops.size()); 3067 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3068 // We found two constants, fold them together! 3069 Ops[0] = getConstant(LHSC->getAPInt() * RHSC->getAPInt()); 3070 if (Ops.size() == 2) return Ops[0]; 3071 Ops.erase(Ops.begin()+1); // Erase the folded element 3072 LHSC = cast<SCEVConstant>(Ops[0]); 3073 } 3074 3075 // If we have a multiply of zero, it will always be zero. 3076 if (LHSC->getValue()->isZero()) 3077 return LHSC; 3078 3079 // If we are left with a constant one being multiplied, strip it off. 3080 if (LHSC->getValue()->isOne()) { 3081 Ops.erase(Ops.begin()); 3082 --Idx; 3083 } 3084 3085 if (Ops.size() == 1) 3086 return Ops[0]; 3087 } 3088 3089 // Delay expensive flag strengthening until necessary. 3090 auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) { 3091 return StrengthenNoWrapFlags(this, scMulExpr, Ops, OrigFlags); 3092 }; 3093 3094 // Limit recursion calls depth. 3095 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 3096 return getOrCreateMulExpr(Ops, ComputeFlags(Ops)); 3097 3098 if (SCEV *S = findExistingSCEVInCache(scMulExpr, Ops)) { 3099 // Don't strengthen flags if we have no new information. 3100 SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S); 3101 if (Mul->getNoWrapFlags(OrigFlags) != OrigFlags) 3102 Mul->setNoWrapFlags(ComputeFlags(Ops)); 3103 return S; 3104 } 3105 3106 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3107 if (Ops.size() == 2) { 3108 // C1*(C2+V) -> C1*C2 + C1*V 3109 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 3110 // If any of Add's ops are Adds or Muls with a constant, apply this 3111 // transformation as well. 3112 // 3113 // TODO: There are some cases where this transformation is not 3114 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of 3115 // this transformation should be narrowed down. 3116 if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add)) 3117 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0), 3118 SCEV::FlagAnyWrap, Depth + 1), 3119 getMulExpr(LHSC, Add->getOperand(1), 3120 SCEV::FlagAnyWrap, Depth + 1), 3121 SCEV::FlagAnyWrap, Depth + 1); 3122 3123 if (Ops[0]->isAllOnesValue()) { 3124 // If we have a mul by -1 of an add, try distributing the -1 among the 3125 // add operands. 3126 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 3127 SmallVector<const SCEV *, 4> NewOps; 3128 bool AnyFolded = false; 3129 for (const SCEV *AddOp : Add->operands()) { 3130 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap, 3131 Depth + 1); 3132 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 3133 NewOps.push_back(Mul); 3134 } 3135 if (AnyFolded) 3136 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1); 3137 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 3138 // Negation preserves a recurrence's no self-wrap property. 3139 SmallVector<const SCEV *, 4> Operands; 3140 for (const SCEV *AddRecOp : AddRec->operands()) 3141 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap, 3142 Depth + 1)); 3143 3144 return getAddRecExpr(Operands, AddRec->getLoop(), 3145 AddRec->getNoWrapFlags(SCEV::FlagNW)); 3146 } 3147 } 3148 } 3149 } 3150 3151 // Skip over the add expression until we get to a multiply. 3152 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 3153 ++Idx; 3154 3155 // If there are mul operands inline them all into this expression. 3156 if (Idx < Ops.size()) { 3157 bool DeletedMul = false; 3158 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 3159 if (Ops.size() > MulOpsInlineThreshold) 3160 break; 3161 // If we have an mul, expand the mul operands onto the end of the 3162 // operands list. 3163 Ops.erase(Ops.begin()+Idx); 3164 Ops.append(Mul->op_begin(), Mul->op_end()); 3165 DeletedMul = true; 3166 } 3167 3168 // If we deleted at least one mul, we added operands to the end of the 3169 // list, and they are not necessarily sorted. Recurse to resort and 3170 // resimplify any operands we just acquired. 3171 if (DeletedMul) 3172 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3173 } 3174 3175 // If there are any add recurrences in the operands list, see if any other 3176 // added values are loop invariant. If so, we can fold them into the 3177 // recurrence. 3178 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 3179 ++Idx; 3180 3181 // Scan over all recurrences, trying to fold loop invariants into them. 3182 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 3183 // Scan all of the other operands to this mul and add them to the vector 3184 // if they are loop invariant w.r.t. the recurrence. 3185 SmallVector<const SCEV *, 8> LIOps; 3186 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 3187 const Loop *AddRecLoop = AddRec->getLoop(); 3188 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3189 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 3190 LIOps.push_back(Ops[i]); 3191 Ops.erase(Ops.begin()+i); 3192 --i; --e; 3193 } 3194 3195 // If we found some loop invariants, fold them into the recurrence. 3196 if (!LIOps.empty()) { 3197 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 3198 SmallVector<const SCEV *, 4> NewOps; 3199 NewOps.reserve(AddRec->getNumOperands()); 3200 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1); 3201 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 3202 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i), 3203 SCEV::FlagAnyWrap, Depth + 1)); 3204 3205 // Build the new addrec. Propagate the NUW and NSW flags if both the 3206 // outer mul and the inner addrec are guaranteed to have no overflow. 3207 // 3208 // No self-wrap cannot be guaranteed after changing the step size, but 3209 // will be inferred if either NUW or NSW is true. 3210 SCEV::NoWrapFlags Flags = ComputeFlags({Scale, AddRec}); 3211 const SCEV *NewRec = getAddRecExpr( 3212 NewOps, AddRecLoop, AddRec->getNoWrapFlags(Flags)); 3213 3214 // If all of the other operands were loop invariant, we are done. 3215 if (Ops.size() == 1) return NewRec; 3216 3217 // Otherwise, multiply the folded AddRec by the non-invariant parts. 3218 for (unsigned i = 0;; ++i) 3219 if (Ops[i] == AddRec) { 3220 Ops[i] = NewRec; 3221 break; 3222 } 3223 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3224 } 3225 3226 // Okay, if there weren't any loop invariants to be folded, check to see 3227 // if there are multiple AddRec's with the same loop induction variable 3228 // being multiplied together. If so, we can fold them. 3229 3230 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 3231 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 3232 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 3233 // ]]],+,...up to x=2n}. 3234 // Note that the arguments to choose() are always integers with values 3235 // known at compile time, never SCEV objects. 3236 // 3237 // The implementation avoids pointless extra computations when the two 3238 // addrec's are of different length (mathematically, it's equivalent to 3239 // an infinite stream of zeros on the right). 3240 bool OpsModified = false; 3241 for (unsigned OtherIdx = Idx+1; 3242 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 3243 ++OtherIdx) { 3244 const SCEVAddRecExpr *OtherAddRec = 3245 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 3246 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 3247 continue; 3248 3249 // Limit max number of arguments to avoid creation of unreasonably big 3250 // SCEVAddRecs with very complex operands. 3251 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 > 3252 MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec})) 3253 continue; 3254 3255 bool Overflow = false; 3256 Type *Ty = AddRec->getType(); 3257 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 3258 SmallVector<const SCEV*, 7> AddRecOps; 3259 for (int x = 0, xe = AddRec->getNumOperands() + 3260 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 3261 SmallVector <const SCEV *, 7> SumOps; 3262 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 3263 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 3264 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 3265 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 3266 z < ze && !Overflow; ++z) { 3267 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 3268 uint64_t Coeff; 3269 if (LargerThan64Bits) 3270 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 3271 else 3272 Coeff = Coeff1*Coeff2; 3273 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 3274 const SCEV *Term1 = AddRec->getOperand(y-z); 3275 const SCEV *Term2 = OtherAddRec->getOperand(z); 3276 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2, 3277 SCEV::FlagAnyWrap, Depth + 1)); 3278 } 3279 } 3280 if (SumOps.empty()) 3281 SumOps.push_back(getZero(Ty)); 3282 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1)); 3283 } 3284 if (!Overflow) { 3285 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop, 3286 SCEV::FlagAnyWrap); 3287 if (Ops.size() == 2) return NewAddRec; 3288 Ops[Idx] = NewAddRec; 3289 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 3290 OpsModified = true; 3291 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 3292 if (!AddRec) 3293 break; 3294 } 3295 } 3296 if (OpsModified) 3297 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3298 3299 // Otherwise couldn't fold anything into this recurrence. Move onto the 3300 // next one. 3301 } 3302 3303 // Okay, it looks like we really DO need an mul expr. Check to see if we 3304 // already have one, otherwise create a new one. 3305 return getOrCreateMulExpr(Ops, ComputeFlags(Ops)); 3306 } 3307 3308 /// Represents an unsigned remainder expression based on unsigned division. 3309 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS, 3310 const SCEV *RHS) { 3311 assert(getEffectiveSCEVType(LHS->getType()) == 3312 getEffectiveSCEVType(RHS->getType()) && 3313 "SCEVURemExpr operand types don't match!"); 3314 3315 // Short-circuit easy cases 3316 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3317 // If constant is one, the result is trivial 3318 if (RHSC->getValue()->isOne()) 3319 return getZero(LHS->getType()); // X urem 1 --> 0 3320 3321 // If constant is a power of two, fold into a zext(trunc(LHS)). 3322 if (RHSC->getAPInt().isPowerOf2()) { 3323 Type *FullTy = LHS->getType(); 3324 Type *TruncTy = 3325 IntegerType::get(getContext(), RHSC->getAPInt().logBase2()); 3326 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy); 3327 } 3328 } 3329 3330 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y) 3331 const SCEV *UDiv = getUDivExpr(LHS, RHS); 3332 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW); 3333 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW); 3334 } 3335 3336 /// Get a canonical unsigned division expression, or something simpler if 3337 /// possible. 3338 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 3339 const SCEV *RHS) { 3340 assert(!LHS->getType()->isPointerTy() && 3341 "SCEVUDivExpr operand can't be pointer!"); 3342 assert(LHS->getType() == RHS->getType() && 3343 "SCEVUDivExpr operand types don't match!"); 3344 3345 FoldingSetNodeID ID; 3346 ID.AddInteger(scUDivExpr); 3347 ID.AddPointer(LHS); 3348 ID.AddPointer(RHS); 3349 void *IP = nullptr; 3350 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 3351 return S; 3352 3353 // 0 udiv Y == 0 3354 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) 3355 if (LHSC->getValue()->isZero()) 3356 return LHS; 3357 3358 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3359 if (RHSC->getValue()->isOne()) 3360 return LHS; // X udiv 1 --> x 3361 // If the denominator is zero, the result of the udiv is undefined. Don't 3362 // try to analyze it, because the resolution chosen here may differ from 3363 // the resolution chosen in other parts of the compiler. 3364 if (!RHSC->getValue()->isZero()) { 3365 // Determine if the division can be folded into the operands of 3366 // its operands. 3367 // TODO: Generalize this to non-constants by using known-bits information. 3368 Type *Ty = LHS->getType(); 3369 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 3370 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 3371 // For non-power-of-two values, effectively round the value up to the 3372 // nearest power of two. 3373 if (!RHSC->getAPInt().isPowerOf2()) 3374 ++MaxShiftAmt; 3375 IntegerType *ExtTy = 3376 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 3377 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 3378 if (const SCEVConstant *Step = 3379 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 3380 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 3381 const APInt &StepInt = Step->getAPInt(); 3382 const APInt &DivInt = RHSC->getAPInt(); 3383 if (!StepInt.urem(DivInt) && 3384 getZeroExtendExpr(AR, ExtTy) == 3385 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3386 getZeroExtendExpr(Step, ExtTy), 3387 AR->getLoop(), SCEV::FlagAnyWrap)) { 3388 SmallVector<const SCEV *, 4> Operands; 3389 for (const SCEV *Op : AR->operands()) 3390 Operands.push_back(getUDivExpr(Op, RHS)); 3391 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 3392 } 3393 /// Get a canonical UDivExpr for a recurrence. 3394 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 3395 // We can currently only fold X%N if X is constant. 3396 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 3397 if (StartC && !DivInt.urem(StepInt) && 3398 getZeroExtendExpr(AR, ExtTy) == 3399 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3400 getZeroExtendExpr(Step, ExtTy), 3401 AR->getLoop(), SCEV::FlagAnyWrap)) { 3402 const APInt &StartInt = StartC->getAPInt(); 3403 const APInt &StartRem = StartInt.urem(StepInt); 3404 if (StartRem != 0) { 3405 const SCEV *NewLHS = 3406 getAddRecExpr(getConstant(StartInt - StartRem), Step, 3407 AR->getLoop(), SCEV::FlagNW); 3408 if (LHS != NewLHS) { 3409 LHS = NewLHS; 3410 3411 // Reset the ID to include the new LHS, and check if it is 3412 // already cached. 3413 ID.clear(); 3414 ID.AddInteger(scUDivExpr); 3415 ID.AddPointer(LHS); 3416 ID.AddPointer(RHS); 3417 IP = nullptr; 3418 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 3419 return S; 3420 } 3421 } 3422 } 3423 } 3424 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 3425 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 3426 SmallVector<const SCEV *, 4> Operands; 3427 for (const SCEV *Op : M->operands()) 3428 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3429 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 3430 // Find an operand that's safely divisible. 3431 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 3432 const SCEV *Op = M->getOperand(i); 3433 const SCEV *Div = getUDivExpr(Op, RHSC); 3434 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 3435 Operands = SmallVector<const SCEV *, 4>(M->operands()); 3436 Operands[i] = Div; 3437 return getMulExpr(Operands); 3438 } 3439 } 3440 } 3441 3442 // (A/B)/C --> A/(B*C) if safe and B*C can be folded. 3443 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) { 3444 if (auto *DivisorConstant = 3445 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) { 3446 bool Overflow = false; 3447 APInt NewRHS = 3448 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow); 3449 if (Overflow) { 3450 return getConstant(RHSC->getType(), 0, false); 3451 } 3452 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS)); 3453 } 3454 } 3455 3456 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 3457 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 3458 SmallVector<const SCEV *, 4> Operands; 3459 for (const SCEV *Op : A->operands()) 3460 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3461 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 3462 Operands.clear(); 3463 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 3464 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 3465 if (isa<SCEVUDivExpr>(Op) || 3466 getMulExpr(Op, RHS) != A->getOperand(i)) 3467 break; 3468 Operands.push_back(Op); 3469 } 3470 if (Operands.size() == A->getNumOperands()) 3471 return getAddExpr(Operands); 3472 } 3473 } 3474 3475 // Fold if both operands are constant. 3476 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 3477 Constant *LHSCV = LHSC->getValue(); 3478 Constant *RHSCV = RHSC->getValue(); 3479 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 3480 RHSCV))); 3481 } 3482 } 3483 } 3484 3485 // The Insertion Point (IP) might be invalid by now (due to UniqueSCEVs 3486 // changes). Make sure we get a new one. 3487 IP = nullptr; 3488 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3489 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 3490 LHS, RHS); 3491 UniqueSCEVs.InsertNode(S, IP); 3492 registerUser(S, {LHS, RHS}); 3493 return S; 3494 } 3495 3496 APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 3497 APInt A = C1->getAPInt().abs(); 3498 APInt B = C2->getAPInt().abs(); 3499 uint32_t ABW = A.getBitWidth(); 3500 uint32_t BBW = B.getBitWidth(); 3501 3502 if (ABW > BBW) 3503 B = B.zext(ABW); 3504 else if (ABW < BBW) 3505 A = A.zext(BBW); 3506 3507 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B)); 3508 } 3509 3510 /// Get a canonical unsigned division expression, or something simpler if 3511 /// possible. There is no representation for an exact udiv in SCEV IR, but we 3512 /// can attempt to remove factors from the LHS and RHS. We can't do this when 3513 /// it's not exact because the udiv may be clearing bits. 3514 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 3515 const SCEV *RHS) { 3516 // TODO: we could try to find factors in all sorts of things, but for now we 3517 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 3518 // end of this file for inspiration. 3519 3520 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 3521 if (!Mul || !Mul->hasNoUnsignedWrap()) 3522 return getUDivExpr(LHS, RHS); 3523 3524 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 3525 // If the mulexpr multiplies by a constant, then that constant must be the 3526 // first element of the mulexpr. 3527 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 3528 if (LHSCst == RHSCst) { 3529 SmallVector<const SCEV *, 2> Operands(drop_begin(Mul->operands())); 3530 return getMulExpr(Operands); 3531 } 3532 3533 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 3534 // that there's a factor provided by one of the other terms. We need to 3535 // check. 3536 APInt Factor = gcd(LHSCst, RHSCst); 3537 if (!Factor.isIntN(1)) { 3538 LHSCst = 3539 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 3540 RHSCst = 3541 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 3542 SmallVector<const SCEV *, 2> Operands; 3543 Operands.push_back(LHSCst); 3544 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3545 LHS = getMulExpr(Operands); 3546 RHS = RHSCst; 3547 Mul = dyn_cast<SCEVMulExpr>(LHS); 3548 if (!Mul) 3549 return getUDivExactExpr(LHS, RHS); 3550 } 3551 } 3552 } 3553 3554 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 3555 if (Mul->getOperand(i) == RHS) { 3556 SmallVector<const SCEV *, 2> Operands; 3557 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 3558 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 3559 return getMulExpr(Operands); 3560 } 3561 } 3562 3563 return getUDivExpr(LHS, RHS); 3564 } 3565 3566 /// Get an add recurrence expression for the specified loop. Simplify the 3567 /// expression as much as possible. 3568 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 3569 const Loop *L, 3570 SCEV::NoWrapFlags Flags) { 3571 SmallVector<const SCEV *, 4> Operands; 3572 Operands.push_back(Start); 3573 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 3574 if (StepChrec->getLoop() == L) { 3575 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 3576 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 3577 } 3578 3579 Operands.push_back(Step); 3580 return getAddRecExpr(Operands, L, Flags); 3581 } 3582 3583 /// Get an add recurrence expression for the specified loop. Simplify the 3584 /// expression as much as possible. 3585 const SCEV * 3586 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 3587 const Loop *L, SCEV::NoWrapFlags Flags) { 3588 if (Operands.size() == 1) return Operands[0]; 3589 #ifndef NDEBUG 3590 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 3591 for (unsigned i = 1, e = Operands.size(); i != e; ++i) { 3592 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 3593 "SCEVAddRecExpr operand types don't match!"); 3594 assert(!Operands[i]->getType()->isPointerTy() && "Step must be integer"); 3595 } 3596 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3597 assert(isLoopInvariant(Operands[i], L) && 3598 "SCEVAddRecExpr operand is not loop-invariant!"); 3599 #endif 3600 3601 if (Operands.back()->isZero()) { 3602 Operands.pop_back(); 3603 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 3604 } 3605 3606 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and 3607 // use that information to infer NUW and NSW flags. However, computing a 3608 // BE count requires calling getAddRecExpr, so we may not yet have a 3609 // meaningful BE count at this point (and if we don't, we'd be stuck 3610 // with a SCEVCouldNotCompute as the cached BE count). 3611 3612 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 3613 3614 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 3615 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 3616 const Loop *NestedLoop = NestedAR->getLoop(); 3617 if (L->contains(NestedLoop) 3618 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 3619 : (!NestedLoop->contains(L) && 3620 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 3621 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->operands()); 3622 Operands[0] = NestedAR->getStart(); 3623 // AddRecs require their operands be loop-invariant with respect to their 3624 // loops. Don't perform this transformation if it would break this 3625 // requirement. 3626 bool AllInvariant = all_of( 3627 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 3628 3629 if (AllInvariant) { 3630 // Create a recurrence for the outer loop with the same step size. 3631 // 3632 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 3633 // inner recurrence has the same property. 3634 SCEV::NoWrapFlags OuterFlags = 3635 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 3636 3637 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 3638 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 3639 return isLoopInvariant(Op, NestedLoop); 3640 }); 3641 3642 if (AllInvariant) { 3643 // Ok, both add recurrences are valid after the transformation. 3644 // 3645 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 3646 // the outer recurrence has the same property. 3647 SCEV::NoWrapFlags InnerFlags = 3648 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 3649 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 3650 } 3651 } 3652 // Reset Operands to its original state. 3653 Operands[0] = NestedAR; 3654 } 3655 } 3656 3657 // Okay, it looks like we really DO need an addrec expr. Check to see if we 3658 // already have one, otherwise create a new one. 3659 return getOrCreateAddRecExpr(Operands, L, Flags); 3660 } 3661 3662 const SCEV * 3663 ScalarEvolution::getGEPExpr(GEPOperator *GEP, 3664 const SmallVectorImpl<const SCEV *> &IndexExprs) { 3665 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand()); 3666 // getSCEV(Base)->getType() has the same address space as Base->getType() 3667 // because SCEV::getType() preserves the address space. 3668 Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType()); 3669 const bool AssumeInBoundsFlags = [&]() { 3670 if (!GEP->isInBounds()) 3671 return false; 3672 3673 // We'd like to propagate flags from the IR to the corresponding SCEV nodes, 3674 // but to do that, we have to ensure that said flag is valid in the entire 3675 // defined scope of the SCEV. 3676 auto *GEPI = dyn_cast<Instruction>(GEP); 3677 // TODO: non-instructions have global scope. We might be able to prove 3678 // some global scope cases 3679 return GEPI && isSCEVExprNeverPoison(GEPI); 3680 }(); 3681 3682 SCEV::NoWrapFlags OffsetWrap = 3683 AssumeInBoundsFlags ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3684 3685 Type *CurTy = GEP->getType(); 3686 bool FirstIter = true; 3687 SmallVector<const SCEV *, 4> Offsets; 3688 for (const SCEV *IndexExpr : IndexExprs) { 3689 // Compute the (potentially symbolic) offset in bytes for this index. 3690 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 3691 // For a struct, add the member offset. 3692 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 3693 unsigned FieldNo = Index->getZExtValue(); 3694 const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo); 3695 Offsets.push_back(FieldOffset); 3696 3697 // Update CurTy to the type of the field at Index. 3698 CurTy = STy->getTypeAtIndex(Index); 3699 } else { 3700 // Update CurTy to its element type. 3701 if (FirstIter) { 3702 assert(isa<PointerType>(CurTy) && 3703 "The first index of a GEP indexes a pointer"); 3704 CurTy = GEP->getSourceElementType(); 3705 FirstIter = false; 3706 } else { 3707 CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0); 3708 } 3709 // For an array, add the element offset, explicitly scaled. 3710 const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy); 3711 // Getelementptr indices are signed. 3712 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy); 3713 3714 // Multiply the index by the element size to compute the element offset. 3715 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap); 3716 Offsets.push_back(LocalOffset); 3717 } 3718 } 3719 3720 // Handle degenerate case of GEP without offsets. 3721 if (Offsets.empty()) 3722 return BaseExpr; 3723 3724 // Add the offsets together, assuming nsw if inbounds. 3725 const SCEV *Offset = getAddExpr(Offsets, OffsetWrap); 3726 // Add the base address and the offset. We cannot use the nsw flag, as the 3727 // base address is unsigned. However, if we know that the offset is 3728 // non-negative, we can use nuw. 3729 SCEV::NoWrapFlags BaseWrap = AssumeInBoundsFlags && isKnownNonNegative(Offset) 3730 ? SCEV::FlagNUW : SCEV::FlagAnyWrap; 3731 auto *GEPExpr = getAddExpr(BaseExpr, Offset, BaseWrap); 3732 assert(BaseExpr->getType() == GEPExpr->getType() && 3733 "GEP should not change type mid-flight."); 3734 return GEPExpr; 3735 } 3736 3737 SCEV *ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType, 3738 ArrayRef<const SCEV *> Ops) { 3739 FoldingSetNodeID ID; 3740 ID.AddInteger(SCEVType); 3741 for (const SCEV *Op : Ops) 3742 ID.AddPointer(Op); 3743 void *IP = nullptr; 3744 return UniqueSCEVs.FindNodeOrInsertPos(ID, IP); 3745 } 3746 3747 const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) { 3748 SCEV::NoWrapFlags Flags = IsNSW ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3749 return getSMaxExpr(Op, getNegativeSCEV(Op, Flags)); 3750 } 3751 3752 const SCEV *ScalarEvolution::getMinMaxExpr(SCEVTypes Kind, 3753 SmallVectorImpl<const SCEV *> &Ops) { 3754 assert(SCEVMinMaxExpr::isMinMaxType(Kind) && "Not a SCEVMinMaxExpr!"); 3755 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!"); 3756 if (Ops.size() == 1) return Ops[0]; 3757 #ifndef NDEBUG 3758 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3759 for (unsigned i = 1, e = Ops.size(); i != e; ++i) { 3760 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3761 "Operand types don't match!"); 3762 assert(Ops[0]->getType()->isPointerTy() == 3763 Ops[i]->getType()->isPointerTy() && 3764 "min/max should be consistently pointerish"); 3765 } 3766 #endif 3767 3768 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr; 3769 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr; 3770 3771 // Sort by complexity, this groups all similar expression types together. 3772 GroupByComplexity(Ops, &LI, DT); 3773 3774 // Check if we have created the same expression before. 3775 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops)) { 3776 return S; 3777 } 3778 3779 // If there are any constants, fold them together. 3780 unsigned Idx = 0; 3781 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3782 ++Idx; 3783 assert(Idx < Ops.size()); 3784 auto FoldOp = [&](const APInt &LHS, const APInt &RHS) { 3785 if (Kind == scSMaxExpr) 3786 return APIntOps::smax(LHS, RHS); 3787 else if (Kind == scSMinExpr) 3788 return APIntOps::smin(LHS, RHS); 3789 else if (Kind == scUMaxExpr) 3790 return APIntOps::umax(LHS, RHS); 3791 else if (Kind == scUMinExpr) 3792 return APIntOps::umin(LHS, RHS); 3793 llvm_unreachable("Unknown SCEV min/max opcode"); 3794 }; 3795 3796 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3797 // We found two constants, fold them together! 3798 ConstantInt *Fold = ConstantInt::get( 3799 getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt())); 3800 Ops[0] = getConstant(Fold); 3801 Ops.erase(Ops.begin()+1); // Erase the folded element 3802 if (Ops.size() == 1) return Ops[0]; 3803 LHSC = cast<SCEVConstant>(Ops[0]); 3804 } 3805 3806 bool IsMinV = LHSC->getValue()->isMinValue(IsSigned); 3807 bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned); 3808 3809 if (IsMax ? IsMinV : IsMaxV) { 3810 // If we are left with a constant minimum(/maximum)-int, strip it off. 3811 Ops.erase(Ops.begin()); 3812 --Idx; 3813 } else if (IsMax ? IsMaxV : IsMinV) { 3814 // If we have a max(/min) with a constant maximum(/minimum)-int, 3815 // it will always be the extremum. 3816 return LHSC; 3817 } 3818 3819 if (Ops.size() == 1) return Ops[0]; 3820 } 3821 3822 // Find the first operation of the same kind 3823 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind) 3824 ++Idx; 3825 3826 // Check to see if one of the operands is of the same kind. If so, expand its 3827 // operands onto our operand list, and recurse to simplify. 3828 if (Idx < Ops.size()) { 3829 bool DeletedAny = false; 3830 while (Ops[Idx]->getSCEVType() == Kind) { 3831 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]); 3832 Ops.erase(Ops.begin()+Idx); 3833 Ops.append(SMME->op_begin(), SMME->op_end()); 3834 DeletedAny = true; 3835 } 3836 3837 if (DeletedAny) 3838 return getMinMaxExpr(Kind, Ops); 3839 } 3840 3841 // Okay, check to see if the same value occurs in the operand list twice. If 3842 // so, delete one. Since we sorted the list, these values are required to 3843 // be adjacent. 3844 llvm::CmpInst::Predicate GEPred = 3845 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 3846 llvm::CmpInst::Predicate LEPred = 3847 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 3848 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred; 3849 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred; 3850 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) { 3851 if (Ops[i] == Ops[i + 1] || 3852 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) { 3853 // X op Y op Y --> X op Y 3854 // X op Y --> X, if we know X, Y are ordered appropriately 3855 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2); 3856 --i; 3857 --e; 3858 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i], 3859 Ops[i + 1])) { 3860 // X op Y --> Y, if we know X, Y are ordered appropriately 3861 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1); 3862 --i; 3863 --e; 3864 } 3865 } 3866 3867 if (Ops.size() == 1) return Ops[0]; 3868 3869 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3870 3871 // Okay, it looks like we really DO need an expr. Check to see if we 3872 // already have one, otherwise create a new one. 3873 FoldingSetNodeID ID; 3874 ID.AddInteger(Kind); 3875 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3876 ID.AddPointer(Ops[i]); 3877 void *IP = nullptr; 3878 const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP); 3879 if (ExistingSCEV) 3880 return ExistingSCEV; 3881 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3882 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3883 SCEV *S = new (SCEVAllocator) 3884 SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size()); 3885 3886 UniqueSCEVs.InsertNode(S, IP); 3887 registerUser(S, Ops); 3888 return S; 3889 } 3890 3891 namespace { 3892 3893 class SCEVSequentialMinMaxDeduplicatingVisitor final 3894 : public SCEVVisitor<SCEVSequentialMinMaxDeduplicatingVisitor, 3895 Optional<const SCEV *>> { 3896 using RetVal = Optional<const SCEV *>; 3897 using Base = SCEVVisitor<SCEVSequentialMinMaxDeduplicatingVisitor, RetVal>; 3898 3899 ScalarEvolution &SE; 3900 const SCEVTypes RootKind; // Must be a sequential min/max expression. 3901 const SCEVTypes NonSequentialRootKind; // Non-sequential variant of RootKind. 3902 SmallPtrSet<const SCEV *, 16> SeenOps; 3903 3904 bool canRecurseInto(SCEVTypes Kind) const { 3905 // We can only recurse into the SCEV expression of the same effective type 3906 // as the type of our root SCEV expression. 3907 return RootKind == Kind || NonSequentialRootKind == Kind; 3908 }; 3909 3910 RetVal visitAnyMinMaxExpr(const SCEV *S) { 3911 assert((isa<SCEVMinMaxExpr>(S) || isa<SCEVSequentialMinMaxExpr>(S)) && 3912 "Only for min/max expressions."); 3913 SCEVTypes Kind = S->getSCEVType(); 3914 3915 if (!canRecurseInto(Kind)) 3916 return S; 3917 3918 auto *NAry = cast<SCEVNAryExpr>(S); 3919 SmallVector<const SCEV *> NewOps; 3920 bool Changed = 3921 visit(Kind, makeArrayRef(NAry->op_begin(), NAry->op_end()), NewOps); 3922 3923 if (!Changed) 3924 return S; 3925 if (NewOps.empty()) 3926 return None; 3927 3928 return isa<SCEVSequentialMinMaxExpr>(S) 3929 ? SE.getSequentialMinMaxExpr(Kind, NewOps) 3930 : SE.getMinMaxExpr(Kind, NewOps); 3931 } 3932 3933 RetVal visit(const SCEV *S) { 3934 // Has the whole operand been seen already? 3935 if (!SeenOps.insert(S).second) 3936 return None; 3937 return Base::visit(S); 3938 } 3939 3940 public: 3941 SCEVSequentialMinMaxDeduplicatingVisitor(ScalarEvolution &SE, 3942 SCEVTypes RootKind) 3943 : SE(SE), RootKind(RootKind), 3944 NonSequentialRootKind( 3945 SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType( 3946 RootKind)) {} 3947 3948 bool /*Changed*/ visit(SCEVTypes Kind, ArrayRef<const SCEV *> OrigOps, 3949 SmallVectorImpl<const SCEV *> &NewOps) { 3950 bool Changed = false; 3951 SmallVector<const SCEV *> Ops; 3952 Ops.reserve(OrigOps.size()); 3953 3954 for (const SCEV *Op : OrigOps) { 3955 RetVal NewOp = visit(Op); 3956 if (NewOp != Op) 3957 Changed = true; 3958 if (NewOp) 3959 Ops.emplace_back(*NewOp); 3960 } 3961 3962 if (Changed) 3963 NewOps = std::move(Ops); 3964 return Changed; 3965 } 3966 3967 RetVal visitConstant(const SCEVConstant *Constant) { return Constant; } 3968 3969 RetVal visitPtrToIntExpr(const SCEVPtrToIntExpr *Expr) { return Expr; } 3970 3971 RetVal visitTruncateExpr(const SCEVTruncateExpr *Expr) { return Expr; } 3972 3973 RetVal visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { return Expr; } 3974 3975 RetVal visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { return Expr; } 3976 3977 RetVal visitAddExpr(const SCEVAddExpr *Expr) { return Expr; } 3978 3979 RetVal visitMulExpr(const SCEVMulExpr *Expr) { return Expr; } 3980 3981 RetVal visitUDivExpr(const SCEVUDivExpr *Expr) { return Expr; } 3982 3983 RetVal visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; } 3984 3985 RetVal visitSMaxExpr(const SCEVSMaxExpr *Expr) { 3986 return visitAnyMinMaxExpr(Expr); 3987 } 3988 3989 RetVal visitUMaxExpr(const SCEVUMaxExpr *Expr) { 3990 return visitAnyMinMaxExpr(Expr); 3991 } 3992 3993 RetVal visitSMinExpr(const SCEVSMinExpr *Expr) { 3994 return visitAnyMinMaxExpr(Expr); 3995 } 3996 3997 RetVal visitUMinExpr(const SCEVUMinExpr *Expr) { 3998 return visitAnyMinMaxExpr(Expr); 3999 } 4000 4001 RetVal visitSequentialUMinExpr(const SCEVSequentialUMinExpr *Expr) { 4002 return visitAnyMinMaxExpr(Expr); 4003 } 4004 4005 RetVal visitUnknown(const SCEVUnknown *Expr) { return Expr; } 4006 4007 RetVal visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { return Expr; } 4008 }; 4009 4010 } // namespace 4011 4012 const SCEV * 4013 ScalarEvolution::getSequentialMinMaxExpr(SCEVTypes Kind, 4014 SmallVectorImpl<const SCEV *> &Ops) { 4015 assert(SCEVSequentialMinMaxExpr::isSequentialMinMaxType(Kind) && 4016 "Not a SCEVSequentialMinMaxExpr!"); 4017 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!"); 4018 if (Ops.size() == 1) 4019 return Ops[0]; 4020 if (Ops.size() == 2 && 4021 any_of(Ops, [](const SCEV *Op) { return isa<SCEVConstant>(Op); })) 4022 return getMinMaxExpr( 4023 SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(Kind), 4024 Ops); 4025 #ifndef NDEBUG 4026 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 4027 for (unsigned i = 1, e = Ops.size(); i != e; ++i) { 4028 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 4029 "Operand types don't match!"); 4030 assert(Ops[0]->getType()->isPointerTy() == 4031 Ops[i]->getType()->isPointerTy() && 4032 "min/max should be consistently pointerish"); 4033 } 4034 #endif 4035 4036 // Note that SCEVSequentialMinMaxExpr is *NOT* commutative, 4037 // so we can *NOT* do any kind of sorting of the expressions! 4038 4039 // Check if we have created the same expression before. 4040 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops)) 4041 return S; 4042 4043 // FIXME: there are *some* simplifications that we can do here. 4044 4045 // Keep only the first instance of an operand. 4046 { 4047 SCEVSequentialMinMaxDeduplicatingVisitor Deduplicator(*this, Kind); 4048 bool Changed = Deduplicator.visit(Kind, Ops, Ops); 4049 if (Changed) 4050 return getSequentialMinMaxExpr(Kind, Ops); 4051 } 4052 4053 // Check to see if one of the operands is of the same kind. If so, expand its 4054 // operands onto our operand list, and recurse to simplify. 4055 { 4056 unsigned Idx = 0; 4057 bool DeletedAny = false; 4058 while (Idx < Ops.size()) { 4059 if (Ops[Idx]->getSCEVType() != Kind) { 4060 ++Idx; 4061 continue; 4062 } 4063 const auto *SMME = cast<SCEVSequentialMinMaxExpr>(Ops[Idx]); 4064 Ops.erase(Ops.begin() + Idx); 4065 Ops.insert(Ops.begin() + Idx, SMME->op_begin(), SMME->op_end()); 4066 DeletedAny = true; 4067 } 4068 4069 if (DeletedAny) 4070 return getSequentialMinMaxExpr(Kind, Ops); 4071 } 4072 4073 // Okay, it looks like we really DO need an expr. Check to see if we 4074 // already have one, otherwise create a new one. 4075 FoldingSetNodeID ID; 4076 ID.AddInteger(Kind); 4077 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 4078 ID.AddPointer(Ops[i]); 4079 void *IP = nullptr; 4080 const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP); 4081 if (ExistingSCEV) 4082 return ExistingSCEV; 4083 4084 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 4085 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 4086 SCEV *S = new (SCEVAllocator) 4087 SCEVSequentialMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size()); 4088 4089 UniqueSCEVs.InsertNode(S, IP); 4090 registerUser(S, Ops); 4091 return S; 4092 } 4093 4094 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) { 4095 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 4096 return getSMaxExpr(Ops); 4097 } 4098 4099 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 4100 return getMinMaxExpr(scSMaxExpr, Ops); 4101 } 4102 4103 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) { 4104 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 4105 return getUMaxExpr(Ops); 4106 } 4107 4108 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 4109 return getMinMaxExpr(scUMaxExpr, Ops); 4110 } 4111 4112 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 4113 const SCEV *RHS) { 4114 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 4115 return getSMinExpr(Ops); 4116 } 4117 4118 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 4119 return getMinMaxExpr(scSMinExpr, Ops); 4120 } 4121 4122 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, const SCEV *RHS, 4123 bool Sequential) { 4124 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 4125 return getUMinExpr(Ops, Sequential); 4126 } 4127 4128 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops, 4129 bool Sequential) { 4130 return Sequential ? getSequentialMinMaxExpr(scSequentialUMinExpr, Ops) 4131 : getMinMaxExpr(scUMinExpr, Ops); 4132 } 4133 4134 const SCEV * 4135 ScalarEvolution::getSizeOfScalableVectorExpr(Type *IntTy, 4136 ScalableVectorType *ScalableTy) { 4137 Constant *NullPtr = Constant::getNullValue(ScalableTy->getPointerTo()); 4138 Constant *One = ConstantInt::get(IntTy, 1); 4139 Constant *GEP = ConstantExpr::getGetElementPtr(ScalableTy, NullPtr, One); 4140 // Note that the expression we created is the final expression, we don't 4141 // want to simplify it any further Also, if we call a normal getSCEV(), 4142 // we'll end up in an endless recursion. So just create an SCEVUnknown. 4143 return getUnknown(ConstantExpr::getPtrToInt(GEP, IntTy)); 4144 } 4145 4146 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 4147 if (auto *ScalableAllocTy = dyn_cast<ScalableVectorType>(AllocTy)) 4148 return getSizeOfScalableVectorExpr(IntTy, ScalableAllocTy); 4149 // We can bypass creating a target-independent constant expression and then 4150 // folding it back into a ConstantInt. This is just a compile-time 4151 // optimization. 4152 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 4153 } 4154 4155 const SCEV *ScalarEvolution::getStoreSizeOfExpr(Type *IntTy, Type *StoreTy) { 4156 if (auto *ScalableStoreTy = dyn_cast<ScalableVectorType>(StoreTy)) 4157 return getSizeOfScalableVectorExpr(IntTy, ScalableStoreTy); 4158 // We can bypass creating a target-independent constant expression and then 4159 // folding it back into a ConstantInt. This is just a compile-time 4160 // optimization. 4161 return getConstant(IntTy, getDataLayout().getTypeStoreSize(StoreTy)); 4162 } 4163 4164 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 4165 StructType *STy, 4166 unsigned FieldNo) { 4167 // We can bypass creating a target-independent constant expression and then 4168 // folding it back into a ConstantInt. This is just a compile-time 4169 // optimization. 4170 return getConstant( 4171 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 4172 } 4173 4174 const SCEV *ScalarEvolution::getUnknown(Value *V) { 4175 // Don't attempt to do anything other than create a SCEVUnknown object 4176 // here. createSCEV only calls getUnknown after checking for all other 4177 // interesting possibilities, and any other code that calls getUnknown 4178 // is doing so in order to hide a value from SCEV canonicalization. 4179 4180 FoldingSetNodeID ID; 4181 ID.AddInteger(scUnknown); 4182 ID.AddPointer(V); 4183 void *IP = nullptr; 4184 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 4185 assert(cast<SCEVUnknown>(S)->getValue() == V && 4186 "Stale SCEVUnknown in uniquing map!"); 4187 return S; 4188 } 4189 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 4190 FirstUnknown); 4191 FirstUnknown = cast<SCEVUnknown>(S); 4192 UniqueSCEVs.InsertNode(S, IP); 4193 return S; 4194 } 4195 4196 //===----------------------------------------------------------------------===// 4197 // Basic SCEV Analysis and PHI Idiom Recognition Code 4198 // 4199 4200 /// Test if values of the given type are analyzable within the SCEV 4201 /// framework. This primarily includes integer types, and it can optionally 4202 /// include pointer types if the ScalarEvolution class has access to 4203 /// target-specific information. 4204 bool ScalarEvolution::isSCEVable(Type *Ty) const { 4205 // Integers and pointers are always SCEVable. 4206 return Ty->isIntOrPtrTy(); 4207 } 4208 4209 /// Return the size in bits of the specified type, for which isSCEVable must 4210 /// return true. 4211 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 4212 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 4213 if (Ty->isPointerTy()) 4214 return getDataLayout().getIndexTypeSizeInBits(Ty); 4215 return getDataLayout().getTypeSizeInBits(Ty); 4216 } 4217 4218 /// Return a type with the same bitwidth as the given type and which represents 4219 /// how SCEV will treat the given type, for which isSCEVable must return 4220 /// true. For pointer types, this is the pointer index sized integer type. 4221 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 4222 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 4223 4224 if (Ty->isIntegerTy()) 4225 return Ty; 4226 4227 // The only other support type is pointer. 4228 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 4229 return getDataLayout().getIndexType(Ty); 4230 } 4231 4232 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const { 4233 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2; 4234 } 4235 4236 bool ScalarEvolution::instructionCouldExistWitthOperands(const SCEV *A, 4237 const SCEV *B) { 4238 /// For a valid use point to exist, the defining scope of one operand 4239 /// must dominate the other. 4240 bool PreciseA, PreciseB; 4241 auto *ScopeA = getDefiningScopeBound({A}, PreciseA); 4242 auto *ScopeB = getDefiningScopeBound({B}, PreciseB); 4243 if (!PreciseA || !PreciseB) 4244 // Can't tell. 4245 return false; 4246 return (ScopeA == ScopeB) || DT.dominates(ScopeA, ScopeB) || 4247 DT.dominates(ScopeB, ScopeA); 4248 } 4249 4250 4251 const SCEV *ScalarEvolution::getCouldNotCompute() { 4252 return CouldNotCompute.get(); 4253 } 4254 4255 bool ScalarEvolution::checkValidity(const SCEV *S) const { 4256 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) { 4257 auto *SU = dyn_cast<SCEVUnknown>(S); 4258 return SU && SU->getValue() == nullptr; 4259 }); 4260 4261 return !ContainsNulls; 4262 } 4263 4264 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 4265 HasRecMapType::iterator I = HasRecMap.find(S); 4266 if (I != HasRecMap.end()) 4267 return I->second; 4268 4269 bool FoundAddRec = 4270 SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); }); 4271 HasRecMap.insert({S, FoundAddRec}); 4272 return FoundAddRec; 4273 } 4274 4275 /// Return the ValueOffsetPair set for \p S. \p S can be represented 4276 /// by the value and offset from any ValueOffsetPair in the set. 4277 ArrayRef<Value *> ScalarEvolution::getSCEVValues(const SCEV *S) { 4278 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 4279 if (SI == ExprValueMap.end()) 4280 return None; 4281 #ifndef NDEBUG 4282 if (VerifySCEVMap) { 4283 // Check there is no dangling Value in the set returned. 4284 for (Value *V : SI->second) 4285 assert(ValueExprMap.count(V)); 4286 } 4287 #endif 4288 return SI->second.getArrayRef(); 4289 } 4290 4291 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) 4292 /// cannot be used separately. eraseValueFromMap should be used to remove 4293 /// V from ValueExprMap and ExprValueMap at the same time. 4294 void ScalarEvolution::eraseValueFromMap(Value *V) { 4295 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 4296 if (I != ValueExprMap.end()) { 4297 auto EVIt = ExprValueMap.find(I->second); 4298 bool Removed = EVIt->second.remove(V); 4299 (void) Removed; 4300 assert(Removed && "Value not in ExprValueMap?"); 4301 ValueExprMap.erase(I); 4302 } 4303 } 4304 4305 void ScalarEvolution::insertValueToMap(Value *V, const SCEV *S) { 4306 // A recursive query may have already computed the SCEV. It should be 4307 // equivalent, but may not necessarily be exactly the same, e.g. due to lazily 4308 // inferred nowrap flags. 4309 auto It = ValueExprMap.find_as(V); 4310 if (It == ValueExprMap.end()) { 4311 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 4312 ExprValueMap[S].insert(V); 4313 } 4314 } 4315 4316 /// Return an existing SCEV if it exists, otherwise analyze the expression and 4317 /// create a new one. 4318 const SCEV *ScalarEvolution::getSCEV(Value *V) { 4319 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 4320 4321 const SCEV *S = getExistingSCEV(V); 4322 if (S == nullptr) { 4323 S = createSCEV(V); 4324 // During PHI resolution, it is possible to create two SCEVs for the same 4325 // V, so it is needed to double check whether V->S is inserted into 4326 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 4327 std::pair<ValueExprMapType::iterator, bool> Pair = 4328 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 4329 if (Pair.second) 4330 ExprValueMap[S].insert(V); 4331 } 4332 return S; 4333 } 4334 4335 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 4336 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 4337 4338 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 4339 if (I != ValueExprMap.end()) { 4340 const SCEV *S = I->second; 4341 assert(checkValidity(S) && 4342 "existing SCEV has not been properly invalidated"); 4343 return S; 4344 } 4345 return nullptr; 4346 } 4347 4348 /// Return a SCEV corresponding to -V = -1*V 4349 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 4350 SCEV::NoWrapFlags Flags) { 4351 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 4352 return getConstant( 4353 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 4354 4355 Type *Ty = V->getType(); 4356 Ty = getEffectiveSCEVType(Ty); 4357 return getMulExpr(V, getMinusOne(Ty), Flags); 4358 } 4359 4360 /// If Expr computes ~A, return A else return nullptr 4361 static const SCEV *MatchNotExpr(const SCEV *Expr) { 4362 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 4363 if (!Add || Add->getNumOperands() != 2 || 4364 !Add->getOperand(0)->isAllOnesValue()) 4365 return nullptr; 4366 4367 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 4368 if (!AddRHS || AddRHS->getNumOperands() != 2 || 4369 !AddRHS->getOperand(0)->isAllOnesValue()) 4370 return nullptr; 4371 4372 return AddRHS->getOperand(1); 4373 } 4374 4375 /// Return a SCEV corresponding to ~V = -1-V 4376 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 4377 assert(!V->getType()->isPointerTy() && "Can't negate pointer"); 4378 4379 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 4380 return getConstant( 4381 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 4382 4383 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y) 4384 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) { 4385 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) { 4386 SmallVector<const SCEV *, 2> MatchedOperands; 4387 for (const SCEV *Operand : MME->operands()) { 4388 const SCEV *Matched = MatchNotExpr(Operand); 4389 if (!Matched) 4390 return (const SCEV *)nullptr; 4391 MatchedOperands.push_back(Matched); 4392 } 4393 return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()), 4394 MatchedOperands); 4395 }; 4396 if (const SCEV *Replaced = MatchMinMaxNegation(MME)) 4397 return Replaced; 4398 } 4399 4400 Type *Ty = V->getType(); 4401 Ty = getEffectiveSCEVType(Ty); 4402 return getMinusSCEV(getMinusOne(Ty), V); 4403 } 4404 4405 const SCEV *ScalarEvolution::removePointerBase(const SCEV *P) { 4406 assert(P->getType()->isPointerTy()); 4407 4408 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(P)) { 4409 // The base of an AddRec is the first operand. 4410 SmallVector<const SCEV *> Ops{AddRec->operands()}; 4411 Ops[0] = removePointerBase(Ops[0]); 4412 // Don't try to transfer nowrap flags for now. We could in some cases 4413 // (for example, if pointer operand of the AddRec is a SCEVUnknown). 4414 return getAddRecExpr(Ops, AddRec->getLoop(), SCEV::FlagAnyWrap); 4415 } 4416 if (auto *Add = dyn_cast<SCEVAddExpr>(P)) { 4417 // The base of an Add is the pointer operand. 4418 SmallVector<const SCEV *> Ops{Add->operands()}; 4419 const SCEV **PtrOp = nullptr; 4420 for (const SCEV *&AddOp : Ops) { 4421 if (AddOp->getType()->isPointerTy()) { 4422 assert(!PtrOp && "Cannot have multiple pointer ops"); 4423 PtrOp = &AddOp; 4424 } 4425 } 4426 *PtrOp = removePointerBase(*PtrOp); 4427 // Don't try to transfer nowrap flags for now. We could in some cases 4428 // (for example, if the pointer operand of the Add is a SCEVUnknown). 4429 return getAddExpr(Ops); 4430 } 4431 // Any other expression must be a pointer base. 4432 return getZero(P->getType()); 4433 } 4434 4435 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 4436 SCEV::NoWrapFlags Flags, 4437 unsigned Depth) { 4438 // Fast path: X - X --> 0. 4439 if (LHS == RHS) 4440 return getZero(LHS->getType()); 4441 4442 // If we subtract two pointers with different pointer bases, bail. 4443 // Eventually, we're going to add an assertion to getMulExpr that we 4444 // can't multiply by a pointer. 4445 if (RHS->getType()->isPointerTy()) { 4446 if (!LHS->getType()->isPointerTy() || 4447 getPointerBase(LHS) != getPointerBase(RHS)) 4448 return getCouldNotCompute(); 4449 LHS = removePointerBase(LHS); 4450 RHS = removePointerBase(RHS); 4451 } 4452 4453 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 4454 // makes it so that we cannot make much use of NUW. 4455 auto AddFlags = SCEV::FlagAnyWrap; 4456 const bool RHSIsNotMinSigned = 4457 !getSignedRangeMin(RHS).isMinSignedValue(); 4458 if (hasFlags(Flags, SCEV::FlagNSW)) { 4459 // Let M be the minimum representable signed value. Then (-1)*RHS 4460 // signed-wraps if and only if RHS is M. That can happen even for 4461 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 4462 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 4463 // (-1)*RHS, we need to prove that RHS != M. 4464 // 4465 // If LHS is non-negative and we know that LHS - RHS does not 4466 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 4467 // either by proving that RHS > M or that LHS >= 0. 4468 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 4469 AddFlags = SCEV::FlagNSW; 4470 } 4471 } 4472 4473 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 4474 // RHS is NSW and LHS >= 0. 4475 // 4476 // The difficulty here is that the NSW flag may have been proven 4477 // relative to a loop that is to be found in a recurrence in LHS and 4478 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 4479 // larger scope than intended. 4480 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 4481 4482 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth); 4483 } 4484 4485 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty, 4486 unsigned Depth) { 4487 Type *SrcTy = V->getType(); 4488 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4489 "Cannot truncate or zero extend with non-integer arguments!"); 4490 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4491 return V; // No conversion 4492 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4493 return getTruncateExpr(V, Ty, Depth); 4494 return getZeroExtendExpr(V, Ty, Depth); 4495 } 4496 4497 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty, 4498 unsigned Depth) { 4499 Type *SrcTy = V->getType(); 4500 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4501 "Cannot truncate or zero extend with non-integer arguments!"); 4502 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4503 return V; // No conversion 4504 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4505 return getTruncateExpr(V, Ty, Depth); 4506 return getSignExtendExpr(V, Ty, Depth); 4507 } 4508 4509 const SCEV * 4510 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 4511 Type *SrcTy = V->getType(); 4512 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4513 "Cannot noop or zero extend with non-integer arguments!"); 4514 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4515 "getNoopOrZeroExtend cannot truncate!"); 4516 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4517 return V; // No conversion 4518 return getZeroExtendExpr(V, Ty); 4519 } 4520 4521 const SCEV * 4522 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 4523 Type *SrcTy = V->getType(); 4524 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4525 "Cannot noop or sign extend with non-integer arguments!"); 4526 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4527 "getNoopOrSignExtend cannot truncate!"); 4528 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4529 return V; // No conversion 4530 return getSignExtendExpr(V, Ty); 4531 } 4532 4533 const SCEV * 4534 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 4535 Type *SrcTy = V->getType(); 4536 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4537 "Cannot noop or any extend with non-integer arguments!"); 4538 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4539 "getNoopOrAnyExtend cannot truncate!"); 4540 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4541 return V; // No conversion 4542 return getAnyExtendExpr(V, Ty); 4543 } 4544 4545 const SCEV * 4546 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 4547 Type *SrcTy = V->getType(); 4548 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4549 "Cannot truncate or noop with non-integer arguments!"); 4550 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 4551 "getTruncateOrNoop cannot extend!"); 4552 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4553 return V; // No conversion 4554 return getTruncateExpr(V, Ty); 4555 } 4556 4557 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 4558 const SCEV *RHS) { 4559 const SCEV *PromotedLHS = LHS; 4560 const SCEV *PromotedRHS = RHS; 4561 4562 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 4563 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 4564 else 4565 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 4566 4567 return getUMaxExpr(PromotedLHS, PromotedRHS); 4568 } 4569 4570 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 4571 const SCEV *RHS, 4572 bool Sequential) { 4573 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 4574 return getUMinFromMismatchedTypes(Ops, Sequential); 4575 } 4576 4577 const SCEV * 4578 ScalarEvolution::getUMinFromMismatchedTypes(SmallVectorImpl<const SCEV *> &Ops, 4579 bool Sequential) { 4580 assert(!Ops.empty() && "At least one operand must be!"); 4581 // Trivial case. 4582 if (Ops.size() == 1) 4583 return Ops[0]; 4584 4585 // Find the max type first. 4586 Type *MaxType = nullptr; 4587 for (auto *S : Ops) 4588 if (MaxType) 4589 MaxType = getWiderType(MaxType, S->getType()); 4590 else 4591 MaxType = S->getType(); 4592 assert(MaxType && "Failed to find maximum type!"); 4593 4594 // Extend all ops to max type. 4595 SmallVector<const SCEV *, 2> PromotedOps; 4596 for (auto *S : Ops) 4597 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType)); 4598 4599 // Generate umin. 4600 return getUMinExpr(PromotedOps, Sequential); 4601 } 4602 4603 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 4604 // A pointer operand may evaluate to a nonpointer expression, such as null. 4605 if (!V->getType()->isPointerTy()) 4606 return V; 4607 4608 while (true) { 4609 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 4610 V = AddRec->getStart(); 4611 } else if (auto *Add = dyn_cast<SCEVAddExpr>(V)) { 4612 const SCEV *PtrOp = nullptr; 4613 for (const SCEV *AddOp : Add->operands()) { 4614 if (AddOp->getType()->isPointerTy()) { 4615 assert(!PtrOp && "Cannot have multiple pointer ops"); 4616 PtrOp = AddOp; 4617 } 4618 } 4619 assert(PtrOp && "Must have pointer op"); 4620 V = PtrOp; 4621 } else // Not something we can look further into. 4622 return V; 4623 } 4624 } 4625 4626 /// Push users of the given Instruction onto the given Worklist. 4627 static void PushDefUseChildren(Instruction *I, 4628 SmallVectorImpl<Instruction *> &Worklist, 4629 SmallPtrSetImpl<Instruction *> &Visited) { 4630 // Push the def-use children onto the Worklist stack. 4631 for (User *U : I->users()) { 4632 auto *UserInsn = cast<Instruction>(U); 4633 if (Visited.insert(UserInsn).second) 4634 Worklist.push_back(UserInsn); 4635 } 4636 } 4637 4638 namespace { 4639 4640 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start 4641 /// expression in case its Loop is L. If it is not L then 4642 /// if IgnoreOtherLoops is true then use AddRec itself 4643 /// otherwise rewrite cannot be done. 4644 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4645 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 4646 public: 4647 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 4648 bool IgnoreOtherLoops = true) { 4649 SCEVInitRewriter Rewriter(L, SE); 4650 const SCEV *Result = Rewriter.visit(S); 4651 if (Rewriter.hasSeenLoopVariantSCEVUnknown()) 4652 return SE.getCouldNotCompute(); 4653 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops 4654 ? SE.getCouldNotCompute() 4655 : Result; 4656 } 4657 4658 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4659 if (!SE.isLoopInvariant(Expr, L)) 4660 SeenLoopVariantSCEVUnknown = true; 4661 return Expr; 4662 } 4663 4664 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4665 // Only re-write AddRecExprs for this loop. 4666 if (Expr->getLoop() == L) 4667 return Expr->getStart(); 4668 SeenOtherLoops = true; 4669 return Expr; 4670 } 4671 4672 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4673 4674 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4675 4676 private: 4677 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 4678 : SCEVRewriteVisitor(SE), L(L) {} 4679 4680 const Loop *L; 4681 bool SeenLoopVariantSCEVUnknown = false; 4682 bool SeenOtherLoops = false; 4683 }; 4684 4685 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post 4686 /// increment expression in case its Loop is L. If it is not L then 4687 /// use AddRec itself. 4688 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4689 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> { 4690 public: 4691 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) { 4692 SCEVPostIncRewriter Rewriter(L, SE); 4693 const SCEV *Result = Rewriter.visit(S); 4694 return Rewriter.hasSeenLoopVariantSCEVUnknown() 4695 ? SE.getCouldNotCompute() 4696 : Result; 4697 } 4698 4699 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4700 if (!SE.isLoopInvariant(Expr, L)) 4701 SeenLoopVariantSCEVUnknown = true; 4702 return Expr; 4703 } 4704 4705 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4706 // Only re-write AddRecExprs for this loop. 4707 if (Expr->getLoop() == L) 4708 return Expr->getPostIncExpr(SE); 4709 SeenOtherLoops = true; 4710 return Expr; 4711 } 4712 4713 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4714 4715 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4716 4717 private: 4718 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE) 4719 : SCEVRewriteVisitor(SE), L(L) {} 4720 4721 const Loop *L; 4722 bool SeenLoopVariantSCEVUnknown = false; 4723 bool SeenOtherLoops = false; 4724 }; 4725 4726 /// This class evaluates the compare condition by matching it against the 4727 /// condition of loop latch. If there is a match we assume a true value 4728 /// for the condition while building SCEV nodes. 4729 class SCEVBackedgeConditionFolder 4730 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> { 4731 public: 4732 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4733 ScalarEvolution &SE) { 4734 bool IsPosBECond = false; 4735 Value *BECond = nullptr; 4736 if (BasicBlock *Latch = L->getLoopLatch()) { 4737 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator()); 4738 if (BI && BI->isConditional()) { 4739 assert(BI->getSuccessor(0) != BI->getSuccessor(1) && 4740 "Both outgoing branches should not target same header!"); 4741 BECond = BI->getCondition(); 4742 IsPosBECond = BI->getSuccessor(0) == L->getHeader(); 4743 } else { 4744 return S; 4745 } 4746 } 4747 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE); 4748 return Rewriter.visit(S); 4749 } 4750 4751 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4752 const SCEV *Result = Expr; 4753 bool InvariantF = SE.isLoopInvariant(Expr, L); 4754 4755 if (!InvariantF) { 4756 Instruction *I = cast<Instruction>(Expr->getValue()); 4757 switch (I->getOpcode()) { 4758 case Instruction::Select: { 4759 SelectInst *SI = cast<SelectInst>(I); 4760 Optional<const SCEV *> Res = 4761 compareWithBackedgeCondition(SI->getCondition()); 4762 if (Res.hasValue()) { 4763 bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne(); 4764 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue()); 4765 } 4766 break; 4767 } 4768 default: { 4769 Optional<const SCEV *> Res = compareWithBackedgeCondition(I); 4770 if (Res.hasValue()) 4771 Result = Res.getValue(); 4772 break; 4773 } 4774 } 4775 } 4776 return Result; 4777 } 4778 4779 private: 4780 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond, 4781 bool IsPosBECond, ScalarEvolution &SE) 4782 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond), 4783 IsPositiveBECond(IsPosBECond) {} 4784 4785 Optional<const SCEV *> compareWithBackedgeCondition(Value *IC); 4786 4787 const Loop *L; 4788 /// Loop back condition. 4789 Value *BackedgeCond = nullptr; 4790 /// Set to true if loop back is on positive branch condition. 4791 bool IsPositiveBECond; 4792 }; 4793 4794 Optional<const SCEV *> 4795 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) { 4796 4797 // If value matches the backedge condition for loop latch, 4798 // then return a constant evolution node based on loopback 4799 // branch taken. 4800 if (BackedgeCond == IC) 4801 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext())) 4802 : SE.getZero(Type::getInt1Ty(SE.getContext())); 4803 return None; 4804 } 4805 4806 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 4807 public: 4808 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4809 ScalarEvolution &SE) { 4810 SCEVShiftRewriter Rewriter(L, SE); 4811 const SCEV *Result = Rewriter.visit(S); 4812 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 4813 } 4814 4815 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4816 // Only allow AddRecExprs for this loop. 4817 if (!SE.isLoopInvariant(Expr, L)) 4818 Valid = false; 4819 return Expr; 4820 } 4821 4822 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4823 if (Expr->getLoop() == L && Expr->isAffine()) 4824 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 4825 Valid = false; 4826 return Expr; 4827 } 4828 4829 bool isValid() { return Valid; } 4830 4831 private: 4832 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 4833 : SCEVRewriteVisitor(SE), L(L) {} 4834 4835 const Loop *L; 4836 bool Valid = true; 4837 }; 4838 4839 } // end anonymous namespace 4840 4841 SCEV::NoWrapFlags 4842 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 4843 if (!AR->isAffine()) 4844 return SCEV::FlagAnyWrap; 4845 4846 using OBO = OverflowingBinaryOperator; 4847 4848 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 4849 4850 if (!AR->hasNoSignedWrap()) { 4851 ConstantRange AddRecRange = getSignedRange(AR); 4852 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 4853 4854 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4855 Instruction::Add, IncRange, OBO::NoSignedWrap); 4856 if (NSWRegion.contains(AddRecRange)) 4857 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 4858 } 4859 4860 if (!AR->hasNoUnsignedWrap()) { 4861 ConstantRange AddRecRange = getUnsignedRange(AR); 4862 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 4863 4864 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4865 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 4866 if (NUWRegion.contains(AddRecRange)) 4867 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 4868 } 4869 4870 return Result; 4871 } 4872 4873 SCEV::NoWrapFlags 4874 ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) { 4875 SCEV::NoWrapFlags Result = AR->getNoWrapFlags(); 4876 4877 if (AR->hasNoSignedWrap()) 4878 return Result; 4879 4880 if (!AR->isAffine()) 4881 return Result; 4882 4883 const SCEV *Step = AR->getStepRecurrence(*this); 4884 const Loop *L = AR->getLoop(); 4885 4886 // Check whether the backedge-taken count is SCEVCouldNotCompute. 4887 // Note that this serves two purposes: It filters out loops that are 4888 // simply not analyzable, and it covers the case where this code is 4889 // being called from within backedge-taken count analysis, such that 4890 // attempting to ask for the backedge-taken count would likely result 4891 // in infinite recursion. In the later case, the analysis code will 4892 // cope with a conservative value, and it will take care to purge 4893 // that value once it has finished. 4894 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 4895 4896 // Normally, in the cases we can prove no-overflow via a 4897 // backedge guarding condition, we can also compute a backedge 4898 // taken count for the loop. The exceptions are assumptions and 4899 // guards present in the loop -- SCEV is not great at exploiting 4900 // these to compute max backedge taken counts, but can still use 4901 // these to prove lack of overflow. Use this fact to avoid 4902 // doing extra work that may not pay off. 4903 4904 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards && 4905 AC.assumptions().empty()) 4906 return Result; 4907 4908 // If the backedge is guarded by a comparison with the pre-inc value the 4909 // addrec is safe. Also, if the entry is guarded by a comparison with the 4910 // start value and the backedge is guarded by a comparison with the post-inc 4911 // value, the addrec is safe. 4912 ICmpInst::Predicate Pred; 4913 const SCEV *OverflowLimit = 4914 getSignedOverflowLimitForStep(Step, &Pred, this); 4915 if (OverflowLimit && 4916 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 4917 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) { 4918 Result = setFlags(Result, SCEV::FlagNSW); 4919 } 4920 return Result; 4921 } 4922 SCEV::NoWrapFlags 4923 ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) { 4924 SCEV::NoWrapFlags Result = AR->getNoWrapFlags(); 4925 4926 if (AR->hasNoUnsignedWrap()) 4927 return Result; 4928 4929 if (!AR->isAffine()) 4930 return Result; 4931 4932 const SCEV *Step = AR->getStepRecurrence(*this); 4933 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 4934 const Loop *L = AR->getLoop(); 4935 4936 // Check whether the backedge-taken count is SCEVCouldNotCompute. 4937 // Note that this serves two purposes: It filters out loops that are 4938 // simply not analyzable, and it covers the case where this code is 4939 // being called from within backedge-taken count analysis, such that 4940 // attempting to ask for the backedge-taken count would likely result 4941 // in infinite recursion. In the later case, the analysis code will 4942 // cope with a conservative value, and it will take care to purge 4943 // that value once it has finished. 4944 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 4945 4946 // Normally, in the cases we can prove no-overflow via a 4947 // backedge guarding condition, we can also compute a backedge 4948 // taken count for the loop. The exceptions are assumptions and 4949 // guards present in the loop -- SCEV is not great at exploiting 4950 // these to compute max backedge taken counts, but can still use 4951 // these to prove lack of overflow. Use this fact to avoid 4952 // doing extra work that may not pay off. 4953 4954 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards && 4955 AC.assumptions().empty()) 4956 return Result; 4957 4958 // If the backedge is guarded by a comparison with the pre-inc value the 4959 // addrec is safe. Also, if the entry is guarded by a comparison with the 4960 // start value and the backedge is guarded by a comparison with the post-inc 4961 // value, the addrec is safe. 4962 if (isKnownPositive(Step)) { 4963 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 4964 getUnsignedRangeMax(Step)); 4965 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 4966 isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) { 4967 Result = setFlags(Result, SCEV::FlagNUW); 4968 } 4969 } 4970 4971 return Result; 4972 } 4973 4974 namespace { 4975 4976 /// Represents an abstract binary operation. This may exist as a 4977 /// normal instruction or constant expression, or may have been 4978 /// derived from an expression tree. 4979 struct BinaryOp { 4980 unsigned Opcode; 4981 Value *LHS; 4982 Value *RHS; 4983 bool IsNSW = false; 4984 bool IsNUW = false; 4985 4986 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 4987 /// constant expression. 4988 Operator *Op = nullptr; 4989 4990 explicit BinaryOp(Operator *Op) 4991 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 4992 Op(Op) { 4993 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 4994 IsNSW = OBO->hasNoSignedWrap(); 4995 IsNUW = OBO->hasNoUnsignedWrap(); 4996 } 4997 } 4998 4999 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 5000 bool IsNUW = false) 5001 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {} 5002 }; 5003 5004 } // end anonymous namespace 5005 5006 /// Try to map \p V into a BinaryOp, and return \c None on failure. 5007 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 5008 auto *Op = dyn_cast<Operator>(V); 5009 if (!Op) 5010 return None; 5011 5012 // Implementation detail: all the cleverness here should happen without 5013 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 5014 // SCEV expressions when possible, and we should not break that. 5015 5016 switch (Op->getOpcode()) { 5017 case Instruction::Add: 5018 case Instruction::Sub: 5019 case Instruction::Mul: 5020 case Instruction::UDiv: 5021 case Instruction::URem: 5022 case Instruction::And: 5023 case Instruction::Or: 5024 case Instruction::AShr: 5025 case Instruction::Shl: 5026 return BinaryOp(Op); 5027 5028 case Instruction::Xor: 5029 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 5030 // If the RHS of the xor is a signmask, then this is just an add. 5031 // Instcombine turns add of signmask into xor as a strength reduction step. 5032 if (RHSC->getValue().isSignMask()) 5033 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 5034 // Binary `xor` is a bit-wise `add`. 5035 if (V->getType()->isIntegerTy(1)) 5036 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 5037 return BinaryOp(Op); 5038 5039 case Instruction::LShr: 5040 // Turn logical shift right of a constant into a unsigned divide. 5041 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 5042 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 5043 5044 // If the shift count is not less than the bitwidth, the result of 5045 // the shift is undefined. Don't try to analyze it, because the 5046 // resolution chosen here may differ from the resolution chosen in 5047 // other parts of the compiler. 5048 if (SA->getValue().ult(BitWidth)) { 5049 Constant *X = 5050 ConstantInt::get(SA->getContext(), 5051 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 5052 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 5053 } 5054 } 5055 return BinaryOp(Op); 5056 5057 case Instruction::ExtractValue: { 5058 auto *EVI = cast<ExtractValueInst>(Op); 5059 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 5060 break; 5061 5062 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()); 5063 if (!WO) 5064 break; 5065 5066 Instruction::BinaryOps BinOp = WO->getBinaryOp(); 5067 bool Signed = WO->isSigned(); 5068 // TODO: Should add nuw/nsw flags for mul as well. 5069 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT)) 5070 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS()); 5071 5072 // Now that we know that all uses of the arithmetic-result component of 5073 // CI are guarded by the overflow check, we can go ahead and pretend 5074 // that the arithmetic is non-overflowing. 5075 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(), 5076 /* IsNSW = */ Signed, /* IsNUW = */ !Signed); 5077 } 5078 5079 default: 5080 break; 5081 } 5082 5083 // Recognise intrinsic loop.decrement.reg, and as this has exactly the same 5084 // semantics as a Sub, return a binary sub expression. 5085 if (auto *II = dyn_cast<IntrinsicInst>(V)) 5086 if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg) 5087 return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1)); 5088 5089 return None; 5090 } 5091 5092 /// Helper function to createAddRecFromPHIWithCasts. We have a phi 5093 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via 5094 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the 5095 /// way. This function checks if \p Op, an operand of this SCEVAddExpr, 5096 /// follows one of the following patterns: 5097 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 5098 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 5099 /// If the SCEV expression of \p Op conforms with one of the expected patterns 5100 /// we return the type of the truncation operation, and indicate whether the 5101 /// truncated type should be treated as signed/unsigned by setting 5102 /// \p Signed to true/false, respectively. 5103 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, 5104 bool &Signed, ScalarEvolution &SE) { 5105 // The case where Op == SymbolicPHI (that is, with no type conversions on 5106 // the way) is handled by the regular add recurrence creating logic and 5107 // would have already been triggered in createAddRecForPHI. Reaching it here 5108 // means that createAddRecFromPHI had failed for this PHI before (e.g., 5109 // because one of the other operands of the SCEVAddExpr updating this PHI is 5110 // not invariant). 5111 // 5112 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in 5113 // this case predicates that allow us to prove that Op == SymbolicPHI will 5114 // be added. 5115 if (Op == SymbolicPHI) 5116 return nullptr; 5117 5118 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType()); 5119 unsigned NewBits = SE.getTypeSizeInBits(Op->getType()); 5120 if (SourceBits != NewBits) 5121 return nullptr; 5122 5123 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op); 5124 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op); 5125 if (!SExt && !ZExt) 5126 return nullptr; 5127 const SCEVTruncateExpr *Trunc = 5128 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand()) 5129 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand()); 5130 if (!Trunc) 5131 return nullptr; 5132 const SCEV *X = Trunc->getOperand(); 5133 if (X != SymbolicPHI) 5134 return nullptr; 5135 Signed = SExt != nullptr; 5136 return Trunc->getType(); 5137 } 5138 5139 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) { 5140 if (!PN->getType()->isIntegerTy()) 5141 return nullptr; 5142 const Loop *L = LI.getLoopFor(PN->getParent()); 5143 if (!L || L->getHeader() != PN->getParent()) 5144 return nullptr; 5145 return L; 5146 } 5147 5148 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the 5149 // computation that updates the phi follows the following pattern: 5150 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum 5151 // which correspond to a phi->trunc->sext/zext->add->phi update chain. 5152 // If so, try to see if it can be rewritten as an AddRecExpr under some 5153 // Predicates. If successful, return them as a pair. Also cache the results 5154 // of the analysis. 5155 // 5156 // Example usage scenario: 5157 // Say the Rewriter is called for the following SCEV: 5158 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 5159 // where: 5160 // %X = phi i64 (%Start, %BEValue) 5161 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X), 5162 // and call this function with %SymbolicPHI = %X. 5163 // 5164 // The analysis will find that the value coming around the backedge has 5165 // the following SCEV: 5166 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 5167 // Upon concluding that this matches the desired pattern, the function 5168 // will return the pair {NewAddRec, SmallPredsVec} where: 5169 // NewAddRec = {%Start,+,%Step} 5170 // SmallPredsVec = {P1, P2, P3} as follows: 5171 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw> 5172 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64) 5173 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64) 5174 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec 5175 // under the predicates {P1,P2,P3}. 5176 // This predicated rewrite will be cached in PredicatedSCEVRewrites: 5177 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)} 5178 // 5179 // TODO's: 5180 // 5181 // 1) Extend the Induction descriptor to also support inductions that involve 5182 // casts: When needed (namely, when we are called in the context of the 5183 // vectorizer induction analysis), a Set of cast instructions will be 5184 // populated by this method, and provided back to isInductionPHI. This is 5185 // needed to allow the vectorizer to properly record them to be ignored by 5186 // the cost model and to avoid vectorizing them (otherwise these casts, 5187 // which are redundant under the runtime overflow checks, will be 5188 // vectorized, which can be costly). 5189 // 5190 // 2) Support additional induction/PHISCEV patterns: We also want to support 5191 // inductions where the sext-trunc / zext-trunc operations (partly) occur 5192 // after the induction update operation (the induction increment): 5193 // 5194 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix) 5195 // which correspond to a phi->add->trunc->sext/zext->phi update chain. 5196 // 5197 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix) 5198 // which correspond to a phi->trunc->add->sext/zext->phi update chain. 5199 // 5200 // 3) Outline common code with createAddRecFromPHI to avoid duplication. 5201 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 5202 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) { 5203 SmallVector<const SCEVPredicate *, 3> Predicates; 5204 5205 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can 5206 // return an AddRec expression under some predicate. 5207 5208 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 5209 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 5210 assert(L && "Expecting an integer loop header phi"); 5211 5212 // The loop may have multiple entrances or multiple exits; we can analyze 5213 // this phi as an addrec if it has a unique entry value and a unique 5214 // backedge value. 5215 Value *BEValueV = nullptr, *StartValueV = nullptr; 5216 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 5217 Value *V = PN->getIncomingValue(i); 5218 if (L->contains(PN->getIncomingBlock(i))) { 5219 if (!BEValueV) { 5220 BEValueV = V; 5221 } else if (BEValueV != V) { 5222 BEValueV = nullptr; 5223 break; 5224 } 5225 } else if (!StartValueV) { 5226 StartValueV = V; 5227 } else if (StartValueV != V) { 5228 StartValueV = nullptr; 5229 break; 5230 } 5231 } 5232 if (!BEValueV || !StartValueV) 5233 return None; 5234 5235 const SCEV *BEValue = getSCEV(BEValueV); 5236 5237 // If the value coming around the backedge is an add with the symbolic 5238 // value we just inserted, possibly with casts that we can ignore under 5239 // an appropriate runtime guard, then we found a simple induction variable! 5240 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue); 5241 if (!Add) 5242 return None; 5243 5244 // If there is a single occurrence of the symbolic value, possibly 5245 // casted, replace it with a recurrence. 5246 unsigned FoundIndex = Add->getNumOperands(); 5247 Type *TruncTy = nullptr; 5248 bool Signed; 5249 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5250 if ((TruncTy = 5251 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this))) 5252 if (FoundIndex == e) { 5253 FoundIndex = i; 5254 break; 5255 } 5256 5257 if (FoundIndex == Add->getNumOperands()) 5258 return None; 5259 5260 // Create an add with everything but the specified operand. 5261 SmallVector<const SCEV *, 8> Ops; 5262 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5263 if (i != FoundIndex) 5264 Ops.push_back(Add->getOperand(i)); 5265 const SCEV *Accum = getAddExpr(Ops); 5266 5267 // The runtime checks will not be valid if the step amount is 5268 // varying inside the loop. 5269 if (!isLoopInvariant(Accum, L)) 5270 return None; 5271 5272 // *** Part2: Create the predicates 5273 5274 // Analysis was successful: we have a phi-with-cast pattern for which we 5275 // can return an AddRec expression under the following predicates: 5276 // 5277 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum) 5278 // fits within the truncated type (does not overflow) for i = 0 to n-1. 5279 // P2: An Equal predicate that guarantees that 5280 // Start = (Ext ix (Trunc iy (Start) to ix) to iy) 5281 // P3: An Equal predicate that guarantees that 5282 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy) 5283 // 5284 // As we next prove, the above predicates guarantee that: 5285 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy) 5286 // 5287 // 5288 // More formally, we want to prove that: 5289 // Expr(i+1) = Start + (i+1) * Accum 5290 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 5291 // 5292 // Given that: 5293 // 1) Expr(0) = Start 5294 // 2) Expr(1) = Start + Accum 5295 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2 5296 // 3) Induction hypothesis (step i): 5297 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum 5298 // 5299 // Proof: 5300 // Expr(i+1) = 5301 // = Start + (i+1)*Accum 5302 // = (Start + i*Accum) + Accum 5303 // = Expr(i) + Accum 5304 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum 5305 // :: from step i 5306 // 5307 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum 5308 // 5309 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) 5310 // + (Ext ix (Trunc iy (Accum) to ix) to iy) 5311 // + Accum :: from P3 5312 // 5313 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy) 5314 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y) 5315 // 5316 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum 5317 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 5318 // 5319 // By induction, the same applies to all iterations 1<=i<n: 5320 // 5321 5322 // Create a truncated addrec for which we will add a no overflow check (P1). 5323 const SCEV *StartVal = getSCEV(StartValueV); 5324 const SCEV *PHISCEV = 5325 getAddRecExpr(getTruncateExpr(StartVal, TruncTy), 5326 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap); 5327 5328 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr. 5329 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV 5330 // will be constant. 5331 // 5332 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't 5333 // add P1. 5334 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) { 5335 SCEVWrapPredicate::IncrementWrapFlags AddedFlags = 5336 Signed ? SCEVWrapPredicate::IncrementNSSW 5337 : SCEVWrapPredicate::IncrementNUSW; 5338 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags); 5339 Predicates.push_back(AddRecPred); 5340 } 5341 5342 // Create the Equal Predicates P2,P3: 5343 5344 // It is possible that the predicates P2 and/or P3 are computable at 5345 // compile time due to StartVal and/or Accum being constants. 5346 // If either one is, then we can check that now and escape if either P2 5347 // or P3 is false. 5348 5349 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy) 5350 // for each of StartVal and Accum 5351 auto getExtendedExpr = [&](const SCEV *Expr, 5352 bool CreateSignExtend) -> const SCEV * { 5353 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant"); 5354 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy); 5355 const SCEV *ExtendedExpr = 5356 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType()) 5357 : getZeroExtendExpr(TruncatedExpr, Expr->getType()); 5358 return ExtendedExpr; 5359 }; 5360 5361 // Given: 5362 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy 5363 // = getExtendedExpr(Expr) 5364 // Determine whether the predicate P: Expr == ExtendedExpr 5365 // is known to be false at compile time 5366 auto PredIsKnownFalse = [&](const SCEV *Expr, 5367 const SCEV *ExtendedExpr) -> bool { 5368 return Expr != ExtendedExpr && 5369 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr); 5370 }; 5371 5372 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed); 5373 if (PredIsKnownFalse(StartVal, StartExtended)) { 5374 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";); 5375 return None; 5376 } 5377 5378 // The Step is always Signed (because the overflow checks are either 5379 // NSSW or NUSW) 5380 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true); 5381 if (PredIsKnownFalse(Accum, AccumExtended)) { 5382 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";); 5383 return None; 5384 } 5385 5386 auto AppendPredicate = [&](const SCEV *Expr, 5387 const SCEV *ExtendedExpr) -> void { 5388 if (Expr != ExtendedExpr && 5389 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) { 5390 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr); 5391 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred); 5392 Predicates.push_back(Pred); 5393 } 5394 }; 5395 5396 AppendPredicate(StartVal, StartExtended); 5397 AppendPredicate(Accum, AccumExtended); 5398 5399 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in 5400 // which the casts had been folded away. The caller can rewrite SymbolicPHI 5401 // into NewAR if it will also add the runtime overflow checks specified in 5402 // Predicates. 5403 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap); 5404 5405 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite = 5406 std::make_pair(NewAR, Predicates); 5407 // Remember the result of the analysis for this SCEV at this locayyytion. 5408 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite; 5409 return PredRewrite; 5410 } 5411 5412 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 5413 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) { 5414 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 5415 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 5416 if (!L) 5417 return None; 5418 5419 // Check to see if we already analyzed this PHI. 5420 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L}); 5421 if (I != PredicatedSCEVRewrites.end()) { 5422 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite = 5423 I->second; 5424 // Analysis was done before and failed to create an AddRec: 5425 if (Rewrite.first == SymbolicPHI) 5426 return None; 5427 // Analysis was done before and succeeded to create an AddRec under 5428 // a predicate: 5429 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec"); 5430 assert(!(Rewrite.second).empty() && "Expected to find Predicates"); 5431 return Rewrite; 5432 } 5433 5434 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 5435 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI); 5436 5437 // Record in the cache that the analysis failed 5438 if (!Rewrite) { 5439 SmallVector<const SCEVPredicate *, 3> Predicates; 5440 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates}; 5441 return None; 5442 } 5443 5444 return Rewrite; 5445 } 5446 5447 // FIXME: This utility is currently required because the Rewriter currently 5448 // does not rewrite this expression: 5449 // {0, +, (sext ix (trunc iy to ix) to iy)} 5450 // into {0, +, %step}, 5451 // even when the following Equal predicate exists: 5452 // "%step == (sext ix (trunc iy to ix) to iy)". 5453 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds( 5454 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const { 5455 if (AR1 == AR2) 5456 return true; 5457 5458 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool { 5459 if (Expr1 != Expr2 && !Preds->implies(SE.getEqualPredicate(Expr1, Expr2)) && 5460 !Preds->implies(SE.getEqualPredicate(Expr2, Expr1))) 5461 return false; 5462 return true; 5463 }; 5464 5465 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) || 5466 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE))) 5467 return false; 5468 return true; 5469 } 5470 5471 /// A helper function for createAddRecFromPHI to handle simple cases. 5472 /// 5473 /// This function tries to find an AddRec expression for the simplest (yet most 5474 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)). 5475 /// If it fails, createAddRecFromPHI will use a more general, but slow, 5476 /// technique for finding the AddRec expression. 5477 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN, 5478 Value *BEValueV, 5479 Value *StartValueV) { 5480 const Loop *L = LI.getLoopFor(PN->getParent()); 5481 assert(L && L->getHeader() == PN->getParent()); 5482 assert(BEValueV && StartValueV); 5483 5484 auto BO = MatchBinaryOp(BEValueV, DT); 5485 if (!BO) 5486 return nullptr; 5487 5488 if (BO->Opcode != Instruction::Add) 5489 return nullptr; 5490 5491 const SCEV *Accum = nullptr; 5492 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS)) 5493 Accum = getSCEV(BO->RHS); 5494 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS)) 5495 Accum = getSCEV(BO->LHS); 5496 5497 if (!Accum) 5498 return nullptr; 5499 5500 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5501 if (BO->IsNUW) 5502 Flags = setFlags(Flags, SCEV::FlagNUW); 5503 if (BO->IsNSW) 5504 Flags = setFlags(Flags, SCEV::FlagNSW); 5505 5506 const SCEV *StartVal = getSCEV(StartValueV); 5507 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5508 insertValueToMap(PN, PHISCEV); 5509 5510 // We can add Flags to the post-inc expression only if we 5511 // know that it is *undefined behavior* for BEValueV to 5512 // overflow. 5513 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) { 5514 assert(isLoopInvariant(Accum, L) && 5515 "Accum is defined outside L, but is not invariant?"); 5516 if (isAddRecNeverPoison(BEInst, L)) 5517 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5518 } 5519 5520 return PHISCEV; 5521 } 5522 5523 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 5524 const Loop *L = LI.getLoopFor(PN->getParent()); 5525 if (!L || L->getHeader() != PN->getParent()) 5526 return nullptr; 5527 5528 // The loop may have multiple entrances or multiple exits; we can analyze 5529 // this phi as an addrec if it has a unique entry value and a unique 5530 // backedge value. 5531 Value *BEValueV = nullptr, *StartValueV = nullptr; 5532 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 5533 Value *V = PN->getIncomingValue(i); 5534 if (L->contains(PN->getIncomingBlock(i))) { 5535 if (!BEValueV) { 5536 BEValueV = V; 5537 } else if (BEValueV != V) { 5538 BEValueV = nullptr; 5539 break; 5540 } 5541 } else if (!StartValueV) { 5542 StartValueV = V; 5543 } else if (StartValueV != V) { 5544 StartValueV = nullptr; 5545 break; 5546 } 5547 } 5548 if (!BEValueV || !StartValueV) 5549 return nullptr; 5550 5551 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 5552 "PHI node already processed?"); 5553 5554 // First, try to find AddRec expression without creating a fictituos symbolic 5555 // value for PN. 5556 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV)) 5557 return S; 5558 5559 // Handle PHI node value symbolically. 5560 const SCEV *SymbolicName = getUnknown(PN); 5561 insertValueToMap(PN, SymbolicName); 5562 5563 // Using this symbolic name for the PHI, analyze the value coming around 5564 // the back-edge. 5565 const SCEV *BEValue = getSCEV(BEValueV); 5566 5567 // NOTE: If BEValue is loop invariant, we know that the PHI node just 5568 // has a special value for the first iteration of the loop. 5569 5570 // If the value coming around the backedge is an add with the symbolic 5571 // value we just inserted, then we found a simple induction variable! 5572 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 5573 // If there is a single occurrence of the symbolic value, replace it 5574 // with a recurrence. 5575 unsigned FoundIndex = Add->getNumOperands(); 5576 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5577 if (Add->getOperand(i) == SymbolicName) 5578 if (FoundIndex == e) { 5579 FoundIndex = i; 5580 break; 5581 } 5582 5583 if (FoundIndex != Add->getNumOperands()) { 5584 // Create an add with everything but the specified operand. 5585 SmallVector<const SCEV *, 8> Ops; 5586 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5587 if (i != FoundIndex) 5588 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i), 5589 L, *this)); 5590 const SCEV *Accum = getAddExpr(Ops); 5591 5592 // This is not a valid addrec if the step amount is varying each 5593 // loop iteration, but is not itself an addrec in this loop. 5594 if (isLoopInvariant(Accum, L) || 5595 (isa<SCEVAddRecExpr>(Accum) && 5596 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 5597 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5598 5599 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 5600 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 5601 if (BO->IsNUW) 5602 Flags = setFlags(Flags, SCEV::FlagNUW); 5603 if (BO->IsNSW) 5604 Flags = setFlags(Flags, SCEV::FlagNSW); 5605 } 5606 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 5607 // If the increment is an inbounds GEP, then we know the address 5608 // space cannot be wrapped around. We cannot make any guarantee 5609 // about signed or unsigned overflow because pointers are 5610 // unsigned but we may have a negative index from the base 5611 // pointer. We can guarantee that no unsigned wrap occurs if the 5612 // indices form a positive value. 5613 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 5614 Flags = setFlags(Flags, SCEV::FlagNW); 5615 5616 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 5617 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 5618 Flags = setFlags(Flags, SCEV::FlagNUW); 5619 } 5620 5621 // We cannot transfer nuw and nsw flags from subtraction 5622 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 5623 // for instance. 5624 } 5625 5626 const SCEV *StartVal = getSCEV(StartValueV); 5627 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5628 5629 // Okay, for the entire analysis of this edge we assumed the PHI 5630 // to be symbolic. We now need to go back and purge all of the 5631 // entries for the scalars that use the symbolic expression. 5632 forgetMemoizedResults(SymbolicName); 5633 insertValueToMap(PN, PHISCEV); 5634 5635 // We can add Flags to the post-inc expression only if we 5636 // know that it is *undefined behavior* for BEValueV to 5637 // overflow. 5638 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5639 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5640 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5641 5642 return PHISCEV; 5643 } 5644 } 5645 } else { 5646 // Otherwise, this could be a loop like this: 5647 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 5648 // In this case, j = {1,+,1} and BEValue is j. 5649 // Because the other in-value of i (0) fits the evolution of BEValue 5650 // i really is an addrec evolution. 5651 // 5652 // We can generalize this saying that i is the shifted value of BEValue 5653 // by one iteration: 5654 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 5655 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 5656 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false); 5657 if (Shifted != getCouldNotCompute() && 5658 Start != getCouldNotCompute()) { 5659 const SCEV *StartVal = getSCEV(StartValueV); 5660 if (Start == StartVal) { 5661 // Okay, for the entire analysis of this edge we assumed the PHI 5662 // to be symbolic. We now need to go back and purge all of the 5663 // entries for the scalars that use the symbolic expression. 5664 forgetMemoizedResults(SymbolicName); 5665 insertValueToMap(PN, Shifted); 5666 return Shifted; 5667 } 5668 } 5669 } 5670 5671 // Remove the temporary PHI node SCEV that has been inserted while intending 5672 // to create an AddRecExpr for this PHI node. We can not keep this temporary 5673 // as it will prevent later (possibly simpler) SCEV expressions to be added 5674 // to the ValueExprMap. 5675 eraseValueFromMap(PN); 5676 5677 return nullptr; 5678 } 5679 5680 // Checks if the SCEV S is available at BB. S is considered available at BB 5681 // if S can be materialized at BB without introducing a fault. 5682 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 5683 BasicBlock *BB) { 5684 struct CheckAvailable { 5685 bool TraversalDone = false; 5686 bool Available = true; 5687 5688 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 5689 BasicBlock *BB = nullptr; 5690 DominatorTree &DT; 5691 5692 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 5693 : L(L), BB(BB), DT(DT) {} 5694 5695 bool setUnavailable() { 5696 TraversalDone = true; 5697 Available = false; 5698 return false; 5699 } 5700 5701 bool follow(const SCEV *S) { 5702 switch (S->getSCEVType()) { 5703 case scConstant: 5704 case scPtrToInt: 5705 case scTruncate: 5706 case scZeroExtend: 5707 case scSignExtend: 5708 case scAddExpr: 5709 case scMulExpr: 5710 case scUMaxExpr: 5711 case scSMaxExpr: 5712 case scUMinExpr: 5713 case scSMinExpr: 5714 case scSequentialUMinExpr: 5715 // These expressions are available if their operand(s) is/are. 5716 return true; 5717 5718 case scAddRecExpr: { 5719 // We allow add recurrences that are on the loop BB is in, or some 5720 // outer loop. This guarantees availability because the value of the 5721 // add recurrence at BB is simply the "current" value of the induction 5722 // variable. We can relax this in the future; for instance an add 5723 // recurrence on a sibling dominating loop is also available at BB. 5724 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 5725 if (L && (ARLoop == L || ARLoop->contains(L))) 5726 return true; 5727 5728 return setUnavailable(); 5729 } 5730 5731 case scUnknown: { 5732 // For SCEVUnknown, we check for simple dominance. 5733 const auto *SU = cast<SCEVUnknown>(S); 5734 Value *V = SU->getValue(); 5735 5736 if (isa<Argument>(V)) 5737 return false; 5738 5739 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 5740 return false; 5741 5742 return setUnavailable(); 5743 } 5744 5745 case scUDivExpr: 5746 case scCouldNotCompute: 5747 // We do not try to smart about these at all. 5748 return setUnavailable(); 5749 } 5750 llvm_unreachable("Unknown SCEV kind!"); 5751 } 5752 5753 bool isDone() { return TraversalDone; } 5754 }; 5755 5756 CheckAvailable CA(L, BB, DT); 5757 SCEVTraversal<CheckAvailable> ST(CA); 5758 5759 ST.visitAll(S); 5760 return CA.Available; 5761 } 5762 5763 // Try to match a control flow sequence that branches out at BI and merges back 5764 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 5765 // match. 5766 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 5767 Value *&C, Value *&LHS, Value *&RHS) { 5768 C = BI->getCondition(); 5769 5770 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 5771 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 5772 5773 if (!LeftEdge.isSingleEdge()) 5774 return false; 5775 5776 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 5777 5778 Use &LeftUse = Merge->getOperandUse(0); 5779 Use &RightUse = Merge->getOperandUse(1); 5780 5781 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 5782 LHS = LeftUse; 5783 RHS = RightUse; 5784 return true; 5785 } 5786 5787 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 5788 LHS = RightUse; 5789 RHS = LeftUse; 5790 return true; 5791 } 5792 5793 return false; 5794 } 5795 5796 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 5797 auto IsReachable = 5798 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 5799 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 5800 const Loop *L = LI.getLoopFor(PN->getParent()); 5801 5802 // We don't want to break LCSSA, even in a SCEV expression tree. 5803 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 5804 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 5805 return nullptr; 5806 5807 // Try to match 5808 // 5809 // br %cond, label %left, label %right 5810 // left: 5811 // br label %merge 5812 // right: 5813 // br label %merge 5814 // merge: 5815 // V = phi [ %x, %left ], [ %y, %right ] 5816 // 5817 // as "select %cond, %x, %y" 5818 5819 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 5820 assert(IDom && "At least the entry block should dominate PN"); 5821 5822 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 5823 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 5824 5825 if (BI && BI->isConditional() && 5826 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 5827 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 5828 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 5829 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 5830 } 5831 5832 return nullptr; 5833 } 5834 5835 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 5836 if (const SCEV *S = createAddRecFromPHI(PN)) 5837 return S; 5838 5839 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 5840 return S; 5841 5842 // If the PHI has a single incoming value, follow that value, unless the 5843 // PHI's incoming blocks are in a different loop, in which case doing so 5844 // risks breaking LCSSA form. Instcombine would normally zap these, but 5845 // it doesn't have DominatorTree information, so it may miss cases. 5846 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC})) 5847 if (LI.replacementPreservesLCSSAForm(PN, V)) 5848 return getSCEV(V); 5849 5850 // If it's not a loop phi, we can't handle it yet. 5851 return getUnknown(PN); 5852 } 5853 5854 bool SCEVMinMaxExprContains(const SCEV *Root, const SCEV *OperandToFind, 5855 SCEVTypes RootKind) { 5856 struct FindClosure { 5857 const SCEV *OperandToFind; 5858 const SCEVTypes RootKind; // Must be a sequential min/max expression. 5859 const SCEVTypes NonSequentialRootKind; // Non-seq variant of RootKind. 5860 5861 bool Found = false; 5862 5863 bool canRecurseInto(SCEVTypes Kind) const { 5864 // We can only recurse into the SCEV expression of the same effective type 5865 // as the type of our root SCEV expression, and into zero-extensions. 5866 return RootKind == Kind || NonSequentialRootKind == Kind || 5867 scZeroExtend == Kind; 5868 }; 5869 5870 FindClosure(const SCEV *OperandToFind, SCEVTypes RootKind) 5871 : OperandToFind(OperandToFind), RootKind(RootKind), 5872 NonSequentialRootKind( 5873 SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType( 5874 RootKind)) {} 5875 5876 bool follow(const SCEV *S) { 5877 Found = S == OperandToFind; 5878 5879 return !isDone() && canRecurseInto(S->getSCEVType()); 5880 } 5881 5882 bool isDone() const { return Found; } 5883 }; 5884 5885 FindClosure FC(OperandToFind, RootKind); 5886 visitAll(Root, FC); 5887 return FC.Found; 5888 } 5889 5890 const SCEV *ScalarEvolution::createNodeForSelectOrPHIInstWithICmpInstCond( 5891 Instruction *I, ICmpInst *Cond, Value *TrueVal, Value *FalseVal) { 5892 // Try to match some simple smax or umax patterns. 5893 auto *ICI = Cond; 5894 5895 Value *LHS = ICI->getOperand(0); 5896 Value *RHS = ICI->getOperand(1); 5897 5898 switch (ICI->getPredicate()) { 5899 case ICmpInst::ICMP_SLT: 5900 case ICmpInst::ICMP_SLE: 5901 case ICmpInst::ICMP_ULT: 5902 case ICmpInst::ICMP_ULE: 5903 std::swap(LHS, RHS); 5904 LLVM_FALLTHROUGH; 5905 case ICmpInst::ICMP_SGT: 5906 case ICmpInst::ICMP_SGE: 5907 case ICmpInst::ICMP_UGT: 5908 case ICmpInst::ICMP_UGE: 5909 // a > b ? a+x : b+x -> max(a, b)+x 5910 // a > b ? b+x : a+x -> min(a, b)+x 5911 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5912 bool Signed = ICI->isSigned(); 5913 const SCEV *LA = getSCEV(TrueVal); 5914 const SCEV *RA = getSCEV(FalseVal); 5915 const SCEV *LS = getSCEV(LHS); 5916 const SCEV *RS = getSCEV(RHS); 5917 if (LA->getType()->isPointerTy()) { 5918 // FIXME: Handle cases where LS/RS are pointers not equal to LA/RA. 5919 // Need to make sure we can't produce weird expressions involving 5920 // negated pointers. 5921 if (LA == LS && RA == RS) 5922 return Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS); 5923 if (LA == RS && RA == LS) 5924 return Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS); 5925 } 5926 auto CoerceOperand = [&](const SCEV *Op) -> const SCEV * { 5927 if (Op->getType()->isPointerTy()) { 5928 Op = getLosslessPtrToIntExpr(Op); 5929 if (isa<SCEVCouldNotCompute>(Op)) 5930 return Op; 5931 } 5932 if (Signed) 5933 Op = getNoopOrSignExtend(Op, I->getType()); 5934 else 5935 Op = getNoopOrZeroExtend(Op, I->getType()); 5936 return Op; 5937 }; 5938 LS = CoerceOperand(LS); 5939 RS = CoerceOperand(RS); 5940 if (isa<SCEVCouldNotCompute>(LS) || isa<SCEVCouldNotCompute>(RS)) 5941 break; 5942 const SCEV *LDiff = getMinusSCEV(LA, LS); 5943 const SCEV *RDiff = getMinusSCEV(RA, RS); 5944 if (LDiff == RDiff) 5945 return getAddExpr(Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS), 5946 LDiff); 5947 LDiff = getMinusSCEV(LA, RS); 5948 RDiff = getMinusSCEV(RA, LS); 5949 if (LDiff == RDiff) 5950 return getAddExpr(Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS), 5951 LDiff); 5952 } 5953 break; 5954 case ICmpInst::ICMP_NE: 5955 // x != 0 ? x+y : C+y -> x == 0 ? C+y : x+y 5956 std::swap(TrueVal, FalseVal); 5957 LLVM_FALLTHROUGH; 5958 case ICmpInst::ICMP_EQ: 5959 // x == 0 ? C+y : x+y -> umax(x, C)+y iff C u<= 1 5960 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5961 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5962 const SCEV *X = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5963 const SCEV *TrueValExpr = getSCEV(TrueVal); // C+y 5964 const SCEV *FalseValExpr = getSCEV(FalseVal); // x+y 5965 const SCEV *Y = getMinusSCEV(FalseValExpr, X); // y = (x+y)-x 5966 const SCEV *C = getMinusSCEV(TrueValExpr, Y); // C = (C+y)-y 5967 if (isa<SCEVConstant>(C) && cast<SCEVConstant>(C)->getAPInt().ule(1)) 5968 return getAddExpr(getUMaxExpr(X, C), Y); 5969 } 5970 // x == 0 ? 0 : umin (..., x, ...) -> umin_seq(x, umin (...)) 5971 // x == 0 ? 0 : umin_seq(..., x, ...) -> umin_seq(x, umin_seq(...)) 5972 // x == 0 ? 0 : umin (..., umin_seq(..., x, ...), ...) 5973 // -> umin_seq(x, umin (..., umin_seq(...), ...)) 5974 if (isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero() && 5975 isa<ConstantInt>(TrueVal) && cast<ConstantInt>(TrueVal)->isZero()) { 5976 const SCEV *X = getSCEV(LHS); 5977 while (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(X)) 5978 X = ZExt->getOperand(); 5979 if (getTypeSizeInBits(X->getType()) <= getTypeSizeInBits(I->getType())) { 5980 const SCEV *FalseValExpr = getSCEV(FalseVal); 5981 if (SCEVMinMaxExprContains(FalseValExpr, X, scSequentialUMinExpr)) 5982 return getUMinExpr(getNoopOrZeroExtend(X, I->getType()), FalseValExpr, 5983 /*Sequential=*/true); 5984 } 5985 } 5986 break; 5987 default: 5988 break; 5989 } 5990 5991 return getUnknown(I); 5992 } 5993 5994 const SCEV *ScalarEvolution::createNodeForSelectOrPHIViaUMinSeq( 5995 Value *V, Value *Cond, Value *TrueVal, Value *FalseVal) { 5996 // For now, only deal with i1-typed `select`s. 5997 if (!V->getType()->isIntegerTy(1) || !Cond->getType()->isIntegerTy(1) || 5998 !TrueVal->getType()->isIntegerTy(1) || 5999 !FalseVal->getType()->isIntegerTy(1)) 6000 return getUnknown(V); 6001 6002 // i1 cond ? i1 x : i1 C --> C + (i1 cond ? (i1 x - i1 C) : i1 0) 6003 // --> C + (umin_seq cond, x - C) 6004 // 6005 // i1 cond ? i1 C : i1 x --> C + (i1 cond ? i1 0 : (i1 x - i1 C)) 6006 // --> C + (i1 ~cond ? (i1 x - i1 C) : i1 0) 6007 // --> C + (umin_seq ~cond, x - C) 6008 if (isa<ConstantInt>(TrueVal) || isa<ConstantInt>(FalseVal)) { 6009 const SCEV *CondExpr = getSCEV(Cond); 6010 const SCEV *TrueExpr = getSCEV(TrueVal); 6011 const SCEV *FalseExpr = getSCEV(FalseVal); 6012 const SCEV *X, *C; 6013 if (isa<ConstantInt>(TrueVal)) { 6014 CondExpr = getNotSCEV(CondExpr); 6015 X = FalseExpr; 6016 C = TrueExpr; 6017 } else { 6018 X = TrueExpr; 6019 C = FalseExpr; 6020 } 6021 return getAddExpr( 6022 C, getUMinExpr(CondExpr, getMinusSCEV(X, C), /*Sequential=*/true)); 6023 } 6024 6025 return getUnknown(V); 6026 } 6027 6028 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Value *V, Value *Cond, 6029 Value *TrueVal, 6030 Value *FalseVal) { 6031 // Handle "constant" branch or select. This can occur for instance when a 6032 // loop pass transforms an inner loop and moves on to process the outer loop. 6033 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 6034 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 6035 6036 if (auto *I = dyn_cast<Instruction>(V)) { 6037 if (auto *ICI = dyn_cast<ICmpInst>(Cond)) { 6038 const SCEV *S = createNodeForSelectOrPHIInstWithICmpInstCond( 6039 I, ICI, TrueVal, FalseVal); 6040 if (!isa<SCEVUnknown>(S)) 6041 return S; 6042 } 6043 } 6044 6045 return createNodeForSelectOrPHIViaUMinSeq(V, Cond, TrueVal, FalseVal); 6046 } 6047 6048 /// Expand GEP instructions into add and multiply operations. This allows them 6049 /// to be analyzed by regular SCEV code. 6050 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 6051 // Don't attempt to analyze GEPs over unsized objects. 6052 if (!GEP->getSourceElementType()->isSized()) 6053 return getUnknown(GEP); 6054 6055 SmallVector<const SCEV *, 4> IndexExprs; 6056 for (Value *Index : GEP->indices()) 6057 IndexExprs.push_back(getSCEV(Index)); 6058 return getGEPExpr(GEP, IndexExprs); 6059 } 6060 6061 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) { 6062 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 6063 return C->getAPInt().countTrailingZeros(); 6064 6065 if (const SCEVPtrToIntExpr *I = dyn_cast<SCEVPtrToIntExpr>(S)) 6066 return GetMinTrailingZeros(I->getOperand()); 6067 6068 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 6069 return std::min(GetMinTrailingZeros(T->getOperand()), 6070 (uint32_t)getTypeSizeInBits(T->getType())); 6071 6072 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 6073 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 6074 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 6075 ? getTypeSizeInBits(E->getType()) 6076 : OpRes; 6077 } 6078 6079 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 6080 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 6081 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 6082 ? getTypeSizeInBits(E->getType()) 6083 : OpRes; 6084 } 6085 6086 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 6087 // The result is the min of all operands results. 6088 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 6089 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 6090 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 6091 return MinOpRes; 6092 } 6093 6094 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 6095 // The result is the sum of all operands results. 6096 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 6097 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 6098 for (unsigned i = 1, e = M->getNumOperands(); 6099 SumOpRes != BitWidth && i != e; ++i) 6100 SumOpRes = 6101 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth); 6102 return SumOpRes; 6103 } 6104 6105 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 6106 // The result is the min of all operands results. 6107 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 6108 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 6109 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 6110 return MinOpRes; 6111 } 6112 6113 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 6114 // The result is the min of all operands results. 6115 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 6116 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 6117 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 6118 return MinOpRes; 6119 } 6120 6121 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 6122 // The result is the min of all operands results. 6123 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 6124 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 6125 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 6126 return MinOpRes; 6127 } 6128 6129 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 6130 // For a SCEVUnknown, ask ValueTracking. 6131 KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT); 6132 return Known.countMinTrailingZeros(); 6133 } 6134 6135 // SCEVUDivExpr 6136 return 0; 6137 } 6138 6139 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 6140 auto I = MinTrailingZerosCache.find(S); 6141 if (I != MinTrailingZerosCache.end()) 6142 return I->second; 6143 6144 uint32_t Result = GetMinTrailingZerosImpl(S); 6145 auto InsertPair = MinTrailingZerosCache.insert({S, Result}); 6146 assert(InsertPair.second && "Should insert a new key"); 6147 return InsertPair.first->second; 6148 } 6149 6150 /// Helper method to assign a range to V from metadata present in the IR. 6151 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 6152 if (Instruction *I = dyn_cast<Instruction>(V)) 6153 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 6154 return getConstantRangeFromMetadata(*MD); 6155 6156 return None; 6157 } 6158 6159 void ScalarEvolution::setNoWrapFlags(SCEVAddRecExpr *AddRec, 6160 SCEV::NoWrapFlags Flags) { 6161 if (AddRec->getNoWrapFlags(Flags) != Flags) { 6162 AddRec->setNoWrapFlags(Flags); 6163 UnsignedRanges.erase(AddRec); 6164 SignedRanges.erase(AddRec); 6165 } 6166 } 6167 6168 ConstantRange ScalarEvolution:: 6169 getRangeForUnknownRecurrence(const SCEVUnknown *U) { 6170 const DataLayout &DL = getDataLayout(); 6171 6172 unsigned BitWidth = getTypeSizeInBits(U->getType()); 6173 const ConstantRange FullSet(BitWidth, /*isFullSet=*/true); 6174 6175 // Match a simple recurrence of the form: <start, ShiftOp, Step>, and then 6176 // use information about the trip count to improve our available range. Note 6177 // that the trip count independent cases are already handled by known bits. 6178 // WARNING: The definition of recurrence used here is subtly different than 6179 // the one used by AddRec (and thus most of this file). Step is allowed to 6180 // be arbitrarily loop varying here, where AddRec allows only loop invariant 6181 // and other addrecs in the same loop (for non-affine addrecs). The code 6182 // below intentionally handles the case where step is not loop invariant. 6183 auto *P = dyn_cast<PHINode>(U->getValue()); 6184 if (!P) 6185 return FullSet; 6186 6187 // Make sure that no Phi input comes from an unreachable block. Otherwise, 6188 // even the values that are not available in these blocks may come from them, 6189 // and this leads to false-positive recurrence test. 6190 for (auto *Pred : predecessors(P->getParent())) 6191 if (!DT.isReachableFromEntry(Pred)) 6192 return FullSet; 6193 6194 BinaryOperator *BO; 6195 Value *Start, *Step; 6196 if (!matchSimpleRecurrence(P, BO, Start, Step)) 6197 return FullSet; 6198 6199 // If we found a recurrence in reachable code, we must be in a loop. Note 6200 // that BO might be in some subloop of L, and that's completely okay. 6201 auto *L = LI.getLoopFor(P->getParent()); 6202 assert(L && L->getHeader() == P->getParent()); 6203 if (!L->contains(BO->getParent())) 6204 // NOTE: This bailout should be an assert instead. However, asserting 6205 // the condition here exposes a case where LoopFusion is querying SCEV 6206 // with malformed loop information during the midst of the transform. 6207 // There doesn't appear to be an obvious fix, so for the moment bailout 6208 // until the caller issue can be fixed. PR49566 tracks the bug. 6209 return FullSet; 6210 6211 // TODO: Extend to other opcodes such as mul, and div 6212 switch (BO->getOpcode()) { 6213 default: 6214 return FullSet; 6215 case Instruction::AShr: 6216 case Instruction::LShr: 6217 case Instruction::Shl: 6218 break; 6219 }; 6220 6221 if (BO->getOperand(0) != P) 6222 // TODO: Handle the power function forms some day. 6223 return FullSet; 6224 6225 unsigned TC = getSmallConstantMaxTripCount(L); 6226 if (!TC || TC >= BitWidth) 6227 return FullSet; 6228 6229 auto KnownStart = computeKnownBits(Start, DL, 0, &AC, nullptr, &DT); 6230 auto KnownStep = computeKnownBits(Step, DL, 0, &AC, nullptr, &DT); 6231 assert(KnownStart.getBitWidth() == BitWidth && 6232 KnownStep.getBitWidth() == BitWidth); 6233 6234 // Compute total shift amount, being careful of overflow and bitwidths. 6235 auto MaxShiftAmt = KnownStep.getMaxValue(); 6236 APInt TCAP(BitWidth, TC-1); 6237 bool Overflow = false; 6238 auto TotalShift = MaxShiftAmt.umul_ov(TCAP, Overflow); 6239 if (Overflow) 6240 return FullSet; 6241 6242 switch (BO->getOpcode()) { 6243 default: 6244 llvm_unreachable("filtered out above"); 6245 case Instruction::AShr: { 6246 // For each ashr, three cases: 6247 // shift = 0 => unchanged value 6248 // saturation => 0 or -1 6249 // other => a value closer to zero (of the same sign) 6250 // Thus, the end value is closer to zero than the start. 6251 auto KnownEnd = KnownBits::ashr(KnownStart, 6252 KnownBits::makeConstant(TotalShift)); 6253 if (KnownStart.isNonNegative()) 6254 // Analogous to lshr (simply not yet canonicalized) 6255 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(), 6256 KnownStart.getMaxValue() + 1); 6257 if (KnownStart.isNegative()) 6258 // End >=u Start && End <=s Start 6259 return ConstantRange::getNonEmpty(KnownStart.getMinValue(), 6260 KnownEnd.getMaxValue() + 1); 6261 break; 6262 } 6263 case Instruction::LShr: { 6264 // For each lshr, three cases: 6265 // shift = 0 => unchanged value 6266 // saturation => 0 6267 // other => a smaller positive number 6268 // Thus, the low end of the unsigned range is the last value produced. 6269 auto KnownEnd = KnownBits::lshr(KnownStart, 6270 KnownBits::makeConstant(TotalShift)); 6271 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(), 6272 KnownStart.getMaxValue() + 1); 6273 } 6274 case Instruction::Shl: { 6275 // Iff no bits are shifted out, value increases on every shift. 6276 auto KnownEnd = KnownBits::shl(KnownStart, 6277 KnownBits::makeConstant(TotalShift)); 6278 if (TotalShift.ult(KnownStart.countMinLeadingZeros())) 6279 return ConstantRange(KnownStart.getMinValue(), 6280 KnownEnd.getMaxValue() + 1); 6281 break; 6282 } 6283 }; 6284 return FullSet; 6285 } 6286 6287 /// Determine the range for a particular SCEV. If SignHint is 6288 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 6289 /// with a "cleaner" unsigned (resp. signed) representation. 6290 const ConstantRange & 6291 ScalarEvolution::getRangeRef(const SCEV *S, 6292 ScalarEvolution::RangeSignHint SignHint) { 6293 DenseMap<const SCEV *, ConstantRange> &Cache = 6294 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 6295 : SignedRanges; 6296 ConstantRange::PreferredRangeType RangeType = 6297 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED 6298 ? ConstantRange::Unsigned : ConstantRange::Signed; 6299 6300 // See if we've computed this range already. 6301 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 6302 if (I != Cache.end()) 6303 return I->second; 6304 6305 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 6306 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 6307 6308 unsigned BitWidth = getTypeSizeInBits(S->getType()); 6309 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 6310 using OBO = OverflowingBinaryOperator; 6311 6312 // If the value has known zeros, the maximum value will have those known zeros 6313 // as well. 6314 uint32_t TZ = GetMinTrailingZeros(S); 6315 if (TZ != 0) { 6316 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 6317 ConservativeResult = 6318 ConstantRange(APInt::getMinValue(BitWidth), 6319 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 6320 else 6321 ConservativeResult = ConstantRange( 6322 APInt::getSignedMinValue(BitWidth), 6323 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 6324 } 6325 6326 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 6327 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint); 6328 unsigned WrapType = OBO::AnyWrap; 6329 if (Add->hasNoSignedWrap()) 6330 WrapType |= OBO::NoSignedWrap; 6331 if (Add->hasNoUnsignedWrap()) 6332 WrapType |= OBO::NoUnsignedWrap; 6333 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 6334 X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint), 6335 WrapType, RangeType); 6336 return setRange(Add, SignHint, 6337 ConservativeResult.intersectWith(X, RangeType)); 6338 } 6339 6340 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 6341 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint); 6342 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 6343 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint)); 6344 return setRange(Mul, SignHint, 6345 ConservativeResult.intersectWith(X, RangeType)); 6346 } 6347 6348 if (isa<SCEVMinMaxExpr>(S) || isa<SCEVSequentialMinMaxExpr>(S)) { 6349 Intrinsic::ID ID; 6350 switch (S->getSCEVType()) { 6351 case scUMaxExpr: 6352 ID = Intrinsic::umax; 6353 break; 6354 case scSMaxExpr: 6355 ID = Intrinsic::smax; 6356 break; 6357 case scUMinExpr: 6358 case scSequentialUMinExpr: 6359 ID = Intrinsic::umin; 6360 break; 6361 case scSMinExpr: 6362 ID = Intrinsic::smin; 6363 break; 6364 default: 6365 llvm_unreachable("Unknown SCEVMinMaxExpr/SCEVSequentialMinMaxExpr."); 6366 } 6367 6368 const auto *NAry = cast<SCEVNAryExpr>(S); 6369 ConstantRange X = getRangeRef(NAry->getOperand(0), SignHint); 6370 for (unsigned i = 1, e = NAry->getNumOperands(); i != e; ++i) 6371 X = X.intrinsic(ID, {X, getRangeRef(NAry->getOperand(i), SignHint)}); 6372 return setRange(S, SignHint, 6373 ConservativeResult.intersectWith(X, RangeType)); 6374 } 6375 6376 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 6377 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint); 6378 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint); 6379 return setRange(UDiv, SignHint, 6380 ConservativeResult.intersectWith(X.udiv(Y), RangeType)); 6381 } 6382 6383 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 6384 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint); 6385 return setRange(ZExt, SignHint, 6386 ConservativeResult.intersectWith(X.zeroExtend(BitWidth), 6387 RangeType)); 6388 } 6389 6390 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 6391 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint); 6392 return setRange(SExt, SignHint, 6393 ConservativeResult.intersectWith(X.signExtend(BitWidth), 6394 RangeType)); 6395 } 6396 6397 if (const SCEVPtrToIntExpr *PtrToInt = dyn_cast<SCEVPtrToIntExpr>(S)) { 6398 ConstantRange X = getRangeRef(PtrToInt->getOperand(), SignHint); 6399 return setRange(PtrToInt, SignHint, X); 6400 } 6401 6402 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 6403 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint); 6404 return setRange(Trunc, SignHint, 6405 ConservativeResult.intersectWith(X.truncate(BitWidth), 6406 RangeType)); 6407 } 6408 6409 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 6410 // If there's no unsigned wrap, the value will never be less than its 6411 // initial value. 6412 if (AddRec->hasNoUnsignedWrap()) { 6413 APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart()); 6414 if (!UnsignedMinValue.isZero()) 6415 ConservativeResult = ConservativeResult.intersectWith( 6416 ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType); 6417 } 6418 6419 // If there's no signed wrap, and all the operands except initial value have 6420 // the same sign or zero, the value won't ever be: 6421 // 1: smaller than initial value if operands are non negative, 6422 // 2: bigger than initial value if operands are non positive. 6423 // For both cases, value can not cross signed min/max boundary. 6424 if (AddRec->hasNoSignedWrap()) { 6425 bool AllNonNeg = true; 6426 bool AllNonPos = true; 6427 for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) { 6428 if (!isKnownNonNegative(AddRec->getOperand(i))) 6429 AllNonNeg = false; 6430 if (!isKnownNonPositive(AddRec->getOperand(i))) 6431 AllNonPos = false; 6432 } 6433 if (AllNonNeg) 6434 ConservativeResult = ConservativeResult.intersectWith( 6435 ConstantRange::getNonEmpty(getSignedRangeMin(AddRec->getStart()), 6436 APInt::getSignedMinValue(BitWidth)), 6437 RangeType); 6438 else if (AllNonPos) 6439 ConservativeResult = ConservativeResult.intersectWith( 6440 ConstantRange::getNonEmpty( 6441 APInt::getSignedMinValue(BitWidth), 6442 getSignedRangeMax(AddRec->getStart()) + 1), 6443 RangeType); 6444 } 6445 6446 // TODO: non-affine addrec 6447 if (AddRec->isAffine()) { 6448 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop()); 6449 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 6450 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 6451 auto RangeFromAffine = getRangeForAffineAR( 6452 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 6453 BitWidth); 6454 ConservativeResult = 6455 ConservativeResult.intersectWith(RangeFromAffine, RangeType); 6456 6457 auto RangeFromFactoring = getRangeViaFactoring( 6458 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 6459 BitWidth); 6460 ConservativeResult = 6461 ConservativeResult.intersectWith(RangeFromFactoring, RangeType); 6462 } 6463 6464 // Now try symbolic BE count and more powerful methods. 6465 if (UseExpensiveRangeSharpening) { 6466 const SCEV *SymbolicMaxBECount = 6467 getSymbolicMaxBackedgeTakenCount(AddRec->getLoop()); 6468 if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) && 6469 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 6470 AddRec->hasNoSelfWrap()) { 6471 auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR( 6472 AddRec, SymbolicMaxBECount, BitWidth, SignHint); 6473 ConservativeResult = 6474 ConservativeResult.intersectWith(RangeFromAffineNew, RangeType); 6475 } 6476 } 6477 } 6478 6479 return setRange(AddRec, SignHint, std::move(ConservativeResult)); 6480 } 6481 6482 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 6483 6484 // Check if the IR explicitly contains !range metadata. 6485 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 6486 if (MDRange.hasValue()) 6487 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(), 6488 RangeType); 6489 6490 // Use facts about recurrences in the underlying IR. Note that add 6491 // recurrences are AddRecExprs and thus don't hit this path. This 6492 // primarily handles shift recurrences. 6493 auto CR = getRangeForUnknownRecurrence(U); 6494 ConservativeResult = ConservativeResult.intersectWith(CR); 6495 6496 // See if ValueTracking can give us a useful range. 6497 const DataLayout &DL = getDataLayout(); 6498 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 6499 if (Known.getBitWidth() != BitWidth) 6500 Known = Known.zextOrTrunc(BitWidth); 6501 6502 // ValueTracking may be able to compute a tighter result for the number of 6503 // sign bits than for the value of those sign bits. 6504 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 6505 if (U->getType()->isPointerTy()) { 6506 // If the pointer size is larger than the index size type, this can cause 6507 // NS to be larger than BitWidth. So compensate for this. 6508 unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType()); 6509 int ptrIdxDiff = ptrSize - BitWidth; 6510 if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff) 6511 NS -= ptrIdxDiff; 6512 } 6513 6514 if (NS > 1) { 6515 // If we know any of the sign bits, we know all of the sign bits. 6516 if (!Known.Zero.getHiBits(NS).isZero()) 6517 Known.Zero.setHighBits(NS); 6518 if (!Known.One.getHiBits(NS).isZero()) 6519 Known.One.setHighBits(NS); 6520 } 6521 6522 if (Known.getMinValue() != Known.getMaxValue() + 1) 6523 ConservativeResult = ConservativeResult.intersectWith( 6524 ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1), 6525 RangeType); 6526 if (NS > 1) 6527 ConservativeResult = ConservativeResult.intersectWith( 6528 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 6529 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1), 6530 RangeType); 6531 6532 // A range of Phi is a subset of union of all ranges of its input. 6533 if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) { 6534 // Make sure that we do not run over cycled Phis. 6535 if (PendingPhiRanges.insert(Phi).second) { 6536 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false); 6537 for (auto &Op : Phi->operands()) { 6538 auto OpRange = getRangeRef(getSCEV(Op), SignHint); 6539 RangeFromOps = RangeFromOps.unionWith(OpRange); 6540 // No point to continue if we already have a full set. 6541 if (RangeFromOps.isFullSet()) 6542 break; 6543 } 6544 ConservativeResult = 6545 ConservativeResult.intersectWith(RangeFromOps, RangeType); 6546 bool Erased = PendingPhiRanges.erase(Phi); 6547 assert(Erased && "Failed to erase Phi properly?"); 6548 (void) Erased; 6549 } 6550 } 6551 6552 return setRange(U, SignHint, std::move(ConservativeResult)); 6553 } 6554 6555 return setRange(S, SignHint, std::move(ConservativeResult)); 6556 } 6557 6558 // Given a StartRange, Step and MaxBECount for an expression compute a range of 6559 // values that the expression can take. Initially, the expression has a value 6560 // from StartRange and then is changed by Step up to MaxBECount times. Signed 6561 // argument defines if we treat Step as signed or unsigned. 6562 static ConstantRange getRangeForAffineARHelper(APInt Step, 6563 const ConstantRange &StartRange, 6564 const APInt &MaxBECount, 6565 unsigned BitWidth, bool Signed) { 6566 // If either Step or MaxBECount is 0, then the expression won't change, and we 6567 // just need to return the initial range. 6568 if (Step == 0 || MaxBECount == 0) 6569 return StartRange; 6570 6571 // If we don't know anything about the initial value (i.e. StartRange is 6572 // FullRange), then we don't know anything about the final range either. 6573 // Return FullRange. 6574 if (StartRange.isFullSet()) 6575 return ConstantRange::getFull(BitWidth); 6576 6577 // If Step is signed and negative, then we use its absolute value, but we also 6578 // note that we're moving in the opposite direction. 6579 bool Descending = Signed && Step.isNegative(); 6580 6581 if (Signed) 6582 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this: 6583 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128. 6584 // This equations hold true due to the well-defined wrap-around behavior of 6585 // APInt. 6586 Step = Step.abs(); 6587 6588 // Check if Offset is more than full span of BitWidth. If it is, the 6589 // expression is guaranteed to overflow. 6590 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount)) 6591 return ConstantRange::getFull(BitWidth); 6592 6593 // Offset is by how much the expression can change. Checks above guarantee no 6594 // overflow here. 6595 APInt Offset = Step * MaxBECount; 6596 6597 // Minimum value of the final range will match the minimal value of StartRange 6598 // if the expression is increasing and will be decreased by Offset otherwise. 6599 // Maximum value of the final range will match the maximal value of StartRange 6600 // if the expression is decreasing and will be increased by Offset otherwise. 6601 APInt StartLower = StartRange.getLower(); 6602 APInt StartUpper = StartRange.getUpper() - 1; 6603 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset)) 6604 : (StartUpper + std::move(Offset)); 6605 6606 // It's possible that the new minimum/maximum value will fall into the initial 6607 // range (due to wrap around). This means that the expression can take any 6608 // value in this bitwidth, and we have to return full range. 6609 if (StartRange.contains(MovedBoundary)) 6610 return ConstantRange::getFull(BitWidth); 6611 6612 APInt NewLower = 6613 Descending ? std::move(MovedBoundary) : std::move(StartLower); 6614 APInt NewUpper = 6615 Descending ? std::move(StartUpper) : std::move(MovedBoundary); 6616 NewUpper += 1; 6617 6618 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range. 6619 return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper)); 6620 } 6621 6622 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 6623 const SCEV *Step, 6624 const SCEV *MaxBECount, 6625 unsigned BitWidth) { 6626 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 6627 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 6628 "Precondition!"); 6629 6630 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 6631 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount); 6632 6633 // First, consider step signed. 6634 ConstantRange StartSRange = getSignedRange(Start); 6635 ConstantRange StepSRange = getSignedRange(Step); 6636 6637 // If Step can be both positive and negative, we need to find ranges for the 6638 // maximum absolute step values in both directions and union them. 6639 ConstantRange SR = 6640 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange, 6641 MaxBECountValue, BitWidth, /* Signed = */ true); 6642 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(), 6643 StartSRange, MaxBECountValue, 6644 BitWidth, /* Signed = */ true)); 6645 6646 // Next, consider step unsigned. 6647 ConstantRange UR = getRangeForAffineARHelper( 6648 getUnsignedRangeMax(Step), getUnsignedRange(Start), 6649 MaxBECountValue, BitWidth, /* Signed = */ false); 6650 6651 // Finally, intersect signed and unsigned ranges. 6652 return SR.intersectWith(UR, ConstantRange::Smallest); 6653 } 6654 6655 ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR( 6656 const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth, 6657 ScalarEvolution::RangeSignHint SignHint) { 6658 assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n"); 6659 assert(AddRec->hasNoSelfWrap() && 6660 "This only works for non-self-wrapping AddRecs!"); 6661 const bool IsSigned = SignHint == HINT_RANGE_SIGNED; 6662 const SCEV *Step = AddRec->getStepRecurrence(*this); 6663 // Only deal with constant step to save compile time. 6664 if (!isa<SCEVConstant>(Step)) 6665 return ConstantRange::getFull(BitWidth); 6666 // Let's make sure that we can prove that we do not self-wrap during 6667 // MaxBECount iterations. We need this because MaxBECount is a maximum 6668 // iteration count estimate, and we might infer nw from some exit for which we 6669 // do not know max exit count (or any other side reasoning). 6670 // TODO: Turn into assert at some point. 6671 if (getTypeSizeInBits(MaxBECount->getType()) > 6672 getTypeSizeInBits(AddRec->getType())) 6673 return ConstantRange::getFull(BitWidth); 6674 MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType()); 6675 const SCEV *RangeWidth = getMinusOne(AddRec->getType()); 6676 const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step)); 6677 const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs); 6678 if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount, 6679 MaxItersWithoutWrap)) 6680 return ConstantRange::getFull(BitWidth); 6681 6682 ICmpInst::Predicate LEPred = 6683 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 6684 ICmpInst::Predicate GEPred = 6685 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 6686 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this); 6687 6688 // We know that there is no self-wrap. Let's take Start and End values and 6689 // look at all intermediate values V1, V2, ..., Vn that IndVar takes during 6690 // the iteration. They either lie inside the range [Min(Start, End), 6691 // Max(Start, End)] or outside it: 6692 // 6693 // Case 1: RangeMin ... Start V1 ... VN End ... RangeMax; 6694 // Case 2: RangeMin Vk ... V1 Start ... End Vn ... Vk + 1 RangeMax; 6695 // 6696 // No self wrap flag guarantees that the intermediate values cannot be BOTH 6697 // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that 6698 // knowledge, let's try to prove that we are dealing with Case 1. It is so if 6699 // Start <= End and step is positive, or Start >= End and step is negative. 6700 const SCEV *Start = AddRec->getStart(); 6701 ConstantRange StartRange = getRangeRef(Start, SignHint); 6702 ConstantRange EndRange = getRangeRef(End, SignHint); 6703 ConstantRange RangeBetween = StartRange.unionWith(EndRange); 6704 // If they already cover full iteration space, we will know nothing useful 6705 // even if we prove what we want to prove. 6706 if (RangeBetween.isFullSet()) 6707 return RangeBetween; 6708 // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax). 6709 bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet() 6710 : RangeBetween.isWrappedSet(); 6711 if (IsWrappedSet) 6712 return ConstantRange::getFull(BitWidth); 6713 6714 if (isKnownPositive(Step) && 6715 isKnownPredicateViaConstantRanges(LEPred, Start, End)) 6716 return RangeBetween; 6717 else if (isKnownNegative(Step) && 6718 isKnownPredicateViaConstantRanges(GEPred, Start, End)) 6719 return RangeBetween; 6720 return ConstantRange::getFull(BitWidth); 6721 } 6722 6723 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 6724 const SCEV *Step, 6725 const SCEV *MaxBECount, 6726 unsigned BitWidth) { 6727 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 6728 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 6729 6730 struct SelectPattern { 6731 Value *Condition = nullptr; 6732 APInt TrueValue; 6733 APInt FalseValue; 6734 6735 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 6736 const SCEV *S) { 6737 Optional<unsigned> CastOp; 6738 APInt Offset(BitWidth, 0); 6739 6740 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 6741 "Should be!"); 6742 6743 // Peel off a constant offset: 6744 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 6745 // In the future we could consider being smarter here and handle 6746 // {Start+Step,+,Step} too. 6747 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 6748 return; 6749 6750 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 6751 S = SA->getOperand(1); 6752 } 6753 6754 // Peel off a cast operation 6755 if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) { 6756 CastOp = SCast->getSCEVType(); 6757 S = SCast->getOperand(); 6758 } 6759 6760 using namespace llvm::PatternMatch; 6761 6762 auto *SU = dyn_cast<SCEVUnknown>(S); 6763 const APInt *TrueVal, *FalseVal; 6764 if (!SU || 6765 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 6766 m_APInt(FalseVal)))) { 6767 Condition = nullptr; 6768 return; 6769 } 6770 6771 TrueValue = *TrueVal; 6772 FalseValue = *FalseVal; 6773 6774 // Re-apply the cast we peeled off earlier 6775 if (CastOp.hasValue()) 6776 switch (*CastOp) { 6777 default: 6778 llvm_unreachable("Unknown SCEV cast type!"); 6779 6780 case scTruncate: 6781 TrueValue = TrueValue.trunc(BitWidth); 6782 FalseValue = FalseValue.trunc(BitWidth); 6783 break; 6784 case scZeroExtend: 6785 TrueValue = TrueValue.zext(BitWidth); 6786 FalseValue = FalseValue.zext(BitWidth); 6787 break; 6788 case scSignExtend: 6789 TrueValue = TrueValue.sext(BitWidth); 6790 FalseValue = FalseValue.sext(BitWidth); 6791 break; 6792 } 6793 6794 // Re-apply the constant offset we peeled off earlier 6795 TrueValue += Offset; 6796 FalseValue += Offset; 6797 } 6798 6799 bool isRecognized() { return Condition != nullptr; } 6800 }; 6801 6802 SelectPattern StartPattern(*this, BitWidth, Start); 6803 if (!StartPattern.isRecognized()) 6804 return ConstantRange::getFull(BitWidth); 6805 6806 SelectPattern StepPattern(*this, BitWidth, Step); 6807 if (!StepPattern.isRecognized()) 6808 return ConstantRange::getFull(BitWidth); 6809 6810 if (StartPattern.Condition != StepPattern.Condition) { 6811 // We don't handle this case today; but we could, by considering four 6812 // possibilities below instead of two. I'm not sure if there are cases where 6813 // that will help over what getRange already does, though. 6814 return ConstantRange::getFull(BitWidth); 6815 } 6816 6817 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 6818 // construct arbitrary general SCEV expressions here. This function is called 6819 // from deep in the call stack, and calling getSCEV (on a sext instruction, 6820 // say) can end up caching a suboptimal value. 6821 6822 // FIXME: without the explicit `this` receiver below, MSVC errors out with 6823 // C2352 and C2512 (otherwise it isn't needed). 6824 6825 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 6826 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 6827 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 6828 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 6829 6830 ConstantRange TrueRange = 6831 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 6832 ConstantRange FalseRange = 6833 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 6834 6835 return TrueRange.unionWith(FalseRange); 6836 } 6837 6838 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 6839 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 6840 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 6841 6842 // Return early if there are no flags to propagate to the SCEV. 6843 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6844 if (BinOp->hasNoUnsignedWrap()) 6845 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 6846 if (BinOp->hasNoSignedWrap()) 6847 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 6848 if (Flags == SCEV::FlagAnyWrap) 6849 return SCEV::FlagAnyWrap; 6850 6851 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 6852 } 6853 6854 const Instruction * 6855 ScalarEvolution::getNonTrivialDefiningScopeBound(const SCEV *S) { 6856 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S)) 6857 return &*AddRec->getLoop()->getHeader()->begin(); 6858 if (auto *U = dyn_cast<SCEVUnknown>(S)) 6859 if (auto *I = dyn_cast<Instruction>(U->getValue())) 6860 return I; 6861 return nullptr; 6862 } 6863 6864 /// Fills \p Ops with unique operands of \p S, if it has operands. If not, 6865 /// \p Ops remains unmodified. 6866 static void collectUniqueOps(const SCEV *S, 6867 SmallVectorImpl<const SCEV *> &Ops) { 6868 SmallPtrSet<const SCEV *, 4> Unique; 6869 auto InsertUnique = [&](const SCEV *S) { 6870 if (Unique.insert(S).second) 6871 Ops.push_back(S); 6872 }; 6873 if (auto *S2 = dyn_cast<SCEVCastExpr>(S)) 6874 for (auto *Op : S2->operands()) 6875 InsertUnique(Op); 6876 else if (auto *S2 = dyn_cast<SCEVNAryExpr>(S)) 6877 for (auto *Op : S2->operands()) 6878 InsertUnique(Op); 6879 else if (auto *S2 = dyn_cast<SCEVUDivExpr>(S)) 6880 for (auto *Op : S2->operands()) 6881 InsertUnique(Op); 6882 } 6883 6884 const Instruction * 6885 ScalarEvolution::getDefiningScopeBound(ArrayRef<const SCEV *> Ops, 6886 bool &Precise) { 6887 Precise = true; 6888 // Do a bounded search of the def relation of the requested SCEVs. 6889 SmallSet<const SCEV *, 16> Visited; 6890 SmallVector<const SCEV *> Worklist; 6891 auto pushOp = [&](const SCEV *S) { 6892 if (!Visited.insert(S).second) 6893 return; 6894 // Threshold of 30 here is arbitrary. 6895 if (Visited.size() > 30) { 6896 Precise = false; 6897 return; 6898 } 6899 Worklist.push_back(S); 6900 }; 6901 6902 for (auto *S : Ops) 6903 pushOp(S); 6904 6905 const Instruction *Bound = nullptr; 6906 while (!Worklist.empty()) { 6907 auto *S = Worklist.pop_back_val(); 6908 if (auto *DefI = getNonTrivialDefiningScopeBound(S)) { 6909 if (!Bound || DT.dominates(Bound, DefI)) 6910 Bound = DefI; 6911 } else { 6912 SmallVector<const SCEV *, 4> Ops; 6913 collectUniqueOps(S, Ops); 6914 for (auto *Op : Ops) 6915 pushOp(Op); 6916 } 6917 } 6918 return Bound ? Bound : &*F.getEntryBlock().begin(); 6919 } 6920 6921 const Instruction * 6922 ScalarEvolution::getDefiningScopeBound(ArrayRef<const SCEV *> Ops) { 6923 bool Discard; 6924 return getDefiningScopeBound(Ops, Discard); 6925 } 6926 6927 bool ScalarEvolution::isGuaranteedToTransferExecutionTo(const Instruction *A, 6928 const Instruction *B) { 6929 if (A->getParent() == B->getParent() && 6930 isGuaranteedToTransferExecutionToSuccessor(A->getIterator(), 6931 B->getIterator())) 6932 return true; 6933 6934 auto *BLoop = LI.getLoopFor(B->getParent()); 6935 if (BLoop && BLoop->getHeader() == B->getParent() && 6936 BLoop->getLoopPreheader() == A->getParent() && 6937 isGuaranteedToTransferExecutionToSuccessor(A->getIterator(), 6938 A->getParent()->end()) && 6939 isGuaranteedToTransferExecutionToSuccessor(B->getParent()->begin(), 6940 B->getIterator())) 6941 return true; 6942 return false; 6943 } 6944 6945 6946 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 6947 // Only proceed if we can prove that I does not yield poison. 6948 if (!programUndefinedIfPoison(I)) 6949 return false; 6950 6951 // At this point we know that if I is executed, then it does not wrap 6952 // according to at least one of NSW or NUW. If I is not executed, then we do 6953 // not know if the calculation that I represents would wrap. Multiple 6954 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 6955 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 6956 // derived from other instructions that map to the same SCEV. We cannot make 6957 // that guarantee for cases where I is not executed. So we need to find a 6958 // upper bound on the defining scope for the SCEV, and prove that I is 6959 // executed every time we enter that scope. When the bounding scope is a 6960 // loop (the common case), this is equivalent to proving I executes on every 6961 // iteration of that loop. 6962 SmallVector<const SCEV *> SCEVOps; 6963 for (const Use &Op : I->operands()) { 6964 // I could be an extractvalue from a call to an overflow intrinsic. 6965 // TODO: We can do better here in some cases. 6966 if (isSCEVable(Op->getType())) 6967 SCEVOps.push_back(getSCEV(Op)); 6968 } 6969 auto *DefI = getDefiningScopeBound(SCEVOps); 6970 return isGuaranteedToTransferExecutionTo(DefI, I); 6971 } 6972 6973 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 6974 // If we know that \c I can never be poison period, then that's enough. 6975 if (isSCEVExprNeverPoison(I)) 6976 return true; 6977 6978 // For an add recurrence specifically, we assume that infinite loops without 6979 // side effects are undefined behavior, and then reason as follows: 6980 // 6981 // If the add recurrence is poison in any iteration, it is poison on all 6982 // future iterations (since incrementing poison yields poison). If the result 6983 // of the add recurrence is fed into the loop latch condition and the loop 6984 // does not contain any throws or exiting blocks other than the latch, we now 6985 // have the ability to "choose" whether the backedge is taken or not (by 6986 // choosing a sufficiently evil value for the poison feeding into the branch) 6987 // for every iteration including and after the one in which \p I first became 6988 // poison. There are two possibilities (let's call the iteration in which \p 6989 // I first became poison as K): 6990 // 6991 // 1. In the set of iterations including and after K, the loop body executes 6992 // no side effects. In this case executing the backege an infinte number 6993 // of times will yield undefined behavior. 6994 // 6995 // 2. In the set of iterations including and after K, the loop body executes 6996 // at least one side effect. In this case, that specific instance of side 6997 // effect is control dependent on poison, which also yields undefined 6998 // behavior. 6999 7000 auto *ExitingBB = L->getExitingBlock(); 7001 auto *LatchBB = L->getLoopLatch(); 7002 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 7003 return false; 7004 7005 SmallPtrSet<const Instruction *, 16> Pushed; 7006 SmallVector<const Instruction *, 8> PoisonStack; 7007 7008 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 7009 // things that are known to be poison under that assumption go on the 7010 // PoisonStack. 7011 Pushed.insert(I); 7012 PoisonStack.push_back(I); 7013 7014 bool LatchControlDependentOnPoison = false; 7015 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 7016 const Instruction *Poison = PoisonStack.pop_back_val(); 7017 7018 for (auto *PoisonUser : Poison->users()) { 7019 if (propagatesPoison(cast<Operator>(PoisonUser))) { 7020 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 7021 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 7022 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 7023 assert(BI->isConditional() && "Only possibility!"); 7024 if (BI->getParent() == LatchBB) { 7025 LatchControlDependentOnPoison = true; 7026 break; 7027 } 7028 } 7029 } 7030 } 7031 7032 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 7033 } 7034 7035 ScalarEvolution::LoopProperties 7036 ScalarEvolution::getLoopProperties(const Loop *L) { 7037 using LoopProperties = ScalarEvolution::LoopProperties; 7038 7039 auto Itr = LoopPropertiesCache.find(L); 7040 if (Itr == LoopPropertiesCache.end()) { 7041 auto HasSideEffects = [](Instruction *I) { 7042 if (auto *SI = dyn_cast<StoreInst>(I)) 7043 return !SI->isSimple(); 7044 7045 return I->mayThrow() || I->mayWriteToMemory(); 7046 }; 7047 7048 LoopProperties LP = {/* HasNoAbnormalExits */ true, 7049 /*HasNoSideEffects*/ true}; 7050 7051 for (auto *BB : L->getBlocks()) 7052 for (auto &I : *BB) { 7053 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 7054 LP.HasNoAbnormalExits = false; 7055 if (HasSideEffects(&I)) 7056 LP.HasNoSideEffects = false; 7057 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 7058 break; // We're already as pessimistic as we can get. 7059 } 7060 7061 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 7062 assert(InsertPair.second && "We just checked!"); 7063 Itr = InsertPair.first; 7064 } 7065 7066 return Itr->second; 7067 } 7068 7069 bool ScalarEvolution::loopIsFiniteByAssumption(const Loop *L) { 7070 // A mustprogress loop without side effects must be finite. 7071 // TODO: The check used here is very conservative. It's only *specific* 7072 // side effects which are well defined in infinite loops. 7073 return isFinite(L) || (isMustProgress(L) && loopHasNoSideEffects(L)); 7074 } 7075 7076 const SCEV *ScalarEvolution::createSCEV(Value *V) { 7077 if (!isSCEVable(V->getType())) 7078 return getUnknown(V); 7079 7080 if (Instruction *I = dyn_cast<Instruction>(V)) { 7081 // Don't attempt to analyze instructions in blocks that aren't 7082 // reachable. Such instructions don't matter, and they aren't required 7083 // to obey basic rules for definitions dominating uses which this 7084 // analysis depends on. 7085 if (!DT.isReachableFromEntry(I->getParent())) 7086 return getUnknown(UndefValue::get(V->getType())); 7087 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 7088 return getConstant(CI); 7089 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 7090 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 7091 else if (!isa<ConstantExpr>(V)) 7092 return getUnknown(V); 7093 7094 Operator *U = cast<Operator>(V); 7095 if (auto BO = MatchBinaryOp(U, DT)) { 7096 switch (BO->Opcode) { 7097 case Instruction::Add: { 7098 // The simple thing to do would be to just call getSCEV on both operands 7099 // and call getAddExpr with the result. However if we're looking at a 7100 // bunch of things all added together, this can be quite inefficient, 7101 // because it leads to N-1 getAddExpr calls for N ultimate operands. 7102 // Instead, gather up all the operands and make a single getAddExpr call. 7103 // LLVM IR canonical form means we need only traverse the left operands. 7104 SmallVector<const SCEV *, 4> AddOps; 7105 do { 7106 if (BO->Op) { 7107 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 7108 AddOps.push_back(OpSCEV); 7109 break; 7110 } 7111 7112 // If a NUW or NSW flag can be applied to the SCEV for this 7113 // addition, then compute the SCEV for this addition by itself 7114 // with a separate call to getAddExpr. We need to do that 7115 // instead of pushing the operands of the addition onto AddOps, 7116 // since the flags are only known to apply to this particular 7117 // addition - they may not apply to other additions that can be 7118 // formed with operands from AddOps. 7119 const SCEV *RHS = getSCEV(BO->RHS); 7120 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 7121 if (Flags != SCEV::FlagAnyWrap) { 7122 const SCEV *LHS = getSCEV(BO->LHS); 7123 if (BO->Opcode == Instruction::Sub) 7124 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 7125 else 7126 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 7127 break; 7128 } 7129 } 7130 7131 if (BO->Opcode == Instruction::Sub) 7132 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 7133 else 7134 AddOps.push_back(getSCEV(BO->RHS)); 7135 7136 auto NewBO = MatchBinaryOp(BO->LHS, DT); 7137 if (!NewBO || (NewBO->Opcode != Instruction::Add && 7138 NewBO->Opcode != Instruction::Sub)) { 7139 AddOps.push_back(getSCEV(BO->LHS)); 7140 break; 7141 } 7142 BO = NewBO; 7143 } while (true); 7144 7145 return getAddExpr(AddOps); 7146 } 7147 7148 case Instruction::Mul: { 7149 SmallVector<const SCEV *, 4> MulOps; 7150 do { 7151 if (BO->Op) { 7152 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 7153 MulOps.push_back(OpSCEV); 7154 break; 7155 } 7156 7157 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 7158 if (Flags != SCEV::FlagAnyWrap) { 7159 MulOps.push_back( 7160 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 7161 break; 7162 } 7163 } 7164 7165 MulOps.push_back(getSCEV(BO->RHS)); 7166 auto NewBO = MatchBinaryOp(BO->LHS, DT); 7167 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 7168 MulOps.push_back(getSCEV(BO->LHS)); 7169 break; 7170 } 7171 BO = NewBO; 7172 } while (true); 7173 7174 return getMulExpr(MulOps); 7175 } 7176 case Instruction::UDiv: 7177 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 7178 case Instruction::URem: 7179 return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 7180 case Instruction::Sub: { 7181 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 7182 if (BO->Op) 7183 Flags = getNoWrapFlagsFromUB(BO->Op); 7184 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 7185 } 7186 case Instruction::And: 7187 // For an expression like x&255 that merely masks off the high bits, 7188 // use zext(trunc(x)) as the SCEV expression. 7189 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 7190 if (CI->isZero()) 7191 return getSCEV(BO->RHS); 7192 if (CI->isMinusOne()) 7193 return getSCEV(BO->LHS); 7194 const APInt &A = CI->getValue(); 7195 7196 // Instcombine's ShrinkDemandedConstant may strip bits out of 7197 // constants, obscuring what would otherwise be a low-bits mask. 7198 // Use computeKnownBits to compute what ShrinkDemandedConstant 7199 // knew about to reconstruct a low-bits mask value. 7200 unsigned LZ = A.countLeadingZeros(); 7201 unsigned TZ = A.countTrailingZeros(); 7202 unsigned BitWidth = A.getBitWidth(); 7203 KnownBits Known(BitWidth); 7204 computeKnownBits(BO->LHS, Known, getDataLayout(), 7205 0, &AC, nullptr, &DT); 7206 7207 APInt EffectiveMask = 7208 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 7209 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) { 7210 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ)); 7211 const SCEV *LHS = getSCEV(BO->LHS); 7212 const SCEV *ShiftedLHS = nullptr; 7213 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) { 7214 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) { 7215 // For an expression like (x * 8) & 8, simplify the multiply. 7216 unsigned MulZeros = OpC->getAPInt().countTrailingZeros(); 7217 unsigned GCD = std::min(MulZeros, TZ); 7218 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD); 7219 SmallVector<const SCEV*, 4> MulOps; 7220 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD))); 7221 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end()); 7222 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags()); 7223 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt)); 7224 } 7225 } 7226 if (!ShiftedLHS) 7227 ShiftedLHS = getUDivExpr(LHS, MulCount); 7228 return getMulExpr( 7229 getZeroExtendExpr( 7230 getTruncateExpr(ShiftedLHS, 7231 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 7232 BO->LHS->getType()), 7233 MulCount); 7234 } 7235 } 7236 // Binary `and` is a bit-wise `umin`. 7237 if (BO->LHS->getType()->isIntegerTy(1)) 7238 return getUMinExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 7239 break; 7240 7241 case Instruction::Or: 7242 // If the RHS of the Or is a constant, we may have something like: 7243 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 7244 // optimizations will transparently handle this case. 7245 // 7246 // In order for this transformation to be safe, the LHS must be of the 7247 // form X*(2^n) and the Or constant must be less than 2^n. 7248 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 7249 const SCEV *LHS = getSCEV(BO->LHS); 7250 const APInt &CIVal = CI->getValue(); 7251 if (GetMinTrailingZeros(LHS) >= 7252 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 7253 // Build a plain add SCEV. 7254 return getAddExpr(LHS, getSCEV(CI), 7255 (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW)); 7256 } 7257 } 7258 // Binary `or` is a bit-wise `umax`. 7259 if (BO->LHS->getType()->isIntegerTy(1)) 7260 return getUMaxExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 7261 break; 7262 7263 case Instruction::Xor: 7264 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 7265 // If the RHS of xor is -1, then this is a not operation. 7266 if (CI->isMinusOne()) 7267 return getNotSCEV(getSCEV(BO->LHS)); 7268 7269 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 7270 // This is a variant of the check for xor with -1, and it handles 7271 // the case where instcombine has trimmed non-demanded bits out 7272 // of an xor with -1. 7273 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 7274 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 7275 if (LBO->getOpcode() == Instruction::And && 7276 LCI->getValue() == CI->getValue()) 7277 if (const SCEVZeroExtendExpr *Z = 7278 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 7279 Type *UTy = BO->LHS->getType(); 7280 const SCEV *Z0 = Z->getOperand(); 7281 Type *Z0Ty = Z0->getType(); 7282 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 7283 7284 // If C is a low-bits mask, the zero extend is serving to 7285 // mask off the high bits. Complement the operand and 7286 // re-apply the zext. 7287 if (CI->getValue().isMask(Z0TySize)) 7288 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 7289 7290 // If C is a single bit, it may be in the sign-bit position 7291 // before the zero-extend. In this case, represent the xor 7292 // using an add, which is equivalent, and re-apply the zext. 7293 APInt Trunc = CI->getValue().trunc(Z0TySize); 7294 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 7295 Trunc.isSignMask()) 7296 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 7297 UTy); 7298 } 7299 } 7300 break; 7301 7302 case Instruction::Shl: 7303 // Turn shift left of a constant amount into a multiply. 7304 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 7305 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 7306 7307 // If the shift count is not less than the bitwidth, the result of 7308 // the shift is undefined. Don't try to analyze it, because the 7309 // resolution chosen here may differ from the resolution chosen in 7310 // other parts of the compiler. 7311 if (SA->getValue().uge(BitWidth)) 7312 break; 7313 7314 // We can safely preserve the nuw flag in all cases. It's also safe to 7315 // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation 7316 // requires special handling. It can be preserved as long as we're not 7317 // left shifting by bitwidth - 1. 7318 auto Flags = SCEV::FlagAnyWrap; 7319 if (BO->Op) { 7320 auto MulFlags = getNoWrapFlagsFromUB(BO->Op); 7321 if ((MulFlags & SCEV::FlagNSW) && 7322 ((MulFlags & SCEV::FlagNUW) || SA->getValue().ult(BitWidth - 1))) 7323 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNSW); 7324 if (MulFlags & SCEV::FlagNUW) 7325 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNUW); 7326 } 7327 7328 Constant *X = ConstantInt::get( 7329 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 7330 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 7331 } 7332 break; 7333 7334 case Instruction::AShr: { 7335 // AShr X, C, where C is a constant. 7336 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS); 7337 if (!CI) 7338 break; 7339 7340 Type *OuterTy = BO->LHS->getType(); 7341 uint64_t BitWidth = getTypeSizeInBits(OuterTy); 7342 // If the shift count is not less than the bitwidth, the result of 7343 // the shift is undefined. Don't try to analyze it, because the 7344 // resolution chosen here may differ from the resolution chosen in 7345 // other parts of the compiler. 7346 if (CI->getValue().uge(BitWidth)) 7347 break; 7348 7349 if (CI->isZero()) 7350 return getSCEV(BO->LHS); // shift by zero --> noop 7351 7352 uint64_t AShrAmt = CI->getZExtValue(); 7353 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt); 7354 7355 Operator *L = dyn_cast<Operator>(BO->LHS); 7356 if (L && L->getOpcode() == Instruction::Shl) { 7357 // X = Shl A, n 7358 // Y = AShr X, m 7359 // Both n and m are constant. 7360 7361 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0)); 7362 if (L->getOperand(1) == BO->RHS) 7363 // For a two-shift sext-inreg, i.e. n = m, 7364 // use sext(trunc(x)) as the SCEV expression. 7365 return getSignExtendExpr( 7366 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy); 7367 7368 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1)); 7369 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) { 7370 uint64_t ShlAmt = ShlAmtCI->getZExtValue(); 7371 if (ShlAmt > AShrAmt) { 7372 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV 7373 // expression. We already checked that ShlAmt < BitWidth, so 7374 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as 7375 // ShlAmt - AShrAmt < Amt. 7376 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt, 7377 ShlAmt - AShrAmt); 7378 return getSignExtendExpr( 7379 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy), 7380 getConstant(Mul)), OuterTy); 7381 } 7382 } 7383 } 7384 break; 7385 } 7386 } 7387 } 7388 7389 switch (U->getOpcode()) { 7390 case Instruction::Trunc: 7391 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 7392 7393 case Instruction::ZExt: 7394 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 7395 7396 case Instruction::SExt: 7397 if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) { 7398 // The NSW flag of a subtract does not always survive the conversion to 7399 // A + (-1)*B. By pushing sign extension onto its operands we are much 7400 // more likely to preserve NSW and allow later AddRec optimisations. 7401 // 7402 // NOTE: This is effectively duplicating this logic from getSignExtend: 7403 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 7404 // but by that point the NSW information has potentially been lost. 7405 if (BO->Opcode == Instruction::Sub && BO->IsNSW) { 7406 Type *Ty = U->getType(); 7407 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty); 7408 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty); 7409 return getMinusSCEV(V1, V2, SCEV::FlagNSW); 7410 } 7411 } 7412 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 7413 7414 case Instruction::BitCast: 7415 // BitCasts are no-op casts so we just eliminate the cast. 7416 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 7417 return getSCEV(U->getOperand(0)); 7418 break; 7419 7420 case Instruction::PtrToInt: { 7421 // Pointer to integer cast is straight-forward, so do model it. 7422 const SCEV *Op = getSCEV(U->getOperand(0)); 7423 Type *DstIntTy = U->getType(); 7424 // But only if effective SCEV (integer) type is wide enough to represent 7425 // all possible pointer values. 7426 const SCEV *IntOp = getPtrToIntExpr(Op, DstIntTy); 7427 if (isa<SCEVCouldNotCompute>(IntOp)) 7428 return getUnknown(V); 7429 return IntOp; 7430 } 7431 case Instruction::IntToPtr: 7432 // Just don't deal with inttoptr casts. 7433 return getUnknown(V); 7434 7435 case Instruction::SDiv: 7436 // If both operands are non-negative, this is just an udiv. 7437 if (isKnownNonNegative(getSCEV(U->getOperand(0))) && 7438 isKnownNonNegative(getSCEV(U->getOperand(1)))) 7439 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1))); 7440 break; 7441 7442 case Instruction::SRem: 7443 // If both operands are non-negative, this is just an urem. 7444 if (isKnownNonNegative(getSCEV(U->getOperand(0))) && 7445 isKnownNonNegative(getSCEV(U->getOperand(1)))) 7446 return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1))); 7447 break; 7448 7449 case Instruction::GetElementPtr: 7450 return createNodeForGEP(cast<GEPOperator>(U)); 7451 7452 case Instruction::PHI: 7453 return createNodeForPHI(cast<PHINode>(U)); 7454 7455 case Instruction::Select: 7456 return createNodeForSelectOrPHI(U, U->getOperand(0), U->getOperand(1), 7457 U->getOperand(2)); 7458 7459 case Instruction::Call: 7460 case Instruction::Invoke: 7461 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand()) 7462 return getSCEV(RV); 7463 7464 if (auto *II = dyn_cast<IntrinsicInst>(U)) { 7465 switch (II->getIntrinsicID()) { 7466 case Intrinsic::abs: 7467 return getAbsExpr( 7468 getSCEV(II->getArgOperand(0)), 7469 /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne()); 7470 case Intrinsic::umax: 7471 return getUMaxExpr(getSCEV(II->getArgOperand(0)), 7472 getSCEV(II->getArgOperand(1))); 7473 case Intrinsic::umin: 7474 return getUMinExpr(getSCEV(II->getArgOperand(0)), 7475 getSCEV(II->getArgOperand(1))); 7476 case Intrinsic::smax: 7477 return getSMaxExpr(getSCEV(II->getArgOperand(0)), 7478 getSCEV(II->getArgOperand(1))); 7479 case Intrinsic::smin: 7480 return getSMinExpr(getSCEV(II->getArgOperand(0)), 7481 getSCEV(II->getArgOperand(1))); 7482 case Intrinsic::usub_sat: { 7483 const SCEV *X = getSCEV(II->getArgOperand(0)); 7484 const SCEV *Y = getSCEV(II->getArgOperand(1)); 7485 const SCEV *ClampedY = getUMinExpr(X, Y); 7486 return getMinusSCEV(X, ClampedY, SCEV::FlagNUW); 7487 } 7488 case Intrinsic::uadd_sat: { 7489 const SCEV *X = getSCEV(II->getArgOperand(0)); 7490 const SCEV *Y = getSCEV(II->getArgOperand(1)); 7491 const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y)); 7492 return getAddExpr(ClampedX, Y, SCEV::FlagNUW); 7493 } 7494 case Intrinsic::start_loop_iterations: 7495 // A start_loop_iterations is just equivalent to the first operand for 7496 // SCEV purposes. 7497 return getSCEV(II->getArgOperand(0)); 7498 default: 7499 break; 7500 } 7501 } 7502 break; 7503 } 7504 7505 return getUnknown(V); 7506 } 7507 7508 //===----------------------------------------------------------------------===// 7509 // Iteration Count Computation Code 7510 // 7511 7512 const SCEV *ScalarEvolution::getTripCountFromExitCount(const SCEV *ExitCount, 7513 bool Extend) { 7514 if (isa<SCEVCouldNotCompute>(ExitCount)) 7515 return getCouldNotCompute(); 7516 7517 auto *ExitCountType = ExitCount->getType(); 7518 assert(ExitCountType->isIntegerTy()); 7519 7520 if (!Extend) 7521 return getAddExpr(ExitCount, getOne(ExitCountType)); 7522 7523 auto *WiderType = Type::getIntNTy(ExitCountType->getContext(), 7524 1 + ExitCountType->getScalarSizeInBits()); 7525 return getAddExpr(getNoopOrZeroExtend(ExitCount, WiderType), 7526 getOne(WiderType)); 7527 } 7528 7529 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 7530 if (!ExitCount) 7531 return 0; 7532 7533 ConstantInt *ExitConst = ExitCount->getValue(); 7534 7535 // Guard against huge trip counts. 7536 if (ExitConst->getValue().getActiveBits() > 32) 7537 return 0; 7538 7539 // In case of integer overflow, this returns 0, which is correct. 7540 return ((unsigned)ExitConst->getZExtValue()) + 1; 7541 } 7542 7543 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) { 7544 auto *ExitCount = dyn_cast<SCEVConstant>(getBackedgeTakenCount(L, Exact)); 7545 return getConstantTripCount(ExitCount); 7546 } 7547 7548 unsigned 7549 ScalarEvolution::getSmallConstantTripCount(const Loop *L, 7550 const BasicBlock *ExitingBlock) { 7551 assert(ExitingBlock && "Must pass a non-null exiting block!"); 7552 assert(L->isLoopExiting(ExitingBlock) && 7553 "Exiting block must actually branch out of the loop!"); 7554 const SCEVConstant *ExitCount = 7555 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 7556 return getConstantTripCount(ExitCount); 7557 } 7558 7559 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) { 7560 const auto *MaxExitCount = 7561 dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L)); 7562 return getConstantTripCount(MaxExitCount); 7563 } 7564 7565 const SCEV *ScalarEvolution::getConstantMaxTripCountFromArray(const Loop *L) { 7566 // We can't infer from Array in Irregular Loop. 7567 // FIXME: It's hard to infer loop bound from array operated in Nested Loop. 7568 if (!L->isLoopSimplifyForm() || !L->isInnermost()) 7569 return getCouldNotCompute(); 7570 7571 // FIXME: To make the scene more typical, we only analysis loops that have 7572 // one exiting block and that block must be the latch. To make it easier to 7573 // capture loops that have memory access and memory access will be executed 7574 // in each iteration. 7575 const BasicBlock *LoopLatch = L->getLoopLatch(); 7576 assert(LoopLatch && "See defination of simplify form loop."); 7577 if (L->getExitingBlock() != LoopLatch) 7578 return getCouldNotCompute(); 7579 7580 const DataLayout &DL = getDataLayout(); 7581 SmallVector<const SCEV *> InferCountColl; 7582 for (auto *BB : L->getBlocks()) { 7583 // Go here, we can know that Loop is a single exiting and simplified form 7584 // loop. Make sure that infer from Memory Operation in those BBs must be 7585 // executed in loop. First step, we can make sure that max execution time 7586 // of MemAccessBB in loop represents latch max excution time. 7587 // If MemAccessBB does not dom Latch, skip. 7588 // Entry 7589 // │ 7590 // ┌─────▼─────┐ 7591 // │Loop Header◄─────┐ 7592 // └──┬──────┬─┘ │ 7593 // │ │ │ 7594 // ┌────────▼──┐ ┌─▼─────┐ │ 7595 // │MemAccessBB│ │OtherBB│ │ 7596 // └────────┬──┘ └─┬─────┘ │ 7597 // │ │ │ 7598 // ┌─▼──────▼─┐ │ 7599 // │Loop Latch├─────┘ 7600 // └────┬─────┘ 7601 // ▼ 7602 // Exit 7603 if (!DT.dominates(BB, LoopLatch)) 7604 continue; 7605 7606 for (Instruction &Inst : *BB) { 7607 // Find Memory Operation Instruction. 7608 auto *GEP = getLoadStorePointerOperand(&Inst); 7609 if (!GEP) 7610 continue; 7611 7612 auto *ElemSize = dyn_cast<SCEVConstant>(getElementSize(&Inst)); 7613 // Do not infer from scalar type, eg."ElemSize = sizeof()". 7614 if (!ElemSize) 7615 continue; 7616 7617 // Use a existing polynomial recurrence on the trip count. 7618 auto *AddRec = dyn_cast<SCEVAddRecExpr>(getSCEV(GEP)); 7619 if (!AddRec) 7620 continue; 7621 auto *ArrBase = dyn_cast<SCEVUnknown>(getPointerBase(AddRec)); 7622 auto *Step = dyn_cast<SCEVConstant>(AddRec->getStepRecurrence(*this)); 7623 if (!ArrBase || !Step) 7624 continue; 7625 assert(isLoopInvariant(ArrBase, L) && "See addrec definition"); 7626 7627 // Only handle { %array + step }, 7628 // FIXME: {(SCEVAddRecExpr) + step } could not be analysed here. 7629 if (AddRec->getStart() != ArrBase) 7630 continue; 7631 7632 // Memory operation pattern which have gaps. 7633 // Or repeat memory opreation. 7634 // And index of GEP wraps arround. 7635 if (Step->getAPInt().getActiveBits() > 32 || 7636 Step->getAPInt().getZExtValue() != 7637 ElemSize->getAPInt().getZExtValue() || 7638 Step->isZero() || Step->getAPInt().isNegative()) 7639 continue; 7640 7641 // Only infer from stack array which has certain size. 7642 // Make sure alloca instruction is not excuted in loop. 7643 AllocaInst *AllocateInst = dyn_cast<AllocaInst>(ArrBase->getValue()); 7644 if (!AllocateInst || L->contains(AllocateInst->getParent())) 7645 continue; 7646 7647 // Make sure only handle normal array. 7648 auto *Ty = dyn_cast<ArrayType>(AllocateInst->getAllocatedType()); 7649 auto *ArrSize = dyn_cast<ConstantInt>(AllocateInst->getArraySize()); 7650 if (!Ty || !ArrSize || !ArrSize->isOne()) 7651 continue; 7652 7653 // FIXME: Since gep indices are silently zext to the indexing type, 7654 // we will have a narrow gep index which wraps around rather than 7655 // increasing strictly, we shoule ensure that step is increasing 7656 // strictly by the loop iteration. 7657 // Now we can infer a max execution time by MemLength/StepLength. 7658 const SCEV *MemSize = 7659 getConstant(Step->getType(), DL.getTypeAllocSize(Ty)); 7660 auto *MaxExeCount = 7661 dyn_cast<SCEVConstant>(getUDivCeilSCEV(MemSize, Step)); 7662 if (!MaxExeCount || MaxExeCount->getAPInt().getActiveBits() > 32) 7663 continue; 7664 7665 // If the loop reaches the maximum number of executions, we can not 7666 // access bytes starting outside the statically allocated size without 7667 // being immediate UB. But it is allowed to enter loop header one more 7668 // time. 7669 auto *InferCount = dyn_cast<SCEVConstant>( 7670 getAddExpr(MaxExeCount, getOne(MaxExeCount->getType()))); 7671 // Discard the maximum number of execution times under 32bits. 7672 if (!InferCount || InferCount->getAPInt().getActiveBits() > 32) 7673 continue; 7674 7675 InferCountColl.push_back(InferCount); 7676 } 7677 } 7678 7679 if (InferCountColl.size() == 0) 7680 return getCouldNotCompute(); 7681 7682 return getUMinFromMismatchedTypes(InferCountColl); 7683 } 7684 7685 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) { 7686 SmallVector<BasicBlock *, 8> ExitingBlocks; 7687 L->getExitingBlocks(ExitingBlocks); 7688 7689 Optional<unsigned> Res = None; 7690 for (auto *ExitingBB : ExitingBlocks) { 7691 unsigned Multiple = getSmallConstantTripMultiple(L, ExitingBB); 7692 if (!Res) 7693 Res = Multiple; 7694 Res = (unsigned)GreatestCommonDivisor64(*Res, Multiple); 7695 } 7696 return Res.getValueOr(1); 7697 } 7698 7699 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 7700 const SCEV *ExitCount) { 7701 if (ExitCount == getCouldNotCompute()) 7702 return 1; 7703 7704 // Get the trip count 7705 const SCEV *TCExpr = getTripCountFromExitCount(ExitCount); 7706 7707 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr); 7708 if (!TC) 7709 // Attempt to factor more general cases. Returns the greatest power of 7710 // two divisor. If overflow happens, the trip count expression is still 7711 // divisible by the greatest power of 2 divisor returned. 7712 return 1U << std::min((uint32_t)31, 7713 GetMinTrailingZeros(applyLoopGuards(TCExpr, L))); 7714 7715 ConstantInt *Result = TC->getValue(); 7716 7717 // Guard against huge trip counts (this requires checking 7718 // for zero to handle the case where the trip count == -1 and the 7719 // addition wraps). 7720 if (!Result || Result->getValue().getActiveBits() > 32 || 7721 Result->getValue().getActiveBits() == 0) 7722 return 1; 7723 7724 return (unsigned)Result->getZExtValue(); 7725 } 7726 7727 /// Returns the largest constant divisor of the trip count of this loop as a 7728 /// normal unsigned value, if possible. This means that the actual trip count is 7729 /// always a multiple of the returned value (don't forget the trip count could 7730 /// very well be zero as well!). 7731 /// 7732 /// Returns 1 if the trip count is unknown or not guaranteed to be the 7733 /// multiple of a constant (which is also the case if the trip count is simply 7734 /// constant, use getSmallConstantTripCount for that case), Will also return 1 7735 /// if the trip count is very large (>= 2^32). 7736 /// 7737 /// As explained in the comments for getSmallConstantTripCount, this assumes 7738 /// that control exits the loop via ExitingBlock. 7739 unsigned 7740 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 7741 const BasicBlock *ExitingBlock) { 7742 assert(ExitingBlock && "Must pass a non-null exiting block!"); 7743 assert(L->isLoopExiting(ExitingBlock) && 7744 "Exiting block must actually branch out of the loop!"); 7745 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 7746 return getSmallConstantTripMultiple(L, ExitCount); 7747 } 7748 7749 const SCEV *ScalarEvolution::getExitCount(const Loop *L, 7750 const BasicBlock *ExitingBlock, 7751 ExitCountKind Kind) { 7752 switch (Kind) { 7753 case Exact: 7754 case SymbolicMaximum: 7755 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 7756 case ConstantMaximum: 7757 return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this); 7758 }; 7759 llvm_unreachable("Invalid ExitCountKind!"); 7760 } 7761 7762 const SCEV * 7763 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 7764 SmallVector<const SCEVPredicate *, 4> &Preds) { 7765 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds); 7766 } 7767 7768 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L, 7769 ExitCountKind Kind) { 7770 switch (Kind) { 7771 case Exact: 7772 return getBackedgeTakenInfo(L).getExact(L, this); 7773 case ConstantMaximum: 7774 return getBackedgeTakenInfo(L).getConstantMax(this); 7775 case SymbolicMaximum: 7776 return getBackedgeTakenInfo(L).getSymbolicMax(L, this); 7777 }; 7778 llvm_unreachable("Invalid ExitCountKind!"); 7779 } 7780 7781 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 7782 return getBackedgeTakenInfo(L).isConstantMaxOrZero(this); 7783 } 7784 7785 /// Push PHI nodes in the header of the given loop onto the given Worklist. 7786 static void PushLoopPHIs(const Loop *L, 7787 SmallVectorImpl<Instruction *> &Worklist, 7788 SmallPtrSetImpl<Instruction *> &Visited) { 7789 BasicBlock *Header = L->getHeader(); 7790 7791 // Push all Loop-header PHIs onto the Worklist stack. 7792 for (PHINode &PN : Header->phis()) 7793 if (Visited.insert(&PN).second) 7794 Worklist.push_back(&PN); 7795 } 7796 7797 const ScalarEvolution::BackedgeTakenInfo & 7798 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 7799 auto &BTI = getBackedgeTakenInfo(L); 7800 if (BTI.hasFullInfo()) 7801 return BTI; 7802 7803 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 7804 7805 if (!Pair.second) 7806 return Pair.first->second; 7807 7808 BackedgeTakenInfo Result = 7809 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 7810 7811 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 7812 } 7813 7814 ScalarEvolution::BackedgeTakenInfo & 7815 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 7816 // Initially insert an invalid entry for this loop. If the insertion 7817 // succeeds, proceed to actually compute a backedge-taken count and 7818 // update the value. The temporary CouldNotCompute value tells SCEV 7819 // code elsewhere that it shouldn't attempt to request a new 7820 // backedge-taken count, which could result in infinite recursion. 7821 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 7822 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 7823 if (!Pair.second) 7824 return Pair.first->second; 7825 7826 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 7827 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 7828 // must be cleared in this scope. 7829 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 7830 7831 // In product build, there are no usage of statistic. 7832 (void)NumTripCountsComputed; 7833 (void)NumTripCountsNotComputed; 7834 #if LLVM_ENABLE_STATS || !defined(NDEBUG) 7835 const SCEV *BEExact = Result.getExact(L, this); 7836 if (BEExact != getCouldNotCompute()) { 7837 assert(isLoopInvariant(BEExact, L) && 7838 isLoopInvariant(Result.getConstantMax(this), L) && 7839 "Computed backedge-taken count isn't loop invariant for loop!"); 7840 ++NumTripCountsComputed; 7841 } else if (Result.getConstantMax(this) == getCouldNotCompute() && 7842 isa<PHINode>(L->getHeader()->begin())) { 7843 // Only count loops that have phi nodes as not being computable. 7844 ++NumTripCountsNotComputed; 7845 } 7846 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG) 7847 7848 // Now that we know more about the trip count for this loop, forget any 7849 // existing SCEV values for PHI nodes in this loop since they are only 7850 // conservative estimates made without the benefit of trip count 7851 // information. This invalidation is not necessary for correctness, and is 7852 // only done to produce more precise results. 7853 if (Result.hasAnyInfo()) { 7854 // Invalidate any expression using an addrec in this loop. 7855 SmallVector<const SCEV *, 8> ToForget; 7856 auto LoopUsersIt = LoopUsers.find(L); 7857 if (LoopUsersIt != LoopUsers.end()) 7858 append_range(ToForget, LoopUsersIt->second); 7859 forgetMemoizedResults(ToForget); 7860 7861 // Invalidate constant-evolved loop header phis. 7862 for (PHINode &PN : L->getHeader()->phis()) 7863 ConstantEvolutionLoopExitValue.erase(&PN); 7864 } 7865 7866 // Re-lookup the insert position, since the call to 7867 // computeBackedgeTakenCount above could result in a 7868 // recusive call to getBackedgeTakenInfo (on a different 7869 // loop), which would invalidate the iterator computed 7870 // earlier. 7871 return BackedgeTakenCounts.find(L)->second = std::move(Result); 7872 } 7873 7874 void ScalarEvolution::forgetAllLoops() { 7875 // This method is intended to forget all info about loops. It should 7876 // invalidate caches as if the following happened: 7877 // - The trip counts of all loops have changed arbitrarily 7878 // - Every llvm::Value has been updated in place to produce a different 7879 // result. 7880 BackedgeTakenCounts.clear(); 7881 PredicatedBackedgeTakenCounts.clear(); 7882 BECountUsers.clear(); 7883 LoopPropertiesCache.clear(); 7884 ConstantEvolutionLoopExitValue.clear(); 7885 ValueExprMap.clear(); 7886 ValuesAtScopes.clear(); 7887 ValuesAtScopesUsers.clear(); 7888 LoopDispositions.clear(); 7889 BlockDispositions.clear(); 7890 UnsignedRanges.clear(); 7891 SignedRanges.clear(); 7892 ExprValueMap.clear(); 7893 HasRecMap.clear(); 7894 MinTrailingZerosCache.clear(); 7895 PredicatedSCEVRewrites.clear(); 7896 } 7897 7898 void ScalarEvolution::forgetLoop(const Loop *L) { 7899 SmallVector<const Loop *, 16> LoopWorklist(1, L); 7900 SmallVector<Instruction *, 32> Worklist; 7901 SmallPtrSet<Instruction *, 16> Visited; 7902 SmallVector<const SCEV *, 16> ToForget; 7903 7904 // Iterate over all the loops and sub-loops to drop SCEV information. 7905 while (!LoopWorklist.empty()) { 7906 auto *CurrL = LoopWorklist.pop_back_val(); 7907 7908 // Drop any stored trip count value. 7909 forgetBackedgeTakenCounts(CurrL, /* Predicated */ false); 7910 forgetBackedgeTakenCounts(CurrL, /* Predicated */ true); 7911 7912 // Drop information about predicated SCEV rewrites for this loop. 7913 for (auto I = PredicatedSCEVRewrites.begin(); 7914 I != PredicatedSCEVRewrites.end();) { 7915 std::pair<const SCEV *, const Loop *> Entry = I->first; 7916 if (Entry.second == CurrL) 7917 PredicatedSCEVRewrites.erase(I++); 7918 else 7919 ++I; 7920 } 7921 7922 auto LoopUsersItr = LoopUsers.find(CurrL); 7923 if (LoopUsersItr != LoopUsers.end()) { 7924 ToForget.insert(ToForget.end(), LoopUsersItr->second.begin(), 7925 LoopUsersItr->second.end()); 7926 } 7927 7928 // Drop information about expressions based on loop-header PHIs. 7929 PushLoopPHIs(CurrL, Worklist, Visited); 7930 7931 while (!Worklist.empty()) { 7932 Instruction *I = Worklist.pop_back_val(); 7933 7934 ValueExprMapType::iterator It = 7935 ValueExprMap.find_as(static_cast<Value *>(I)); 7936 if (It != ValueExprMap.end()) { 7937 eraseValueFromMap(It->first); 7938 ToForget.push_back(It->second); 7939 if (PHINode *PN = dyn_cast<PHINode>(I)) 7940 ConstantEvolutionLoopExitValue.erase(PN); 7941 } 7942 7943 PushDefUseChildren(I, Worklist, Visited); 7944 } 7945 7946 LoopPropertiesCache.erase(CurrL); 7947 // Forget all contained loops too, to avoid dangling entries in the 7948 // ValuesAtScopes map. 7949 LoopWorklist.append(CurrL->begin(), CurrL->end()); 7950 } 7951 forgetMemoizedResults(ToForget); 7952 } 7953 7954 void ScalarEvolution::forgetTopmostLoop(const Loop *L) { 7955 while (Loop *Parent = L->getParentLoop()) 7956 L = Parent; 7957 forgetLoop(L); 7958 } 7959 7960 void ScalarEvolution::forgetValue(Value *V) { 7961 Instruction *I = dyn_cast<Instruction>(V); 7962 if (!I) return; 7963 7964 // Drop information about expressions based on loop-header PHIs. 7965 SmallVector<Instruction *, 16> Worklist; 7966 SmallPtrSet<Instruction *, 8> Visited; 7967 SmallVector<const SCEV *, 8> ToForget; 7968 Worklist.push_back(I); 7969 Visited.insert(I); 7970 7971 while (!Worklist.empty()) { 7972 I = Worklist.pop_back_val(); 7973 ValueExprMapType::iterator It = 7974 ValueExprMap.find_as(static_cast<Value *>(I)); 7975 if (It != ValueExprMap.end()) { 7976 eraseValueFromMap(It->first); 7977 ToForget.push_back(It->second); 7978 if (PHINode *PN = dyn_cast<PHINode>(I)) 7979 ConstantEvolutionLoopExitValue.erase(PN); 7980 } 7981 7982 PushDefUseChildren(I, Worklist, Visited); 7983 } 7984 forgetMemoizedResults(ToForget); 7985 } 7986 7987 void ScalarEvolution::forgetLoopDispositions(const Loop *L) { 7988 LoopDispositions.clear(); 7989 } 7990 7991 /// Get the exact loop backedge taken count considering all loop exits. A 7992 /// computable result can only be returned for loops with all exiting blocks 7993 /// dominating the latch. howFarToZero assumes that the limit of each loop test 7994 /// is never skipped. This is a valid assumption as long as the loop exits via 7995 /// that test. For precise results, it is the caller's responsibility to specify 7996 /// the relevant loop exiting block using getExact(ExitingBlock, SE). 7997 const SCEV * 7998 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE, 7999 SmallVector<const SCEVPredicate *, 4> *Preds) const { 8000 // If any exits were not computable, the loop is not computable. 8001 if (!isComplete() || ExitNotTaken.empty()) 8002 return SE->getCouldNotCompute(); 8003 8004 const BasicBlock *Latch = L->getLoopLatch(); 8005 // All exiting blocks we have collected must dominate the only backedge. 8006 if (!Latch) 8007 return SE->getCouldNotCompute(); 8008 8009 // All exiting blocks we have gathered dominate loop's latch, so exact trip 8010 // count is simply a minimum out of all these calculated exit counts. 8011 SmallVector<const SCEV *, 2> Ops; 8012 for (auto &ENT : ExitNotTaken) { 8013 const SCEV *BECount = ENT.ExactNotTaken; 8014 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!"); 8015 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) && 8016 "We should only have known counts for exiting blocks that dominate " 8017 "latch!"); 8018 8019 Ops.push_back(BECount); 8020 8021 if (Preds) 8022 for (auto *P : ENT.Predicates) 8023 Preds->push_back(P); 8024 8025 assert((Preds || ENT.hasAlwaysTruePredicate()) && 8026 "Predicate should be always true!"); 8027 } 8028 8029 return SE->getUMinFromMismatchedTypes(Ops); 8030 } 8031 8032 /// Get the exact not taken count for this loop exit. 8033 const SCEV * 8034 ScalarEvolution::BackedgeTakenInfo::getExact(const BasicBlock *ExitingBlock, 8035 ScalarEvolution *SE) const { 8036 for (auto &ENT : ExitNotTaken) 8037 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 8038 return ENT.ExactNotTaken; 8039 8040 return SE->getCouldNotCompute(); 8041 } 8042 8043 const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax( 8044 const BasicBlock *ExitingBlock, ScalarEvolution *SE) const { 8045 for (auto &ENT : ExitNotTaken) 8046 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 8047 return ENT.MaxNotTaken; 8048 8049 return SE->getCouldNotCompute(); 8050 } 8051 8052 /// getConstantMax - Get the constant max backedge taken count for the loop. 8053 const SCEV * 8054 ScalarEvolution::BackedgeTakenInfo::getConstantMax(ScalarEvolution *SE) const { 8055 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 8056 return !ENT.hasAlwaysTruePredicate(); 8057 }; 8058 8059 if (!getConstantMax() || any_of(ExitNotTaken, PredicateNotAlwaysTrue)) 8060 return SE->getCouldNotCompute(); 8061 8062 assert((isa<SCEVCouldNotCompute>(getConstantMax()) || 8063 isa<SCEVConstant>(getConstantMax())) && 8064 "No point in having a non-constant max backedge taken count!"); 8065 return getConstantMax(); 8066 } 8067 8068 const SCEV * 8069 ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(const Loop *L, 8070 ScalarEvolution *SE) { 8071 if (!SymbolicMax) 8072 SymbolicMax = SE->computeSymbolicMaxBackedgeTakenCount(L); 8073 return SymbolicMax; 8074 } 8075 8076 bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero( 8077 ScalarEvolution *SE) const { 8078 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 8079 return !ENT.hasAlwaysTruePredicate(); 8080 }; 8081 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 8082 } 8083 8084 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E) 8085 : ExitLimit(E, E, false, None) { 8086 } 8087 8088 ScalarEvolution::ExitLimit::ExitLimit( 8089 const SCEV *E, const SCEV *M, bool MaxOrZero, 8090 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList) 8091 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) { 8092 // If we prove the max count is zero, so is the symbolic bound. This happens 8093 // in practice due to differences in a) how context sensitive we've chosen 8094 // to be and b) how we reason about bounds impied by UB. 8095 if (MaxNotTaken->isZero()) 8096 ExactNotTaken = MaxNotTaken; 8097 8098 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) || 8099 !isa<SCEVCouldNotCompute>(MaxNotTaken)) && 8100 "Exact is not allowed to be less precise than Max"); 8101 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 8102 isa<SCEVConstant>(MaxNotTaken)) && 8103 "No point in having a non-constant max backedge taken count!"); 8104 for (auto *PredSet : PredSetList) 8105 for (auto *P : *PredSet) 8106 addPredicate(P); 8107 assert((isa<SCEVCouldNotCompute>(E) || !E->getType()->isPointerTy()) && 8108 "Backedge count should be int"); 8109 assert((isa<SCEVCouldNotCompute>(M) || !M->getType()->isPointerTy()) && 8110 "Max backedge count should be int"); 8111 } 8112 8113 ScalarEvolution::ExitLimit::ExitLimit( 8114 const SCEV *E, const SCEV *M, bool MaxOrZero, 8115 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet) 8116 : ExitLimit(E, M, MaxOrZero, {&PredSet}) { 8117 } 8118 8119 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M, 8120 bool MaxOrZero) 8121 : ExitLimit(E, M, MaxOrZero, None) { 8122 } 8123 8124 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 8125 /// computable exit into a persistent ExitNotTakenInfo array. 8126 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 8127 ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> ExitCounts, 8128 bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero) 8129 : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) { 8130 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 8131 8132 ExitNotTaken.reserve(ExitCounts.size()); 8133 std::transform( 8134 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 8135 [&](const EdgeExitInfo &EEI) { 8136 BasicBlock *ExitBB = EEI.first; 8137 const ExitLimit &EL = EEI.second; 8138 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 8139 EL.Predicates); 8140 }); 8141 assert((isa<SCEVCouldNotCompute>(ConstantMax) || 8142 isa<SCEVConstant>(ConstantMax)) && 8143 "No point in having a non-constant max backedge taken count!"); 8144 } 8145 8146 /// Compute the number of times the backedge of the specified loop will execute. 8147 ScalarEvolution::BackedgeTakenInfo 8148 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 8149 bool AllowPredicates) { 8150 SmallVector<BasicBlock *, 8> ExitingBlocks; 8151 L->getExitingBlocks(ExitingBlocks); 8152 8153 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 8154 8155 SmallVector<EdgeExitInfo, 4> ExitCounts; 8156 bool CouldComputeBECount = true; 8157 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 8158 const SCEV *MustExitMaxBECount = nullptr; 8159 const SCEV *MayExitMaxBECount = nullptr; 8160 bool MustExitMaxOrZero = false; 8161 8162 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 8163 // and compute maxBECount. 8164 // Do a union of all the predicates here. 8165 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 8166 BasicBlock *ExitBB = ExitingBlocks[i]; 8167 8168 // We canonicalize untaken exits to br (constant), ignore them so that 8169 // proving an exit untaken doesn't negatively impact our ability to reason 8170 // about the loop as whole. 8171 if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator())) 8172 if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) { 8173 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 8174 if (ExitIfTrue == CI->isZero()) 8175 continue; 8176 } 8177 8178 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 8179 8180 assert((AllowPredicates || EL.Predicates.empty()) && 8181 "Predicated exit limit when predicates are not allowed!"); 8182 8183 // 1. For each exit that can be computed, add an entry to ExitCounts. 8184 // CouldComputeBECount is true only if all exits can be computed. 8185 if (EL.ExactNotTaken == getCouldNotCompute()) 8186 // We couldn't compute an exact value for this exit, so 8187 // we won't be able to compute an exact value for the loop. 8188 CouldComputeBECount = false; 8189 else 8190 ExitCounts.emplace_back(ExitBB, EL); 8191 8192 // 2. Derive the loop's MaxBECount from each exit's max number of 8193 // non-exiting iterations. Partition the loop exits into two kinds: 8194 // LoopMustExits and LoopMayExits. 8195 // 8196 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 8197 // is a LoopMayExit. If any computable LoopMustExit is found, then 8198 // MaxBECount is the minimum EL.MaxNotTaken of computable 8199 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 8200 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 8201 // computable EL.MaxNotTaken. 8202 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 8203 DT.dominates(ExitBB, Latch)) { 8204 if (!MustExitMaxBECount) { 8205 MustExitMaxBECount = EL.MaxNotTaken; 8206 MustExitMaxOrZero = EL.MaxOrZero; 8207 } else { 8208 MustExitMaxBECount = 8209 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 8210 } 8211 } else if (MayExitMaxBECount != getCouldNotCompute()) { 8212 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 8213 MayExitMaxBECount = EL.MaxNotTaken; 8214 else { 8215 MayExitMaxBECount = 8216 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 8217 } 8218 } 8219 } 8220 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 8221 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 8222 // The loop backedge will be taken the maximum or zero times if there's 8223 // a single exit that must be taken the maximum or zero times. 8224 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 8225 8226 // Remember which SCEVs are used in exit limits for invalidation purposes. 8227 // We only care about non-constant SCEVs here, so we can ignore EL.MaxNotTaken 8228 // and MaxBECount, which must be SCEVConstant. 8229 for (const auto &Pair : ExitCounts) 8230 if (!isa<SCEVConstant>(Pair.second.ExactNotTaken)) 8231 BECountUsers[Pair.second.ExactNotTaken].insert({L, AllowPredicates}); 8232 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 8233 MaxBECount, MaxOrZero); 8234 } 8235 8236 ScalarEvolution::ExitLimit 8237 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 8238 bool AllowPredicates) { 8239 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?"); 8240 // If our exiting block does not dominate the latch, then its connection with 8241 // loop's exit limit may be far from trivial. 8242 const BasicBlock *Latch = L->getLoopLatch(); 8243 if (!Latch || !DT.dominates(ExitingBlock, Latch)) 8244 return getCouldNotCompute(); 8245 8246 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 8247 Instruction *Term = ExitingBlock->getTerminator(); 8248 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 8249 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 8250 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 8251 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) && 8252 "It should have one successor in loop and one exit block!"); 8253 // Proceed to the next level to examine the exit condition expression. 8254 return computeExitLimitFromCond( 8255 L, BI->getCondition(), ExitIfTrue, 8256 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 8257 } 8258 8259 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) { 8260 // For switch, make sure that there is a single exit from the loop. 8261 BasicBlock *Exit = nullptr; 8262 for (auto *SBB : successors(ExitingBlock)) 8263 if (!L->contains(SBB)) { 8264 if (Exit) // Multiple exit successors. 8265 return getCouldNotCompute(); 8266 Exit = SBB; 8267 } 8268 assert(Exit && "Exiting block must have at least one exit"); 8269 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 8270 /*ControlsExit=*/IsOnlyExit); 8271 } 8272 8273 return getCouldNotCompute(); 8274 } 8275 8276 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond( 8277 const Loop *L, Value *ExitCond, bool ExitIfTrue, 8278 bool ControlsExit, bool AllowPredicates) { 8279 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates); 8280 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue, 8281 ControlsExit, AllowPredicates); 8282 } 8283 8284 Optional<ScalarEvolution::ExitLimit> 8285 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond, 8286 bool ExitIfTrue, bool ControlsExit, 8287 bool AllowPredicates) { 8288 (void)this->L; 8289 (void)this->ExitIfTrue; 8290 (void)this->AllowPredicates; 8291 8292 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 8293 this->AllowPredicates == AllowPredicates && 8294 "Variance in assumed invariant key components!"); 8295 auto Itr = TripCountMap.find({ExitCond, ControlsExit}); 8296 if (Itr == TripCountMap.end()) 8297 return None; 8298 return Itr->second; 8299 } 8300 8301 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond, 8302 bool ExitIfTrue, 8303 bool ControlsExit, 8304 bool AllowPredicates, 8305 const ExitLimit &EL) { 8306 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 8307 this->AllowPredicates == AllowPredicates && 8308 "Variance in assumed invariant key components!"); 8309 8310 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL}); 8311 assert(InsertResult.second && "Expected successful insertion!"); 8312 (void)InsertResult; 8313 (void)ExitIfTrue; 8314 } 8315 8316 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached( 8317 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 8318 bool ControlsExit, bool AllowPredicates) { 8319 8320 if (auto MaybeEL = 8321 Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 8322 return *MaybeEL; 8323 8324 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue, 8325 ControlsExit, AllowPredicates); 8326 Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL); 8327 return EL; 8328 } 8329 8330 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl( 8331 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 8332 bool ControlsExit, bool AllowPredicates) { 8333 // Handle BinOp conditions (And, Or). 8334 if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp( 8335 Cache, L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 8336 return *LimitFromBinOp; 8337 8338 // With an icmp, it may be feasible to compute an exact backedge-taken count. 8339 // Proceed to the next level to examine the icmp. 8340 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 8341 ExitLimit EL = 8342 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit); 8343 if (EL.hasFullInfo() || !AllowPredicates) 8344 return EL; 8345 8346 // Try again, but use SCEV predicates this time. 8347 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit, 8348 /*AllowPredicates=*/true); 8349 } 8350 8351 // Check for a constant condition. These are normally stripped out by 8352 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 8353 // preserve the CFG and is temporarily leaving constant conditions 8354 // in place. 8355 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 8356 if (ExitIfTrue == !CI->getZExtValue()) 8357 // The backedge is always taken. 8358 return getCouldNotCompute(); 8359 else 8360 // The backedge is never taken. 8361 return getZero(CI->getType()); 8362 } 8363 8364 // If we're exiting based on the overflow flag of an x.with.overflow intrinsic 8365 // with a constant step, we can form an equivalent icmp predicate and figure 8366 // out how many iterations will be taken before we exit. 8367 const WithOverflowInst *WO; 8368 const APInt *C; 8369 if (match(ExitCond, m_ExtractValue<1>(m_WithOverflowInst(WO))) && 8370 match(WO->getRHS(), m_APInt(C))) { 8371 ConstantRange NWR = 8372 ConstantRange::makeExactNoWrapRegion(WO->getBinaryOp(), *C, 8373 WO->getNoWrapKind()); 8374 CmpInst::Predicate Pred; 8375 APInt NewRHSC, Offset; 8376 NWR.getEquivalentICmp(Pred, NewRHSC, Offset); 8377 if (!ExitIfTrue) 8378 Pred = ICmpInst::getInversePredicate(Pred); 8379 auto *LHS = getSCEV(WO->getLHS()); 8380 if (Offset != 0) 8381 LHS = getAddExpr(LHS, getConstant(Offset)); 8382 auto EL = computeExitLimitFromICmp(L, Pred, LHS, getConstant(NewRHSC), 8383 ControlsExit, AllowPredicates); 8384 if (EL.hasAnyInfo()) return EL; 8385 } 8386 8387 // If it's not an integer or pointer comparison then compute it the hard way. 8388 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 8389 } 8390 8391 Optional<ScalarEvolution::ExitLimit> 8392 ScalarEvolution::computeExitLimitFromCondFromBinOp( 8393 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 8394 bool ControlsExit, bool AllowPredicates) { 8395 // Check if the controlling expression for this loop is an And or Or. 8396 Value *Op0, *Op1; 8397 bool IsAnd = false; 8398 if (match(ExitCond, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) 8399 IsAnd = true; 8400 else if (match(ExitCond, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) 8401 IsAnd = false; 8402 else 8403 return None; 8404 8405 // EitherMayExit is true in these two cases: 8406 // br (and Op0 Op1), loop, exit 8407 // br (or Op0 Op1), exit, loop 8408 bool EitherMayExit = IsAnd ^ ExitIfTrue; 8409 ExitLimit EL0 = computeExitLimitFromCondCached(Cache, L, Op0, ExitIfTrue, 8410 ControlsExit && !EitherMayExit, 8411 AllowPredicates); 8412 ExitLimit EL1 = computeExitLimitFromCondCached(Cache, L, Op1, ExitIfTrue, 8413 ControlsExit && !EitherMayExit, 8414 AllowPredicates); 8415 8416 // Be robust against unsimplified IR for the form "op i1 X, NeutralElement" 8417 const Constant *NeutralElement = ConstantInt::get(ExitCond->getType(), IsAnd); 8418 if (isa<ConstantInt>(Op1)) 8419 return Op1 == NeutralElement ? EL0 : EL1; 8420 if (isa<ConstantInt>(Op0)) 8421 return Op0 == NeutralElement ? EL1 : EL0; 8422 8423 const SCEV *BECount = getCouldNotCompute(); 8424 const SCEV *MaxBECount = getCouldNotCompute(); 8425 if (EitherMayExit) { 8426 // Both conditions must be same for the loop to continue executing. 8427 // Choose the less conservative count. 8428 if (EL0.ExactNotTaken != getCouldNotCompute() && 8429 EL1.ExactNotTaken != getCouldNotCompute()) { 8430 BECount = getUMinFromMismatchedTypes( 8431 EL0.ExactNotTaken, EL1.ExactNotTaken, 8432 /*Sequential=*/!isa<BinaryOperator>(ExitCond)); 8433 8434 // If EL0.ExactNotTaken was zero and ExitCond was a short-circuit form, 8435 // it should have been simplified to zero (see the condition (3) above) 8436 assert(!isa<BinaryOperator>(ExitCond) || !EL0.ExactNotTaken->isZero() || 8437 BECount->isZero()); 8438 } 8439 if (EL0.MaxNotTaken == getCouldNotCompute()) 8440 MaxBECount = EL1.MaxNotTaken; 8441 else if (EL1.MaxNotTaken == getCouldNotCompute()) 8442 MaxBECount = EL0.MaxNotTaken; 8443 else 8444 MaxBECount = getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 8445 } else { 8446 // Both conditions must be same at the same time for the loop to exit. 8447 // For now, be conservative. 8448 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 8449 BECount = EL0.ExactNotTaken; 8450 } 8451 8452 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 8453 // to be more aggressive when computing BECount than when computing 8454 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 8455 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 8456 // to not. 8457 if (isa<SCEVCouldNotCompute>(MaxBECount) && 8458 !isa<SCEVCouldNotCompute>(BECount)) 8459 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 8460 8461 return ExitLimit(BECount, MaxBECount, false, 8462 { &EL0.Predicates, &EL1.Predicates }); 8463 } 8464 8465 ScalarEvolution::ExitLimit 8466 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 8467 ICmpInst *ExitCond, 8468 bool ExitIfTrue, 8469 bool ControlsExit, 8470 bool AllowPredicates) { 8471 // If the condition was exit on true, convert the condition to exit on false 8472 ICmpInst::Predicate Pred; 8473 if (!ExitIfTrue) 8474 Pred = ExitCond->getPredicate(); 8475 else 8476 Pred = ExitCond->getInversePredicate(); 8477 const ICmpInst::Predicate OriginalPred = Pred; 8478 8479 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 8480 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 8481 8482 ExitLimit EL = computeExitLimitFromICmp(L, Pred, LHS, RHS, ControlsExit, 8483 AllowPredicates); 8484 if (EL.hasAnyInfo()) return EL; 8485 8486 auto *ExhaustiveCount = 8487 computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 8488 8489 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 8490 return ExhaustiveCount; 8491 8492 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 8493 ExitCond->getOperand(1), L, OriginalPred); 8494 } 8495 ScalarEvolution::ExitLimit 8496 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 8497 ICmpInst::Predicate Pred, 8498 const SCEV *LHS, const SCEV *RHS, 8499 bool ControlsExit, 8500 bool AllowPredicates) { 8501 8502 // Try to evaluate any dependencies out of the loop. 8503 LHS = getSCEVAtScope(LHS, L); 8504 RHS = getSCEVAtScope(RHS, L); 8505 8506 // At this point, we would like to compute how many iterations of the 8507 // loop the predicate will return true for these inputs. 8508 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 8509 // If there is a loop-invariant, force it into the RHS. 8510 std::swap(LHS, RHS); 8511 Pred = ICmpInst::getSwappedPredicate(Pred); 8512 } 8513 8514 bool ControllingFiniteLoop = 8515 ControlsExit && loopHasNoAbnormalExits(L) && loopIsFiniteByAssumption(L); 8516 // Simplify the operands before analyzing them. 8517 (void)SimplifyICmpOperands(Pred, LHS, RHS, /*Depth=*/0, 8518 (EnableFiniteLoopControl ? ControllingFiniteLoop 8519 : false)); 8520 8521 // If we have a comparison of a chrec against a constant, try to use value 8522 // ranges to answer this query. 8523 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 8524 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 8525 if (AddRec->getLoop() == L) { 8526 // Form the constant range. 8527 ConstantRange CompRange = 8528 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt()); 8529 8530 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 8531 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 8532 } 8533 8534 // If this loop must exit based on this condition (or execute undefined 8535 // behaviour), and we can prove the test sequence produced must repeat 8536 // the same values on self-wrap of the IV, then we can infer that IV 8537 // doesn't self wrap because if it did, we'd have an infinite (undefined) 8538 // loop. 8539 if (ControllingFiniteLoop && isLoopInvariant(RHS, L)) { 8540 // TODO: We can peel off any functions which are invertible *in L*. Loop 8541 // invariant terms are effectively constants for our purposes here. 8542 auto *InnerLHS = LHS; 8543 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS)) 8544 InnerLHS = ZExt->getOperand(); 8545 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(InnerLHS)) { 8546 auto *StrideC = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)); 8547 if (!AR->hasNoSelfWrap() && AR->getLoop() == L && AR->isAffine() && 8548 StrideC && StrideC->getAPInt().isPowerOf2()) { 8549 auto Flags = AR->getNoWrapFlags(); 8550 Flags = setFlags(Flags, SCEV::FlagNW); 8551 SmallVector<const SCEV*> Operands{AR->operands()}; 8552 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 8553 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags); 8554 } 8555 } 8556 } 8557 8558 switch (Pred) { 8559 case ICmpInst::ICMP_NE: { // while (X != Y) 8560 // Convert to: while (X-Y != 0) 8561 if (LHS->getType()->isPointerTy()) { 8562 LHS = getLosslessPtrToIntExpr(LHS); 8563 if (isa<SCEVCouldNotCompute>(LHS)) 8564 return LHS; 8565 } 8566 if (RHS->getType()->isPointerTy()) { 8567 RHS = getLosslessPtrToIntExpr(RHS); 8568 if (isa<SCEVCouldNotCompute>(RHS)) 8569 return RHS; 8570 } 8571 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 8572 AllowPredicates); 8573 if (EL.hasAnyInfo()) return EL; 8574 break; 8575 } 8576 case ICmpInst::ICMP_EQ: { // while (X == Y) 8577 // Convert to: while (X-Y == 0) 8578 if (LHS->getType()->isPointerTy()) { 8579 LHS = getLosslessPtrToIntExpr(LHS); 8580 if (isa<SCEVCouldNotCompute>(LHS)) 8581 return LHS; 8582 } 8583 if (RHS->getType()->isPointerTy()) { 8584 RHS = getLosslessPtrToIntExpr(RHS); 8585 if (isa<SCEVCouldNotCompute>(RHS)) 8586 return RHS; 8587 } 8588 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 8589 if (EL.hasAnyInfo()) return EL; 8590 break; 8591 } 8592 case ICmpInst::ICMP_SLT: 8593 case ICmpInst::ICMP_ULT: { // while (X < Y) 8594 bool IsSigned = Pred == ICmpInst::ICMP_SLT; 8595 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 8596 AllowPredicates); 8597 if (EL.hasAnyInfo()) return EL; 8598 break; 8599 } 8600 case ICmpInst::ICMP_SGT: 8601 case ICmpInst::ICMP_UGT: { // while (X > Y) 8602 bool IsSigned = Pred == ICmpInst::ICMP_SGT; 8603 ExitLimit EL = 8604 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 8605 AllowPredicates); 8606 if (EL.hasAnyInfo()) return EL; 8607 break; 8608 } 8609 default: 8610 break; 8611 } 8612 8613 return getCouldNotCompute(); 8614 } 8615 8616 ScalarEvolution::ExitLimit 8617 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 8618 SwitchInst *Switch, 8619 BasicBlock *ExitingBlock, 8620 bool ControlsExit) { 8621 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 8622 8623 // Give up if the exit is the default dest of a switch. 8624 if (Switch->getDefaultDest() == ExitingBlock) 8625 return getCouldNotCompute(); 8626 8627 assert(L->contains(Switch->getDefaultDest()) && 8628 "Default case must not exit the loop!"); 8629 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 8630 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 8631 8632 // while (X != Y) --> while (X-Y != 0) 8633 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 8634 if (EL.hasAnyInfo()) 8635 return EL; 8636 8637 return getCouldNotCompute(); 8638 } 8639 8640 static ConstantInt * 8641 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 8642 ScalarEvolution &SE) { 8643 const SCEV *InVal = SE.getConstant(C); 8644 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 8645 assert(isa<SCEVConstant>(Val) && 8646 "Evaluation of SCEV at constant didn't fold correctly?"); 8647 return cast<SCEVConstant>(Val)->getValue(); 8648 } 8649 8650 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 8651 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 8652 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 8653 if (!RHS) 8654 return getCouldNotCompute(); 8655 8656 const BasicBlock *Latch = L->getLoopLatch(); 8657 if (!Latch) 8658 return getCouldNotCompute(); 8659 8660 const BasicBlock *Predecessor = L->getLoopPredecessor(); 8661 if (!Predecessor) 8662 return getCouldNotCompute(); 8663 8664 // Return true if V is of the form "LHS `shift_op` <positive constant>". 8665 // Return LHS in OutLHS and shift_opt in OutOpCode. 8666 auto MatchPositiveShift = 8667 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 8668 8669 using namespace PatternMatch; 8670 8671 ConstantInt *ShiftAmt; 8672 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 8673 OutOpCode = Instruction::LShr; 8674 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 8675 OutOpCode = Instruction::AShr; 8676 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 8677 OutOpCode = Instruction::Shl; 8678 else 8679 return false; 8680 8681 return ShiftAmt->getValue().isStrictlyPositive(); 8682 }; 8683 8684 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 8685 // 8686 // loop: 8687 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 8688 // %iv.shifted = lshr i32 %iv, <positive constant> 8689 // 8690 // Return true on a successful match. Return the corresponding PHI node (%iv 8691 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 8692 auto MatchShiftRecurrence = 8693 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 8694 Optional<Instruction::BinaryOps> PostShiftOpCode; 8695 8696 { 8697 Instruction::BinaryOps OpC; 8698 Value *V; 8699 8700 // If we encounter a shift instruction, "peel off" the shift operation, 8701 // and remember that we did so. Later when we inspect %iv's backedge 8702 // value, we will make sure that the backedge value uses the same 8703 // operation. 8704 // 8705 // Note: the peeled shift operation does not have to be the same 8706 // instruction as the one feeding into the PHI's backedge value. We only 8707 // really care about it being the same *kind* of shift instruction -- 8708 // that's all that is required for our later inferences to hold. 8709 if (MatchPositiveShift(LHS, V, OpC)) { 8710 PostShiftOpCode = OpC; 8711 LHS = V; 8712 } 8713 } 8714 8715 PNOut = dyn_cast<PHINode>(LHS); 8716 if (!PNOut || PNOut->getParent() != L->getHeader()) 8717 return false; 8718 8719 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 8720 Value *OpLHS; 8721 8722 return 8723 // The backedge value for the PHI node must be a shift by a positive 8724 // amount 8725 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 8726 8727 // of the PHI node itself 8728 OpLHS == PNOut && 8729 8730 // and the kind of shift should be match the kind of shift we peeled 8731 // off, if any. 8732 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 8733 }; 8734 8735 PHINode *PN; 8736 Instruction::BinaryOps OpCode; 8737 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 8738 return getCouldNotCompute(); 8739 8740 const DataLayout &DL = getDataLayout(); 8741 8742 // The key rationale for this optimization is that for some kinds of shift 8743 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 8744 // within a finite number of iterations. If the condition guarding the 8745 // backedge (in the sense that the backedge is taken if the condition is true) 8746 // is false for the value the shift recurrence stabilizes to, then we know 8747 // that the backedge is taken only a finite number of times. 8748 8749 ConstantInt *StableValue = nullptr; 8750 switch (OpCode) { 8751 default: 8752 llvm_unreachable("Impossible case!"); 8753 8754 case Instruction::AShr: { 8755 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 8756 // bitwidth(K) iterations. 8757 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 8758 KnownBits Known = computeKnownBits(FirstValue, DL, 0, &AC, 8759 Predecessor->getTerminator(), &DT); 8760 auto *Ty = cast<IntegerType>(RHS->getType()); 8761 if (Known.isNonNegative()) 8762 StableValue = ConstantInt::get(Ty, 0); 8763 else if (Known.isNegative()) 8764 StableValue = ConstantInt::get(Ty, -1, true); 8765 else 8766 return getCouldNotCompute(); 8767 8768 break; 8769 } 8770 case Instruction::LShr: 8771 case Instruction::Shl: 8772 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 8773 // stabilize to 0 in at most bitwidth(K) iterations. 8774 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 8775 break; 8776 } 8777 8778 auto *Result = 8779 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 8780 assert(Result->getType()->isIntegerTy(1) && 8781 "Otherwise cannot be an operand to a branch instruction"); 8782 8783 if (Result->isZeroValue()) { 8784 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 8785 const SCEV *UpperBound = 8786 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 8787 return ExitLimit(getCouldNotCompute(), UpperBound, false); 8788 } 8789 8790 return getCouldNotCompute(); 8791 } 8792 8793 /// Return true if we can constant fold an instruction of the specified type, 8794 /// assuming that all operands were constants. 8795 static bool CanConstantFold(const Instruction *I) { 8796 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 8797 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 8798 isa<LoadInst>(I) || isa<ExtractValueInst>(I)) 8799 return true; 8800 8801 if (const CallInst *CI = dyn_cast<CallInst>(I)) 8802 if (const Function *F = CI->getCalledFunction()) 8803 return canConstantFoldCallTo(CI, F); 8804 return false; 8805 } 8806 8807 /// Determine whether this instruction can constant evolve within this loop 8808 /// assuming its operands can all constant evolve. 8809 static bool canConstantEvolve(Instruction *I, const Loop *L) { 8810 // An instruction outside of the loop can't be derived from a loop PHI. 8811 if (!L->contains(I)) return false; 8812 8813 if (isa<PHINode>(I)) { 8814 // We don't currently keep track of the control flow needed to evaluate 8815 // PHIs, so we cannot handle PHIs inside of loops. 8816 return L->getHeader() == I->getParent(); 8817 } 8818 8819 // If we won't be able to constant fold this expression even if the operands 8820 // are constants, bail early. 8821 return CanConstantFold(I); 8822 } 8823 8824 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 8825 /// recursing through each instruction operand until reaching a loop header phi. 8826 static PHINode * 8827 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 8828 DenseMap<Instruction *, PHINode *> &PHIMap, 8829 unsigned Depth) { 8830 if (Depth > MaxConstantEvolvingDepth) 8831 return nullptr; 8832 8833 // Otherwise, we can evaluate this instruction if all of its operands are 8834 // constant or derived from a PHI node themselves. 8835 PHINode *PHI = nullptr; 8836 for (Value *Op : UseInst->operands()) { 8837 if (isa<Constant>(Op)) continue; 8838 8839 Instruction *OpInst = dyn_cast<Instruction>(Op); 8840 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 8841 8842 PHINode *P = dyn_cast<PHINode>(OpInst); 8843 if (!P) 8844 // If this operand is already visited, reuse the prior result. 8845 // We may have P != PHI if this is the deepest point at which the 8846 // inconsistent paths meet. 8847 P = PHIMap.lookup(OpInst); 8848 if (!P) { 8849 // Recurse and memoize the results, whether a phi is found or not. 8850 // This recursive call invalidates pointers into PHIMap. 8851 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1); 8852 PHIMap[OpInst] = P; 8853 } 8854 if (!P) 8855 return nullptr; // Not evolving from PHI 8856 if (PHI && PHI != P) 8857 return nullptr; // Evolving from multiple different PHIs. 8858 PHI = P; 8859 } 8860 // This is a expression evolving from a constant PHI! 8861 return PHI; 8862 } 8863 8864 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 8865 /// in the loop that V is derived from. We allow arbitrary operations along the 8866 /// way, but the operands of an operation must either be constants or a value 8867 /// derived from a constant PHI. If this expression does not fit with these 8868 /// constraints, return null. 8869 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 8870 Instruction *I = dyn_cast<Instruction>(V); 8871 if (!I || !canConstantEvolve(I, L)) return nullptr; 8872 8873 if (PHINode *PN = dyn_cast<PHINode>(I)) 8874 return PN; 8875 8876 // Record non-constant instructions contained by the loop. 8877 DenseMap<Instruction *, PHINode *> PHIMap; 8878 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0); 8879 } 8880 8881 /// EvaluateExpression - Given an expression that passes the 8882 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 8883 /// in the loop has the value PHIVal. If we can't fold this expression for some 8884 /// reason, return null. 8885 static Constant *EvaluateExpression(Value *V, const Loop *L, 8886 DenseMap<Instruction *, Constant *> &Vals, 8887 const DataLayout &DL, 8888 const TargetLibraryInfo *TLI) { 8889 // Convenient constant check, but redundant for recursive calls. 8890 if (Constant *C = dyn_cast<Constant>(V)) return C; 8891 Instruction *I = dyn_cast<Instruction>(V); 8892 if (!I) return nullptr; 8893 8894 if (Constant *C = Vals.lookup(I)) return C; 8895 8896 // An instruction inside the loop depends on a value outside the loop that we 8897 // weren't given a mapping for, or a value such as a call inside the loop. 8898 if (!canConstantEvolve(I, L)) return nullptr; 8899 8900 // An unmapped PHI can be due to a branch or another loop inside this loop, 8901 // or due to this not being the initial iteration through a loop where we 8902 // couldn't compute the evolution of this particular PHI last time. 8903 if (isa<PHINode>(I)) return nullptr; 8904 8905 std::vector<Constant*> Operands(I->getNumOperands()); 8906 8907 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 8908 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 8909 if (!Operand) { 8910 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 8911 if (!Operands[i]) return nullptr; 8912 continue; 8913 } 8914 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 8915 Vals[Operand] = C; 8916 if (!C) return nullptr; 8917 Operands[i] = C; 8918 } 8919 8920 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 8921 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8922 Operands[1], DL, TLI); 8923 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 8924 if (!LI->isVolatile()) 8925 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 8926 } 8927 return ConstantFoldInstOperands(I, Operands, DL, TLI); 8928 } 8929 8930 8931 // If every incoming value to PN except the one for BB is a specific Constant, 8932 // return that, else return nullptr. 8933 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 8934 Constant *IncomingVal = nullptr; 8935 8936 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 8937 if (PN->getIncomingBlock(i) == BB) 8938 continue; 8939 8940 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 8941 if (!CurrentVal) 8942 return nullptr; 8943 8944 if (IncomingVal != CurrentVal) { 8945 if (IncomingVal) 8946 return nullptr; 8947 IncomingVal = CurrentVal; 8948 } 8949 } 8950 8951 return IncomingVal; 8952 } 8953 8954 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 8955 /// in the header of its containing loop, we know the loop executes a 8956 /// constant number of times, and the PHI node is just a recurrence 8957 /// involving constants, fold it. 8958 Constant * 8959 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 8960 const APInt &BEs, 8961 const Loop *L) { 8962 auto I = ConstantEvolutionLoopExitValue.find(PN); 8963 if (I != ConstantEvolutionLoopExitValue.end()) 8964 return I->second; 8965 8966 if (BEs.ugt(MaxBruteForceIterations)) 8967 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 8968 8969 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 8970 8971 DenseMap<Instruction *, Constant *> CurrentIterVals; 8972 BasicBlock *Header = L->getHeader(); 8973 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 8974 8975 BasicBlock *Latch = L->getLoopLatch(); 8976 if (!Latch) 8977 return nullptr; 8978 8979 for (PHINode &PHI : Header->phis()) { 8980 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 8981 CurrentIterVals[&PHI] = StartCST; 8982 } 8983 if (!CurrentIterVals.count(PN)) 8984 return RetVal = nullptr; 8985 8986 Value *BEValue = PN->getIncomingValueForBlock(Latch); 8987 8988 // Execute the loop symbolically to determine the exit value. 8989 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) && 8990 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!"); 8991 8992 unsigned NumIterations = BEs.getZExtValue(); // must be in range 8993 unsigned IterationNum = 0; 8994 const DataLayout &DL = getDataLayout(); 8995 for (; ; ++IterationNum) { 8996 if (IterationNum == NumIterations) 8997 return RetVal = CurrentIterVals[PN]; // Got exit value! 8998 8999 // Compute the value of the PHIs for the next iteration. 9000 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 9001 DenseMap<Instruction *, Constant *> NextIterVals; 9002 Constant *NextPHI = 9003 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 9004 if (!NextPHI) 9005 return nullptr; // Couldn't evaluate! 9006 NextIterVals[PN] = NextPHI; 9007 9008 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 9009 9010 // Also evaluate the other PHI nodes. However, we don't get to stop if we 9011 // cease to be able to evaluate one of them or if they stop evolving, 9012 // because that doesn't necessarily prevent us from computing PN. 9013 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 9014 for (const auto &I : CurrentIterVals) { 9015 PHINode *PHI = dyn_cast<PHINode>(I.first); 9016 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 9017 PHIsToCompute.emplace_back(PHI, I.second); 9018 } 9019 // We use two distinct loops because EvaluateExpression may invalidate any 9020 // iterators into CurrentIterVals. 9021 for (const auto &I : PHIsToCompute) { 9022 PHINode *PHI = I.first; 9023 Constant *&NextPHI = NextIterVals[PHI]; 9024 if (!NextPHI) { // Not already computed. 9025 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 9026 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 9027 } 9028 if (NextPHI != I.second) 9029 StoppedEvolving = false; 9030 } 9031 9032 // If all entries in CurrentIterVals == NextIterVals then we can stop 9033 // iterating, the loop can't continue to change. 9034 if (StoppedEvolving) 9035 return RetVal = CurrentIterVals[PN]; 9036 9037 CurrentIterVals.swap(NextIterVals); 9038 } 9039 } 9040 9041 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 9042 Value *Cond, 9043 bool ExitWhen) { 9044 PHINode *PN = getConstantEvolvingPHI(Cond, L); 9045 if (!PN) return getCouldNotCompute(); 9046 9047 // If the loop is canonicalized, the PHI will have exactly two entries. 9048 // That's the only form we support here. 9049 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 9050 9051 DenseMap<Instruction *, Constant *> CurrentIterVals; 9052 BasicBlock *Header = L->getHeader(); 9053 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 9054 9055 BasicBlock *Latch = L->getLoopLatch(); 9056 assert(Latch && "Should follow from NumIncomingValues == 2!"); 9057 9058 for (PHINode &PHI : Header->phis()) { 9059 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 9060 CurrentIterVals[&PHI] = StartCST; 9061 } 9062 if (!CurrentIterVals.count(PN)) 9063 return getCouldNotCompute(); 9064 9065 // Okay, we find a PHI node that defines the trip count of this loop. Execute 9066 // the loop symbolically to determine when the condition gets a value of 9067 // "ExitWhen". 9068 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 9069 const DataLayout &DL = getDataLayout(); 9070 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 9071 auto *CondVal = dyn_cast_or_null<ConstantInt>( 9072 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 9073 9074 // Couldn't symbolically evaluate. 9075 if (!CondVal) return getCouldNotCompute(); 9076 9077 if (CondVal->getValue() == uint64_t(ExitWhen)) { 9078 ++NumBruteForceTripCountsComputed; 9079 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 9080 } 9081 9082 // Update all the PHI nodes for the next iteration. 9083 DenseMap<Instruction *, Constant *> NextIterVals; 9084 9085 // Create a list of which PHIs we need to compute. We want to do this before 9086 // calling EvaluateExpression on them because that may invalidate iterators 9087 // into CurrentIterVals. 9088 SmallVector<PHINode *, 8> PHIsToCompute; 9089 for (const auto &I : CurrentIterVals) { 9090 PHINode *PHI = dyn_cast<PHINode>(I.first); 9091 if (!PHI || PHI->getParent() != Header) continue; 9092 PHIsToCompute.push_back(PHI); 9093 } 9094 for (PHINode *PHI : PHIsToCompute) { 9095 Constant *&NextPHI = NextIterVals[PHI]; 9096 if (NextPHI) continue; // Already computed! 9097 9098 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 9099 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 9100 } 9101 CurrentIterVals.swap(NextIterVals); 9102 } 9103 9104 // Too many iterations were needed to evaluate. 9105 return getCouldNotCompute(); 9106 } 9107 9108 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 9109 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 9110 ValuesAtScopes[V]; 9111 // Check to see if we've folded this expression at this loop before. 9112 for (auto &LS : Values) 9113 if (LS.first == L) 9114 return LS.second ? LS.second : V; 9115 9116 Values.emplace_back(L, nullptr); 9117 9118 // Otherwise compute it. 9119 const SCEV *C = computeSCEVAtScope(V, L); 9120 for (auto &LS : reverse(ValuesAtScopes[V])) 9121 if (LS.first == L) { 9122 LS.second = C; 9123 if (!isa<SCEVConstant>(C)) 9124 ValuesAtScopesUsers[C].push_back({L, V}); 9125 break; 9126 } 9127 return C; 9128 } 9129 9130 /// This builds up a Constant using the ConstantExpr interface. That way, we 9131 /// will return Constants for objects which aren't represented by a 9132 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 9133 /// Returns NULL if the SCEV isn't representable as a Constant. 9134 static Constant *BuildConstantFromSCEV(const SCEV *V) { 9135 switch (V->getSCEVType()) { 9136 case scCouldNotCompute: 9137 case scAddRecExpr: 9138 return nullptr; 9139 case scConstant: 9140 return cast<SCEVConstant>(V)->getValue(); 9141 case scUnknown: 9142 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 9143 case scSignExtend: { 9144 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 9145 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 9146 return ConstantExpr::getSExt(CastOp, SS->getType()); 9147 return nullptr; 9148 } 9149 case scZeroExtend: { 9150 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 9151 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 9152 return ConstantExpr::getZExt(CastOp, SZ->getType()); 9153 return nullptr; 9154 } 9155 case scPtrToInt: { 9156 const SCEVPtrToIntExpr *P2I = cast<SCEVPtrToIntExpr>(V); 9157 if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand())) 9158 return ConstantExpr::getPtrToInt(CastOp, P2I->getType()); 9159 9160 return nullptr; 9161 } 9162 case scTruncate: { 9163 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 9164 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 9165 return ConstantExpr::getTrunc(CastOp, ST->getType()); 9166 return nullptr; 9167 } 9168 case scAddExpr: { 9169 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 9170 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 9171 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 9172 unsigned AS = PTy->getAddressSpace(); 9173 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 9174 C = ConstantExpr::getBitCast(C, DestPtrTy); 9175 } 9176 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 9177 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 9178 if (!C2) 9179 return nullptr; 9180 9181 // First pointer! 9182 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 9183 unsigned AS = C2->getType()->getPointerAddressSpace(); 9184 std::swap(C, C2); 9185 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 9186 // The offsets have been converted to bytes. We can add bytes to an 9187 // i8* by GEP with the byte count in the first index. 9188 C = ConstantExpr::getBitCast(C, DestPtrTy); 9189 } 9190 9191 // Don't bother trying to sum two pointers. We probably can't 9192 // statically compute a load that results from it anyway. 9193 if (C2->getType()->isPointerTy()) 9194 return nullptr; 9195 9196 if (C->getType()->isPointerTy()) { 9197 C = ConstantExpr::getGetElementPtr(Type::getInt8Ty(C->getContext()), 9198 C, C2); 9199 } else { 9200 C = ConstantExpr::getAdd(C, C2); 9201 } 9202 } 9203 return C; 9204 } 9205 return nullptr; 9206 } 9207 case scMulExpr: { 9208 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 9209 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 9210 // Don't bother with pointers at all. 9211 if (C->getType()->isPointerTy()) 9212 return nullptr; 9213 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 9214 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 9215 if (!C2 || C2->getType()->isPointerTy()) 9216 return nullptr; 9217 C = ConstantExpr::getMul(C, C2); 9218 } 9219 return C; 9220 } 9221 return nullptr; 9222 } 9223 case scUDivExpr: { 9224 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 9225 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 9226 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 9227 if (LHS->getType() == RHS->getType()) 9228 return ConstantExpr::getUDiv(LHS, RHS); 9229 return nullptr; 9230 } 9231 case scSMaxExpr: 9232 case scUMaxExpr: 9233 case scSMinExpr: 9234 case scUMinExpr: 9235 case scSequentialUMinExpr: 9236 return nullptr; // TODO: smax, umax, smin, umax, umin_seq. 9237 } 9238 llvm_unreachable("Unknown SCEV kind!"); 9239 } 9240 9241 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 9242 if (isa<SCEVConstant>(V)) return V; 9243 9244 // If this instruction is evolved from a constant-evolving PHI, compute the 9245 // exit value from the loop without using SCEVs. 9246 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 9247 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 9248 if (PHINode *PN = dyn_cast<PHINode>(I)) { 9249 const Loop *CurrLoop = this->LI[I->getParent()]; 9250 // Looking for loop exit value. 9251 if (CurrLoop && CurrLoop->getParentLoop() == L && 9252 PN->getParent() == CurrLoop->getHeader()) { 9253 // Okay, there is no closed form solution for the PHI node. Check 9254 // to see if the loop that contains it has a known backedge-taken 9255 // count. If so, we may be able to force computation of the exit 9256 // value. 9257 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop); 9258 // This trivial case can show up in some degenerate cases where 9259 // the incoming IR has not yet been fully simplified. 9260 if (BackedgeTakenCount->isZero()) { 9261 Value *InitValue = nullptr; 9262 bool MultipleInitValues = false; 9263 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { 9264 if (!CurrLoop->contains(PN->getIncomingBlock(i))) { 9265 if (!InitValue) 9266 InitValue = PN->getIncomingValue(i); 9267 else if (InitValue != PN->getIncomingValue(i)) { 9268 MultipleInitValues = true; 9269 break; 9270 } 9271 } 9272 } 9273 if (!MultipleInitValues && InitValue) 9274 return getSCEV(InitValue); 9275 } 9276 // Do we have a loop invariant value flowing around the backedge 9277 // for a loop which must execute the backedge? 9278 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) && 9279 isKnownPositive(BackedgeTakenCount) && 9280 PN->getNumIncomingValues() == 2) { 9281 9282 unsigned InLoopPred = 9283 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1; 9284 Value *BackedgeVal = PN->getIncomingValue(InLoopPred); 9285 if (CurrLoop->isLoopInvariant(BackedgeVal)) 9286 return getSCEV(BackedgeVal); 9287 } 9288 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 9289 // Okay, we know how many times the containing loop executes. If 9290 // this is a constant evolving PHI node, get the final value at 9291 // the specified iteration number. 9292 Constant *RV = getConstantEvolutionLoopExitValue( 9293 PN, BTCC->getAPInt(), CurrLoop); 9294 if (RV) return getSCEV(RV); 9295 } 9296 } 9297 9298 // If there is a single-input Phi, evaluate it at our scope. If we can 9299 // prove that this replacement does not break LCSSA form, use new value. 9300 if (PN->getNumOperands() == 1) { 9301 const SCEV *Input = getSCEV(PN->getOperand(0)); 9302 const SCEV *InputAtScope = getSCEVAtScope(Input, L); 9303 // TODO: We can generalize it using LI.replacementPreservesLCSSAForm, 9304 // for the simplest case just support constants. 9305 if (isa<SCEVConstant>(InputAtScope)) return InputAtScope; 9306 } 9307 } 9308 9309 // Okay, this is an expression that we cannot symbolically evaluate 9310 // into a SCEV. Check to see if it's possible to symbolically evaluate 9311 // the arguments into constants, and if so, try to constant propagate the 9312 // result. This is particularly useful for computing loop exit values. 9313 if (CanConstantFold(I)) { 9314 SmallVector<Constant *, 4> Operands; 9315 bool MadeImprovement = false; 9316 for (Value *Op : I->operands()) { 9317 if (Constant *C = dyn_cast<Constant>(Op)) { 9318 Operands.push_back(C); 9319 continue; 9320 } 9321 9322 // If any of the operands is non-constant and if they are 9323 // non-integer and non-pointer, don't even try to analyze them 9324 // with scev techniques. 9325 if (!isSCEVable(Op->getType())) 9326 return V; 9327 9328 const SCEV *OrigV = getSCEV(Op); 9329 const SCEV *OpV = getSCEVAtScope(OrigV, L); 9330 MadeImprovement |= OrigV != OpV; 9331 9332 Constant *C = BuildConstantFromSCEV(OpV); 9333 if (!C) return V; 9334 if (C->getType() != Op->getType()) 9335 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 9336 Op->getType(), 9337 false), 9338 C, Op->getType()); 9339 Operands.push_back(C); 9340 } 9341 9342 // Check to see if getSCEVAtScope actually made an improvement. 9343 if (MadeImprovement) { 9344 Constant *C = nullptr; 9345 const DataLayout &DL = getDataLayout(); 9346 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 9347 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 9348 Operands[1], DL, &TLI); 9349 else if (const LoadInst *Load = dyn_cast<LoadInst>(I)) { 9350 if (!Load->isVolatile()) 9351 C = ConstantFoldLoadFromConstPtr(Operands[0], Load->getType(), 9352 DL); 9353 } else 9354 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 9355 if (!C) return V; 9356 return getSCEV(C); 9357 } 9358 } 9359 } 9360 9361 // This is some other type of SCEVUnknown, just return it. 9362 return V; 9363 } 9364 9365 if (isa<SCEVCommutativeExpr>(V) || isa<SCEVSequentialMinMaxExpr>(V)) { 9366 const auto *Comm = cast<SCEVNAryExpr>(V); 9367 // Avoid performing the look-up in the common case where the specified 9368 // expression has no loop-variant portions. 9369 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 9370 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 9371 if (OpAtScope != Comm->getOperand(i)) { 9372 // Okay, at least one of these operands is loop variant but might be 9373 // foldable. Build a new instance of the folded commutative expression. 9374 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 9375 Comm->op_begin()+i); 9376 NewOps.push_back(OpAtScope); 9377 9378 for (++i; i != e; ++i) { 9379 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 9380 NewOps.push_back(OpAtScope); 9381 } 9382 if (isa<SCEVAddExpr>(Comm)) 9383 return getAddExpr(NewOps, Comm->getNoWrapFlags()); 9384 if (isa<SCEVMulExpr>(Comm)) 9385 return getMulExpr(NewOps, Comm->getNoWrapFlags()); 9386 if (isa<SCEVMinMaxExpr>(Comm)) 9387 return getMinMaxExpr(Comm->getSCEVType(), NewOps); 9388 if (isa<SCEVSequentialMinMaxExpr>(Comm)) 9389 return getSequentialMinMaxExpr(Comm->getSCEVType(), NewOps); 9390 llvm_unreachable("Unknown commutative / sequential min/max SCEV type!"); 9391 } 9392 } 9393 // If we got here, all operands are loop invariant. 9394 return Comm; 9395 } 9396 9397 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 9398 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 9399 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 9400 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 9401 return Div; // must be loop invariant 9402 return getUDivExpr(LHS, RHS); 9403 } 9404 9405 // If this is a loop recurrence for a loop that does not contain L, then we 9406 // are dealing with the final value computed by the loop. 9407 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 9408 // First, attempt to evaluate each operand. 9409 // Avoid performing the look-up in the common case where the specified 9410 // expression has no loop-variant portions. 9411 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 9412 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 9413 if (OpAtScope == AddRec->getOperand(i)) 9414 continue; 9415 9416 // Okay, at least one of these operands is loop variant but might be 9417 // foldable. Build a new instance of the folded commutative expression. 9418 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 9419 AddRec->op_begin()+i); 9420 NewOps.push_back(OpAtScope); 9421 for (++i; i != e; ++i) 9422 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 9423 9424 const SCEV *FoldedRec = 9425 getAddRecExpr(NewOps, AddRec->getLoop(), 9426 AddRec->getNoWrapFlags(SCEV::FlagNW)); 9427 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 9428 // The addrec may be folded to a nonrecurrence, for example, if the 9429 // induction variable is multiplied by zero after constant folding. Go 9430 // ahead and return the folded value. 9431 if (!AddRec) 9432 return FoldedRec; 9433 break; 9434 } 9435 9436 // If the scope is outside the addrec's loop, evaluate it by using the 9437 // loop exit value of the addrec. 9438 if (!AddRec->getLoop()->contains(L)) { 9439 // To evaluate this recurrence, we need to know how many times the AddRec 9440 // loop iterates. Compute this now. 9441 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 9442 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 9443 9444 // Then, evaluate the AddRec. 9445 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 9446 } 9447 9448 return AddRec; 9449 } 9450 9451 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) { 9452 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 9453 if (Op == Cast->getOperand()) 9454 return Cast; // must be loop invariant 9455 return getCastExpr(Cast->getSCEVType(), Op, Cast->getType()); 9456 } 9457 9458 llvm_unreachable("Unknown SCEV type!"); 9459 } 9460 9461 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 9462 return getSCEVAtScope(getSCEV(V), L); 9463 } 9464 9465 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const { 9466 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) 9467 return stripInjectiveFunctions(ZExt->getOperand()); 9468 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) 9469 return stripInjectiveFunctions(SExt->getOperand()); 9470 return S; 9471 } 9472 9473 /// Finds the minimum unsigned root of the following equation: 9474 /// 9475 /// A * X = B (mod N) 9476 /// 9477 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 9478 /// A and B isn't important. 9479 /// 9480 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 9481 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, 9482 ScalarEvolution &SE) { 9483 uint32_t BW = A.getBitWidth(); 9484 assert(BW == SE.getTypeSizeInBits(B->getType())); 9485 assert(A != 0 && "A must be non-zero."); 9486 9487 // 1. D = gcd(A, N) 9488 // 9489 // The gcd of A and N may have only one prime factor: 2. The number of 9490 // trailing zeros in A is its multiplicity 9491 uint32_t Mult2 = A.countTrailingZeros(); 9492 // D = 2^Mult2 9493 9494 // 2. Check if B is divisible by D. 9495 // 9496 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 9497 // is not less than multiplicity of this prime factor for D. 9498 if (SE.GetMinTrailingZeros(B) < Mult2) 9499 return SE.getCouldNotCompute(); 9500 9501 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 9502 // modulo (N / D). 9503 // 9504 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent 9505 // (N / D) in general. The inverse itself always fits into BW bits, though, 9506 // so we immediately truncate it. 9507 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 9508 APInt Mod(BW + 1, 0); 9509 Mod.setBit(BW - Mult2); // Mod = N / D 9510 APInt I = AD.multiplicativeInverse(Mod).trunc(BW); 9511 9512 // 4. Compute the minimum unsigned root of the equation: 9513 // I * (B / D) mod (N / D) 9514 // To simplify the computation, we factor out the divide by D: 9515 // (I * B mod N) / D 9516 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2)); 9517 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D); 9518 } 9519 9520 /// For a given quadratic addrec, generate coefficients of the corresponding 9521 /// quadratic equation, multiplied by a common value to ensure that they are 9522 /// integers. 9523 /// The returned value is a tuple { A, B, C, M, BitWidth }, where 9524 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C 9525 /// were multiplied by, and BitWidth is the bit width of the original addrec 9526 /// coefficients. 9527 /// This function returns None if the addrec coefficients are not compile- 9528 /// time constants. 9529 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>> 9530 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) { 9531 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 9532 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 9533 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 9534 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 9535 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: " 9536 << *AddRec << '\n'); 9537 9538 // We currently can only solve this if the coefficients are constants. 9539 if (!LC || !MC || !NC) { 9540 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n"); 9541 return None; 9542 } 9543 9544 APInt L = LC->getAPInt(); 9545 APInt M = MC->getAPInt(); 9546 APInt N = NC->getAPInt(); 9547 assert(!N.isZero() && "This is not a quadratic addrec"); 9548 9549 unsigned BitWidth = LC->getAPInt().getBitWidth(); 9550 unsigned NewWidth = BitWidth + 1; 9551 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: " 9552 << BitWidth << '\n'); 9553 // The sign-extension (as opposed to a zero-extension) here matches the 9554 // extension used in SolveQuadraticEquationWrap (with the same motivation). 9555 N = N.sext(NewWidth); 9556 M = M.sext(NewWidth); 9557 L = L.sext(NewWidth); 9558 9559 // The increments are M, M+N, M+2N, ..., so the accumulated values are 9560 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is, 9561 // L+M, L+2M+N, L+3M+3N, ... 9562 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N. 9563 // 9564 // The equation Acc = 0 is then 9565 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0. 9566 // In a quadratic form it becomes: 9567 // N n^2 + (2M-N) n + 2L = 0. 9568 9569 APInt A = N; 9570 APInt B = 2 * M - A; 9571 APInt C = 2 * L; 9572 APInt T = APInt(NewWidth, 2); 9573 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B 9574 << "x + " << C << ", coeff bw: " << NewWidth 9575 << ", multiplied by " << T << '\n'); 9576 return std::make_tuple(A, B, C, T, BitWidth); 9577 } 9578 9579 /// Helper function to compare optional APInts: 9580 /// (a) if X and Y both exist, return min(X, Y), 9581 /// (b) if neither X nor Y exist, return None, 9582 /// (c) if exactly one of X and Y exists, return that value. 9583 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) { 9584 if (X.hasValue() && Y.hasValue()) { 9585 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth()); 9586 APInt XW = X->sextOrSelf(W); 9587 APInt YW = Y->sextOrSelf(W); 9588 return XW.slt(YW) ? *X : *Y; 9589 } 9590 if (!X.hasValue() && !Y.hasValue()) 9591 return None; 9592 return X.hasValue() ? *X : *Y; 9593 } 9594 9595 /// Helper function to truncate an optional APInt to a given BitWidth. 9596 /// When solving addrec-related equations, it is preferable to return a value 9597 /// that has the same bit width as the original addrec's coefficients. If the 9598 /// solution fits in the original bit width, truncate it (except for i1). 9599 /// Returning a value of a different bit width may inhibit some optimizations. 9600 /// 9601 /// In general, a solution to a quadratic equation generated from an addrec 9602 /// may require BW+1 bits, where BW is the bit width of the addrec's 9603 /// coefficients. The reason is that the coefficients of the quadratic 9604 /// equation are BW+1 bits wide (to avoid truncation when converting from 9605 /// the addrec to the equation). 9606 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) { 9607 if (!X.hasValue()) 9608 return None; 9609 unsigned W = X->getBitWidth(); 9610 if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth)) 9611 return X->trunc(BitWidth); 9612 return X; 9613 } 9614 9615 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n 9616 /// iterations. The values L, M, N are assumed to be signed, and they 9617 /// should all have the same bit widths. 9618 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW, 9619 /// where BW is the bit width of the addrec's coefficients. 9620 /// If the calculated value is a BW-bit integer (for BW > 1), it will be 9621 /// returned as such, otherwise the bit width of the returned value may 9622 /// be greater than BW. 9623 /// 9624 /// This function returns None if 9625 /// (a) the addrec coefficients are not constant, or 9626 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases 9627 /// like x^2 = 5, no integer solutions exist, in other cases an integer 9628 /// solution may exist, but SolveQuadraticEquationWrap may fail to find it. 9629 static Optional<APInt> 9630 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 9631 APInt A, B, C, M; 9632 unsigned BitWidth; 9633 auto T = GetQuadraticEquation(AddRec); 9634 if (!T.hasValue()) 9635 return None; 9636 9637 std::tie(A, B, C, M, BitWidth) = *T; 9638 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n"); 9639 Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1); 9640 if (!X.hasValue()) 9641 return None; 9642 9643 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X); 9644 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE); 9645 if (!V->isZero()) 9646 return None; 9647 9648 return TruncIfPossible(X, BitWidth); 9649 } 9650 9651 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n 9652 /// iterations. The values M, N are assumed to be signed, and they 9653 /// should all have the same bit widths. 9654 /// Find the least n such that c(n) does not belong to the given range, 9655 /// while c(n-1) does. 9656 /// 9657 /// This function returns None if 9658 /// (a) the addrec coefficients are not constant, or 9659 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the 9660 /// bounds of the range. 9661 static Optional<APInt> 9662 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec, 9663 const ConstantRange &Range, ScalarEvolution &SE) { 9664 assert(AddRec->getOperand(0)->isZero() && 9665 "Starting value of addrec should be 0"); 9666 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range " 9667 << Range << ", addrec " << *AddRec << '\n'); 9668 // This case is handled in getNumIterationsInRange. Here we can assume that 9669 // we start in the range. 9670 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) && 9671 "Addrec's initial value should be in range"); 9672 9673 APInt A, B, C, M; 9674 unsigned BitWidth; 9675 auto T = GetQuadraticEquation(AddRec); 9676 if (!T.hasValue()) 9677 return None; 9678 9679 // Be careful about the return value: there can be two reasons for not 9680 // returning an actual number. First, if no solutions to the equations 9681 // were found, and second, if the solutions don't leave the given range. 9682 // The first case means that the actual solution is "unknown", the second 9683 // means that it's known, but not valid. If the solution is unknown, we 9684 // cannot make any conclusions. 9685 // Return a pair: the optional solution and a flag indicating if the 9686 // solution was found. 9687 auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> { 9688 // Solve for signed overflow and unsigned overflow, pick the lower 9689 // solution. 9690 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary " 9691 << Bound << " (before multiplying by " << M << ")\n"); 9692 Bound *= M; // The quadratic equation multiplier. 9693 9694 Optional<APInt> SO = None; 9695 if (BitWidth > 1) { 9696 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 9697 "signed overflow\n"); 9698 SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth); 9699 } 9700 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 9701 "unsigned overflow\n"); 9702 Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, 9703 BitWidth+1); 9704 9705 auto LeavesRange = [&] (const APInt &X) { 9706 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X); 9707 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE); 9708 if (Range.contains(V0->getValue())) 9709 return false; 9710 // X should be at least 1, so X-1 is non-negative. 9711 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1); 9712 ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE); 9713 if (Range.contains(V1->getValue())) 9714 return true; 9715 return false; 9716 }; 9717 9718 // If SolveQuadraticEquationWrap returns None, it means that there can 9719 // be a solution, but the function failed to find it. We cannot treat it 9720 // as "no solution". 9721 if (!SO.hasValue() || !UO.hasValue()) 9722 return { None, false }; 9723 9724 // Check the smaller value first to see if it leaves the range. 9725 // At this point, both SO and UO must have values. 9726 Optional<APInt> Min = MinOptional(SO, UO); 9727 if (LeavesRange(*Min)) 9728 return { Min, true }; 9729 Optional<APInt> Max = Min == SO ? UO : SO; 9730 if (LeavesRange(*Max)) 9731 return { Max, true }; 9732 9733 // Solutions were found, but were eliminated, hence the "true". 9734 return { None, true }; 9735 }; 9736 9737 std::tie(A, B, C, M, BitWidth) = *T; 9738 // Lower bound is inclusive, subtract 1 to represent the exiting value. 9739 APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1; 9740 APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth()); 9741 auto SL = SolveForBoundary(Lower); 9742 auto SU = SolveForBoundary(Upper); 9743 // If any of the solutions was unknown, no meaninigful conclusions can 9744 // be made. 9745 if (!SL.second || !SU.second) 9746 return None; 9747 9748 // Claim: The correct solution is not some value between Min and Max. 9749 // 9750 // Justification: Assuming that Min and Max are different values, one of 9751 // them is when the first signed overflow happens, the other is when the 9752 // first unsigned overflow happens. Crossing the range boundary is only 9753 // possible via an overflow (treating 0 as a special case of it, modeling 9754 // an overflow as crossing k*2^W for some k). 9755 // 9756 // The interesting case here is when Min was eliminated as an invalid 9757 // solution, but Max was not. The argument is that if there was another 9758 // overflow between Min and Max, it would also have been eliminated if 9759 // it was considered. 9760 // 9761 // For a given boundary, it is possible to have two overflows of the same 9762 // type (signed/unsigned) without having the other type in between: this 9763 // can happen when the vertex of the parabola is between the iterations 9764 // corresponding to the overflows. This is only possible when the two 9765 // overflows cross k*2^W for the same k. In such case, if the second one 9766 // left the range (and was the first one to do so), the first overflow 9767 // would have to enter the range, which would mean that either we had left 9768 // the range before or that we started outside of it. Both of these cases 9769 // are contradictions. 9770 // 9771 // Claim: In the case where SolveForBoundary returns None, the correct 9772 // solution is not some value between the Max for this boundary and the 9773 // Min of the other boundary. 9774 // 9775 // Justification: Assume that we had such Max_A and Min_B corresponding 9776 // to range boundaries A and B and such that Max_A < Min_B. If there was 9777 // a solution between Max_A and Min_B, it would have to be caused by an 9778 // overflow corresponding to either A or B. It cannot correspond to B, 9779 // since Min_B is the first occurrence of such an overflow. If it 9780 // corresponded to A, it would have to be either a signed or an unsigned 9781 // overflow that is larger than both eliminated overflows for A. But 9782 // between the eliminated overflows and this overflow, the values would 9783 // cover the entire value space, thus crossing the other boundary, which 9784 // is a contradiction. 9785 9786 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth); 9787 } 9788 9789 ScalarEvolution::ExitLimit 9790 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 9791 bool AllowPredicates) { 9792 9793 // This is only used for loops with a "x != y" exit test. The exit condition 9794 // is now expressed as a single expression, V = x-y. So the exit test is 9795 // effectively V != 0. We know and take advantage of the fact that this 9796 // expression only being used in a comparison by zero context. 9797 9798 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 9799 // If the value is a constant 9800 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 9801 // If the value is already zero, the branch will execute zero times. 9802 if (C->getValue()->isZero()) return C; 9803 return getCouldNotCompute(); // Otherwise it will loop infinitely. 9804 } 9805 9806 const SCEVAddRecExpr *AddRec = 9807 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V)); 9808 9809 if (!AddRec && AllowPredicates) 9810 // Try to make this an AddRec using runtime tests, in the first X 9811 // iterations of this loop, where X is the SCEV expression found by the 9812 // algorithm below. 9813 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 9814 9815 if (!AddRec || AddRec->getLoop() != L) 9816 return getCouldNotCompute(); 9817 9818 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 9819 // the quadratic equation to solve it. 9820 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 9821 // We can only use this value if the chrec ends up with an exact zero 9822 // value at this index. When solving for "X*X != 5", for example, we 9823 // should not accept a root of 2. 9824 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) { 9825 const auto *R = cast<SCEVConstant>(getConstant(S.getValue())); 9826 return ExitLimit(R, R, false, Predicates); 9827 } 9828 return getCouldNotCompute(); 9829 } 9830 9831 // Otherwise we can only handle this if it is affine. 9832 if (!AddRec->isAffine()) 9833 return getCouldNotCompute(); 9834 9835 // If this is an affine expression, the execution count of this branch is 9836 // the minimum unsigned root of the following equation: 9837 // 9838 // Start + Step*N = 0 (mod 2^BW) 9839 // 9840 // equivalent to: 9841 // 9842 // Step*N = -Start (mod 2^BW) 9843 // 9844 // where BW is the common bit width of Start and Step. 9845 9846 // Get the initial value for the loop. 9847 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 9848 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 9849 9850 // For now we handle only constant steps. 9851 // 9852 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 9853 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 9854 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 9855 // We have not yet seen any such cases. 9856 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 9857 if (!StepC || StepC->getValue()->isZero()) 9858 return getCouldNotCompute(); 9859 9860 // For positive steps (counting up until unsigned overflow): 9861 // N = -Start/Step (as unsigned) 9862 // For negative steps (counting down to zero): 9863 // N = Start/-Step 9864 // First compute the unsigned distance from zero in the direction of Step. 9865 bool CountDown = StepC->getAPInt().isNegative(); 9866 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 9867 9868 // Handle unitary steps, which cannot wraparound. 9869 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 9870 // N = Distance (as unsigned) 9871 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) { 9872 APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, L)); 9873 MaxBECount = APIntOps::umin(MaxBECount, getUnsignedRangeMax(Distance)); 9874 9875 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated, 9876 // we end up with a loop whose backedge-taken count is n - 1. Detect this 9877 // case, and see if we can improve the bound. 9878 // 9879 // Explicitly handling this here is necessary because getUnsignedRange 9880 // isn't context-sensitive; it doesn't know that we only care about the 9881 // range inside the loop. 9882 const SCEV *Zero = getZero(Distance->getType()); 9883 const SCEV *One = getOne(Distance->getType()); 9884 const SCEV *DistancePlusOne = getAddExpr(Distance, One); 9885 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) { 9886 // If Distance + 1 doesn't overflow, we can compute the maximum distance 9887 // as "unsigned_max(Distance + 1) - 1". 9888 ConstantRange CR = getUnsignedRange(DistancePlusOne); 9889 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1); 9890 } 9891 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates); 9892 } 9893 9894 // If the condition controls loop exit (the loop exits only if the expression 9895 // is true) and the addition is no-wrap we can use unsigned divide to 9896 // compute the backedge count. In this case, the step may not divide the 9897 // distance, but we don't care because if the condition is "missed" the loop 9898 // will have undefined behavior due to wrapping. 9899 if (ControlsExit && AddRec->hasNoSelfWrap() && 9900 loopHasNoAbnormalExits(AddRec->getLoop())) { 9901 const SCEV *Exact = 9902 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 9903 const SCEV *Max = getCouldNotCompute(); 9904 if (Exact != getCouldNotCompute()) { 9905 APInt MaxInt = getUnsignedRangeMax(applyLoopGuards(Exact, L)); 9906 Max = getConstant(APIntOps::umin(MaxInt, getUnsignedRangeMax(Exact))); 9907 } 9908 return ExitLimit(Exact, Max, false, Predicates); 9909 } 9910 9911 // Solve the general equation. 9912 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(), 9913 getNegativeSCEV(Start), *this); 9914 9915 const SCEV *M = E; 9916 if (E != getCouldNotCompute()) { 9917 APInt MaxWithGuards = getUnsignedRangeMax(applyLoopGuards(E, L)); 9918 M = getConstant(APIntOps::umin(MaxWithGuards, getUnsignedRangeMax(E))); 9919 } 9920 return ExitLimit(E, M, false, Predicates); 9921 } 9922 9923 ScalarEvolution::ExitLimit 9924 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 9925 // Loops that look like: while (X == 0) are very strange indeed. We don't 9926 // handle them yet except for the trivial case. This could be expanded in the 9927 // future as needed. 9928 9929 // If the value is a constant, check to see if it is known to be non-zero 9930 // already. If so, the backedge will execute zero times. 9931 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 9932 if (!C->getValue()->isZero()) 9933 return getZero(C->getType()); 9934 return getCouldNotCompute(); // Otherwise it will loop infinitely. 9935 } 9936 9937 // We could implement others, but I really doubt anyone writes loops like 9938 // this, and if they did, they would already be constant folded. 9939 return getCouldNotCompute(); 9940 } 9941 9942 std::pair<const BasicBlock *, const BasicBlock *> 9943 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB) 9944 const { 9945 // If the block has a unique predecessor, then there is no path from the 9946 // predecessor to the block that does not go through the direct edge 9947 // from the predecessor to the block. 9948 if (const BasicBlock *Pred = BB->getSinglePredecessor()) 9949 return {Pred, BB}; 9950 9951 // A loop's header is defined to be a block that dominates the loop. 9952 // If the header has a unique predecessor outside the loop, it must be 9953 // a block that has exactly one successor that can reach the loop. 9954 if (const Loop *L = LI.getLoopFor(BB)) 9955 return {L->getLoopPredecessor(), L->getHeader()}; 9956 9957 return {nullptr, nullptr}; 9958 } 9959 9960 /// SCEV structural equivalence is usually sufficient for testing whether two 9961 /// expressions are equal, however for the purposes of looking for a condition 9962 /// guarding a loop, it can be useful to be a little more general, since a 9963 /// front-end may have replicated the controlling expression. 9964 static bool HasSameValue(const SCEV *A, const SCEV *B) { 9965 // Quick check to see if they are the same SCEV. 9966 if (A == B) return true; 9967 9968 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 9969 // Not all instructions that are "identical" compute the same value. For 9970 // instance, two distinct alloca instructions allocating the same type are 9971 // identical and do not read memory; but compute distinct values. 9972 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 9973 }; 9974 9975 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 9976 // two different instructions with the same value. Check for this case. 9977 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 9978 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 9979 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 9980 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 9981 if (ComputesEqualValues(AI, BI)) 9982 return true; 9983 9984 // Otherwise assume they may have a different value. 9985 return false; 9986 } 9987 9988 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 9989 const SCEV *&LHS, const SCEV *&RHS, 9990 unsigned Depth, 9991 bool ControllingFiniteLoop) { 9992 bool Changed = false; 9993 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or 9994 // '0 != 0'. 9995 auto TrivialCase = [&](bool TriviallyTrue) { 9996 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 9997 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE; 9998 return true; 9999 }; 10000 // If we hit the max recursion limit bail out. 10001 if (Depth >= 3) 10002 return false; 10003 10004 // Canonicalize a constant to the right side. 10005 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 10006 // Check for both operands constant. 10007 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 10008 if (ConstantExpr::getICmp(Pred, 10009 LHSC->getValue(), 10010 RHSC->getValue())->isNullValue()) 10011 return TrivialCase(false); 10012 else 10013 return TrivialCase(true); 10014 } 10015 // Otherwise swap the operands to put the constant on the right. 10016 std::swap(LHS, RHS); 10017 Pred = ICmpInst::getSwappedPredicate(Pred); 10018 Changed = true; 10019 } 10020 10021 // If we're comparing an addrec with a value which is loop-invariant in the 10022 // addrec's loop, put the addrec on the left. Also make a dominance check, 10023 // as both operands could be addrecs loop-invariant in each other's loop. 10024 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 10025 const Loop *L = AR->getLoop(); 10026 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 10027 std::swap(LHS, RHS); 10028 Pred = ICmpInst::getSwappedPredicate(Pred); 10029 Changed = true; 10030 } 10031 } 10032 10033 // If there's a constant operand, canonicalize comparisons with boundary 10034 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 10035 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 10036 const APInt &RA = RC->getAPInt(); 10037 10038 bool SimplifiedByConstantRange = false; 10039 10040 if (!ICmpInst::isEquality(Pred)) { 10041 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 10042 if (ExactCR.isFullSet()) 10043 return TrivialCase(true); 10044 else if (ExactCR.isEmptySet()) 10045 return TrivialCase(false); 10046 10047 APInt NewRHS; 10048 CmpInst::Predicate NewPred; 10049 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 10050 ICmpInst::isEquality(NewPred)) { 10051 // We were able to convert an inequality to an equality. 10052 Pred = NewPred; 10053 RHS = getConstant(NewRHS); 10054 Changed = SimplifiedByConstantRange = true; 10055 } 10056 } 10057 10058 if (!SimplifiedByConstantRange) { 10059 switch (Pred) { 10060 default: 10061 break; 10062 case ICmpInst::ICMP_EQ: 10063 case ICmpInst::ICMP_NE: 10064 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 10065 if (!RA) 10066 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 10067 if (const SCEVMulExpr *ME = 10068 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 10069 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 10070 ME->getOperand(0)->isAllOnesValue()) { 10071 RHS = AE->getOperand(1); 10072 LHS = ME->getOperand(1); 10073 Changed = true; 10074 } 10075 break; 10076 10077 10078 // The "Should have been caught earlier!" messages refer to the fact 10079 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 10080 // should have fired on the corresponding cases, and canonicalized the 10081 // check to trivial case. 10082 10083 case ICmpInst::ICMP_UGE: 10084 assert(!RA.isMinValue() && "Should have been caught earlier!"); 10085 Pred = ICmpInst::ICMP_UGT; 10086 RHS = getConstant(RA - 1); 10087 Changed = true; 10088 break; 10089 case ICmpInst::ICMP_ULE: 10090 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 10091 Pred = ICmpInst::ICMP_ULT; 10092 RHS = getConstant(RA + 1); 10093 Changed = true; 10094 break; 10095 case ICmpInst::ICMP_SGE: 10096 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 10097 Pred = ICmpInst::ICMP_SGT; 10098 RHS = getConstant(RA - 1); 10099 Changed = true; 10100 break; 10101 case ICmpInst::ICMP_SLE: 10102 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 10103 Pred = ICmpInst::ICMP_SLT; 10104 RHS = getConstant(RA + 1); 10105 Changed = true; 10106 break; 10107 } 10108 } 10109 } 10110 10111 // Check for obvious equality. 10112 if (HasSameValue(LHS, RHS)) { 10113 if (ICmpInst::isTrueWhenEqual(Pred)) 10114 return TrivialCase(true); 10115 if (ICmpInst::isFalseWhenEqual(Pred)) 10116 return TrivialCase(false); 10117 } 10118 10119 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 10120 // adding or subtracting 1 from one of the operands. This can be done for 10121 // one of two reasons: 10122 // 1) The range of the RHS does not include the (signed/unsigned) boundaries 10123 // 2) The loop is finite, with this comparison controlling the exit. Since the 10124 // loop is finite, the bound cannot include the corresponding boundary 10125 // (otherwise it would loop forever). 10126 switch (Pred) { 10127 case ICmpInst::ICMP_SLE: 10128 if (ControllingFiniteLoop || !getSignedRangeMax(RHS).isMaxSignedValue()) { 10129 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 10130 SCEV::FlagNSW); 10131 Pred = ICmpInst::ICMP_SLT; 10132 Changed = true; 10133 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) { 10134 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 10135 SCEV::FlagNSW); 10136 Pred = ICmpInst::ICMP_SLT; 10137 Changed = true; 10138 } 10139 break; 10140 case ICmpInst::ICMP_SGE: 10141 if (ControllingFiniteLoop || !getSignedRangeMin(RHS).isMinSignedValue()) { 10142 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 10143 SCEV::FlagNSW); 10144 Pred = ICmpInst::ICMP_SGT; 10145 Changed = true; 10146 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) { 10147 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 10148 SCEV::FlagNSW); 10149 Pred = ICmpInst::ICMP_SGT; 10150 Changed = true; 10151 } 10152 break; 10153 case ICmpInst::ICMP_ULE: 10154 if (ControllingFiniteLoop || !getUnsignedRangeMax(RHS).isMaxValue()) { 10155 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 10156 SCEV::FlagNUW); 10157 Pred = ICmpInst::ICMP_ULT; 10158 Changed = true; 10159 } else if (!getUnsignedRangeMin(LHS).isMinValue()) { 10160 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 10161 Pred = ICmpInst::ICMP_ULT; 10162 Changed = true; 10163 } 10164 break; 10165 case ICmpInst::ICMP_UGE: 10166 if (ControllingFiniteLoop || !getUnsignedRangeMin(RHS).isMinValue()) { 10167 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 10168 Pred = ICmpInst::ICMP_UGT; 10169 Changed = true; 10170 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) { 10171 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 10172 SCEV::FlagNUW); 10173 Pred = ICmpInst::ICMP_UGT; 10174 Changed = true; 10175 } 10176 break; 10177 default: 10178 break; 10179 } 10180 10181 // TODO: More simplifications are possible here. 10182 10183 // Recursively simplify until we either hit a recursion limit or nothing 10184 // changes. 10185 if (Changed) 10186 return SimplifyICmpOperands(Pred, LHS, RHS, Depth + 1, 10187 ControllingFiniteLoop); 10188 10189 return Changed; 10190 } 10191 10192 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 10193 return getSignedRangeMax(S).isNegative(); 10194 } 10195 10196 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 10197 return getSignedRangeMin(S).isStrictlyPositive(); 10198 } 10199 10200 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 10201 return !getSignedRangeMin(S).isNegative(); 10202 } 10203 10204 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 10205 return !getSignedRangeMax(S).isStrictlyPositive(); 10206 } 10207 10208 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 10209 return getUnsignedRangeMin(S) != 0; 10210 } 10211 10212 std::pair<const SCEV *, const SCEV *> 10213 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) { 10214 // Compute SCEV on entry of loop L. 10215 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this); 10216 if (Start == getCouldNotCompute()) 10217 return { Start, Start }; 10218 // Compute post increment SCEV for loop L. 10219 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this); 10220 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute"); 10221 return { Start, PostInc }; 10222 } 10223 10224 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred, 10225 const SCEV *LHS, const SCEV *RHS) { 10226 // First collect all loops. 10227 SmallPtrSet<const Loop *, 8> LoopsUsed; 10228 getUsedLoops(LHS, LoopsUsed); 10229 getUsedLoops(RHS, LoopsUsed); 10230 10231 if (LoopsUsed.empty()) 10232 return false; 10233 10234 // Domination relationship must be a linear order on collected loops. 10235 #ifndef NDEBUG 10236 for (auto *L1 : LoopsUsed) 10237 for (auto *L2 : LoopsUsed) 10238 assert((DT.dominates(L1->getHeader(), L2->getHeader()) || 10239 DT.dominates(L2->getHeader(), L1->getHeader())) && 10240 "Domination relationship is not a linear order"); 10241 #endif 10242 10243 const Loop *MDL = 10244 *std::max_element(LoopsUsed.begin(), LoopsUsed.end(), 10245 [&](const Loop *L1, const Loop *L2) { 10246 return DT.properlyDominates(L1->getHeader(), L2->getHeader()); 10247 }); 10248 10249 // Get init and post increment value for LHS. 10250 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS); 10251 // if LHS contains unknown non-invariant SCEV then bail out. 10252 if (SplitLHS.first == getCouldNotCompute()) 10253 return false; 10254 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC"); 10255 // Get init and post increment value for RHS. 10256 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS); 10257 // if RHS contains unknown non-invariant SCEV then bail out. 10258 if (SplitRHS.first == getCouldNotCompute()) 10259 return false; 10260 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC"); 10261 // It is possible that init SCEV contains an invariant load but it does 10262 // not dominate MDL and is not available at MDL loop entry, so we should 10263 // check it here. 10264 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) || 10265 !isAvailableAtLoopEntry(SplitRHS.first, MDL)) 10266 return false; 10267 10268 // It seems backedge guard check is faster than entry one so in some cases 10269 // it can speed up whole estimation by short circuit 10270 return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second, 10271 SplitRHS.second) && 10272 isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first); 10273 } 10274 10275 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 10276 const SCEV *LHS, const SCEV *RHS) { 10277 // Canonicalize the inputs first. 10278 (void)SimplifyICmpOperands(Pred, LHS, RHS); 10279 10280 if (isKnownViaInduction(Pred, LHS, RHS)) 10281 return true; 10282 10283 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 10284 return true; 10285 10286 // Otherwise see what can be done with some simple reasoning. 10287 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS); 10288 } 10289 10290 Optional<bool> ScalarEvolution::evaluatePredicate(ICmpInst::Predicate Pred, 10291 const SCEV *LHS, 10292 const SCEV *RHS) { 10293 if (isKnownPredicate(Pred, LHS, RHS)) 10294 return true; 10295 else if (isKnownPredicate(ICmpInst::getInversePredicate(Pred), LHS, RHS)) 10296 return false; 10297 return None; 10298 } 10299 10300 bool ScalarEvolution::isKnownPredicateAt(ICmpInst::Predicate Pred, 10301 const SCEV *LHS, const SCEV *RHS, 10302 const Instruction *CtxI) { 10303 // TODO: Analyze guards and assumes from Context's block. 10304 return isKnownPredicate(Pred, LHS, RHS) || 10305 isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS); 10306 } 10307 10308 Optional<bool> ScalarEvolution::evaluatePredicateAt(ICmpInst::Predicate Pred, 10309 const SCEV *LHS, 10310 const SCEV *RHS, 10311 const Instruction *CtxI) { 10312 Optional<bool> KnownWithoutContext = evaluatePredicate(Pred, LHS, RHS); 10313 if (KnownWithoutContext) 10314 return KnownWithoutContext; 10315 10316 if (isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS)) 10317 return true; 10318 else if (isBasicBlockEntryGuardedByCond(CtxI->getParent(), 10319 ICmpInst::getInversePredicate(Pred), 10320 LHS, RHS)) 10321 return false; 10322 return None; 10323 } 10324 10325 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred, 10326 const SCEVAddRecExpr *LHS, 10327 const SCEV *RHS) { 10328 const Loop *L = LHS->getLoop(); 10329 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) && 10330 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS); 10331 } 10332 10333 Optional<ScalarEvolution::MonotonicPredicateType> 10334 ScalarEvolution::getMonotonicPredicateType(const SCEVAddRecExpr *LHS, 10335 ICmpInst::Predicate Pred) { 10336 auto Result = getMonotonicPredicateTypeImpl(LHS, Pred); 10337 10338 #ifndef NDEBUG 10339 // Verify an invariant: inverting the predicate should turn a monotonically 10340 // increasing change to a monotonically decreasing one, and vice versa. 10341 if (Result) { 10342 auto ResultSwapped = 10343 getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred)); 10344 10345 assert(ResultSwapped.hasValue() && "should be able to analyze both!"); 10346 assert(ResultSwapped.getValue() != Result.getValue() && 10347 "monotonicity should flip as we flip the predicate"); 10348 } 10349 #endif 10350 10351 return Result; 10352 } 10353 10354 Optional<ScalarEvolution::MonotonicPredicateType> 10355 ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS, 10356 ICmpInst::Predicate Pred) { 10357 // A zero step value for LHS means the induction variable is essentially a 10358 // loop invariant value. We don't really depend on the predicate actually 10359 // flipping from false to true (for increasing predicates, and the other way 10360 // around for decreasing predicates), all we care about is that *if* the 10361 // predicate changes then it only changes from false to true. 10362 // 10363 // A zero step value in itself is not very useful, but there may be places 10364 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 10365 // as general as possible. 10366 10367 // Only handle LE/LT/GE/GT predicates. 10368 if (!ICmpInst::isRelational(Pred)) 10369 return None; 10370 10371 bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred); 10372 assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) && 10373 "Should be greater or less!"); 10374 10375 // Check that AR does not wrap. 10376 if (ICmpInst::isUnsigned(Pred)) { 10377 if (!LHS->hasNoUnsignedWrap()) 10378 return None; 10379 return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 10380 } else { 10381 assert(ICmpInst::isSigned(Pred) && 10382 "Relational predicate is either signed or unsigned!"); 10383 if (!LHS->hasNoSignedWrap()) 10384 return None; 10385 10386 const SCEV *Step = LHS->getStepRecurrence(*this); 10387 10388 if (isKnownNonNegative(Step)) 10389 return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 10390 10391 if (isKnownNonPositive(Step)) 10392 return !IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 10393 10394 return None; 10395 } 10396 } 10397 10398 Optional<ScalarEvolution::LoopInvariantPredicate> 10399 ScalarEvolution::getLoopInvariantPredicate(ICmpInst::Predicate Pred, 10400 const SCEV *LHS, const SCEV *RHS, 10401 const Loop *L) { 10402 10403 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 10404 if (!isLoopInvariant(RHS, L)) { 10405 if (!isLoopInvariant(LHS, L)) 10406 return None; 10407 10408 std::swap(LHS, RHS); 10409 Pred = ICmpInst::getSwappedPredicate(Pred); 10410 } 10411 10412 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 10413 if (!ArLHS || ArLHS->getLoop() != L) 10414 return None; 10415 10416 auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred); 10417 if (!MonotonicType) 10418 return None; 10419 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 10420 // true as the loop iterates, and the backedge is control dependent on 10421 // "ArLHS `Pred` RHS" == true then we can reason as follows: 10422 // 10423 // * if the predicate was false in the first iteration then the predicate 10424 // is never evaluated again, since the loop exits without taking the 10425 // backedge. 10426 // * if the predicate was true in the first iteration then it will 10427 // continue to be true for all future iterations since it is 10428 // monotonically increasing. 10429 // 10430 // For both the above possibilities, we can replace the loop varying 10431 // predicate with its value on the first iteration of the loop (which is 10432 // loop invariant). 10433 // 10434 // A similar reasoning applies for a monotonically decreasing predicate, by 10435 // replacing true with false and false with true in the above two bullets. 10436 bool Increasing = *MonotonicType == ScalarEvolution::MonotonicallyIncreasing; 10437 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 10438 10439 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 10440 return None; 10441 10442 return ScalarEvolution::LoopInvariantPredicate(Pred, ArLHS->getStart(), RHS); 10443 } 10444 10445 Optional<ScalarEvolution::LoopInvariantPredicate> 10446 ScalarEvolution::getLoopInvariantExitCondDuringFirstIterations( 10447 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 10448 const Instruction *CtxI, const SCEV *MaxIter) { 10449 // Try to prove the following set of facts: 10450 // - The predicate is monotonic in the iteration space. 10451 // - If the check does not fail on the 1st iteration: 10452 // - No overflow will happen during first MaxIter iterations; 10453 // - It will not fail on the MaxIter'th iteration. 10454 // If the check does fail on the 1st iteration, we leave the loop and no 10455 // other checks matter. 10456 10457 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 10458 if (!isLoopInvariant(RHS, L)) { 10459 if (!isLoopInvariant(LHS, L)) 10460 return None; 10461 10462 std::swap(LHS, RHS); 10463 Pred = ICmpInst::getSwappedPredicate(Pred); 10464 } 10465 10466 auto *AR = dyn_cast<SCEVAddRecExpr>(LHS); 10467 if (!AR || AR->getLoop() != L) 10468 return None; 10469 10470 // The predicate must be relational (i.e. <, <=, >=, >). 10471 if (!ICmpInst::isRelational(Pred)) 10472 return None; 10473 10474 // TODO: Support steps other than +/- 1. 10475 const SCEV *Step = AR->getStepRecurrence(*this); 10476 auto *One = getOne(Step->getType()); 10477 auto *MinusOne = getNegativeSCEV(One); 10478 if (Step != One && Step != MinusOne) 10479 return None; 10480 10481 // Type mismatch here means that MaxIter is potentially larger than max 10482 // unsigned value in start type, which mean we cannot prove no wrap for the 10483 // indvar. 10484 if (AR->getType() != MaxIter->getType()) 10485 return None; 10486 10487 // Value of IV on suggested last iteration. 10488 const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this); 10489 // Does it still meet the requirement? 10490 if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS)) 10491 return None; 10492 // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does 10493 // not exceed max unsigned value of this type), this effectively proves 10494 // that there is no wrap during the iteration. To prove that there is no 10495 // signed/unsigned wrap, we need to check that 10496 // Start <= Last for step = 1 or Start >= Last for step = -1. 10497 ICmpInst::Predicate NoOverflowPred = 10498 CmpInst::isSigned(Pred) ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 10499 if (Step == MinusOne) 10500 NoOverflowPred = CmpInst::getSwappedPredicate(NoOverflowPred); 10501 const SCEV *Start = AR->getStart(); 10502 if (!isKnownPredicateAt(NoOverflowPred, Start, Last, CtxI)) 10503 return None; 10504 10505 // Everything is fine. 10506 return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS); 10507 } 10508 10509 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 10510 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 10511 if (HasSameValue(LHS, RHS)) 10512 return ICmpInst::isTrueWhenEqual(Pred); 10513 10514 // This code is split out from isKnownPredicate because it is called from 10515 // within isLoopEntryGuardedByCond. 10516 10517 auto CheckRanges = [&](const ConstantRange &RangeLHS, 10518 const ConstantRange &RangeRHS) { 10519 return RangeLHS.icmp(Pred, RangeRHS); 10520 }; 10521 10522 // The check at the top of the function catches the case where the values are 10523 // known to be equal. 10524 if (Pred == CmpInst::ICMP_EQ) 10525 return false; 10526 10527 if (Pred == CmpInst::ICMP_NE) { 10528 if (CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 10529 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS))) 10530 return true; 10531 auto *Diff = getMinusSCEV(LHS, RHS); 10532 return !isa<SCEVCouldNotCompute>(Diff) && isKnownNonZero(Diff); 10533 } 10534 10535 if (CmpInst::isSigned(Pred)) 10536 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 10537 10538 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 10539 } 10540 10541 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 10542 const SCEV *LHS, 10543 const SCEV *RHS) { 10544 // Match X to (A + C1)<ExpectedFlags> and Y to (A + C2)<ExpectedFlags>, where 10545 // C1 and C2 are constant integers. If either X or Y are not add expressions, 10546 // consider them as X + 0 and Y + 0 respectively. C1 and C2 are returned via 10547 // OutC1 and OutC2. 10548 auto MatchBinaryAddToConst = [this](const SCEV *X, const SCEV *Y, 10549 APInt &OutC1, APInt &OutC2, 10550 SCEV::NoWrapFlags ExpectedFlags) { 10551 const SCEV *XNonConstOp, *XConstOp; 10552 const SCEV *YNonConstOp, *YConstOp; 10553 SCEV::NoWrapFlags XFlagsPresent; 10554 SCEV::NoWrapFlags YFlagsPresent; 10555 10556 if (!splitBinaryAdd(X, XConstOp, XNonConstOp, XFlagsPresent)) { 10557 XConstOp = getZero(X->getType()); 10558 XNonConstOp = X; 10559 XFlagsPresent = ExpectedFlags; 10560 } 10561 if (!isa<SCEVConstant>(XConstOp) || 10562 (XFlagsPresent & ExpectedFlags) != ExpectedFlags) 10563 return false; 10564 10565 if (!splitBinaryAdd(Y, YConstOp, YNonConstOp, YFlagsPresent)) { 10566 YConstOp = getZero(Y->getType()); 10567 YNonConstOp = Y; 10568 YFlagsPresent = ExpectedFlags; 10569 } 10570 10571 if (!isa<SCEVConstant>(YConstOp) || 10572 (YFlagsPresent & ExpectedFlags) != ExpectedFlags) 10573 return false; 10574 10575 if (YNonConstOp != XNonConstOp) 10576 return false; 10577 10578 OutC1 = cast<SCEVConstant>(XConstOp)->getAPInt(); 10579 OutC2 = cast<SCEVConstant>(YConstOp)->getAPInt(); 10580 10581 return true; 10582 }; 10583 10584 APInt C1; 10585 APInt C2; 10586 10587 switch (Pred) { 10588 default: 10589 break; 10590 10591 case ICmpInst::ICMP_SGE: 10592 std::swap(LHS, RHS); 10593 LLVM_FALLTHROUGH; 10594 case ICmpInst::ICMP_SLE: 10595 // (X + C1)<nsw> s<= (X + C2)<nsw> if C1 s<= C2. 10596 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.sle(C2)) 10597 return true; 10598 10599 break; 10600 10601 case ICmpInst::ICMP_SGT: 10602 std::swap(LHS, RHS); 10603 LLVM_FALLTHROUGH; 10604 case ICmpInst::ICMP_SLT: 10605 // (X + C1)<nsw> s< (X + C2)<nsw> if C1 s< C2. 10606 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.slt(C2)) 10607 return true; 10608 10609 break; 10610 10611 case ICmpInst::ICMP_UGE: 10612 std::swap(LHS, RHS); 10613 LLVM_FALLTHROUGH; 10614 case ICmpInst::ICMP_ULE: 10615 // (X + C1)<nuw> u<= (X + C2)<nuw> for C1 u<= C2. 10616 if (MatchBinaryAddToConst(RHS, LHS, C2, C1, SCEV::FlagNUW) && C1.ule(C2)) 10617 return true; 10618 10619 break; 10620 10621 case ICmpInst::ICMP_UGT: 10622 std::swap(LHS, RHS); 10623 LLVM_FALLTHROUGH; 10624 case ICmpInst::ICMP_ULT: 10625 // (X + C1)<nuw> u< (X + C2)<nuw> if C1 u< C2. 10626 if (MatchBinaryAddToConst(RHS, LHS, C2, C1, SCEV::FlagNUW) && C1.ult(C2)) 10627 return true; 10628 break; 10629 } 10630 10631 return false; 10632 } 10633 10634 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 10635 const SCEV *LHS, 10636 const SCEV *RHS) { 10637 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 10638 return false; 10639 10640 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 10641 // the stack can result in exponential time complexity. 10642 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 10643 10644 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 10645 // 10646 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 10647 // isKnownPredicate. isKnownPredicate is more powerful, but also more 10648 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 10649 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 10650 // use isKnownPredicate later if needed. 10651 return isKnownNonNegative(RHS) && 10652 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 10653 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 10654 } 10655 10656 bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB, 10657 ICmpInst::Predicate Pred, 10658 const SCEV *LHS, const SCEV *RHS) { 10659 // No need to even try if we know the module has no guards. 10660 if (!HasGuards) 10661 return false; 10662 10663 return any_of(*BB, [&](const Instruction &I) { 10664 using namespace llvm::PatternMatch; 10665 10666 Value *Condition; 10667 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 10668 m_Value(Condition))) && 10669 isImpliedCond(Pred, LHS, RHS, Condition, false); 10670 }); 10671 } 10672 10673 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 10674 /// protected by a conditional between LHS and RHS. This is used to 10675 /// to eliminate casts. 10676 bool 10677 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 10678 ICmpInst::Predicate Pred, 10679 const SCEV *LHS, const SCEV *RHS) { 10680 // Interpret a null as meaning no loop, where there is obviously no guard 10681 // (interprocedural conditions notwithstanding). 10682 if (!L) return true; 10683 10684 if (VerifyIR) 10685 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && 10686 "This cannot be done on broken IR!"); 10687 10688 10689 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 10690 return true; 10691 10692 BasicBlock *Latch = L->getLoopLatch(); 10693 if (!Latch) 10694 return false; 10695 10696 BranchInst *LoopContinuePredicate = 10697 dyn_cast<BranchInst>(Latch->getTerminator()); 10698 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 10699 isImpliedCond(Pred, LHS, RHS, 10700 LoopContinuePredicate->getCondition(), 10701 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 10702 return true; 10703 10704 // We don't want more than one activation of the following loops on the stack 10705 // -- that can lead to O(n!) time complexity. 10706 if (WalkingBEDominatingConds) 10707 return false; 10708 10709 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 10710 10711 // See if we can exploit a trip count to prove the predicate. 10712 const auto &BETakenInfo = getBackedgeTakenInfo(L); 10713 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 10714 if (LatchBECount != getCouldNotCompute()) { 10715 // We know that Latch branches back to the loop header exactly 10716 // LatchBECount times. This means the backdege condition at Latch is 10717 // equivalent to "{0,+,1} u< LatchBECount". 10718 Type *Ty = LatchBECount->getType(); 10719 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 10720 const SCEV *LoopCounter = 10721 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 10722 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 10723 LatchBECount)) 10724 return true; 10725 } 10726 10727 // Check conditions due to any @llvm.assume intrinsics. 10728 for (auto &AssumeVH : AC.assumptions()) { 10729 if (!AssumeVH) 10730 continue; 10731 auto *CI = cast<CallInst>(AssumeVH); 10732 if (!DT.dominates(CI, Latch->getTerminator())) 10733 continue; 10734 10735 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 10736 return true; 10737 } 10738 10739 // If the loop is not reachable from the entry block, we risk running into an 10740 // infinite loop as we walk up into the dom tree. These loops do not matter 10741 // anyway, so we just return a conservative answer when we see them. 10742 if (!DT.isReachableFromEntry(L->getHeader())) 10743 return false; 10744 10745 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 10746 return true; 10747 10748 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 10749 DTN != HeaderDTN; DTN = DTN->getIDom()) { 10750 assert(DTN && "should reach the loop header before reaching the root!"); 10751 10752 BasicBlock *BB = DTN->getBlock(); 10753 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 10754 return true; 10755 10756 BasicBlock *PBB = BB->getSinglePredecessor(); 10757 if (!PBB) 10758 continue; 10759 10760 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 10761 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 10762 continue; 10763 10764 Value *Condition = ContinuePredicate->getCondition(); 10765 10766 // If we have an edge `E` within the loop body that dominates the only 10767 // latch, the condition guarding `E` also guards the backedge. This 10768 // reasoning works only for loops with a single latch. 10769 10770 BasicBlockEdge DominatingEdge(PBB, BB); 10771 if (DominatingEdge.isSingleEdge()) { 10772 // We're constructively (and conservatively) enumerating edges within the 10773 // loop body that dominate the latch. The dominator tree better agree 10774 // with us on this: 10775 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 10776 10777 if (isImpliedCond(Pred, LHS, RHS, Condition, 10778 BB != ContinuePredicate->getSuccessor(0))) 10779 return true; 10780 } 10781 } 10782 10783 return false; 10784 } 10785 10786 bool ScalarEvolution::isBasicBlockEntryGuardedByCond(const BasicBlock *BB, 10787 ICmpInst::Predicate Pred, 10788 const SCEV *LHS, 10789 const SCEV *RHS) { 10790 if (VerifyIR) 10791 assert(!verifyFunction(*BB->getParent(), &dbgs()) && 10792 "This cannot be done on broken IR!"); 10793 10794 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove 10795 // the facts (a >= b && a != b) separately. A typical situation is when the 10796 // non-strict comparison is known from ranges and non-equality is known from 10797 // dominating predicates. If we are proving strict comparison, we always try 10798 // to prove non-equality and non-strict comparison separately. 10799 auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred); 10800 const bool ProvingStrictComparison = (Pred != NonStrictPredicate); 10801 bool ProvedNonStrictComparison = false; 10802 bool ProvedNonEquality = false; 10803 10804 auto SplitAndProve = 10805 [&](std::function<bool(ICmpInst::Predicate)> Fn) -> bool { 10806 if (!ProvedNonStrictComparison) 10807 ProvedNonStrictComparison = Fn(NonStrictPredicate); 10808 if (!ProvedNonEquality) 10809 ProvedNonEquality = Fn(ICmpInst::ICMP_NE); 10810 if (ProvedNonStrictComparison && ProvedNonEquality) 10811 return true; 10812 return false; 10813 }; 10814 10815 if (ProvingStrictComparison) { 10816 auto ProofFn = [&](ICmpInst::Predicate P) { 10817 return isKnownViaNonRecursiveReasoning(P, LHS, RHS); 10818 }; 10819 if (SplitAndProve(ProofFn)) 10820 return true; 10821 } 10822 10823 // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard. 10824 auto ProveViaGuard = [&](const BasicBlock *Block) { 10825 if (isImpliedViaGuard(Block, Pred, LHS, RHS)) 10826 return true; 10827 if (ProvingStrictComparison) { 10828 auto ProofFn = [&](ICmpInst::Predicate P) { 10829 return isImpliedViaGuard(Block, P, LHS, RHS); 10830 }; 10831 if (SplitAndProve(ProofFn)) 10832 return true; 10833 } 10834 return false; 10835 }; 10836 10837 // Try to prove (Pred, LHS, RHS) using isImpliedCond. 10838 auto ProveViaCond = [&](const Value *Condition, bool Inverse) { 10839 const Instruction *CtxI = &BB->front(); 10840 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, CtxI)) 10841 return true; 10842 if (ProvingStrictComparison) { 10843 auto ProofFn = [&](ICmpInst::Predicate P) { 10844 return isImpliedCond(P, LHS, RHS, Condition, Inverse, CtxI); 10845 }; 10846 if (SplitAndProve(ProofFn)) 10847 return true; 10848 } 10849 return false; 10850 }; 10851 10852 // Starting at the block's predecessor, climb up the predecessor chain, as long 10853 // as there are predecessors that can be found that have unique successors 10854 // leading to the original block. 10855 const Loop *ContainingLoop = LI.getLoopFor(BB); 10856 const BasicBlock *PredBB; 10857 if (ContainingLoop && ContainingLoop->getHeader() == BB) 10858 PredBB = ContainingLoop->getLoopPredecessor(); 10859 else 10860 PredBB = BB->getSinglePredecessor(); 10861 for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB); 10862 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 10863 if (ProveViaGuard(Pair.first)) 10864 return true; 10865 10866 const BranchInst *LoopEntryPredicate = 10867 dyn_cast<BranchInst>(Pair.first->getTerminator()); 10868 if (!LoopEntryPredicate || 10869 LoopEntryPredicate->isUnconditional()) 10870 continue; 10871 10872 if (ProveViaCond(LoopEntryPredicate->getCondition(), 10873 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 10874 return true; 10875 } 10876 10877 // Check conditions due to any @llvm.assume intrinsics. 10878 for (auto &AssumeVH : AC.assumptions()) { 10879 if (!AssumeVH) 10880 continue; 10881 auto *CI = cast<CallInst>(AssumeVH); 10882 if (!DT.dominates(CI, BB)) 10883 continue; 10884 10885 if (ProveViaCond(CI->getArgOperand(0), false)) 10886 return true; 10887 } 10888 10889 return false; 10890 } 10891 10892 bool ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 10893 ICmpInst::Predicate Pred, 10894 const SCEV *LHS, 10895 const SCEV *RHS) { 10896 // Interpret a null as meaning no loop, where there is obviously no guard 10897 // (interprocedural conditions notwithstanding). 10898 if (!L) 10899 return false; 10900 10901 // Both LHS and RHS must be available at loop entry. 10902 assert(isAvailableAtLoopEntry(LHS, L) && 10903 "LHS is not available at Loop Entry"); 10904 assert(isAvailableAtLoopEntry(RHS, L) && 10905 "RHS is not available at Loop Entry"); 10906 10907 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 10908 return true; 10909 10910 return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS); 10911 } 10912 10913 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 10914 const SCEV *RHS, 10915 const Value *FoundCondValue, bool Inverse, 10916 const Instruction *CtxI) { 10917 // False conditions implies anything. Do not bother analyzing it further. 10918 if (FoundCondValue == 10919 ConstantInt::getBool(FoundCondValue->getContext(), Inverse)) 10920 return true; 10921 10922 if (!PendingLoopPredicates.insert(FoundCondValue).second) 10923 return false; 10924 10925 auto ClearOnExit = 10926 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 10927 10928 // Recursively handle And and Or conditions. 10929 const Value *Op0, *Op1; 10930 if (match(FoundCondValue, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) { 10931 if (!Inverse) 10932 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) || 10933 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI); 10934 } else if (match(FoundCondValue, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) { 10935 if (Inverse) 10936 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) || 10937 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI); 10938 } 10939 10940 const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 10941 if (!ICI) return false; 10942 10943 // Now that we found a conditional branch that dominates the loop or controls 10944 // the loop latch. Check to see if it is the comparison we are looking for. 10945 ICmpInst::Predicate FoundPred; 10946 if (Inverse) 10947 FoundPred = ICI->getInversePredicate(); 10948 else 10949 FoundPred = ICI->getPredicate(); 10950 10951 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 10952 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 10953 10954 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, CtxI); 10955 } 10956 10957 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 10958 const SCEV *RHS, 10959 ICmpInst::Predicate FoundPred, 10960 const SCEV *FoundLHS, const SCEV *FoundRHS, 10961 const Instruction *CtxI) { 10962 // Balance the types. 10963 if (getTypeSizeInBits(LHS->getType()) < 10964 getTypeSizeInBits(FoundLHS->getType())) { 10965 // For unsigned and equality predicates, try to prove that both found 10966 // operands fit into narrow unsigned range. If so, try to prove facts in 10967 // narrow types. 10968 if (!CmpInst::isSigned(FoundPred) && !FoundLHS->getType()->isPointerTy() && 10969 !FoundRHS->getType()->isPointerTy()) { 10970 auto *NarrowType = LHS->getType(); 10971 auto *WideType = FoundLHS->getType(); 10972 auto BitWidth = getTypeSizeInBits(NarrowType); 10973 const SCEV *MaxValue = getZeroExtendExpr( 10974 getConstant(APInt::getMaxValue(BitWidth)), WideType); 10975 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundLHS, 10976 MaxValue) && 10977 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundRHS, 10978 MaxValue)) { 10979 const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType); 10980 const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType); 10981 if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, TruncFoundLHS, 10982 TruncFoundRHS, CtxI)) 10983 return true; 10984 } 10985 } 10986 10987 if (LHS->getType()->isPointerTy() || RHS->getType()->isPointerTy()) 10988 return false; 10989 if (CmpInst::isSigned(Pred)) { 10990 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 10991 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 10992 } else { 10993 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 10994 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 10995 } 10996 } else if (getTypeSizeInBits(LHS->getType()) > 10997 getTypeSizeInBits(FoundLHS->getType())) { 10998 if (FoundLHS->getType()->isPointerTy() || FoundRHS->getType()->isPointerTy()) 10999 return false; 11000 if (CmpInst::isSigned(FoundPred)) { 11001 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 11002 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 11003 } else { 11004 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 11005 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 11006 } 11007 } 11008 return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS, 11009 FoundRHS, CtxI); 11010 } 11011 11012 bool ScalarEvolution::isImpliedCondBalancedTypes( 11013 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 11014 ICmpInst::Predicate FoundPred, const SCEV *FoundLHS, const SCEV *FoundRHS, 11015 const Instruction *CtxI) { 11016 assert(getTypeSizeInBits(LHS->getType()) == 11017 getTypeSizeInBits(FoundLHS->getType()) && 11018 "Types should be balanced!"); 11019 // Canonicalize the query to match the way instcombine will have 11020 // canonicalized the comparison. 11021 if (SimplifyICmpOperands(Pred, LHS, RHS)) 11022 if (LHS == RHS) 11023 return CmpInst::isTrueWhenEqual(Pred); 11024 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 11025 if (FoundLHS == FoundRHS) 11026 return CmpInst::isFalseWhenEqual(FoundPred); 11027 11028 // Check to see if we can make the LHS or RHS match. 11029 if (LHS == FoundRHS || RHS == FoundLHS) { 11030 if (isa<SCEVConstant>(RHS)) { 11031 std::swap(FoundLHS, FoundRHS); 11032 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 11033 } else { 11034 std::swap(LHS, RHS); 11035 Pred = ICmpInst::getSwappedPredicate(Pred); 11036 } 11037 } 11038 11039 // Check whether the found predicate is the same as the desired predicate. 11040 if (FoundPred == Pred) 11041 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI); 11042 11043 // Check whether swapping the found predicate makes it the same as the 11044 // desired predicate. 11045 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 11046 // We can write the implication 11047 // 0. LHS Pred RHS <- FoundLHS SwapPred FoundRHS 11048 // using one of the following ways: 11049 // 1. LHS Pred RHS <- FoundRHS Pred FoundLHS 11050 // 2. RHS SwapPred LHS <- FoundLHS SwapPred FoundRHS 11051 // 3. LHS Pred RHS <- ~FoundLHS Pred ~FoundRHS 11052 // 4. ~LHS SwapPred ~RHS <- FoundLHS SwapPred FoundRHS 11053 // Forms 1. and 2. require swapping the operands of one condition. Don't 11054 // do this if it would break canonical constant/addrec ordering. 11055 if (!isa<SCEVConstant>(RHS) && !isa<SCEVAddRecExpr>(LHS)) 11056 return isImpliedCondOperands(FoundPred, RHS, LHS, FoundLHS, FoundRHS, 11057 CtxI); 11058 if (!isa<SCEVConstant>(FoundRHS) && !isa<SCEVAddRecExpr>(FoundLHS)) 11059 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS, CtxI); 11060 11061 // There's no clear preference between forms 3. and 4., try both. Avoid 11062 // forming getNotSCEV of pointer values as the resulting subtract is 11063 // not legal. 11064 if (!LHS->getType()->isPointerTy() && !RHS->getType()->isPointerTy() && 11065 isImpliedCondOperands(FoundPred, getNotSCEV(LHS), getNotSCEV(RHS), 11066 FoundLHS, FoundRHS, CtxI)) 11067 return true; 11068 11069 if (!FoundLHS->getType()->isPointerTy() && 11070 !FoundRHS->getType()->isPointerTy() && 11071 isImpliedCondOperands(Pred, LHS, RHS, getNotSCEV(FoundLHS), 11072 getNotSCEV(FoundRHS), CtxI)) 11073 return true; 11074 11075 return false; 11076 } 11077 11078 auto IsSignFlippedPredicate = [](CmpInst::Predicate P1, 11079 CmpInst::Predicate P2) { 11080 assert(P1 != P2 && "Handled earlier!"); 11081 return CmpInst::isRelational(P2) && 11082 P1 == CmpInst::getFlippedSignednessPredicate(P2); 11083 }; 11084 if (IsSignFlippedPredicate(Pred, FoundPred)) { 11085 // Unsigned comparison is the same as signed comparison when both the 11086 // operands are non-negative or negative. 11087 if ((isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) || 11088 (isKnownNegative(FoundLHS) && isKnownNegative(FoundRHS))) 11089 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI); 11090 // Create local copies that we can freely swap and canonicalize our 11091 // conditions to "le/lt". 11092 ICmpInst::Predicate CanonicalPred = Pred, CanonicalFoundPred = FoundPred; 11093 const SCEV *CanonicalLHS = LHS, *CanonicalRHS = RHS, 11094 *CanonicalFoundLHS = FoundLHS, *CanonicalFoundRHS = FoundRHS; 11095 if (ICmpInst::isGT(CanonicalPred) || ICmpInst::isGE(CanonicalPred)) { 11096 CanonicalPred = ICmpInst::getSwappedPredicate(CanonicalPred); 11097 CanonicalFoundPred = ICmpInst::getSwappedPredicate(CanonicalFoundPred); 11098 std::swap(CanonicalLHS, CanonicalRHS); 11099 std::swap(CanonicalFoundLHS, CanonicalFoundRHS); 11100 } 11101 assert((ICmpInst::isLT(CanonicalPred) || ICmpInst::isLE(CanonicalPred)) && 11102 "Must be!"); 11103 assert((ICmpInst::isLT(CanonicalFoundPred) || 11104 ICmpInst::isLE(CanonicalFoundPred)) && 11105 "Must be!"); 11106 if (ICmpInst::isSigned(CanonicalPred) && isKnownNonNegative(CanonicalRHS)) 11107 // Use implication: 11108 // x <u y && y >=s 0 --> x <s y. 11109 // If we can prove the left part, the right part is also proven. 11110 return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS, 11111 CanonicalRHS, CanonicalFoundLHS, 11112 CanonicalFoundRHS); 11113 if (ICmpInst::isUnsigned(CanonicalPred) && isKnownNegative(CanonicalRHS)) 11114 // Use implication: 11115 // x <s y && y <s 0 --> x <u y. 11116 // If we can prove the left part, the right part is also proven. 11117 return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS, 11118 CanonicalRHS, CanonicalFoundLHS, 11119 CanonicalFoundRHS); 11120 } 11121 11122 // Check if we can make progress by sharpening ranges. 11123 if (FoundPred == ICmpInst::ICMP_NE && 11124 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 11125 11126 const SCEVConstant *C = nullptr; 11127 const SCEV *V = nullptr; 11128 11129 if (isa<SCEVConstant>(FoundLHS)) { 11130 C = cast<SCEVConstant>(FoundLHS); 11131 V = FoundRHS; 11132 } else { 11133 C = cast<SCEVConstant>(FoundRHS); 11134 V = FoundLHS; 11135 } 11136 11137 // The guarding predicate tells us that C != V. If the known range 11138 // of V is [C, t), we can sharpen the range to [C + 1, t). The 11139 // range we consider has to correspond to same signedness as the 11140 // predicate we're interested in folding. 11141 11142 APInt Min = ICmpInst::isSigned(Pred) ? 11143 getSignedRangeMin(V) : getUnsignedRangeMin(V); 11144 11145 if (Min == C->getAPInt()) { 11146 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 11147 // This is true even if (Min + 1) wraps around -- in case of 11148 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 11149 11150 APInt SharperMin = Min + 1; 11151 11152 switch (Pred) { 11153 case ICmpInst::ICMP_SGE: 11154 case ICmpInst::ICMP_UGE: 11155 // We know V `Pred` SharperMin. If this implies LHS `Pred` 11156 // RHS, we're done. 11157 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin), 11158 CtxI)) 11159 return true; 11160 LLVM_FALLTHROUGH; 11161 11162 case ICmpInst::ICMP_SGT: 11163 case ICmpInst::ICMP_UGT: 11164 // We know from the range information that (V `Pred` Min || 11165 // V == Min). We know from the guarding condition that !(V 11166 // == Min). This gives us 11167 // 11168 // V `Pred` Min || V == Min && !(V == Min) 11169 // => V `Pred` Min 11170 // 11171 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 11172 11173 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min), CtxI)) 11174 return true; 11175 break; 11176 11177 // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively. 11178 case ICmpInst::ICMP_SLE: 11179 case ICmpInst::ICMP_ULE: 11180 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS, 11181 LHS, V, getConstant(SharperMin), CtxI)) 11182 return true; 11183 LLVM_FALLTHROUGH; 11184 11185 case ICmpInst::ICMP_SLT: 11186 case ICmpInst::ICMP_ULT: 11187 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS, 11188 LHS, V, getConstant(Min), CtxI)) 11189 return true; 11190 break; 11191 11192 default: 11193 // No change 11194 break; 11195 } 11196 } 11197 } 11198 11199 // Check whether the actual condition is beyond sufficient. 11200 if (FoundPred == ICmpInst::ICMP_EQ) 11201 if (ICmpInst::isTrueWhenEqual(Pred)) 11202 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI)) 11203 return true; 11204 if (Pred == ICmpInst::ICMP_NE) 11205 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 11206 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS, CtxI)) 11207 return true; 11208 11209 // Otherwise assume the worst. 11210 return false; 11211 } 11212 11213 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 11214 const SCEV *&L, const SCEV *&R, 11215 SCEV::NoWrapFlags &Flags) { 11216 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 11217 if (!AE || AE->getNumOperands() != 2) 11218 return false; 11219 11220 L = AE->getOperand(0); 11221 R = AE->getOperand(1); 11222 Flags = AE->getNoWrapFlags(); 11223 return true; 11224 } 11225 11226 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 11227 const SCEV *Less) { 11228 // We avoid subtracting expressions here because this function is usually 11229 // fairly deep in the call stack (i.e. is called many times). 11230 11231 // X - X = 0. 11232 if (More == Less) 11233 return APInt(getTypeSizeInBits(More->getType()), 0); 11234 11235 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 11236 const auto *LAR = cast<SCEVAddRecExpr>(Less); 11237 const auto *MAR = cast<SCEVAddRecExpr>(More); 11238 11239 if (LAR->getLoop() != MAR->getLoop()) 11240 return None; 11241 11242 // We look at affine expressions only; not for correctness but to keep 11243 // getStepRecurrence cheap. 11244 if (!LAR->isAffine() || !MAR->isAffine()) 11245 return None; 11246 11247 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 11248 return None; 11249 11250 Less = LAR->getStart(); 11251 More = MAR->getStart(); 11252 11253 // fall through 11254 } 11255 11256 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 11257 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 11258 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 11259 return M - L; 11260 } 11261 11262 SCEV::NoWrapFlags Flags; 11263 const SCEV *LLess = nullptr, *RLess = nullptr; 11264 const SCEV *LMore = nullptr, *RMore = nullptr; 11265 const SCEVConstant *C1 = nullptr, *C2 = nullptr; 11266 // Compare (X + C1) vs X. 11267 if (splitBinaryAdd(Less, LLess, RLess, Flags)) 11268 if ((C1 = dyn_cast<SCEVConstant>(LLess))) 11269 if (RLess == More) 11270 return -(C1->getAPInt()); 11271 11272 // Compare X vs (X + C2). 11273 if (splitBinaryAdd(More, LMore, RMore, Flags)) 11274 if ((C2 = dyn_cast<SCEVConstant>(LMore))) 11275 if (RMore == Less) 11276 return C2->getAPInt(); 11277 11278 // Compare (X + C1) vs (X + C2). 11279 if (C1 && C2 && RLess == RMore) 11280 return C2->getAPInt() - C1->getAPInt(); 11281 11282 return None; 11283 } 11284 11285 bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart( 11286 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 11287 const SCEV *FoundLHS, const SCEV *FoundRHS, const Instruction *CtxI) { 11288 // Try to recognize the following pattern: 11289 // 11290 // FoundRHS = ... 11291 // ... 11292 // loop: 11293 // FoundLHS = {Start,+,W} 11294 // context_bb: // Basic block from the same loop 11295 // known(Pred, FoundLHS, FoundRHS) 11296 // 11297 // If some predicate is known in the context of a loop, it is also known on 11298 // each iteration of this loop, including the first iteration. Therefore, in 11299 // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to 11300 // prove the original pred using this fact. 11301 if (!CtxI) 11302 return false; 11303 const BasicBlock *ContextBB = CtxI->getParent(); 11304 // Make sure AR varies in the context block. 11305 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) { 11306 const Loop *L = AR->getLoop(); 11307 // Make sure that context belongs to the loop and executes on 1st iteration 11308 // (if it ever executes at all). 11309 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch())) 11310 return false; 11311 if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop())) 11312 return false; 11313 return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS); 11314 } 11315 11316 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) { 11317 const Loop *L = AR->getLoop(); 11318 // Make sure that context belongs to the loop and executes on 1st iteration 11319 // (if it ever executes at all). 11320 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch())) 11321 return false; 11322 if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop())) 11323 return false; 11324 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart()); 11325 } 11326 11327 return false; 11328 } 11329 11330 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 11331 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 11332 const SCEV *FoundLHS, const SCEV *FoundRHS) { 11333 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 11334 return false; 11335 11336 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 11337 if (!AddRecLHS) 11338 return false; 11339 11340 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 11341 if (!AddRecFoundLHS) 11342 return false; 11343 11344 // We'd like to let SCEV reason about control dependencies, so we constrain 11345 // both the inequalities to be about add recurrences on the same loop. This 11346 // way we can use isLoopEntryGuardedByCond later. 11347 11348 const Loop *L = AddRecFoundLHS->getLoop(); 11349 if (L != AddRecLHS->getLoop()) 11350 return false; 11351 11352 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 11353 // 11354 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 11355 // ... (2) 11356 // 11357 // Informal proof for (2), assuming (1) [*]: 11358 // 11359 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 11360 // 11361 // Then 11362 // 11363 // FoundLHS s< FoundRHS s< INT_MIN - C 11364 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 11365 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 11366 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 11367 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 11368 // <=> FoundLHS + C s< FoundRHS + C 11369 // 11370 // [*]: (1) can be proved by ruling out overflow. 11371 // 11372 // [**]: This can be proved by analyzing all the four possibilities: 11373 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 11374 // (A s>= 0, B s>= 0). 11375 // 11376 // Note: 11377 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 11378 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 11379 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 11380 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 11381 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 11382 // C)". 11383 11384 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 11385 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 11386 if (!LDiff || !RDiff || *LDiff != *RDiff) 11387 return false; 11388 11389 if (LDiff->isMinValue()) 11390 return true; 11391 11392 APInt FoundRHSLimit; 11393 11394 if (Pred == CmpInst::ICMP_ULT) { 11395 FoundRHSLimit = -(*RDiff); 11396 } else { 11397 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 11398 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 11399 } 11400 11401 // Try to prove (1) or (2), as needed. 11402 return isAvailableAtLoopEntry(FoundRHS, L) && 11403 isLoopEntryGuardedByCond(L, Pred, FoundRHS, 11404 getConstant(FoundRHSLimit)); 11405 } 11406 11407 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred, 11408 const SCEV *LHS, const SCEV *RHS, 11409 const SCEV *FoundLHS, 11410 const SCEV *FoundRHS, unsigned Depth) { 11411 const PHINode *LPhi = nullptr, *RPhi = nullptr; 11412 11413 auto ClearOnExit = make_scope_exit([&]() { 11414 if (LPhi) { 11415 bool Erased = PendingMerges.erase(LPhi); 11416 assert(Erased && "Failed to erase LPhi!"); 11417 (void)Erased; 11418 } 11419 if (RPhi) { 11420 bool Erased = PendingMerges.erase(RPhi); 11421 assert(Erased && "Failed to erase RPhi!"); 11422 (void)Erased; 11423 } 11424 }); 11425 11426 // Find respective Phis and check that they are not being pending. 11427 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) 11428 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) { 11429 if (!PendingMerges.insert(Phi).second) 11430 return false; 11431 LPhi = Phi; 11432 } 11433 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS)) 11434 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) { 11435 // If we detect a loop of Phi nodes being processed by this method, for 11436 // example: 11437 // 11438 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ] 11439 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ] 11440 // 11441 // we don't want to deal with a case that complex, so return conservative 11442 // answer false. 11443 if (!PendingMerges.insert(Phi).second) 11444 return false; 11445 RPhi = Phi; 11446 } 11447 11448 // If none of LHS, RHS is a Phi, nothing to do here. 11449 if (!LPhi && !RPhi) 11450 return false; 11451 11452 // If there is a SCEVUnknown Phi we are interested in, make it left. 11453 if (!LPhi) { 11454 std::swap(LHS, RHS); 11455 std::swap(FoundLHS, FoundRHS); 11456 std::swap(LPhi, RPhi); 11457 Pred = ICmpInst::getSwappedPredicate(Pred); 11458 } 11459 11460 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!"); 11461 const BasicBlock *LBB = LPhi->getParent(); 11462 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 11463 11464 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) { 11465 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) || 11466 isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) || 11467 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth); 11468 }; 11469 11470 if (RPhi && RPhi->getParent() == LBB) { 11471 // Case one: RHS is also a SCEVUnknown Phi from the same basic block. 11472 // If we compare two Phis from the same block, and for each entry block 11473 // the predicate is true for incoming values from this block, then the 11474 // predicate is also true for the Phis. 11475 for (const BasicBlock *IncBB : predecessors(LBB)) { 11476 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 11477 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB)); 11478 if (!ProvedEasily(L, R)) 11479 return false; 11480 } 11481 } else if (RAR && RAR->getLoop()->getHeader() == LBB) { 11482 // Case two: RHS is also a Phi from the same basic block, and it is an 11483 // AddRec. It means that there is a loop which has both AddRec and Unknown 11484 // PHIs, for it we can compare incoming values of AddRec from above the loop 11485 // and latch with their respective incoming values of LPhi. 11486 // TODO: Generalize to handle loops with many inputs in a header. 11487 if (LPhi->getNumIncomingValues() != 2) return false; 11488 11489 auto *RLoop = RAR->getLoop(); 11490 auto *Predecessor = RLoop->getLoopPredecessor(); 11491 assert(Predecessor && "Loop with AddRec with no predecessor?"); 11492 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor)); 11493 if (!ProvedEasily(L1, RAR->getStart())) 11494 return false; 11495 auto *Latch = RLoop->getLoopLatch(); 11496 assert(Latch && "Loop with AddRec with no latch?"); 11497 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch)); 11498 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this))) 11499 return false; 11500 } else { 11501 // In all other cases go over inputs of LHS and compare each of them to RHS, 11502 // the predicate is true for (LHS, RHS) if it is true for all such pairs. 11503 // At this point RHS is either a non-Phi, or it is a Phi from some block 11504 // different from LBB. 11505 for (const BasicBlock *IncBB : predecessors(LBB)) { 11506 // Check that RHS is available in this block. 11507 if (!dominates(RHS, IncBB)) 11508 return false; 11509 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 11510 // Make sure L does not refer to a value from a potentially previous 11511 // iteration of a loop. 11512 if (!properlyDominates(L, IncBB)) 11513 return false; 11514 if (!ProvedEasily(L, RHS)) 11515 return false; 11516 } 11517 } 11518 return true; 11519 } 11520 11521 bool ScalarEvolution::isImpliedCondOperandsViaShift(ICmpInst::Predicate Pred, 11522 const SCEV *LHS, 11523 const SCEV *RHS, 11524 const SCEV *FoundLHS, 11525 const SCEV *FoundRHS) { 11526 // We want to imply LHS < RHS from LHS < (RHS >> shiftvalue). First, make 11527 // sure that we are dealing with same LHS. 11528 if (RHS == FoundRHS) { 11529 std::swap(LHS, RHS); 11530 std::swap(FoundLHS, FoundRHS); 11531 Pred = ICmpInst::getSwappedPredicate(Pred); 11532 } 11533 if (LHS != FoundLHS) 11534 return false; 11535 11536 auto *SUFoundRHS = dyn_cast<SCEVUnknown>(FoundRHS); 11537 if (!SUFoundRHS) 11538 return false; 11539 11540 Value *Shiftee, *ShiftValue; 11541 11542 using namespace PatternMatch; 11543 if (match(SUFoundRHS->getValue(), 11544 m_LShr(m_Value(Shiftee), m_Value(ShiftValue)))) { 11545 auto *ShifteeS = getSCEV(Shiftee); 11546 // Prove one of the following: 11547 // LHS <u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <u RHS 11548 // LHS <=u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <=u RHS 11549 // LHS <s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0 11550 // ---> LHS <s RHS 11551 // LHS <=s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0 11552 // ---> LHS <=s RHS 11553 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) 11554 return isKnownPredicate(ICmpInst::ICMP_ULE, ShifteeS, RHS); 11555 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) 11556 if (isKnownNonNegative(ShifteeS)) 11557 return isKnownPredicate(ICmpInst::ICMP_SLE, ShifteeS, RHS); 11558 } 11559 11560 return false; 11561 } 11562 11563 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 11564 const SCEV *LHS, const SCEV *RHS, 11565 const SCEV *FoundLHS, 11566 const SCEV *FoundRHS, 11567 const Instruction *CtxI) { 11568 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 11569 return true; 11570 11571 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 11572 return true; 11573 11574 if (isImpliedCondOperandsViaShift(Pred, LHS, RHS, FoundLHS, FoundRHS)) 11575 return true; 11576 11577 if (isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS, 11578 CtxI)) 11579 return true; 11580 11581 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 11582 FoundLHS, FoundRHS); 11583 } 11584 11585 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values? 11586 template <typename MinMaxExprType> 11587 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr, 11588 const SCEV *Candidate) { 11589 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr); 11590 if (!MinMaxExpr) 11591 return false; 11592 11593 return is_contained(MinMaxExpr->operands(), Candidate); 11594 } 11595 11596 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 11597 ICmpInst::Predicate Pred, 11598 const SCEV *LHS, const SCEV *RHS) { 11599 // If both sides are affine addrecs for the same loop, with equal 11600 // steps, and we know the recurrences don't wrap, then we only 11601 // need to check the predicate on the starting values. 11602 11603 if (!ICmpInst::isRelational(Pred)) 11604 return false; 11605 11606 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 11607 if (!LAR) 11608 return false; 11609 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 11610 if (!RAR) 11611 return false; 11612 if (LAR->getLoop() != RAR->getLoop()) 11613 return false; 11614 if (!LAR->isAffine() || !RAR->isAffine()) 11615 return false; 11616 11617 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 11618 return false; 11619 11620 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 11621 SCEV::FlagNSW : SCEV::FlagNUW; 11622 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 11623 return false; 11624 11625 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 11626 } 11627 11628 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 11629 /// expression? 11630 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 11631 ICmpInst::Predicate Pred, 11632 const SCEV *LHS, const SCEV *RHS) { 11633 switch (Pred) { 11634 default: 11635 return false; 11636 11637 case ICmpInst::ICMP_SGE: 11638 std::swap(LHS, RHS); 11639 LLVM_FALLTHROUGH; 11640 case ICmpInst::ICMP_SLE: 11641 return 11642 // min(A, ...) <= A 11643 IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) || 11644 // A <= max(A, ...) 11645 IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 11646 11647 case ICmpInst::ICMP_UGE: 11648 std::swap(LHS, RHS); 11649 LLVM_FALLTHROUGH; 11650 case ICmpInst::ICMP_ULE: 11651 return 11652 // min(A, ...) <= A 11653 // FIXME: what about umin_seq? 11654 IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) || 11655 // A <= max(A, ...) 11656 IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 11657 } 11658 11659 llvm_unreachable("covered switch fell through?!"); 11660 } 11661 11662 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred, 11663 const SCEV *LHS, const SCEV *RHS, 11664 const SCEV *FoundLHS, 11665 const SCEV *FoundRHS, 11666 unsigned Depth) { 11667 assert(getTypeSizeInBits(LHS->getType()) == 11668 getTypeSizeInBits(RHS->getType()) && 11669 "LHS and RHS have different sizes?"); 11670 assert(getTypeSizeInBits(FoundLHS->getType()) == 11671 getTypeSizeInBits(FoundRHS->getType()) && 11672 "FoundLHS and FoundRHS have different sizes?"); 11673 // We want to avoid hurting the compile time with analysis of too big trees. 11674 if (Depth > MaxSCEVOperationsImplicationDepth) 11675 return false; 11676 11677 // We only want to work with GT comparison so far. 11678 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) { 11679 Pred = CmpInst::getSwappedPredicate(Pred); 11680 std::swap(LHS, RHS); 11681 std::swap(FoundLHS, FoundRHS); 11682 } 11683 11684 // For unsigned, try to reduce it to corresponding signed comparison. 11685 if (Pred == ICmpInst::ICMP_UGT) 11686 // We can replace unsigned predicate with its signed counterpart if all 11687 // involved values are non-negative. 11688 // TODO: We could have better support for unsigned. 11689 if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) { 11690 // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing 11691 // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us 11692 // use this fact to prove that LHS and RHS are non-negative. 11693 const SCEV *MinusOne = getMinusOne(LHS->getType()); 11694 if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS, 11695 FoundRHS) && 11696 isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS, 11697 FoundRHS)) 11698 Pred = ICmpInst::ICMP_SGT; 11699 } 11700 11701 if (Pred != ICmpInst::ICMP_SGT) 11702 return false; 11703 11704 auto GetOpFromSExt = [&](const SCEV *S) { 11705 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S)) 11706 return Ext->getOperand(); 11707 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off 11708 // the constant in some cases. 11709 return S; 11710 }; 11711 11712 // Acquire values from extensions. 11713 auto *OrigLHS = LHS; 11714 auto *OrigFoundLHS = FoundLHS; 11715 LHS = GetOpFromSExt(LHS); 11716 FoundLHS = GetOpFromSExt(FoundLHS); 11717 11718 // Is the SGT predicate can be proved trivially or using the found context. 11719 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) { 11720 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) || 11721 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS, 11722 FoundRHS, Depth + 1); 11723 }; 11724 11725 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) { 11726 // We want to avoid creation of any new non-constant SCEV. Since we are 11727 // going to compare the operands to RHS, we should be certain that we don't 11728 // need any size extensions for this. So let's decline all cases when the 11729 // sizes of types of LHS and RHS do not match. 11730 // TODO: Maybe try to get RHS from sext to catch more cases? 11731 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType())) 11732 return false; 11733 11734 // Should not overflow. 11735 if (!LHSAddExpr->hasNoSignedWrap()) 11736 return false; 11737 11738 auto *LL = LHSAddExpr->getOperand(0); 11739 auto *LR = LHSAddExpr->getOperand(1); 11740 auto *MinusOne = getMinusOne(RHS->getType()); 11741 11742 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context. 11743 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) { 11744 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS); 11745 }; 11746 // Try to prove the following rule: 11747 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS). 11748 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS). 11749 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL)) 11750 return true; 11751 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) { 11752 Value *LL, *LR; 11753 // FIXME: Once we have SDiv implemented, we can get rid of this matching. 11754 11755 using namespace llvm::PatternMatch; 11756 11757 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) { 11758 // Rules for division. 11759 // We are going to perform some comparisons with Denominator and its 11760 // derivative expressions. In general case, creating a SCEV for it may 11761 // lead to a complex analysis of the entire graph, and in particular it 11762 // can request trip count recalculation for the same loop. This would 11763 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid 11764 // this, we only want to create SCEVs that are constants in this section. 11765 // So we bail if Denominator is not a constant. 11766 if (!isa<ConstantInt>(LR)) 11767 return false; 11768 11769 auto *Denominator = cast<SCEVConstant>(getSCEV(LR)); 11770 11771 // We want to make sure that LHS = FoundLHS / Denominator. If it is so, 11772 // then a SCEV for the numerator already exists and matches with FoundLHS. 11773 auto *Numerator = getExistingSCEV(LL); 11774 if (!Numerator || Numerator->getType() != FoundLHS->getType()) 11775 return false; 11776 11777 // Make sure that the numerator matches with FoundLHS and the denominator 11778 // is positive. 11779 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator)) 11780 return false; 11781 11782 auto *DTy = Denominator->getType(); 11783 auto *FRHSTy = FoundRHS->getType(); 11784 if (DTy->isPointerTy() != FRHSTy->isPointerTy()) 11785 // One of types is a pointer and another one is not. We cannot extend 11786 // them properly to a wider type, so let us just reject this case. 11787 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help 11788 // to avoid this check. 11789 return false; 11790 11791 // Given that: 11792 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0. 11793 auto *WTy = getWiderType(DTy, FRHSTy); 11794 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy); 11795 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy); 11796 11797 // Try to prove the following rule: 11798 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS). 11799 // For example, given that FoundLHS > 2. It means that FoundLHS is at 11800 // least 3. If we divide it by Denominator < 4, we will have at least 1. 11801 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2)); 11802 if (isKnownNonPositive(RHS) && 11803 IsSGTViaContext(FoundRHSExt, DenomMinusTwo)) 11804 return true; 11805 11806 // Try to prove the following rule: 11807 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS). 11808 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2. 11809 // If we divide it by Denominator > 2, then: 11810 // 1. If FoundLHS is negative, then the result is 0. 11811 // 2. If FoundLHS is non-negative, then the result is non-negative. 11812 // Anyways, the result is non-negative. 11813 auto *MinusOne = getMinusOne(WTy); 11814 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt); 11815 if (isKnownNegative(RHS) && 11816 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne)) 11817 return true; 11818 } 11819 } 11820 11821 // If our expression contained SCEVUnknown Phis, and we split it down and now 11822 // need to prove something for them, try to prove the predicate for every 11823 // possible incoming values of those Phis. 11824 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1)) 11825 return true; 11826 11827 return false; 11828 } 11829 11830 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred, 11831 const SCEV *LHS, const SCEV *RHS) { 11832 // zext x u<= sext x, sext x s<= zext x 11833 switch (Pred) { 11834 case ICmpInst::ICMP_SGE: 11835 std::swap(LHS, RHS); 11836 LLVM_FALLTHROUGH; 11837 case ICmpInst::ICMP_SLE: { 11838 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt. 11839 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS); 11840 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS); 11841 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 11842 return true; 11843 break; 11844 } 11845 case ICmpInst::ICMP_UGE: 11846 std::swap(LHS, RHS); 11847 LLVM_FALLTHROUGH; 11848 case ICmpInst::ICMP_ULE: { 11849 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then ZExt <u SExt. 11850 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS); 11851 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS); 11852 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 11853 return true; 11854 break; 11855 } 11856 default: 11857 break; 11858 }; 11859 return false; 11860 } 11861 11862 bool 11863 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred, 11864 const SCEV *LHS, const SCEV *RHS) { 11865 return isKnownPredicateExtendIdiom(Pred, LHS, RHS) || 11866 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 11867 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 11868 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 11869 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 11870 } 11871 11872 bool 11873 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 11874 const SCEV *LHS, const SCEV *RHS, 11875 const SCEV *FoundLHS, 11876 const SCEV *FoundRHS) { 11877 switch (Pred) { 11878 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 11879 case ICmpInst::ICMP_EQ: 11880 case ICmpInst::ICMP_NE: 11881 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 11882 return true; 11883 break; 11884 case ICmpInst::ICMP_SLT: 11885 case ICmpInst::ICMP_SLE: 11886 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 11887 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 11888 return true; 11889 break; 11890 case ICmpInst::ICMP_SGT: 11891 case ICmpInst::ICMP_SGE: 11892 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 11893 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 11894 return true; 11895 break; 11896 case ICmpInst::ICMP_ULT: 11897 case ICmpInst::ICMP_ULE: 11898 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 11899 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 11900 return true; 11901 break; 11902 case ICmpInst::ICMP_UGT: 11903 case ICmpInst::ICMP_UGE: 11904 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 11905 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 11906 return true; 11907 break; 11908 } 11909 11910 // Maybe it can be proved via operations? 11911 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS)) 11912 return true; 11913 11914 return false; 11915 } 11916 11917 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 11918 const SCEV *LHS, 11919 const SCEV *RHS, 11920 const SCEV *FoundLHS, 11921 const SCEV *FoundRHS) { 11922 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 11923 // The restriction on `FoundRHS` be lifted easily -- it exists only to 11924 // reduce the compile time impact of this optimization. 11925 return false; 11926 11927 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 11928 if (!Addend) 11929 return false; 11930 11931 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 11932 11933 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 11934 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 11935 ConstantRange FoundLHSRange = 11936 ConstantRange::makeExactICmpRegion(Pred, ConstFoundRHS); 11937 11938 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 11939 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 11940 11941 // We can also compute the range of values for `LHS` that satisfy the 11942 // consequent, "`LHS` `Pred` `RHS`": 11943 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 11944 // The antecedent implies the consequent if every value of `LHS` that 11945 // satisfies the antecedent also satisfies the consequent. 11946 return LHSRange.icmp(Pred, ConstRHS); 11947 } 11948 11949 bool ScalarEvolution::canIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 11950 bool IsSigned) { 11951 assert(isKnownPositive(Stride) && "Positive stride expected!"); 11952 11953 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 11954 const SCEV *One = getOne(Stride->getType()); 11955 11956 if (IsSigned) { 11957 APInt MaxRHS = getSignedRangeMax(RHS); 11958 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 11959 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 11960 11961 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 11962 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS); 11963 } 11964 11965 APInt MaxRHS = getUnsignedRangeMax(RHS); 11966 APInt MaxValue = APInt::getMaxValue(BitWidth); 11967 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 11968 11969 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 11970 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS); 11971 } 11972 11973 bool ScalarEvolution::canIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 11974 bool IsSigned) { 11975 11976 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 11977 const SCEV *One = getOne(Stride->getType()); 11978 11979 if (IsSigned) { 11980 APInt MinRHS = getSignedRangeMin(RHS); 11981 APInt MinValue = APInt::getSignedMinValue(BitWidth); 11982 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 11983 11984 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 11985 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS); 11986 } 11987 11988 APInt MinRHS = getUnsignedRangeMin(RHS); 11989 APInt MinValue = APInt::getMinValue(BitWidth); 11990 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 11991 11992 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 11993 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS); 11994 } 11995 11996 const SCEV *ScalarEvolution::getUDivCeilSCEV(const SCEV *N, const SCEV *D) { 11997 // umin(N, 1) + floor((N - umin(N, 1)) / D) 11998 // This is equivalent to "1 + floor((N - 1) / D)" for N != 0. The umin 11999 // expression fixes the case of N=0. 12000 const SCEV *MinNOne = getUMinExpr(N, getOne(N->getType())); 12001 const SCEV *NMinusOne = getMinusSCEV(N, MinNOne); 12002 return getAddExpr(MinNOne, getUDivExpr(NMinusOne, D)); 12003 } 12004 12005 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, 12006 const SCEV *Stride, 12007 const SCEV *End, 12008 unsigned BitWidth, 12009 bool IsSigned) { 12010 // The logic in this function assumes we can represent a positive stride. 12011 // If we can't, the backedge-taken count must be zero. 12012 if (IsSigned && BitWidth == 1) 12013 return getZero(Stride->getType()); 12014 12015 // This code has only been closely audited for negative strides in the 12016 // unsigned comparison case, it may be correct for signed comparison, but 12017 // that needs to be established. 12018 assert((!IsSigned || !isKnownNonPositive(Stride)) && 12019 "Stride is expected strictly positive for signed case!"); 12020 12021 // Calculate the maximum backedge count based on the range of values 12022 // permitted by Start, End, and Stride. 12023 APInt MinStart = 12024 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start); 12025 12026 APInt MinStride = 12027 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride); 12028 12029 // We assume either the stride is positive, or the backedge-taken count 12030 // is zero. So force StrideForMaxBECount to be at least one. 12031 APInt One(BitWidth, 1); 12032 APInt StrideForMaxBECount = IsSigned ? APIntOps::smax(One, MinStride) 12033 : APIntOps::umax(One, MinStride); 12034 12035 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth) 12036 : APInt::getMaxValue(BitWidth); 12037 APInt Limit = MaxValue - (StrideForMaxBECount - 1); 12038 12039 // Although End can be a MAX expression we estimate MaxEnd considering only 12040 // the case End = RHS of the loop termination condition. This is safe because 12041 // in the other case (End - Start) is zero, leading to a zero maximum backedge 12042 // taken count. 12043 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit) 12044 : APIntOps::umin(getUnsignedRangeMax(End), Limit); 12045 12046 // MaxBECount = ceil((max(MaxEnd, MinStart) - MinStart) / Stride) 12047 MaxEnd = IsSigned ? APIntOps::smax(MaxEnd, MinStart) 12048 : APIntOps::umax(MaxEnd, MinStart); 12049 12050 return getUDivCeilSCEV(getConstant(MaxEnd - MinStart) /* Delta */, 12051 getConstant(StrideForMaxBECount) /* Step */); 12052 } 12053 12054 ScalarEvolution::ExitLimit 12055 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 12056 const Loop *L, bool IsSigned, 12057 bool ControlsExit, bool AllowPredicates) { 12058 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 12059 12060 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 12061 bool PredicatedIV = false; 12062 12063 auto canAssumeNoSelfWrap = [&](const SCEVAddRecExpr *AR) { 12064 // Can we prove this loop *must* be UB if overflow of IV occurs? 12065 // Reasoning goes as follows: 12066 // * Suppose the IV did self wrap. 12067 // * If Stride evenly divides the iteration space, then once wrap 12068 // occurs, the loop must revisit the same values. 12069 // * We know that RHS is invariant, and that none of those values 12070 // caused this exit to be taken previously. Thus, this exit is 12071 // dynamically dead. 12072 // * If this is the sole exit, then a dead exit implies the loop 12073 // must be infinite if there are no abnormal exits. 12074 // * If the loop were infinite, then it must either not be mustprogress 12075 // or have side effects. Otherwise, it must be UB. 12076 // * It can't (by assumption), be UB so we have contradicted our 12077 // premise and can conclude the IV did not in fact self-wrap. 12078 if (!isLoopInvariant(RHS, L)) 12079 return false; 12080 12081 auto *StrideC = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)); 12082 if (!StrideC || !StrideC->getAPInt().isPowerOf2()) 12083 return false; 12084 12085 if (!ControlsExit || !loopHasNoAbnormalExits(L)) 12086 return false; 12087 12088 return loopIsFiniteByAssumption(L); 12089 }; 12090 12091 if (!IV) { 12092 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS)) { 12093 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(ZExt->getOperand()); 12094 if (AR && AR->getLoop() == L && AR->isAffine()) { 12095 auto canProveNUW = [&]() { 12096 if (!isLoopInvariant(RHS, L)) 12097 return false; 12098 12099 if (!isKnownNonZero(AR->getStepRecurrence(*this))) 12100 // We need the sequence defined by AR to strictly increase in the 12101 // unsigned integer domain for the logic below to hold. 12102 return false; 12103 12104 const unsigned InnerBitWidth = getTypeSizeInBits(AR->getType()); 12105 const unsigned OuterBitWidth = getTypeSizeInBits(RHS->getType()); 12106 // If RHS <=u Limit, then there must exist a value V in the sequence 12107 // defined by AR (e.g. {Start,+,Step}) such that V >u RHS, and 12108 // V <=u UINT_MAX. Thus, we must exit the loop before unsigned 12109 // overflow occurs. This limit also implies that a signed comparison 12110 // (in the wide bitwidth) is equivalent to an unsigned comparison as 12111 // the high bits on both sides must be zero. 12112 APInt StrideMax = getUnsignedRangeMax(AR->getStepRecurrence(*this)); 12113 APInt Limit = APInt::getMaxValue(InnerBitWidth) - (StrideMax - 1); 12114 Limit = Limit.zext(OuterBitWidth); 12115 return getUnsignedRangeMax(applyLoopGuards(RHS, L)).ule(Limit); 12116 }; 12117 auto Flags = AR->getNoWrapFlags(); 12118 if (!hasFlags(Flags, SCEV::FlagNUW) && canProveNUW()) 12119 Flags = setFlags(Flags, SCEV::FlagNUW); 12120 12121 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags); 12122 if (AR->hasNoUnsignedWrap()) { 12123 // Emulate what getZeroExtendExpr would have done during construction 12124 // if we'd been able to infer the fact just above at that time. 12125 const SCEV *Step = AR->getStepRecurrence(*this); 12126 Type *Ty = ZExt->getType(); 12127 auto *S = getAddRecExpr( 12128 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 0), 12129 getZeroExtendExpr(Step, Ty, 0), L, AR->getNoWrapFlags()); 12130 IV = dyn_cast<SCEVAddRecExpr>(S); 12131 } 12132 } 12133 } 12134 } 12135 12136 12137 if (!IV && AllowPredicates) { 12138 // Try to make this an AddRec using runtime tests, in the first X 12139 // iterations of this loop, where X is the SCEV expression found by the 12140 // algorithm below. 12141 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 12142 PredicatedIV = true; 12143 } 12144 12145 // Avoid weird loops 12146 if (!IV || IV->getLoop() != L || !IV->isAffine()) 12147 return getCouldNotCompute(); 12148 12149 // A precondition of this method is that the condition being analyzed 12150 // reaches an exiting branch which dominates the latch. Given that, we can 12151 // assume that an increment which violates the nowrap specification and 12152 // produces poison must cause undefined behavior when the resulting poison 12153 // value is branched upon and thus we can conclude that the backedge is 12154 // taken no more often than would be required to produce that poison value. 12155 // Note that a well defined loop can exit on the iteration which violates 12156 // the nowrap specification if there is another exit (either explicit or 12157 // implicit/exceptional) which causes the loop to execute before the 12158 // exiting instruction we're analyzing would trigger UB. 12159 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW; 12160 bool NoWrap = ControlsExit && IV->getNoWrapFlags(WrapType); 12161 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; 12162 12163 const SCEV *Stride = IV->getStepRecurrence(*this); 12164 12165 bool PositiveStride = isKnownPositive(Stride); 12166 12167 // Avoid negative or zero stride values. 12168 if (!PositiveStride) { 12169 // We can compute the correct backedge taken count for loops with unknown 12170 // strides if we can prove that the loop is not an infinite loop with side 12171 // effects. Here's the loop structure we are trying to handle - 12172 // 12173 // i = start 12174 // do { 12175 // A[i] = i; 12176 // i += s; 12177 // } while (i < end); 12178 // 12179 // The backedge taken count for such loops is evaluated as - 12180 // (max(end, start + stride) - start - 1) /u stride 12181 // 12182 // The additional preconditions that we need to check to prove correctness 12183 // of the above formula is as follows - 12184 // 12185 // a) IV is either nuw or nsw depending upon signedness (indicated by the 12186 // NoWrap flag). 12187 // b) the loop is guaranteed to be finite (e.g. is mustprogress and has 12188 // no side effects within the loop) 12189 // c) loop has a single static exit (with no abnormal exits) 12190 // 12191 // Precondition a) implies that if the stride is negative, this is a single 12192 // trip loop. The backedge taken count formula reduces to zero in this case. 12193 // 12194 // Precondition b) and c) combine to imply that if rhs is invariant in L, 12195 // then a zero stride means the backedge can't be taken without executing 12196 // undefined behavior. 12197 // 12198 // The positive stride case is the same as isKnownPositive(Stride) returning 12199 // true (original behavior of the function). 12200 // 12201 if (PredicatedIV || !NoWrap || !loopIsFiniteByAssumption(L) || 12202 !loopHasNoAbnormalExits(L)) 12203 return getCouldNotCompute(); 12204 12205 // This bailout is protecting the logic in computeMaxBECountForLT which 12206 // has not yet been sufficiently auditted or tested with negative strides. 12207 // We used to filter out all known-non-positive cases here, we're in the 12208 // process of being less restrictive bit by bit. 12209 if (IsSigned && isKnownNonPositive(Stride)) 12210 return getCouldNotCompute(); 12211 12212 if (!isKnownNonZero(Stride)) { 12213 // If we have a step of zero, and RHS isn't invariant in L, we don't know 12214 // if it might eventually be greater than start and if so, on which 12215 // iteration. We can't even produce a useful upper bound. 12216 if (!isLoopInvariant(RHS, L)) 12217 return getCouldNotCompute(); 12218 12219 // We allow a potentially zero stride, but we need to divide by stride 12220 // below. Since the loop can't be infinite and this check must control 12221 // the sole exit, we can infer the exit must be taken on the first 12222 // iteration (e.g. backedge count = 0) if the stride is zero. Given that, 12223 // we know the numerator in the divides below must be zero, so we can 12224 // pick an arbitrary non-zero value for the denominator (e.g. stride) 12225 // and produce the right result. 12226 // FIXME: Handle the case where Stride is poison? 12227 auto wouldZeroStrideBeUB = [&]() { 12228 // Proof by contradiction. Suppose the stride were zero. If we can 12229 // prove that the backedge *is* taken on the first iteration, then since 12230 // we know this condition controls the sole exit, we must have an 12231 // infinite loop. We can't have a (well defined) infinite loop per 12232 // check just above. 12233 // Note: The (Start - Stride) term is used to get the start' term from 12234 // (start' + stride,+,stride). Remember that we only care about the 12235 // result of this expression when stride == 0 at runtime. 12236 auto *StartIfZero = getMinusSCEV(IV->getStart(), Stride); 12237 return isLoopEntryGuardedByCond(L, Cond, StartIfZero, RHS); 12238 }; 12239 if (!wouldZeroStrideBeUB()) { 12240 Stride = getUMaxExpr(Stride, getOne(Stride->getType())); 12241 } 12242 } 12243 } else if (!Stride->isOne() && !NoWrap) { 12244 auto isUBOnWrap = [&]() { 12245 // From no-self-wrap, we need to then prove no-(un)signed-wrap. This 12246 // follows trivially from the fact that every (un)signed-wrapped, but 12247 // not self-wrapped value must be LT than the last value before 12248 // (un)signed wrap. Since we know that last value didn't exit, nor 12249 // will any smaller one. 12250 return canAssumeNoSelfWrap(IV); 12251 }; 12252 12253 // Avoid proven overflow cases: this will ensure that the backedge taken 12254 // count will not generate any unsigned overflow. Relaxed no-overflow 12255 // conditions exploit NoWrapFlags, allowing to optimize in presence of 12256 // undefined behaviors like the case of C language. 12257 if (canIVOverflowOnLT(RHS, Stride, IsSigned) && !isUBOnWrap()) 12258 return getCouldNotCompute(); 12259 } 12260 12261 // On all paths just preceeding, we established the following invariant: 12262 // IV can be assumed not to overflow up to and including the exiting 12263 // iteration. We proved this in one of two ways: 12264 // 1) We can show overflow doesn't occur before the exiting iteration 12265 // 1a) canIVOverflowOnLT, and b) step of one 12266 // 2) We can show that if overflow occurs, the loop must execute UB 12267 // before any possible exit. 12268 // Note that we have not yet proved RHS invariant (in general). 12269 12270 const SCEV *Start = IV->getStart(); 12271 12272 // Preserve pointer-typed Start/RHS to pass to isLoopEntryGuardedByCond. 12273 // If we convert to integers, isLoopEntryGuardedByCond will miss some cases. 12274 // Use integer-typed versions for actual computation; we can't subtract 12275 // pointers in general. 12276 const SCEV *OrigStart = Start; 12277 const SCEV *OrigRHS = RHS; 12278 if (Start->getType()->isPointerTy()) { 12279 Start = getLosslessPtrToIntExpr(Start); 12280 if (isa<SCEVCouldNotCompute>(Start)) 12281 return Start; 12282 } 12283 if (RHS->getType()->isPointerTy()) { 12284 RHS = getLosslessPtrToIntExpr(RHS); 12285 if (isa<SCEVCouldNotCompute>(RHS)) 12286 return RHS; 12287 } 12288 12289 // When the RHS is not invariant, we do not know the end bound of the loop and 12290 // cannot calculate the ExactBECount needed by ExitLimit. However, we can 12291 // calculate the MaxBECount, given the start, stride and max value for the end 12292 // bound of the loop (RHS), and the fact that IV does not overflow (which is 12293 // checked above). 12294 if (!isLoopInvariant(RHS, L)) { 12295 const SCEV *MaxBECount = computeMaxBECountForLT( 12296 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 12297 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount, 12298 false /*MaxOrZero*/, Predicates); 12299 } 12300 12301 // We use the expression (max(End,Start)-Start)/Stride to describe the 12302 // backedge count, as if the backedge is taken at least once max(End,Start) 12303 // is End and so the result is as above, and if not max(End,Start) is Start 12304 // so we get a backedge count of zero. 12305 const SCEV *BECount = nullptr; 12306 auto *OrigStartMinusStride = getMinusSCEV(OrigStart, Stride); 12307 assert(isAvailableAtLoopEntry(OrigStartMinusStride, L) && "Must be!"); 12308 assert(isAvailableAtLoopEntry(OrigStart, L) && "Must be!"); 12309 assert(isAvailableAtLoopEntry(OrigRHS, L) && "Must be!"); 12310 // Can we prove (max(RHS,Start) > Start - Stride? 12311 if (isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigStart) && 12312 isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigRHS)) { 12313 // In this case, we can use a refined formula for computing backedge taken 12314 // count. The general formula remains: 12315 // "End-Start /uceiling Stride" where "End = max(RHS,Start)" 12316 // We want to use the alternate formula: 12317 // "((End - 1) - (Start - Stride)) /u Stride" 12318 // Let's do a quick case analysis to show these are equivalent under 12319 // our precondition that max(RHS,Start) > Start - Stride. 12320 // * For RHS <= Start, the backedge-taken count must be zero. 12321 // "((End - 1) - (Start - Stride)) /u Stride" reduces to 12322 // "((Start - 1) - (Start - Stride)) /u Stride" which simplies to 12323 // "Stride - 1 /u Stride" which is indeed zero for all non-zero values 12324 // of Stride. For 0 stride, we've use umin(1,Stride) above, reducing 12325 // this to the stride of 1 case. 12326 // * For RHS >= Start, the backedge count must be "RHS-Start /uceil Stride". 12327 // "((End - 1) - (Start - Stride)) /u Stride" reduces to 12328 // "((RHS - 1) - (Start - Stride)) /u Stride" reassociates to 12329 // "((RHS - (Start - Stride) - 1) /u Stride". 12330 // Our preconditions trivially imply no overflow in that form. 12331 const SCEV *MinusOne = getMinusOne(Stride->getType()); 12332 const SCEV *Numerator = 12333 getMinusSCEV(getAddExpr(RHS, MinusOne), getMinusSCEV(Start, Stride)); 12334 BECount = getUDivExpr(Numerator, Stride); 12335 } 12336 12337 const SCEV *BECountIfBackedgeTaken = nullptr; 12338 if (!BECount) { 12339 auto canProveRHSGreaterThanEqualStart = [&]() { 12340 auto CondGE = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 12341 if (isLoopEntryGuardedByCond(L, CondGE, OrigRHS, OrigStart)) 12342 return true; 12343 12344 // (RHS > Start - 1) implies RHS >= Start. 12345 // * "RHS >= Start" is trivially equivalent to "RHS > Start - 1" if 12346 // "Start - 1" doesn't overflow. 12347 // * For signed comparison, if Start - 1 does overflow, it's equal 12348 // to INT_MAX, and "RHS >s INT_MAX" is trivially false. 12349 // * For unsigned comparison, if Start - 1 does overflow, it's equal 12350 // to UINT_MAX, and "RHS >u UINT_MAX" is trivially false. 12351 // 12352 // FIXME: Should isLoopEntryGuardedByCond do this for us? 12353 auto CondGT = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 12354 auto *StartMinusOne = getAddExpr(OrigStart, 12355 getMinusOne(OrigStart->getType())); 12356 return isLoopEntryGuardedByCond(L, CondGT, OrigRHS, StartMinusOne); 12357 }; 12358 12359 // If we know that RHS >= Start in the context of loop, then we know that 12360 // max(RHS, Start) = RHS at this point. 12361 const SCEV *End; 12362 if (canProveRHSGreaterThanEqualStart()) { 12363 End = RHS; 12364 } else { 12365 // If RHS < Start, the backedge will be taken zero times. So in 12366 // general, we can write the backedge-taken count as: 12367 // 12368 // RHS >= Start ? ceil(RHS - Start) / Stride : 0 12369 // 12370 // We convert it to the following to make it more convenient for SCEV: 12371 // 12372 // ceil(max(RHS, Start) - Start) / Stride 12373 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 12374 12375 // See what would happen if we assume the backedge is taken. This is 12376 // used to compute MaxBECount. 12377 BECountIfBackedgeTaken = getUDivCeilSCEV(getMinusSCEV(RHS, Start), Stride); 12378 } 12379 12380 // At this point, we know: 12381 // 12382 // 1. If IsSigned, Start <=s End; otherwise, Start <=u End 12383 // 2. The index variable doesn't overflow. 12384 // 12385 // Therefore, we know N exists such that 12386 // (Start + Stride * N) >= End, and computing "(Start + Stride * N)" 12387 // doesn't overflow. 12388 // 12389 // Using this information, try to prove whether the addition in 12390 // "(Start - End) + (Stride - 1)" has unsigned overflow. 12391 const SCEV *One = getOne(Stride->getType()); 12392 bool MayAddOverflow = [&] { 12393 if (auto *StrideC = dyn_cast<SCEVConstant>(Stride)) { 12394 if (StrideC->getAPInt().isPowerOf2()) { 12395 // Suppose Stride is a power of two, and Start/End are unsigned 12396 // integers. Let UMAX be the largest representable unsigned 12397 // integer. 12398 // 12399 // By the preconditions of this function, we know 12400 // "(Start + Stride * N) >= End", and this doesn't overflow. 12401 // As a formula: 12402 // 12403 // End <= (Start + Stride * N) <= UMAX 12404 // 12405 // Subtracting Start from all the terms: 12406 // 12407 // End - Start <= Stride * N <= UMAX - Start 12408 // 12409 // Since Start is unsigned, UMAX - Start <= UMAX. Therefore: 12410 // 12411 // End - Start <= Stride * N <= UMAX 12412 // 12413 // Stride * N is a multiple of Stride. Therefore, 12414 // 12415 // End - Start <= Stride * N <= UMAX - (UMAX mod Stride) 12416 // 12417 // Since Stride is a power of two, UMAX + 1 is divisible by Stride. 12418 // Therefore, UMAX mod Stride == Stride - 1. So we can write: 12419 // 12420 // End - Start <= Stride * N <= UMAX - Stride - 1 12421 // 12422 // Dropping the middle term: 12423 // 12424 // End - Start <= UMAX - Stride - 1 12425 // 12426 // Adding Stride - 1 to both sides: 12427 // 12428 // (End - Start) + (Stride - 1) <= UMAX 12429 // 12430 // In other words, the addition doesn't have unsigned overflow. 12431 // 12432 // A similar proof works if we treat Start/End as signed values. 12433 // Just rewrite steps before "End - Start <= Stride * N <= UMAX" to 12434 // use signed max instead of unsigned max. Note that we're trying 12435 // to prove a lack of unsigned overflow in either case. 12436 return false; 12437 } 12438 } 12439 if (Start == Stride || Start == getMinusSCEV(Stride, One)) { 12440 // If Start is equal to Stride, (End - Start) + (Stride - 1) == End - 1. 12441 // If !IsSigned, 0 <u Stride == Start <=u End; so 0 <u End - 1 <u End. 12442 // If IsSigned, 0 <s Stride == Start <=s End; so 0 <s End - 1 <s End. 12443 // 12444 // If Start is equal to Stride - 1, (End - Start) + Stride - 1 == End. 12445 return false; 12446 } 12447 return true; 12448 }(); 12449 12450 const SCEV *Delta = getMinusSCEV(End, Start); 12451 if (!MayAddOverflow) { 12452 // floor((D + (S - 1)) / S) 12453 // We prefer this formulation if it's legal because it's fewer operations. 12454 BECount = 12455 getUDivExpr(getAddExpr(Delta, getMinusSCEV(Stride, One)), Stride); 12456 } else { 12457 BECount = getUDivCeilSCEV(Delta, Stride); 12458 } 12459 } 12460 12461 const SCEV *MaxBECount; 12462 bool MaxOrZero = false; 12463 if (isa<SCEVConstant>(BECount)) { 12464 MaxBECount = BECount; 12465 } else if (BECountIfBackedgeTaken && 12466 isa<SCEVConstant>(BECountIfBackedgeTaken)) { 12467 // If we know exactly how many times the backedge will be taken if it's 12468 // taken at least once, then the backedge count will either be that or 12469 // zero. 12470 MaxBECount = BECountIfBackedgeTaken; 12471 MaxOrZero = true; 12472 } else { 12473 MaxBECount = computeMaxBECountForLT( 12474 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 12475 } 12476 12477 if (isa<SCEVCouldNotCompute>(MaxBECount) && 12478 !isa<SCEVCouldNotCompute>(BECount)) 12479 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 12480 12481 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 12482 } 12483 12484 ScalarEvolution::ExitLimit 12485 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 12486 const Loop *L, bool IsSigned, 12487 bool ControlsExit, bool AllowPredicates) { 12488 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 12489 // We handle only IV > Invariant 12490 if (!isLoopInvariant(RHS, L)) 12491 return getCouldNotCompute(); 12492 12493 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 12494 if (!IV && AllowPredicates) 12495 // Try to make this an AddRec using runtime tests, in the first X 12496 // iterations of this loop, where X is the SCEV expression found by the 12497 // algorithm below. 12498 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 12499 12500 // Avoid weird loops 12501 if (!IV || IV->getLoop() != L || !IV->isAffine()) 12502 return getCouldNotCompute(); 12503 12504 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW; 12505 bool NoWrap = ControlsExit && IV->getNoWrapFlags(WrapType); 12506 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 12507 12508 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 12509 12510 // Avoid negative or zero stride values 12511 if (!isKnownPositive(Stride)) 12512 return getCouldNotCompute(); 12513 12514 // Avoid proven overflow cases: this will ensure that the backedge taken count 12515 // will not generate any unsigned overflow. Relaxed no-overflow conditions 12516 // exploit NoWrapFlags, allowing to optimize in presence of undefined 12517 // behaviors like the case of C language. 12518 if (!Stride->isOne() && !NoWrap) 12519 if (canIVOverflowOnGT(RHS, Stride, IsSigned)) 12520 return getCouldNotCompute(); 12521 12522 const SCEV *Start = IV->getStart(); 12523 const SCEV *End = RHS; 12524 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) { 12525 // If we know that Start >= RHS in the context of loop, then we know that 12526 // min(RHS, Start) = RHS at this point. 12527 if (isLoopEntryGuardedByCond( 12528 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS)) 12529 End = RHS; 12530 else 12531 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 12532 } 12533 12534 if (Start->getType()->isPointerTy()) { 12535 Start = getLosslessPtrToIntExpr(Start); 12536 if (isa<SCEVCouldNotCompute>(Start)) 12537 return Start; 12538 } 12539 if (End->getType()->isPointerTy()) { 12540 End = getLosslessPtrToIntExpr(End); 12541 if (isa<SCEVCouldNotCompute>(End)) 12542 return End; 12543 } 12544 12545 // Compute ((Start - End) + (Stride - 1)) / Stride. 12546 // FIXME: This can overflow. Holding off on fixing this for now; 12547 // howManyGreaterThans will hopefully be gone soon. 12548 const SCEV *One = getOne(Stride->getType()); 12549 const SCEV *BECount = getUDivExpr( 12550 getAddExpr(getMinusSCEV(Start, End), getMinusSCEV(Stride, One)), Stride); 12551 12552 APInt MaxStart = IsSigned ? getSignedRangeMax(Start) 12553 : getUnsignedRangeMax(Start); 12554 12555 APInt MinStride = IsSigned ? getSignedRangeMin(Stride) 12556 : getUnsignedRangeMin(Stride); 12557 12558 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 12559 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 12560 : APInt::getMinValue(BitWidth) + (MinStride - 1); 12561 12562 // Although End can be a MIN expression we estimate MinEnd considering only 12563 // the case End = RHS. This is safe because in the other case (Start - End) 12564 // is zero, leading to a zero maximum backedge taken count. 12565 APInt MinEnd = 12566 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit) 12567 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit); 12568 12569 const SCEV *MaxBECount = isa<SCEVConstant>(BECount) 12570 ? BECount 12571 : getUDivCeilSCEV(getConstant(MaxStart - MinEnd), 12572 getConstant(MinStride)); 12573 12574 if (isa<SCEVCouldNotCompute>(MaxBECount)) 12575 MaxBECount = BECount; 12576 12577 return ExitLimit(BECount, MaxBECount, false, Predicates); 12578 } 12579 12580 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 12581 ScalarEvolution &SE) const { 12582 if (Range.isFullSet()) // Infinite loop. 12583 return SE.getCouldNotCompute(); 12584 12585 // If the start is a non-zero constant, shift the range to simplify things. 12586 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 12587 if (!SC->getValue()->isZero()) { 12588 SmallVector<const SCEV *, 4> Operands(operands()); 12589 Operands[0] = SE.getZero(SC->getType()); 12590 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 12591 getNoWrapFlags(FlagNW)); 12592 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 12593 return ShiftedAddRec->getNumIterationsInRange( 12594 Range.subtract(SC->getAPInt()), SE); 12595 // This is strange and shouldn't happen. 12596 return SE.getCouldNotCompute(); 12597 } 12598 12599 // The only time we can solve this is when we have all constant indices. 12600 // Otherwise, we cannot determine the overflow conditions. 12601 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 12602 return SE.getCouldNotCompute(); 12603 12604 // Okay at this point we know that all elements of the chrec are constants and 12605 // that the start element is zero. 12606 12607 // First check to see if the range contains zero. If not, the first 12608 // iteration exits. 12609 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 12610 if (!Range.contains(APInt(BitWidth, 0))) 12611 return SE.getZero(getType()); 12612 12613 if (isAffine()) { 12614 // If this is an affine expression then we have this situation: 12615 // Solve {0,+,A} in Range === Ax in Range 12616 12617 // We know that zero is in the range. If A is positive then we know that 12618 // the upper value of the range must be the first possible exit value. 12619 // If A is negative then the lower of the range is the last possible loop 12620 // value. Also note that we already checked for a full range. 12621 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 12622 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower(); 12623 12624 // The exit value should be (End+A)/A. 12625 APInt ExitVal = (End + A).udiv(A); 12626 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 12627 12628 // Evaluate at the exit value. If we really did fall out of the valid 12629 // range, then we computed our trip count, otherwise wrap around or other 12630 // things must have happened. 12631 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 12632 if (Range.contains(Val->getValue())) 12633 return SE.getCouldNotCompute(); // Something strange happened 12634 12635 // Ensure that the previous value is in the range. 12636 assert(Range.contains( 12637 EvaluateConstantChrecAtConstant(this, 12638 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && 12639 "Linear scev computation is off in a bad way!"); 12640 return SE.getConstant(ExitValue); 12641 } 12642 12643 if (isQuadratic()) { 12644 if (auto S = SolveQuadraticAddRecRange(this, Range, SE)) 12645 return SE.getConstant(S.getValue()); 12646 } 12647 12648 return SE.getCouldNotCompute(); 12649 } 12650 12651 const SCEVAddRecExpr * 12652 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const { 12653 assert(getNumOperands() > 1 && "AddRec with zero step?"); 12654 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)), 12655 // but in this case we cannot guarantee that the value returned will be an 12656 // AddRec because SCEV does not have a fixed point where it stops 12657 // simplification: it is legal to return ({rec1} + {rec2}). For example, it 12658 // may happen if we reach arithmetic depth limit while simplifying. So we 12659 // construct the returned value explicitly. 12660 SmallVector<const SCEV *, 3> Ops; 12661 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and 12662 // (this + Step) is {A+B,+,B+C,+...,+,N}. 12663 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i) 12664 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1))); 12665 // We know that the last operand is not a constant zero (otherwise it would 12666 // have been popped out earlier). This guarantees us that if the result has 12667 // the same last operand, then it will also not be popped out, meaning that 12668 // the returned value will be an AddRec. 12669 const SCEV *Last = getOperand(getNumOperands() - 1); 12670 assert(!Last->isZero() && "Recurrency with zero step?"); 12671 Ops.push_back(Last); 12672 return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(), 12673 SCEV::FlagAnyWrap)); 12674 } 12675 12676 // Return true when S contains at least an undef value. 12677 bool ScalarEvolution::containsUndefs(const SCEV *S) const { 12678 return SCEVExprContains(S, [](const SCEV *S) { 12679 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 12680 return isa<UndefValue>(SU->getValue()); 12681 return false; 12682 }); 12683 } 12684 12685 /// Return the size of an element read or written by Inst. 12686 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 12687 Type *Ty; 12688 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 12689 Ty = Store->getValueOperand()->getType(); 12690 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 12691 Ty = Load->getType(); 12692 else 12693 return nullptr; 12694 12695 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 12696 return getSizeOfExpr(ETy, Ty); 12697 } 12698 12699 //===----------------------------------------------------------------------===// 12700 // SCEVCallbackVH Class Implementation 12701 //===----------------------------------------------------------------------===// 12702 12703 void ScalarEvolution::SCEVCallbackVH::deleted() { 12704 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 12705 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 12706 SE->ConstantEvolutionLoopExitValue.erase(PN); 12707 SE->eraseValueFromMap(getValPtr()); 12708 // this now dangles! 12709 } 12710 12711 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 12712 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 12713 12714 // Forget all the expressions associated with users of the old value, 12715 // so that future queries will recompute the expressions using the new 12716 // value. 12717 Value *Old = getValPtr(); 12718 SmallVector<User *, 16> Worklist(Old->users()); 12719 SmallPtrSet<User *, 8> Visited; 12720 while (!Worklist.empty()) { 12721 User *U = Worklist.pop_back_val(); 12722 // Deleting the Old value will cause this to dangle. Postpone 12723 // that until everything else is done. 12724 if (U == Old) 12725 continue; 12726 if (!Visited.insert(U).second) 12727 continue; 12728 if (PHINode *PN = dyn_cast<PHINode>(U)) 12729 SE->ConstantEvolutionLoopExitValue.erase(PN); 12730 SE->eraseValueFromMap(U); 12731 llvm::append_range(Worklist, U->users()); 12732 } 12733 // Delete the Old value. 12734 if (PHINode *PN = dyn_cast<PHINode>(Old)) 12735 SE->ConstantEvolutionLoopExitValue.erase(PN); 12736 SE->eraseValueFromMap(Old); 12737 // this now dangles! 12738 } 12739 12740 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 12741 : CallbackVH(V), SE(se) {} 12742 12743 //===----------------------------------------------------------------------===// 12744 // ScalarEvolution Class Implementation 12745 //===----------------------------------------------------------------------===// 12746 12747 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 12748 AssumptionCache &AC, DominatorTree &DT, 12749 LoopInfo &LI) 12750 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 12751 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64), 12752 LoopDispositions(64), BlockDispositions(64) { 12753 // To use guards for proving predicates, we need to scan every instruction in 12754 // relevant basic blocks, and not just terminators. Doing this is a waste of 12755 // time if the IR does not actually contain any calls to 12756 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 12757 // 12758 // This pessimizes the case where a pass that preserves ScalarEvolution wants 12759 // to _add_ guards to the module when there weren't any before, and wants 12760 // ScalarEvolution to optimize based on those guards. For now we prefer to be 12761 // efficient in lieu of being smart in that rather obscure case. 12762 12763 auto *GuardDecl = F.getParent()->getFunction( 12764 Intrinsic::getName(Intrinsic::experimental_guard)); 12765 HasGuards = GuardDecl && !GuardDecl->use_empty(); 12766 } 12767 12768 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 12769 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 12770 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 12771 ValueExprMap(std::move(Arg.ValueExprMap)), 12772 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 12773 PendingPhiRanges(std::move(Arg.PendingPhiRanges)), 12774 PendingMerges(std::move(Arg.PendingMerges)), 12775 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)), 12776 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 12777 PredicatedBackedgeTakenCounts( 12778 std::move(Arg.PredicatedBackedgeTakenCounts)), 12779 BECountUsers(std::move(Arg.BECountUsers)), 12780 ConstantEvolutionLoopExitValue( 12781 std::move(Arg.ConstantEvolutionLoopExitValue)), 12782 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 12783 ValuesAtScopesUsers(std::move(Arg.ValuesAtScopesUsers)), 12784 LoopDispositions(std::move(Arg.LoopDispositions)), 12785 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 12786 BlockDispositions(std::move(Arg.BlockDispositions)), 12787 SCEVUsers(std::move(Arg.SCEVUsers)), 12788 UnsignedRanges(std::move(Arg.UnsignedRanges)), 12789 SignedRanges(std::move(Arg.SignedRanges)), 12790 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 12791 UniquePreds(std::move(Arg.UniquePreds)), 12792 SCEVAllocator(std::move(Arg.SCEVAllocator)), 12793 LoopUsers(std::move(Arg.LoopUsers)), 12794 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)), 12795 FirstUnknown(Arg.FirstUnknown) { 12796 Arg.FirstUnknown = nullptr; 12797 } 12798 12799 ScalarEvolution::~ScalarEvolution() { 12800 // Iterate through all the SCEVUnknown instances and call their 12801 // destructors, so that they release their references to their values. 12802 for (SCEVUnknown *U = FirstUnknown; U;) { 12803 SCEVUnknown *Tmp = U; 12804 U = U->Next; 12805 Tmp->~SCEVUnknown(); 12806 } 12807 FirstUnknown = nullptr; 12808 12809 ExprValueMap.clear(); 12810 ValueExprMap.clear(); 12811 HasRecMap.clear(); 12812 BackedgeTakenCounts.clear(); 12813 PredicatedBackedgeTakenCounts.clear(); 12814 12815 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 12816 assert(PendingPhiRanges.empty() && "getRangeRef garbage"); 12817 assert(PendingMerges.empty() && "isImpliedViaMerge garbage"); 12818 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 12819 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 12820 } 12821 12822 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 12823 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 12824 } 12825 12826 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 12827 const Loop *L) { 12828 // Print all inner loops first 12829 for (Loop *I : *L) 12830 PrintLoopInfo(OS, SE, I); 12831 12832 OS << "Loop "; 12833 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12834 OS << ": "; 12835 12836 SmallVector<BasicBlock *, 8> ExitingBlocks; 12837 L->getExitingBlocks(ExitingBlocks); 12838 if (ExitingBlocks.size() != 1) 12839 OS << "<multiple exits> "; 12840 12841 if (SE->hasLoopInvariantBackedgeTakenCount(L)) 12842 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n"; 12843 else 12844 OS << "Unpredictable backedge-taken count.\n"; 12845 12846 if (ExitingBlocks.size() > 1) 12847 for (BasicBlock *ExitingBlock : ExitingBlocks) { 12848 OS << " exit count for " << ExitingBlock->getName() << ": " 12849 << *SE->getExitCount(L, ExitingBlock) << "\n"; 12850 } 12851 12852 OS << "Loop "; 12853 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12854 OS << ": "; 12855 12856 if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) { 12857 OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L); 12858 if (SE->isBackedgeTakenCountMaxOrZero(L)) 12859 OS << ", actual taken count either this or zero."; 12860 } else { 12861 OS << "Unpredictable max backedge-taken count. "; 12862 } 12863 12864 OS << "\n" 12865 "Loop "; 12866 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12867 OS << ": "; 12868 12869 SmallVector<const SCEVPredicate *, 4> Preds; 12870 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Preds); 12871 if (!isa<SCEVCouldNotCompute>(PBT)) { 12872 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 12873 OS << " Predicates:\n"; 12874 for (auto *P : Preds) 12875 P->print(OS, 4); 12876 } else { 12877 OS << "Unpredictable predicated backedge-taken count. "; 12878 } 12879 OS << "\n"; 12880 12881 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 12882 OS << "Loop "; 12883 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12884 OS << ": "; 12885 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n"; 12886 } 12887 } 12888 12889 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 12890 switch (LD) { 12891 case ScalarEvolution::LoopVariant: 12892 return "Variant"; 12893 case ScalarEvolution::LoopInvariant: 12894 return "Invariant"; 12895 case ScalarEvolution::LoopComputable: 12896 return "Computable"; 12897 } 12898 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 12899 } 12900 12901 void ScalarEvolution::print(raw_ostream &OS) const { 12902 // ScalarEvolution's implementation of the print method is to print 12903 // out SCEV values of all instructions that are interesting. Doing 12904 // this potentially causes it to create new SCEV objects though, 12905 // which technically conflicts with the const qualifier. This isn't 12906 // observable from outside the class though, so casting away the 12907 // const isn't dangerous. 12908 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 12909 12910 if (ClassifyExpressions) { 12911 OS << "Classifying expressions for: "; 12912 F.printAsOperand(OS, /*PrintType=*/false); 12913 OS << "\n"; 12914 for (Instruction &I : instructions(F)) 12915 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 12916 OS << I << '\n'; 12917 OS << " --> "; 12918 const SCEV *SV = SE.getSCEV(&I); 12919 SV->print(OS); 12920 if (!isa<SCEVCouldNotCompute>(SV)) { 12921 OS << " U: "; 12922 SE.getUnsignedRange(SV).print(OS); 12923 OS << " S: "; 12924 SE.getSignedRange(SV).print(OS); 12925 } 12926 12927 const Loop *L = LI.getLoopFor(I.getParent()); 12928 12929 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 12930 if (AtUse != SV) { 12931 OS << " --> "; 12932 AtUse->print(OS); 12933 if (!isa<SCEVCouldNotCompute>(AtUse)) { 12934 OS << " U: "; 12935 SE.getUnsignedRange(AtUse).print(OS); 12936 OS << " S: "; 12937 SE.getSignedRange(AtUse).print(OS); 12938 } 12939 } 12940 12941 if (L) { 12942 OS << "\t\t" "Exits: "; 12943 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 12944 if (!SE.isLoopInvariant(ExitValue, L)) { 12945 OS << "<<Unknown>>"; 12946 } else { 12947 OS << *ExitValue; 12948 } 12949 12950 bool First = true; 12951 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 12952 if (First) { 12953 OS << "\t\t" "LoopDispositions: { "; 12954 First = false; 12955 } else { 12956 OS << ", "; 12957 } 12958 12959 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12960 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 12961 } 12962 12963 for (auto *InnerL : depth_first(L)) { 12964 if (InnerL == L) 12965 continue; 12966 if (First) { 12967 OS << "\t\t" "LoopDispositions: { "; 12968 First = false; 12969 } else { 12970 OS << ", "; 12971 } 12972 12973 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12974 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 12975 } 12976 12977 OS << " }"; 12978 } 12979 12980 OS << "\n"; 12981 } 12982 } 12983 12984 OS << "Determining loop execution counts for: "; 12985 F.printAsOperand(OS, /*PrintType=*/false); 12986 OS << "\n"; 12987 for (Loop *I : LI) 12988 PrintLoopInfo(OS, &SE, I); 12989 } 12990 12991 ScalarEvolution::LoopDisposition 12992 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 12993 auto &Values = LoopDispositions[S]; 12994 for (auto &V : Values) { 12995 if (V.getPointer() == L) 12996 return V.getInt(); 12997 } 12998 Values.emplace_back(L, LoopVariant); 12999 LoopDisposition D = computeLoopDisposition(S, L); 13000 auto &Values2 = LoopDispositions[S]; 13001 for (auto &V : llvm::reverse(Values2)) { 13002 if (V.getPointer() == L) { 13003 V.setInt(D); 13004 break; 13005 } 13006 } 13007 return D; 13008 } 13009 13010 ScalarEvolution::LoopDisposition 13011 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 13012 switch (S->getSCEVType()) { 13013 case scConstant: 13014 return LoopInvariant; 13015 case scPtrToInt: 13016 case scTruncate: 13017 case scZeroExtend: 13018 case scSignExtend: 13019 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 13020 case scAddRecExpr: { 13021 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 13022 13023 // If L is the addrec's loop, it's computable. 13024 if (AR->getLoop() == L) 13025 return LoopComputable; 13026 13027 // Add recurrences are never invariant in the function-body (null loop). 13028 if (!L) 13029 return LoopVariant; 13030 13031 // Everything that is not defined at loop entry is variant. 13032 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) 13033 return LoopVariant; 13034 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not" 13035 " dominate the contained loop's header?"); 13036 13037 // This recurrence is invariant w.r.t. L if AR's loop contains L. 13038 if (AR->getLoop()->contains(L)) 13039 return LoopInvariant; 13040 13041 // This recurrence is variant w.r.t. L if any of its operands 13042 // are variant. 13043 for (auto *Op : AR->operands()) 13044 if (!isLoopInvariant(Op, L)) 13045 return LoopVariant; 13046 13047 // Otherwise it's loop-invariant. 13048 return LoopInvariant; 13049 } 13050 case scAddExpr: 13051 case scMulExpr: 13052 case scUMaxExpr: 13053 case scSMaxExpr: 13054 case scUMinExpr: 13055 case scSMinExpr: 13056 case scSequentialUMinExpr: { 13057 bool HasVarying = false; 13058 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 13059 LoopDisposition D = getLoopDisposition(Op, L); 13060 if (D == LoopVariant) 13061 return LoopVariant; 13062 if (D == LoopComputable) 13063 HasVarying = true; 13064 } 13065 return HasVarying ? LoopComputable : LoopInvariant; 13066 } 13067 case scUDivExpr: { 13068 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 13069 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 13070 if (LD == LoopVariant) 13071 return LoopVariant; 13072 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 13073 if (RD == LoopVariant) 13074 return LoopVariant; 13075 return (LD == LoopInvariant && RD == LoopInvariant) ? 13076 LoopInvariant : LoopComputable; 13077 } 13078 case scUnknown: 13079 // All non-instruction values are loop invariant. All instructions are loop 13080 // invariant if they are not contained in the specified loop. 13081 // Instructions are never considered invariant in the function body 13082 // (null loop) because they are defined within the "loop". 13083 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 13084 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 13085 return LoopInvariant; 13086 case scCouldNotCompute: 13087 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 13088 } 13089 llvm_unreachable("Unknown SCEV kind!"); 13090 } 13091 13092 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 13093 return getLoopDisposition(S, L) == LoopInvariant; 13094 } 13095 13096 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 13097 return getLoopDisposition(S, L) == LoopComputable; 13098 } 13099 13100 ScalarEvolution::BlockDisposition 13101 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 13102 auto &Values = BlockDispositions[S]; 13103 for (auto &V : Values) { 13104 if (V.getPointer() == BB) 13105 return V.getInt(); 13106 } 13107 Values.emplace_back(BB, DoesNotDominateBlock); 13108 BlockDisposition D = computeBlockDisposition(S, BB); 13109 auto &Values2 = BlockDispositions[S]; 13110 for (auto &V : llvm::reverse(Values2)) { 13111 if (V.getPointer() == BB) { 13112 V.setInt(D); 13113 break; 13114 } 13115 } 13116 return D; 13117 } 13118 13119 ScalarEvolution::BlockDisposition 13120 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 13121 switch (S->getSCEVType()) { 13122 case scConstant: 13123 return ProperlyDominatesBlock; 13124 case scPtrToInt: 13125 case scTruncate: 13126 case scZeroExtend: 13127 case scSignExtend: 13128 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 13129 case scAddRecExpr: { 13130 // This uses a "dominates" query instead of "properly dominates" query 13131 // to test for proper dominance too, because the instruction which 13132 // produces the addrec's value is a PHI, and a PHI effectively properly 13133 // dominates its entire containing block. 13134 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 13135 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 13136 return DoesNotDominateBlock; 13137 13138 // Fall through into SCEVNAryExpr handling. 13139 LLVM_FALLTHROUGH; 13140 } 13141 case scAddExpr: 13142 case scMulExpr: 13143 case scUMaxExpr: 13144 case scSMaxExpr: 13145 case scUMinExpr: 13146 case scSMinExpr: 13147 case scSequentialUMinExpr: { 13148 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 13149 bool Proper = true; 13150 for (const SCEV *NAryOp : NAry->operands()) { 13151 BlockDisposition D = getBlockDisposition(NAryOp, BB); 13152 if (D == DoesNotDominateBlock) 13153 return DoesNotDominateBlock; 13154 if (D == DominatesBlock) 13155 Proper = false; 13156 } 13157 return Proper ? ProperlyDominatesBlock : DominatesBlock; 13158 } 13159 case scUDivExpr: { 13160 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 13161 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 13162 BlockDisposition LD = getBlockDisposition(LHS, BB); 13163 if (LD == DoesNotDominateBlock) 13164 return DoesNotDominateBlock; 13165 BlockDisposition RD = getBlockDisposition(RHS, BB); 13166 if (RD == DoesNotDominateBlock) 13167 return DoesNotDominateBlock; 13168 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 13169 ProperlyDominatesBlock : DominatesBlock; 13170 } 13171 case scUnknown: 13172 if (Instruction *I = 13173 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 13174 if (I->getParent() == BB) 13175 return DominatesBlock; 13176 if (DT.properlyDominates(I->getParent(), BB)) 13177 return ProperlyDominatesBlock; 13178 return DoesNotDominateBlock; 13179 } 13180 return ProperlyDominatesBlock; 13181 case scCouldNotCompute: 13182 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 13183 } 13184 llvm_unreachable("Unknown SCEV kind!"); 13185 } 13186 13187 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 13188 return getBlockDisposition(S, BB) >= DominatesBlock; 13189 } 13190 13191 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 13192 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 13193 } 13194 13195 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 13196 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); 13197 } 13198 13199 void ScalarEvolution::forgetBackedgeTakenCounts(const Loop *L, 13200 bool Predicated) { 13201 auto &BECounts = 13202 Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts; 13203 auto It = BECounts.find(L); 13204 if (It != BECounts.end()) { 13205 for (const ExitNotTakenInfo &ENT : It->second.ExitNotTaken) { 13206 if (!isa<SCEVConstant>(ENT.ExactNotTaken)) { 13207 auto UserIt = BECountUsers.find(ENT.ExactNotTaken); 13208 assert(UserIt != BECountUsers.end()); 13209 UserIt->second.erase({L, Predicated}); 13210 } 13211 } 13212 BECounts.erase(It); 13213 } 13214 } 13215 13216 void ScalarEvolution::forgetMemoizedResults(ArrayRef<const SCEV *> SCEVs) { 13217 SmallPtrSet<const SCEV *, 8> ToForget(SCEVs.begin(), SCEVs.end()); 13218 SmallVector<const SCEV *, 8> Worklist(ToForget.begin(), ToForget.end()); 13219 13220 while (!Worklist.empty()) { 13221 const SCEV *Curr = Worklist.pop_back_val(); 13222 auto Users = SCEVUsers.find(Curr); 13223 if (Users != SCEVUsers.end()) 13224 for (auto *User : Users->second) 13225 if (ToForget.insert(User).second) 13226 Worklist.push_back(User); 13227 } 13228 13229 for (auto *S : ToForget) 13230 forgetMemoizedResultsImpl(S); 13231 13232 for (auto I = PredicatedSCEVRewrites.begin(); 13233 I != PredicatedSCEVRewrites.end();) { 13234 std::pair<const SCEV *, const Loop *> Entry = I->first; 13235 if (ToForget.count(Entry.first)) 13236 PredicatedSCEVRewrites.erase(I++); 13237 else 13238 ++I; 13239 } 13240 } 13241 13242 void ScalarEvolution::forgetMemoizedResultsImpl(const SCEV *S) { 13243 LoopDispositions.erase(S); 13244 BlockDispositions.erase(S); 13245 UnsignedRanges.erase(S); 13246 SignedRanges.erase(S); 13247 HasRecMap.erase(S); 13248 MinTrailingZerosCache.erase(S); 13249 13250 auto ExprIt = ExprValueMap.find(S); 13251 if (ExprIt != ExprValueMap.end()) { 13252 for (Value *V : ExprIt->second) { 13253 auto ValueIt = ValueExprMap.find_as(V); 13254 if (ValueIt != ValueExprMap.end()) 13255 ValueExprMap.erase(ValueIt); 13256 } 13257 ExprValueMap.erase(ExprIt); 13258 } 13259 13260 auto ScopeIt = ValuesAtScopes.find(S); 13261 if (ScopeIt != ValuesAtScopes.end()) { 13262 for (const auto &Pair : ScopeIt->second) 13263 if (!isa_and_nonnull<SCEVConstant>(Pair.second)) 13264 erase_value(ValuesAtScopesUsers[Pair.second], 13265 std::make_pair(Pair.first, S)); 13266 ValuesAtScopes.erase(ScopeIt); 13267 } 13268 13269 auto ScopeUserIt = ValuesAtScopesUsers.find(S); 13270 if (ScopeUserIt != ValuesAtScopesUsers.end()) { 13271 for (const auto &Pair : ScopeUserIt->second) 13272 erase_value(ValuesAtScopes[Pair.second], std::make_pair(Pair.first, S)); 13273 ValuesAtScopesUsers.erase(ScopeUserIt); 13274 } 13275 13276 auto BEUsersIt = BECountUsers.find(S); 13277 if (BEUsersIt != BECountUsers.end()) { 13278 // Work on a copy, as forgetBackedgeTakenCounts() will modify the original. 13279 auto Copy = BEUsersIt->second; 13280 for (const auto &Pair : Copy) 13281 forgetBackedgeTakenCounts(Pair.getPointer(), Pair.getInt()); 13282 BECountUsers.erase(BEUsersIt); 13283 } 13284 } 13285 13286 void 13287 ScalarEvolution::getUsedLoops(const SCEV *S, 13288 SmallPtrSetImpl<const Loop *> &LoopsUsed) { 13289 struct FindUsedLoops { 13290 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed) 13291 : LoopsUsed(LoopsUsed) {} 13292 SmallPtrSetImpl<const Loop *> &LoopsUsed; 13293 bool follow(const SCEV *S) { 13294 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) 13295 LoopsUsed.insert(AR->getLoop()); 13296 return true; 13297 } 13298 13299 bool isDone() const { return false; } 13300 }; 13301 13302 FindUsedLoops F(LoopsUsed); 13303 SCEVTraversal<FindUsedLoops>(F).visitAll(S); 13304 } 13305 13306 static void getReachableBlocks(SmallPtrSetImpl<BasicBlock *> &Reachable, 13307 Function &F) { 13308 SmallVector<BasicBlock *> Worklist; 13309 Worklist.push_back(&F.getEntryBlock()); 13310 while (!Worklist.empty()) { 13311 BasicBlock *BB = Worklist.pop_back_val(); 13312 if (!Reachable.insert(BB).second) 13313 continue; 13314 13315 const APInt *Cond; 13316 BasicBlock *TrueBB, *FalseBB; 13317 if (match(BB->getTerminator(), 13318 m_Br(m_APInt(Cond), m_BasicBlock(TrueBB), m_BasicBlock(FalseBB)))) 13319 Worklist.push_back(Cond->isOne() ? TrueBB : FalseBB); 13320 else 13321 append_range(Worklist, successors(BB)); 13322 } 13323 } 13324 13325 void ScalarEvolution::verify() const { 13326 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 13327 ScalarEvolution SE2(F, TLI, AC, DT, LI); 13328 13329 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end()); 13330 13331 // Map's SCEV expressions from one ScalarEvolution "universe" to another. 13332 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> { 13333 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {} 13334 13335 const SCEV *visitConstant(const SCEVConstant *Constant) { 13336 return SE.getConstant(Constant->getAPInt()); 13337 } 13338 13339 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 13340 return SE.getUnknown(Expr->getValue()); 13341 } 13342 13343 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { 13344 return SE.getCouldNotCompute(); 13345 } 13346 }; 13347 13348 SCEVMapper SCM(SE2); 13349 SmallPtrSet<BasicBlock *, 16> ReachableBlocks; 13350 getReachableBlocks(ReachableBlocks, F); 13351 13352 while (!LoopStack.empty()) { 13353 auto *L = LoopStack.pop_back_val(); 13354 llvm::append_range(LoopStack, *L); 13355 13356 // Only verify BECounts in reachable loops. For an unreachable loop, 13357 // any BECount is legal. 13358 if (!ReachableBlocks.contains(L->getHeader())) 13359 continue; 13360 13361 auto *CurBECount = SCM.visit( 13362 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L)); 13363 auto *NewBECount = SE2.getBackedgeTakenCount(L); 13364 13365 if (CurBECount == SE2.getCouldNotCompute() || 13366 NewBECount == SE2.getCouldNotCompute()) { 13367 // NB! This situation is legal, but is very suspicious -- whatever pass 13368 // change the loop to make a trip count go from could not compute to 13369 // computable or vice-versa *should have* invalidated SCEV. However, we 13370 // choose not to assert here (for now) since we don't want false 13371 // positives. 13372 continue; 13373 } 13374 13375 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) { 13376 // SCEV treats "undef" as an unknown but consistent value (i.e. it does 13377 // not propagate undef aggressively). This means we can (and do) fail 13378 // verification in cases where a transform makes the trip count of a loop 13379 // go from "undef" to "undef+1" (say). The transform is fine, since in 13380 // both cases the loop iterates "undef" times, but SCEV thinks we 13381 // increased the trip count of the loop by 1 incorrectly. 13382 continue; 13383 } 13384 13385 if (SE.getTypeSizeInBits(CurBECount->getType()) > 13386 SE.getTypeSizeInBits(NewBECount->getType())) 13387 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType()); 13388 else if (SE.getTypeSizeInBits(CurBECount->getType()) < 13389 SE.getTypeSizeInBits(NewBECount->getType())) 13390 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType()); 13391 13392 const SCEV *Delta = SE2.getMinusSCEV(CurBECount, NewBECount); 13393 13394 // Unless VerifySCEVStrict is set, we only compare constant deltas. 13395 if ((VerifySCEVStrict || isa<SCEVConstant>(Delta)) && !Delta->isZero()) { 13396 dbgs() << "Trip Count for " << *L << " Changed!\n"; 13397 dbgs() << "Old: " << *CurBECount << "\n"; 13398 dbgs() << "New: " << *NewBECount << "\n"; 13399 dbgs() << "Delta: " << *Delta << "\n"; 13400 std::abort(); 13401 } 13402 } 13403 13404 // Collect all valid loops currently in LoopInfo. 13405 SmallPtrSet<Loop *, 32> ValidLoops; 13406 SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end()); 13407 while (!Worklist.empty()) { 13408 Loop *L = Worklist.pop_back_val(); 13409 if (ValidLoops.insert(L).second) 13410 Worklist.append(L->begin(), L->end()); 13411 } 13412 for (auto &KV : ValueExprMap) { 13413 #ifndef NDEBUG 13414 // Check for SCEV expressions referencing invalid/deleted loops. 13415 if (auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second)) { 13416 assert(ValidLoops.contains(AR->getLoop()) && 13417 "AddRec references invalid loop"); 13418 } 13419 #endif 13420 13421 // Check that the value is also part of the reverse map. 13422 auto It = ExprValueMap.find(KV.second); 13423 if (It == ExprValueMap.end() || !It->second.contains(KV.first)) { 13424 dbgs() << "Value " << *KV.first 13425 << " is in ValueExprMap but not in ExprValueMap\n"; 13426 std::abort(); 13427 } 13428 } 13429 13430 for (const auto &KV : ExprValueMap) { 13431 for (Value *V : KV.second) { 13432 auto It = ValueExprMap.find_as(V); 13433 if (It == ValueExprMap.end()) { 13434 dbgs() << "Value " << *V 13435 << " is in ExprValueMap but not in ValueExprMap\n"; 13436 std::abort(); 13437 } 13438 if (It->second != KV.first) { 13439 dbgs() << "Value " << *V << " mapped to " << *It->second 13440 << " rather than " << *KV.first << "\n"; 13441 std::abort(); 13442 } 13443 } 13444 } 13445 13446 // Verify integrity of SCEV users. 13447 for (const auto &S : UniqueSCEVs) { 13448 SmallVector<const SCEV *, 4> Ops; 13449 collectUniqueOps(&S, Ops); 13450 for (const auto *Op : Ops) { 13451 // We do not store dependencies of constants. 13452 if (isa<SCEVConstant>(Op)) 13453 continue; 13454 auto It = SCEVUsers.find(Op); 13455 if (It != SCEVUsers.end() && It->second.count(&S)) 13456 continue; 13457 dbgs() << "Use of operand " << *Op << " by user " << S 13458 << " is not being tracked!\n"; 13459 std::abort(); 13460 } 13461 } 13462 13463 // Verify integrity of ValuesAtScopes users. 13464 for (const auto &ValueAndVec : ValuesAtScopes) { 13465 const SCEV *Value = ValueAndVec.first; 13466 for (const auto &LoopAndValueAtScope : ValueAndVec.second) { 13467 const Loop *L = LoopAndValueAtScope.first; 13468 const SCEV *ValueAtScope = LoopAndValueAtScope.second; 13469 if (!isa<SCEVConstant>(ValueAtScope)) { 13470 auto It = ValuesAtScopesUsers.find(ValueAtScope); 13471 if (It != ValuesAtScopesUsers.end() && 13472 is_contained(It->second, std::make_pair(L, Value))) 13473 continue; 13474 dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: " 13475 << *ValueAtScope << " missing in ValuesAtScopesUsers\n"; 13476 std::abort(); 13477 } 13478 } 13479 } 13480 13481 for (const auto &ValueAtScopeAndVec : ValuesAtScopesUsers) { 13482 const SCEV *ValueAtScope = ValueAtScopeAndVec.first; 13483 for (const auto &LoopAndValue : ValueAtScopeAndVec.second) { 13484 const Loop *L = LoopAndValue.first; 13485 const SCEV *Value = LoopAndValue.second; 13486 assert(!isa<SCEVConstant>(Value)); 13487 auto It = ValuesAtScopes.find(Value); 13488 if (It != ValuesAtScopes.end() && 13489 is_contained(It->second, std::make_pair(L, ValueAtScope))) 13490 continue; 13491 dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: " 13492 << *ValueAtScope << " missing in ValuesAtScopes\n"; 13493 std::abort(); 13494 } 13495 } 13496 13497 // Verify integrity of BECountUsers. 13498 auto VerifyBECountUsers = [&](bool Predicated) { 13499 auto &BECounts = 13500 Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts; 13501 for (const auto &LoopAndBEInfo : BECounts) { 13502 for (const ExitNotTakenInfo &ENT : LoopAndBEInfo.second.ExitNotTaken) { 13503 if (!isa<SCEVConstant>(ENT.ExactNotTaken)) { 13504 auto UserIt = BECountUsers.find(ENT.ExactNotTaken); 13505 if (UserIt != BECountUsers.end() && 13506 UserIt->second.contains({ LoopAndBEInfo.first, Predicated })) 13507 continue; 13508 dbgs() << "Value " << *ENT.ExactNotTaken << " for loop " 13509 << *LoopAndBEInfo.first << " missing from BECountUsers\n"; 13510 std::abort(); 13511 } 13512 } 13513 } 13514 }; 13515 VerifyBECountUsers(/* Predicated */ false); 13516 VerifyBECountUsers(/* Predicated */ true); 13517 } 13518 13519 bool ScalarEvolution::invalidate( 13520 Function &F, const PreservedAnalyses &PA, 13521 FunctionAnalysisManager::Invalidator &Inv) { 13522 // Invalidate the ScalarEvolution object whenever it isn't preserved or one 13523 // of its dependencies is invalidated. 13524 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>(); 13525 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || 13526 Inv.invalidate<AssumptionAnalysis>(F, PA) || 13527 Inv.invalidate<DominatorTreeAnalysis>(F, PA) || 13528 Inv.invalidate<LoopAnalysis>(F, PA); 13529 } 13530 13531 AnalysisKey ScalarEvolutionAnalysis::Key; 13532 13533 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 13534 FunctionAnalysisManager &AM) { 13535 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 13536 AM.getResult<AssumptionAnalysis>(F), 13537 AM.getResult<DominatorTreeAnalysis>(F), 13538 AM.getResult<LoopAnalysis>(F)); 13539 } 13540 13541 PreservedAnalyses 13542 ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) { 13543 AM.getResult<ScalarEvolutionAnalysis>(F).verify(); 13544 return PreservedAnalyses::all(); 13545 } 13546 13547 PreservedAnalyses 13548 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 13549 // For compatibility with opt's -analyze feature under legacy pass manager 13550 // which was not ported to NPM. This keeps tests using 13551 // update_analyze_test_checks.py working. 13552 OS << "Printing analysis 'Scalar Evolution Analysis' for function '" 13553 << F.getName() << "':\n"; 13554 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 13555 return PreservedAnalyses::all(); 13556 } 13557 13558 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 13559 "Scalar Evolution Analysis", false, true) 13560 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 13561 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 13562 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 13563 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 13564 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 13565 "Scalar Evolution Analysis", false, true) 13566 13567 char ScalarEvolutionWrapperPass::ID = 0; 13568 13569 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 13570 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 13571 } 13572 13573 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 13574 SE.reset(new ScalarEvolution( 13575 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F), 13576 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 13577 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 13578 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 13579 return false; 13580 } 13581 13582 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 13583 13584 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 13585 SE->print(OS); 13586 } 13587 13588 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 13589 if (!VerifySCEV) 13590 return; 13591 13592 SE->verify(); 13593 } 13594 13595 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 13596 AU.setPreservesAll(); 13597 AU.addRequiredTransitive<AssumptionCacheTracker>(); 13598 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 13599 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 13600 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 13601 } 13602 13603 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS, 13604 const SCEV *RHS) { 13605 return getComparePredicate(ICmpInst::ICMP_EQ, LHS, RHS); 13606 } 13607 13608 const SCEVPredicate * 13609 ScalarEvolution::getComparePredicate(const ICmpInst::Predicate Pred, 13610 const SCEV *LHS, const SCEV *RHS) { 13611 FoldingSetNodeID ID; 13612 assert(LHS->getType() == RHS->getType() && 13613 "Type mismatch between LHS and RHS"); 13614 // Unique this node based on the arguments 13615 ID.AddInteger(SCEVPredicate::P_Compare); 13616 ID.AddInteger(Pred); 13617 ID.AddPointer(LHS); 13618 ID.AddPointer(RHS); 13619 void *IP = nullptr; 13620 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 13621 return S; 13622 SCEVComparePredicate *Eq = new (SCEVAllocator) 13623 SCEVComparePredicate(ID.Intern(SCEVAllocator), Pred, LHS, RHS); 13624 UniquePreds.InsertNode(Eq, IP); 13625 return Eq; 13626 } 13627 13628 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 13629 const SCEVAddRecExpr *AR, 13630 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 13631 FoldingSetNodeID ID; 13632 // Unique this node based on the arguments 13633 ID.AddInteger(SCEVPredicate::P_Wrap); 13634 ID.AddPointer(AR); 13635 ID.AddInteger(AddedFlags); 13636 void *IP = nullptr; 13637 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 13638 return S; 13639 auto *OF = new (SCEVAllocator) 13640 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 13641 UniquePreds.InsertNode(OF, IP); 13642 return OF; 13643 } 13644 13645 namespace { 13646 13647 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 13648 public: 13649 13650 /// Rewrites \p S in the context of a loop L and the SCEV predication 13651 /// infrastructure. 13652 /// 13653 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 13654 /// equivalences present in \p Pred. 13655 /// 13656 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 13657 /// \p NewPreds such that the result will be an AddRecExpr. 13658 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 13659 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 13660 const SCEVPredicate *Pred) { 13661 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 13662 return Rewriter.visit(S); 13663 } 13664 13665 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 13666 if (Pred) { 13667 if (auto *U = dyn_cast<SCEVUnionPredicate>(Pred)) { 13668 for (auto *Pred : U->getPredicates()) 13669 if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred)) 13670 if (IPred->getLHS() == Expr && 13671 IPred->getPredicate() == ICmpInst::ICMP_EQ) 13672 return IPred->getRHS(); 13673 } else if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred)) { 13674 if (IPred->getLHS() == Expr && 13675 IPred->getPredicate() == ICmpInst::ICMP_EQ) 13676 return IPred->getRHS(); 13677 } 13678 } 13679 return convertToAddRecWithPreds(Expr); 13680 } 13681 13682 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 13683 const SCEV *Operand = visit(Expr->getOperand()); 13684 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 13685 if (AR && AR->getLoop() == L && AR->isAffine()) { 13686 // This couldn't be folded because the operand didn't have the nuw 13687 // flag. Add the nusw flag as an assumption that we could make. 13688 const SCEV *Step = AR->getStepRecurrence(SE); 13689 Type *Ty = Expr->getType(); 13690 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 13691 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 13692 SE.getSignExtendExpr(Step, Ty), L, 13693 AR->getNoWrapFlags()); 13694 } 13695 return SE.getZeroExtendExpr(Operand, Expr->getType()); 13696 } 13697 13698 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 13699 const SCEV *Operand = visit(Expr->getOperand()); 13700 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 13701 if (AR && AR->getLoop() == L && AR->isAffine()) { 13702 // This couldn't be folded because the operand didn't have the nsw 13703 // flag. Add the nssw flag as an assumption that we could make. 13704 const SCEV *Step = AR->getStepRecurrence(SE); 13705 Type *Ty = Expr->getType(); 13706 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 13707 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 13708 SE.getSignExtendExpr(Step, Ty), L, 13709 AR->getNoWrapFlags()); 13710 } 13711 return SE.getSignExtendExpr(Operand, Expr->getType()); 13712 } 13713 13714 private: 13715 explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 13716 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 13717 const SCEVPredicate *Pred) 13718 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 13719 13720 bool addOverflowAssumption(const SCEVPredicate *P) { 13721 if (!NewPreds) { 13722 // Check if we've already made this assumption. 13723 return Pred && Pred->implies(P); 13724 } 13725 NewPreds->insert(P); 13726 return true; 13727 } 13728 13729 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 13730 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 13731 auto *A = SE.getWrapPredicate(AR, AddedFlags); 13732 return addOverflowAssumption(A); 13733 } 13734 13735 // If \p Expr represents a PHINode, we try to see if it can be represented 13736 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible 13737 // to add this predicate as a runtime overflow check, we return the AddRec. 13738 // If \p Expr does not meet these conditions (is not a PHI node, or we 13739 // couldn't create an AddRec for it, or couldn't add the predicate), we just 13740 // return \p Expr. 13741 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) { 13742 if (!isa<PHINode>(Expr->getValue())) 13743 return Expr; 13744 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 13745 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr); 13746 if (!PredicatedRewrite) 13747 return Expr; 13748 for (auto *P : PredicatedRewrite->second){ 13749 // Wrap predicates from outer loops are not supported. 13750 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) { 13751 if (L != WP->getExpr()->getLoop()) 13752 return Expr; 13753 } 13754 if (!addOverflowAssumption(P)) 13755 return Expr; 13756 } 13757 return PredicatedRewrite->first; 13758 } 13759 13760 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 13761 const SCEVPredicate *Pred; 13762 const Loop *L; 13763 }; 13764 13765 } // end anonymous namespace 13766 13767 const SCEV * 13768 ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 13769 const SCEVPredicate &Preds) { 13770 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 13771 } 13772 13773 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 13774 const SCEV *S, const Loop *L, 13775 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 13776 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 13777 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 13778 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 13779 13780 if (!AddRec) 13781 return nullptr; 13782 13783 // Since the transformation was successful, we can now transfer the SCEV 13784 // predicates. 13785 for (auto *P : TransformPreds) 13786 Preds.insert(P); 13787 13788 return AddRec; 13789 } 13790 13791 /// SCEV predicates 13792 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 13793 SCEVPredicateKind Kind) 13794 : FastID(ID), Kind(Kind) {} 13795 13796 SCEVComparePredicate::SCEVComparePredicate(const FoldingSetNodeIDRef ID, 13797 const ICmpInst::Predicate Pred, 13798 const SCEV *LHS, const SCEV *RHS) 13799 : SCEVPredicate(ID, P_Compare), Pred(Pred), LHS(LHS), RHS(RHS) { 13800 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match"); 13801 assert(LHS != RHS && "LHS and RHS are the same SCEV"); 13802 } 13803 13804 bool SCEVComparePredicate::implies(const SCEVPredicate *N) const { 13805 const auto *Op = dyn_cast<SCEVComparePredicate>(N); 13806 13807 if (!Op) 13808 return false; 13809 13810 if (Pred != ICmpInst::ICMP_EQ) 13811 return false; 13812 13813 return Op->LHS == LHS && Op->RHS == RHS; 13814 } 13815 13816 bool SCEVComparePredicate::isAlwaysTrue() const { return false; } 13817 13818 void SCEVComparePredicate::print(raw_ostream &OS, unsigned Depth) const { 13819 if (Pred == ICmpInst::ICMP_EQ) 13820 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 13821 else 13822 OS.indent(Depth) << "Compare predicate: " << *LHS 13823 << " " << CmpInst::getPredicateName(Pred) << ") " 13824 << *RHS << "\n"; 13825 13826 } 13827 13828 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 13829 const SCEVAddRecExpr *AR, 13830 IncrementWrapFlags Flags) 13831 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 13832 13833 const SCEVAddRecExpr *SCEVWrapPredicate::getExpr() const { return AR; } 13834 13835 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 13836 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 13837 13838 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 13839 } 13840 13841 bool SCEVWrapPredicate::isAlwaysTrue() const { 13842 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 13843 IncrementWrapFlags IFlags = Flags; 13844 13845 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 13846 IFlags = clearFlags(IFlags, IncrementNSSW); 13847 13848 return IFlags == IncrementAnyWrap; 13849 } 13850 13851 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 13852 OS.indent(Depth) << *getExpr() << " Added Flags: "; 13853 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 13854 OS << "<nusw>"; 13855 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 13856 OS << "<nssw>"; 13857 OS << "\n"; 13858 } 13859 13860 SCEVWrapPredicate::IncrementWrapFlags 13861 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 13862 ScalarEvolution &SE) { 13863 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 13864 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 13865 13866 // We can safely transfer the NSW flag as NSSW. 13867 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 13868 ImpliedFlags = IncrementNSSW; 13869 13870 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 13871 // If the increment is positive, the SCEV NUW flag will also imply the 13872 // WrapPredicate NUSW flag. 13873 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 13874 if (Step->getValue()->getValue().isNonNegative()) 13875 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 13876 } 13877 13878 return ImpliedFlags; 13879 } 13880 13881 /// Union predicates don't get cached so create a dummy set ID for it. 13882 SCEVUnionPredicate::SCEVUnionPredicate(ArrayRef<const SCEVPredicate *> Preds) 13883 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) { 13884 for (auto *P : Preds) 13885 add(P); 13886 } 13887 13888 bool SCEVUnionPredicate::isAlwaysTrue() const { 13889 return all_of(Preds, 13890 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 13891 } 13892 13893 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 13894 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 13895 return all_of(Set->Preds, 13896 [this](const SCEVPredicate *I) { return this->implies(I); }); 13897 13898 return any_of(Preds, 13899 [N](const SCEVPredicate *I) { return I->implies(N); }); 13900 } 13901 13902 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 13903 for (auto Pred : Preds) 13904 Pred->print(OS, Depth); 13905 } 13906 13907 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 13908 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 13909 for (auto Pred : Set->Preds) 13910 add(Pred); 13911 return; 13912 } 13913 13914 Preds.push_back(N); 13915 } 13916 13917 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 13918 Loop &L) 13919 : SE(SE), L(L) { 13920 SmallVector<const SCEVPredicate*, 4> Empty; 13921 Preds = std::make_unique<SCEVUnionPredicate>(Empty); 13922 } 13923 13924 void ScalarEvolution::registerUser(const SCEV *User, 13925 ArrayRef<const SCEV *> Ops) { 13926 for (auto *Op : Ops) 13927 // We do not expect that forgetting cached data for SCEVConstants will ever 13928 // open any prospects for sharpening or introduce any correctness issues, 13929 // so we don't bother storing their dependencies. 13930 if (!isa<SCEVConstant>(Op)) 13931 SCEVUsers[Op].insert(User); 13932 } 13933 13934 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 13935 const SCEV *Expr = SE.getSCEV(V); 13936 RewriteEntry &Entry = RewriteMap[Expr]; 13937 13938 // If we already have an entry and the version matches, return it. 13939 if (Entry.second && Generation == Entry.first) 13940 return Entry.second; 13941 13942 // We found an entry but it's stale. Rewrite the stale entry 13943 // according to the current predicate. 13944 if (Entry.second) 13945 Expr = Entry.second; 13946 13947 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, *Preds); 13948 Entry = {Generation, NewSCEV}; 13949 13950 return NewSCEV; 13951 } 13952 13953 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 13954 if (!BackedgeCount) { 13955 SmallVector<const SCEVPredicate *, 4> Preds; 13956 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, Preds); 13957 for (auto *P : Preds) 13958 addPredicate(*P); 13959 } 13960 return BackedgeCount; 13961 } 13962 13963 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 13964 if (Preds->implies(&Pred)) 13965 return; 13966 13967 auto &OldPreds = Preds->getPredicates(); 13968 SmallVector<const SCEVPredicate*, 4> NewPreds(OldPreds.begin(), OldPreds.end()); 13969 NewPreds.push_back(&Pred); 13970 Preds = std::make_unique<SCEVUnionPredicate>(NewPreds); 13971 updateGeneration(); 13972 } 13973 13974 const SCEVPredicate &PredicatedScalarEvolution::getPredicate() const { 13975 return *Preds; 13976 } 13977 13978 void PredicatedScalarEvolution::updateGeneration() { 13979 // If the generation number wrapped recompute everything. 13980 if (++Generation == 0) { 13981 for (auto &II : RewriteMap) { 13982 const SCEV *Rewritten = II.second.second; 13983 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, *Preds)}; 13984 } 13985 } 13986 } 13987 13988 void PredicatedScalarEvolution::setNoOverflow( 13989 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 13990 const SCEV *Expr = getSCEV(V); 13991 const auto *AR = cast<SCEVAddRecExpr>(Expr); 13992 13993 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 13994 13995 // Clear the statically implied flags. 13996 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 13997 addPredicate(*SE.getWrapPredicate(AR, Flags)); 13998 13999 auto II = FlagsMap.insert({V, Flags}); 14000 if (!II.second) 14001 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 14002 } 14003 14004 bool PredicatedScalarEvolution::hasNoOverflow( 14005 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 14006 const SCEV *Expr = getSCEV(V); 14007 const auto *AR = cast<SCEVAddRecExpr>(Expr); 14008 14009 Flags = SCEVWrapPredicate::clearFlags( 14010 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 14011 14012 auto II = FlagsMap.find(V); 14013 14014 if (II != FlagsMap.end()) 14015 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 14016 14017 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 14018 } 14019 14020 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 14021 const SCEV *Expr = this->getSCEV(V); 14022 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 14023 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 14024 14025 if (!New) 14026 return nullptr; 14027 14028 for (auto *P : NewPreds) 14029 addPredicate(*P); 14030 14031 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 14032 return New; 14033 } 14034 14035 PredicatedScalarEvolution::PredicatedScalarEvolution( 14036 const PredicatedScalarEvolution &Init) 14037 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), 14038 Preds(std::make_unique<SCEVUnionPredicate>(Init.Preds->getPredicates())), 14039 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 14040 for (auto I : Init.FlagsMap) 14041 FlagsMap.insert(I); 14042 } 14043 14044 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 14045 // For each block. 14046 for (auto *BB : L.getBlocks()) 14047 for (auto &I : *BB) { 14048 if (!SE.isSCEVable(I.getType())) 14049 continue; 14050 14051 auto *Expr = SE.getSCEV(&I); 14052 auto II = RewriteMap.find(Expr); 14053 14054 if (II == RewriteMap.end()) 14055 continue; 14056 14057 // Don't print things that are not interesting. 14058 if (II->second.second == Expr) 14059 continue; 14060 14061 OS.indent(Depth) << "[PSE]" << I << ":\n"; 14062 OS.indent(Depth + 2) << *Expr << "\n"; 14063 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 14064 } 14065 } 14066 14067 // Match the mathematical pattern A - (A / B) * B, where A and B can be 14068 // arbitrary expressions. Also match zext (trunc A to iB) to iY, which is used 14069 // for URem with constant power-of-2 second operands. 14070 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is 14071 // 4, A / B becomes X / 8). 14072 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS, 14073 const SCEV *&RHS) { 14074 // Try to match 'zext (trunc A to iB) to iY', which is used 14075 // for URem with constant power-of-2 second operands. Make sure the size of 14076 // the operand A matches the size of the whole expressions. 14077 if (const auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(Expr)) 14078 if (const auto *Trunc = dyn_cast<SCEVTruncateExpr>(ZExt->getOperand(0))) { 14079 LHS = Trunc->getOperand(); 14080 // Bail out if the type of the LHS is larger than the type of the 14081 // expression for now. 14082 if (getTypeSizeInBits(LHS->getType()) > 14083 getTypeSizeInBits(Expr->getType())) 14084 return false; 14085 if (LHS->getType() != Expr->getType()) 14086 LHS = getZeroExtendExpr(LHS, Expr->getType()); 14087 RHS = getConstant(APInt(getTypeSizeInBits(Expr->getType()), 1) 14088 << getTypeSizeInBits(Trunc->getType())); 14089 return true; 14090 } 14091 const auto *Add = dyn_cast<SCEVAddExpr>(Expr); 14092 if (Add == nullptr || Add->getNumOperands() != 2) 14093 return false; 14094 14095 const SCEV *A = Add->getOperand(1); 14096 const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0)); 14097 14098 if (Mul == nullptr) 14099 return false; 14100 14101 const auto MatchURemWithDivisor = [&](const SCEV *B) { 14102 // (SomeExpr + (-(SomeExpr / B) * B)). 14103 if (Expr == getURemExpr(A, B)) { 14104 LHS = A; 14105 RHS = B; 14106 return true; 14107 } 14108 return false; 14109 }; 14110 14111 // (SomeExpr + (-1 * (SomeExpr / B) * B)). 14112 if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0))) 14113 return MatchURemWithDivisor(Mul->getOperand(1)) || 14114 MatchURemWithDivisor(Mul->getOperand(2)); 14115 14116 // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)). 14117 if (Mul->getNumOperands() == 2) 14118 return MatchURemWithDivisor(Mul->getOperand(1)) || 14119 MatchURemWithDivisor(Mul->getOperand(0)) || 14120 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) || 14121 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0))); 14122 return false; 14123 } 14124 14125 const SCEV * 14126 ScalarEvolution::computeSymbolicMaxBackedgeTakenCount(const Loop *L) { 14127 SmallVector<BasicBlock*, 16> ExitingBlocks; 14128 L->getExitingBlocks(ExitingBlocks); 14129 14130 // Form an expression for the maximum exit count possible for this loop. We 14131 // merge the max and exact information to approximate a version of 14132 // getConstantMaxBackedgeTakenCount which isn't restricted to just constants. 14133 SmallVector<const SCEV*, 4> ExitCounts; 14134 for (BasicBlock *ExitingBB : ExitingBlocks) { 14135 const SCEV *ExitCount = getExitCount(L, ExitingBB); 14136 if (isa<SCEVCouldNotCompute>(ExitCount)) 14137 ExitCount = getExitCount(L, ExitingBB, 14138 ScalarEvolution::ConstantMaximum); 14139 if (!isa<SCEVCouldNotCompute>(ExitCount)) { 14140 assert(DT.dominates(ExitingBB, L->getLoopLatch()) && 14141 "We should only have known counts for exiting blocks that " 14142 "dominate latch!"); 14143 ExitCounts.push_back(ExitCount); 14144 } 14145 } 14146 if (ExitCounts.empty()) 14147 return getCouldNotCompute(); 14148 return getUMinFromMismatchedTypes(ExitCounts); 14149 } 14150 14151 /// A rewriter to replace SCEV expressions in Map with the corresponding entry 14152 /// in the map. It skips AddRecExpr because we cannot guarantee that the 14153 /// replacement is loop invariant in the loop of the AddRec. 14154 /// 14155 /// At the moment only rewriting SCEVUnknown and SCEVZeroExtendExpr is 14156 /// supported. 14157 class SCEVLoopGuardRewriter : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> { 14158 const DenseMap<const SCEV *, const SCEV *> ⤅ 14159 14160 public: 14161 SCEVLoopGuardRewriter(ScalarEvolution &SE, 14162 DenseMap<const SCEV *, const SCEV *> &M) 14163 : SCEVRewriteVisitor(SE), Map(M) {} 14164 14165 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; } 14166 14167 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 14168 auto I = Map.find(Expr); 14169 if (I == Map.end()) 14170 return Expr; 14171 return I->second; 14172 } 14173 14174 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 14175 auto I = Map.find(Expr); 14176 if (I == Map.end()) 14177 return SCEVRewriteVisitor<SCEVLoopGuardRewriter>::visitZeroExtendExpr( 14178 Expr); 14179 return I->second; 14180 } 14181 }; 14182 14183 const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) { 14184 SmallVector<const SCEV *> ExprsToRewrite; 14185 auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS, 14186 const SCEV *RHS, 14187 DenseMap<const SCEV *, const SCEV *> 14188 &RewriteMap) { 14189 // WARNING: It is generally unsound to apply any wrap flags to the proposed 14190 // replacement SCEV which isn't directly implied by the structure of that 14191 // SCEV. In particular, using contextual facts to imply flags is *NOT* 14192 // legal. See the scoping rules for flags in the header to understand why. 14193 14194 // If LHS is a constant, apply information to the other expression. 14195 if (isa<SCEVConstant>(LHS)) { 14196 std::swap(LHS, RHS); 14197 Predicate = CmpInst::getSwappedPredicate(Predicate); 14198 } 14199 14200 // Check for a condition of the form (-C1 + X < C2). InstCombine will 14201 // create this form when combining two checks of the form (X u< C2 + C1) and 14202 // (X >=u C1). 14203 auto MatchRangeCheckIdiom = [this, Predicate, LHS, RHS, &RewriteMap, 14204 &ExprsToRewrite]() { 14205 auto *AddExpr = dyn_cast<SCEVAddExpr>(LHS); 14206 if (!AddExpr || AddExpr->getNumOperands() != 2) 14207 return false; 14208 14209 auto *C1 = dyn_cast<SCEVConstant>(AddExpr->getOperand(0)); 14210 auto *LHSUnknown = dyn_cast<SCEVUnknown>(AddExpr->getOperand(1)); 14211 auto *C2 = dyn_cast<SCEVConstant>(RHS); 14212 if (!C1 || !C2 || !LHSUnknown) 14213 return false; 14214 14215 auto ExactRegion = 14216 ConstantRange::makeExactICmpRegion(Predicate, C2->getAPInt()) 14217 .sub(C1->getAPInt()); 14218 14219 // Bail out, unless we have a non-wrapping, monotonic range. 14220 if (ExactRegion.isWrappedSet() || ExactRegion.isFullSet()) 14221 return false; 14222 auto I = RewriteMap.find(LHSUnknown); 14223 const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHSUnknown; 14224 RewriteMap[LHSUnknown] = getUMaxExpr( 14225 getConstant(ExactRegion.getUnsignedMin()), 14226 getUMinExpr(RewrittenLHS, getConstant(ExactRegion.getUnsignedMax()))); 14227 ExprsToRewrite.push_back(LHSUnknown); 14228 return true; 14229 }; 14230 if (MatchRangeCheckIdiom()) 14231 return; 14232 14233 // If we have LHS == 0, check if LHS is computing a property of some unknown 14234 // SCEV %v which we can rewrite %v to express explicitly. 14235 const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS); 14236 if (Predicate == CmpInst::ICMP_EQ && RHSC && 14237 RHSC->getValue()->isNullValue()) { 14238 // If LHS is A % B, i.e. A % B == 0, rewrite A to (A /u B) * B to 14239 // explicitly express that. 14240 const SCEV *URemLHS = nullptr; 14241 const SCEV *URemRHS = nullptr; 14242 if (matchURem(LHS, URemLHS, URemRHS)) { 14243 if (const SCEVUnknown *LHSUnknown = dyn_cast<SCEVUnknown>(URemLHS)) { 14244 auto Multiple = getMulExpr(getUDivExpr(URemLHS, URemRHS), URemRHS); 14245 RewriteMap[LHSUnknown] = Multiple; 14246 ExprsToRewrite.push_back(LHSUnknown); 14247 return; 14248 } 14249 } 14250 } 14251 14252 // Do not apply information for constants or if RHS contains an AddRec. 14253 if (isa<SCEVConstant>(LHS) || containsAddRecurrence(RHS)) 14254 return; 14255 14256 // If RHS is SCEVUnknown, make sure the information is applied to it. 14257 if (!isa<SCEVUnknown>(LHS) && isa<SCEVUnknown>(RHS)) { 14258 std::swap(LHS, RHS); 14259 Predicate = CmpInst::getSwappedPredicate(Predicate); 14260 } 14261 14262 // Limit to expressions that can be rewritten. 14263 if (!isa<SCEVUnknown>(LHS) && !isa<SCEVZeroExtendExpr>(LHS)) 14264 return; 14265 14266 // Check whether LHS has already been rewritten. In that case we want to 14267 // chain further rewrites onto the already rewritten value. 14268 auto I = RewriteMap.find(LHS); 14269 const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHS; 14270 14271 const SCEV *RewrittenRHS = nullptr; 14272 switch (Predicate) { 14273 case CmpInst::ICMP_ULT: 14274 RewrittenRHS = 14275 getUMinExpr(RewrittenLHS, getMinusSCEV(RHS, getOne(RHS->getType()))); 14276 break; 14277 case CmpInst::ICMP_SLT: 14278 RewrittenRHS = 14279 getSMinExpr(RewrittenLHS, getMinusSCEV(RHS, getOne(RHS->getType()))); 14280 break; 14281 case CmpInst::ICMP_ULE: 14282 RewrittenRHS = getUMinExpr(RewrittenLHS, RHS); 14283 break; 14284 case CmpInst::ICMP_SLE: 14285 RewrittenRHS = getSMinExpr(RewrittenLHS, RHS); 14286 break; 14287 case CmpInst::ICMP_UGT: 14288 RewrittenRHS = 14289 getUMaxExpr(RewrittenLHS, getAddExpr(RHS, getOne(RHS->getType()))); 14290 break; 14291 case CmpInst::ICMP_SGT: 14292 RewrittenRHS = 14293 getSMaxExpr(RewrittenLHS, getAddExpr(RHS, getOne(RHS->getType()))); 14294 break; 14295 case CmpInst::ICMP_UGE: 14296 RewrittenRHS = getUMaxExpr(RewrittenLHS, RHS); 14297 break; 14298 case CmpInst::ICMP_SGE: 14299 RewrittenRHS = getSMaxExpr(RewrittenLHS, RHS); 14300 break; 14301 case CmpInst::ICMP_EQ: 14302 if (isa<SCEVConstant>(RHS)) 14303 RewrittenRHS = RHS; 14304 break; 14305 case CmpInst::ICMP_NE: 14306 if (isa<SCEVConstant>(RHS) && 14307 cast<SCEVConstant>(RHS)->getValue()->isNullValue()) 14308 RewrittenRHS = getUMaxExpr(RewrittenLHS, getOne(RHS->getType())); 14309 break; 14310 default: 14311 break; 14312 } 14313 14314 if (RewrittenRHS) { 14315 RewriteMap[LHS] = RewrittenRHS; 14316 if (LHS == RewrittenLHS) 14317 ExprsToRewrite.push_back(LHS); 14318 } 14319 }; 14320 // First, collect conditions from dominating branches. Starting at the loop 14321 // predecessor, climb up the predecessor chain, as long as there are 14322 // predecessors that can be found that have unique successors leading to the 14323 // original header. 14324 // TODO: share this logic with isLoopEntryGuardedByCond. 14325 SmallVector<std::pair<Value *, bool>> Terms; 14326 for (std::pair<const BasicBlock *, const BasicBlock *> Pair( 14327 L->getLoopPredecessor(), L->getHeader()); 14328 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 14329 14330 const BranchInst *LoopEntryPredicate = 14331 dyn_cast<BranchInst>(Pair.first->getTerminator()); 14332 if (!LoopEntryPredicate || LoopEntryPredicate->isUnconditional()) 14333 continue; 14334 14335 Terms.emplace_back(LoopEntryPredicate->getCondition(), 14336 LoopEntryPredicate->getSuccessor(0) == Pair.second); 14337 } 14338 14339 // Now apply the information from the collected conditions to RewriteMap. 14340 // Conditions are processed in reverse order, so the earliest conditions is 14341 // processed first. This ensures the SCEVs with the shortest dependency chains 14342 // are constructed first. 14343 DenseMap<const SCEV *, const SCEV *> RewriteMap; 14344 for (auto &E : reverse(Terms)) { 14345 bool EnterIfTrue = E.second; 14346 SmallVector<Value *, 8> Worklist; 14347 SmallPtrSet<Value *, 8> Visited; 14348 Worklist.push_back(E.first); 14349 while (!Worklist.empty()) { 14350 Value *Cond = Worklist.pop_back_val(); 14351 if (!Visited.insert(Cond).second) 14352 continue; 14353 14354 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) { 14355 auto Predicate = 14356 EnterIfTrue ? Cmp->getPredicate() : Cmp->getInversePredicate(); 14357 CollectCondition(Predicate, getSCEV(Cmp->getOperand(0)), 14358 getSCEV(Cmp->getOperand(1)), RewriteMap); 14359 continue; 14360 } 14361 14362 Value *L, *R; 14363 if (EnterIfTrue ? match(Cond, m_LogicalAnd(m_Value(L), m_Value(R))) 14364 : match(Cond, m_LogicalOr(m_Value(L), m_Value(R)))) { 14365 Worklist.push_back(L); 14366 Worklist.push_back(R); 14367 } 14368 } 14369 } 14370 14371 // Also collect information from assumptions dominating the loop. 14372 for (auto &AssumeVH : AC.assumptions()) { 14373 if (!AssumeVH) 14374 continue; 14375 auto *AssumeI = cast<CallInst>(AssumeVH); 14376 auto *Cmp = dyn_cast<ICmpInst>(AssumeI->getOperand(0)); 14377 if (!Cmp || !DT.dominates(AssumeI, L->getHeader())) 14378 continue; 14379 CollectCondition(Cmp->getPredicate(), getSCEV(Cmp->getOperand(0)), 14380 getSCEV(Cmp->getOperand(1)), RewriteMap); 14381 } 14382 14383 if (RewriteMap.empty()) 14384 return Expr; 14385 14386 // Now that all rewrite information is collect, rewrite the collected 14387 // expressions with the information in the map. This applies information to 14388 // sub-expressions. 14389 if (ExprsToRewrite.size() > 1) { 14390 for (const SCEV *Expr : ExprsToRewrite) { 14391 const SCEV *RewriteTo = RewriteMap[Expr]; 14392 RewriteMap.erase(Expr); 14393 SCEVLoopGuardRewriter Rewriter(*this, RewriteMap); 14394 RewriteMap.insert({Expr, Rewriter.visit(RewriteTo)}); 14395 } 14396 } 14397 14398 SCEVLoopGuardRewriter Rewriter(*this, RewriteMap); 14399 return Rewriter.visit(Expr); 14400 } 14401