1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file contains the implementation of the scalar evolution analysis 10 // engine, which is used primarily to analyze expressions involving induction 11 // variables in loops. 12 // 13 // There are several aspects to this library. First is the representation of 14 // scalar expressions, which are represented as subclasses of the SCEV class. 15 // These classes are used to represent certain types of subexpressions that we 16 // can handle. We only create one SCEV of a particular shape, so 17 // pointer-comparisons for equality are legal. 18 // 19 // One important aspect of the SCEV objects is that they are never cyclic, even 20 // if there is a cycle in the dataflow for an expression (ie, a PHI node). If 21 // the PHI node is one of the idioms that we can represent (e.g., a polynomial 22 // recurrence) then we represent it directly as a recurrence node, otherwise we 23 // represent it as a SCEVUnknown node. 24 // 25 // In addition to being able to represent expressions of various types, we also 26 // have folders that are used to build the *canonical* representation for a 27 // particular expression. These folders are capable of using a variety of 28 // rewrite rules to simplify the expressions. 29 // 30 // Once the folders are defined, we can implement the more interesting 31 // higher-level code, such as the code that recognizes PHI nodes of various 32 // types, computes the execution count of a loop, etc. 33 // 34 // TODO: We should use these routines and value representations to implement 35 // dependence analysis! 36 // 37 //===----------------------------------------------------------------------===// 38 // 39 // There are several good references for the techniques used in this analysis. 40 // 41 // Chains of recurrences -- a method to expedite the evaluation 42 // of closed-form functions 43 // Olaf Bachmann, Paul S. Wang, Eugene V. Zima 44 // 45 // On computational properties of chains of recurrences 46 // Eugene V. Zima 47 // 48 // Symbolic Evaluation of Chains of Recurrences for Loop Optimization 49 // Robert A. van Engelen 50 // 51 // Efficient Symbolic Analysis for Optimizing Compilers 52 // Robert A. van Engelen 53 // 54 // Using the chains of recurrences algebra for data dependence testing and 55 // induction variable substitution 56 // MS Thesis, Johnie Birch 57 // 58 //===----------------------------------------------------------------------===// 59 60 #include "llvm/Analysis/ScalarEvolution.h" 61 #include "llvm/ADT/APInt.h" 62 #include "llvm/ADT/ArrayRef.h" 63 #include "llvm/ADT/DenseMap.h" 64 #include "llvm/ADT/DepthFirstIterator.h" 65 #include "llvm/ADT/EquivalenceClasses.h" 66 #include "llvm/ADT/FoldingSet.h" 67 #include "llvm/ADT/None.h" 68 #include "llvm/ADT/Optional.h" 69 #include "llvm/ADT/STLExtras.h" 70 #include "llvm/ADT/ScopeExit.h" 71 #include "llvm/ADT/Sequence.h" 72 #include "llvm/ADT/SetVector.h" 73 #include "llvm/ADT/SmallPtrSet.h" 74 #include "llvm/ADT/SmallSet.h" 75 #include "llvm/ADT/SmallVector.h" 76 #include "llvm/ADT/Statistic.h" 77 #include "llvm/ADT/StringRef.h" 78 #include "llvm/Analysis/AssumptionCache.h" 79 #include "llvm/Analysis/ConstantFolding.h" 80 #include "llvm/Analysis/InstructionSimplify.h" 81 #include "llvm/Analysis/LoopInfo.h" 82 #include "llvm/Analysis/ScalarEvolutionDivision.h" 83 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 84 #include "llvm/Analysis/TargetLibraryInfo.h" 85 #include "llvm/Analysis/ValueTracking.h" 86 #include "llvm/Config/llvm-config.h" 87 #include "llvm/IR/Argument.h" 88 #include "llvm/IR/BasicBlock.h" 89 #include "llvm/IR/CFG.h" 90 #include "llvm/IR/Constant.h" 91 #include "llvm/IR/ConstantRange.h" 92 #include "llvm/IR/Constants.h" 93 #include "llvm/IR/DataLayout.h" 94 #include "llvm/IR/DerivedTypes.h" 95 #include "llvm/IR/Dominators.h" 96 #include "llvm/IR/Function.h" 97 #include "llvm/IR/GlobalAlias.h" 98 #include "llvm/IR/GlobalValue.h" 99 #include "llvm/IR/GlobalVariable.h" 100 #include "llvm/IR/InstIterator.h" 101 #include "llvm/IR/InstrTypes.h" 102 #include "llvm/IR/Instruction.h" 103 #include "llvm/IR/Instructions.h" 104 #include "llvm/IR/IntrinsicInst.h" 105 #include "llvm/IR/Intrinsics.h" 106 #include "llvm/IR/LLVMContext.h" 107 #include "llvm/IR/Metadata.h" 108 #include "llvm/IR/Operator.h" 109 #include "llvm/IR/PatternMatch.h" 110 #include "llvm/IR/Type.h" 111 #include "llvm/IR/Use.h" 112 #include "llvm/IR/User.h" 113 #include "llvm/IR/Value.h" 114 #include "llvm/IR/Verifier.h" 115 #include "llvm/InitializePasses.h" 116 #include "llvm/Pass.h" 117 #include "llvm/Support/Casting.h" 118 #include "llvm/Support/CommandLine.h" 119 #include "llvm/Support/Compiler.h" 120 #include "llvm/Support/Debug.h" 121 #include "llvm/Support/ErrorHandling.h" 122 #include "llvm/Support/KnownBits.h" 123 #include "llvm/Support/SaveAndRestore.h" 124 #include "llvm/Support/raw_ostream.h" 125 #include <algorithm> 126 #include <cassert> 127 #include <climits> 128 #include <cstddef> 129 #include <cstdint> 130 #include <cstdlib> 131 #include <map> 132 #include <memory> 133 #include <tuple> 134 #include <utility> 135 #include <vector> 136 137 using namespace llvm; 138 using namespace PatternMatch; 139 140 #define DEBUG_TYPE "scalar-evolution" 141 142 STATISTIC(NumTripCountsComputed, 143 "Number of loops with predictable loop counts"); 144 STATISTIC(NumTripCountsNotComputed, 145 "Number of loops without predictable loop counts"); 146 STATISTIC(NumBruteForceTripCountsComputed, 147 "Number of loops with trip counts computed by force"); 148 149 static cl::opt<unsigned> 150 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, 151 cl::ZeroOrMore, 152 cl::desc("Maximum number of iterations SCEV will " 153 "symbolically execute a constant " 154 "derived loop"), 155 cl::init(100)); 156 157 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean. 158 static cl::opt<bool> VerifySCEV( 159 "verify-scev", cl::Hidden, 160 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)")); 161 static cl::opt<bool> VerifySCEVStrict( 162 "verify-scev-strict", cl::Hidden, 163 cl::desc("Enable stricter verification with -verify-scev is passed")); 164 static cl::opt<bool> 165 VerifySCEVMap("verify-scev-maps", cl::Hidden, 166 cl::desc("Verify no dangling value in ScalarEvolution's " 167 "ExprValueMap (slow)")); 168 169 static cl::opt<bool> VerifyIR( 170 "scev-verify-ir", cl::Hidden, 171 cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"), 172 cl::init(false)); 173 174 static cl::opt<unsigned> MulOpsInlineThreshold( 175 "scev-mulops-inline-threshold", cl::Hidden, 176 cl::desc("Threshold for inlining multiplication operands into a SCEV"), 177 cl::init(32)); 178 179 static cl::opt<unsigned> AddOpsInlineThreshold( 180 "scev-addops-inline-threshold", cl::Hidden, 181 cl::desc("Threshold for inlining addition operands into a SCEV"), 182 cl::init(500)); 183 184 static cl::opt<unsigned> MaxSCEVCompareDepth( 185 "scalar-evolution-max-scev-compare-depth", cl::Hidden, 186 cl::desc("Maximum depth of recursive SCEV complexity comparisons"), 187 cl::init(32)); 188 189 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth( 190 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden, 191 cl::desc("Maximum depth of recursive SCEV operations implication analysis"), 192 cl::init(2)); 193 194 static cl::opt<unsigned> MaxValueCompareDepth( 195 "scalar-evolution-max-value-compare-depth", cl::Hidden, 196 cl::desc("Maximum depth of recursive value complexity comparisons"), 197 cl::init(2)); 198 199 static cl::opt<unsigned> 200 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden, 201 cl::desc("Maximum depth of recursive arithmetics"), 202 cl::init(32)); 203 204 static cl::opt<unsigned> MaxConstantEvolvingDepth( 205 "scalar-evolution-max-constant-evolving-depth", cl::Hidden, 206 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32)); 207 208 static cl::opt<unsigned> 209 MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden, 210 cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"), 211 cl::init(8)); 212 213 static cl::opt<unsigned> 214 MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden, 215 cl::desc("Max coefficients in AddRec during evolving"), 216 cl::init(8)); 217 218 static cl::opt<unsigned> 219 HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden, 220 cl::desc("Size of the expression which is considered huge"), 221 cl::init(4096)); 222 223 static cl::opt<bool> 224 ClassifyExpressions("scalar-evolution-classify-expressions", 225 cl::Hidden, cl::init(true), 226 cl::desc("When printing analysis, include information on every instruction")); 227 228 static cl::opt<bool> UseExpensiveRangeSharpening( 229 "scalar-evolution-use-expensive-range-sharpening", cl::Hidden, 230 cl::init(false), 231 cl::desc("Use more powerful methods of sharpening expression ranges. May " 232 "be costly in terms of compile time")); 233 234 //===----------------------------------------------------------------------===// 235 // SCEV class definitions 236 //===----------------------------------------------------------------------===// 237 238 //===----------------------------------------------------------------------===// 239 // Implementation of the SCEV class. 240 // 241 242 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 243 LLVM_DUMP_METHOD void SCEV::dump() const { 244 print(dbgs()); 245 dbgs() << '\n'; 246 } 247 #endif 248 249 void SCEV::print(raw_ostream &OS) const { 250 switch (getSCEVType()) { 251 case scConstant: 252 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false); 253 return; 254 case scPtrToInt: { 255 const SCEVPtrToIntExpr *PtrToInt = cast<SCEVPtrToIntExpr>(this); 256 const SCEV *Op = PtrToInt->getOperand(); 257 OS << "(ptrtoint " << *Op->getType() << " " << *Op << " to " 258 << *PtrToInt->getType() << ")"; 259 return; 260 } 261 case scTruncate: { 262 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this); 263 const SCEV *Op = Trunc->getOperand(); 264 OS << "(trunc " << *Op->getType() << " " << *Op << " to " 265 << *Trunc->getType() << ")"; 266 return; 267 } 268 case scZeroExtend: { 269 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this); 270 const SCEV *Op = ZExt->getOperand(); 271 OS << "(zext " << *Op->getType() << " " << *Op << " to " 272 << *ZExt->getType() << ")"; 273 return; 274 } 275 case scSignExtend: { 276 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this); 277 const SCEV *Op = SExt->getOperand(); 278 OS << "(sext " << *Op->getType() << " " << *Op << " to " 279 << *SExt->getType() << ")"; 280 return; 281 } 282 case scAddRecExpr: { 283 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this); 284 OS << "{" << *AR->getOperand(0); 285 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i) 286 OS << ",+," << *AR->getOperand(i); 287 OS << "}<"; 288 if (AR->hasNoUnsignedWrap()) 289 OS << "nuw><"; 290 if (AR->hasNoSignedWrap()) 291 OS << "nsw><"; 292 if (AR->hasNoSelfWrap() && 293 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW))) 294 OS << "nw><"; 295 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false); 296 OS << ">"; 297 return; 298 } 299 case scAddExpr: 300 case scMulExpr: 301 case scUMaxExpr: 302 case scSMaxExpr: 303 case scUMinExpr: 304 case scSMinExpr: 305 case scSequentialUMinExpr: { 306 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this); 307 const char *OpStr = nullptr; 308 switch (NAry->getSCEVType()) { 309 case scAddExpr: OpStr = " + "; break; 310 case scMulExpr: OpStr = " * "; break; 311 case scUMaxExpr: OpStr = " umax "; break; 312 case scSMaxExpr: OpStr = " smax "; break; 313 case scUMinExpr: 314 OpStr = " umin "; 315 break; 316 case scSMinExpr: 317 OpStr = " smin "; 318 break; 319 case scSequentialUMinExpr: 320 OpStr = " umin_seq "; 321 break; 322 default: 323 llvm_unreachable("There are no other nary expression types."); 324 } 325 OS << "("; 326 ListSeparator LS(OpStr); 327 for (const SCEV *Op : NAry->operands()) 328 OS << LS << *Op; 329 OS << ")"; 330 switch (NAry->getSCEVType()) { 331 case scAddExpr: 332 case scMulExpr: 333 if (NAry->hasNoUnsignedWrap()) 334 OS << "<nuw>"; 335 if (NAry->hasNoSignedWrap()) 336 OS << "<nsw>"; 337 break; 338 default: 339 // Nothing to print for other nary expressions. 340 break; 341 } 342 return; 343 } 344 case scUDivExpr: { 345 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this); 346 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")"; 347 return; 348 } 349 case scUnknown: { 350 const SCEVUnknown *U = cast<SCEVUnknown>(this); 351 Type *AllocTy; 352 if (U->isSizeOf(AllocTy)) { 353 OS << "sizeof(" << *AllocTy << ")"; 354 return; 355 } 356 if (U->isAlignOf(AllocTy)) { 357 OS << "alignof(" << *AllocTy << ")"; 358 return; 359 } 360 361 Type *CTy; 362 Constant *FieldNo; 363 if (U->isOffsetOf(CTy, FieldNo)) { 364 OS << "offsetof(" << *CTy << ", "; 365 FieldNo->printAsOperand(OS, false); 366 OS << ")"; 367 return; 368 } 369 370 // Otherwise just print it normally. 371 U->getValue()->printAsOperand(OS, false); 372 return; 373 } 374 case scCouldNotCompute: 375 OS << "***COULDNOTCOMPUTE***"; 376 return; 377 } 378 llvm_unreachable("Unknown SCEV kind!"); 379 } 380 381 Type *SCEV::getType() const { 382 switch (getSCEVType()) { 383 case scConstant: 384 return cast<SCEVConstant>(this)->getType(); 385 case scPtrToInt: 386 case scTruncate: 387 case scZeroExtend: 388 case scSignExtend: 389 return cast<SCEVCastExpr>(this)->getType(); 390 case scAddRecExpr: 391 return cast<SCEVAddRecExpr>(this)->getType(); 392 case scMulExpr: 393 return cast<SCEVMulExpr>(this)->getType(); 394 case scUMaxExpr: 395 case scSMaxExpr: 396 case scUMinExpr: 397 case scSMinExpr: 398 return cast<SCEVMinMaxExpr>(this)->getType(); 399 case scSequentialUMinExpr: 400 return cast<SCEVSequentialMinMaxExpr>(this)->getType(); 401 case scAddExpr: 402 return cast<SCEVAddExpr>(this)->getType(); 403 case scUDivExpr: 404 return cast<SCEVUDivExpr>(this)->getType(); 405 case scUnknown: 406 return cast<SCEVUnknown>(this)->getType(); 407 case scCouldNotCompute: 408 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 409 } 410 llvm_unreachable("Unknown SCEV kind!"); 411 } 412 413 bool SCEV::isZero() const { 414 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 415 return SC->getValue()->isZero(); 416 return false; 417 } 418 419 bool SCEV::isOne() const { 420 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 421 return SC->getValue()->isOne(); 422 return false; 423 } 424 425 bool SCEV::isAllOnesValue() const { 426 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 427 return SC->getValue()->isMinusOne(); 428 return false; 429 } 430 431 bool SCEV::isNonConstantNegative() const { 432 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this); 433 if (!Mul) return false; 434 435 // If there is a constant factor, it will be first. 436 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); 437 if (!SC) return false; 438 439 // Return true if the value is negative, this matches things like (-42 * V). 440 return SC->getAPInt().isNegative(); 441 } 442 443 SCEVCouldNotCompute::SCEVCouldNotCompute() : 444 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {} 445 446 bool SCEVCouldNotCompute::classof(const SCEV *S) { 447 return S->getSCEVType() == scCouldNotCompute; 448 } 449 450 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) { 451 FoldingSetNodeID ID; 452 ID.AddInteger(scConstant); 453 ID.AddPointer(V); 454 void *IP = nullptr; 455 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 456 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V); 457 UniqueSCEVs.InsertNode(S, IP); 458 return S; 459 } 460 461 const SCEV *ScalarEvolution::getConstant(const APInt &Val) { 462 return getConstant(ConstantInt::get(getContext(), Val)); 463 } 464 465 const SCEV * 466 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) { 467 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty)); 468 return getConstant(ConstantInt::get(ITy, V, isSigned)); 469 } 470 471 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy, 472 const SCEV *op, Type *ty) 473 : SCEV(ID, SCEVTy, computeExpressionSize(op)), Ty(ty) { 474 Operands[0] = op; 475 } 476 477 SCEVPtrToIntExpr::SCEVPtrToIntExpr(const FoldingSetNodeIDRef ID, const SCEV *Op, 478 Type *ITy) 479 : SCEVCastExpr(ID, scPtrToInt, Op, ITy) { 480 assert(getOperand()->getType()->isPointerTy() && Ty->isIntegerTy() && 481 "Must be a non-bit-width-changing pointer-to-integer cast!"); 482 } 483 484 SCEVIntegralCastExpr::SCEVIntegralCastExpr(const FoldingSetNodeIDRef ID, 485 SCEVTypes SCEVTy, const SCEV *op, 486 Type *ty) 487 : SCEVCastExpr(ID, SCEVTy, op, ty) {} 488 489 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, const SCEV *op, 490 Type *ty) 491 : SCEVIntegralCastExpr(ID, scTruncate, op, ty) { 492 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 493 "Cannot truncate non-integer value!"); 494 } 495 496 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, 497 const SCEV *op, Type *ty) 498 : SCEVIntegralCastExpr(ID, scZeroExtend, op, ty) { 499 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 500 "Cannot zero extend non-integer value!"); 501 } 502 503 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, 504 const SCEV *op, Type *ty) 505 : SCEVIntegralCastExpr(ID, scSignExtend, op, ty) { 506 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 507 "Cannot sign extend non-integer value!"); 508 } 509 510 void SCEVUnknown::deleted() { 511 // Clear this SCEVUnknown from various maps. 512 SE->forgetMemoizedResults(this); 513 514 // Remove this SCEVUnknown from the uniquing map. 515 SE->UniqueSCEVs.RemoveNode(this); 516 517 // Release the value. 518 setValPtr(nullptr); 519 } 520 521 void SCEVUnknown::allUsesReplacedWith(Value *New) { 522 // Remove this SCEVUnknown from the uniquing map. 523 SE->UniqueSCEVs.RemoveNode(this); 524 525 // Update this SCEVUnknown to point to the new value. This is needed 526 // because there may still be outstanding SCEVs which still point to 527 // this SCEVUnknown. 528 setValPtr(New); 529 } 530 531 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const { 532 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 533 if (VCE->getOpcode() == Instruction::PtrToInt) 534 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 535 if (CE->getOpcode() == Instruction::GetElementPtr && 536 CE->getOperand(0)->isNullValue() && 537 CE->getNumOperands() == 2) 538 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1))) 539 if (CI->isOne()) { 540 AllocTy = cast<GEPOperator>(CE)->getSourceElementType(); 541 return true; 542 } 543 544 return false; 545 } 546 547 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const { 548 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 549 if (VCE->getOpcode() == Instruction::PtrToInt) 550 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 551 if (CE->getOpcode() == Instruction::GetElementPtr && 552 CE->getOperand(0)->isNullValue()) { 553 Type *Ty = cast<GEPOperator>(CE)->getSourceElementType(); 554 if (StructType *STy = dyn_cast<StructType>(Ty)) 555 if (!STy->isPacked() && 556 CE->getNumOperands() == 3 && 557 CE->getOperand(1)->isNullValue()) { 558 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2))) 559 if (CI->isOne() && 560 STy->getNumElements() == 2 && 561 STy->getElementType(0)->isIntegerTy(1)) { 562 AllocTy = STy->getElementType(1); 563 return true; 564 } 565 } 566 } 567 568 return false; 569 } 570 571 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const { 572 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 573 if (VCE->getOpcode() == Instruction::PtrToInt) 574 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 575 if (CE->getOpcode() == Instruction::GetElementPtr && 576 CE->getNumOperands() == 3 && 577 CE->getOperand(0)->isNullValue() && 578 CE->getOperand(1)->isNullValue()) { 579 Type *Ty = cast<GEPOperator>(CE)->getSourceElementType(); 580 // Ignore vector types here so that ScalarEvolutionExpander doesn't 581 // emit getelementptrs that index into vectors. 582 if (Ty->isStructTy() || Ty->isArrayTy()) { 583 CTy = Ty; 584 FieldNo = CE->getOperand(2); 585 return true; 586 } 587 } 588 589 return false; 590 } 591 592 //===----------------------------------------------------------------------===// 593 // SCEV Utilities 594 //===----------------------------------------------------------------------===// 595 596 /// Compare the two values \p LV and \p RV in terms of their "complexity" where 597 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order 598 /// operands in SCEV expressions. \p EqCache is a set of pairs of values that 599 /// have been previously deemed to be "equally complex" by this routine. It is 600 /// intended to avoid exponential time complexity in cases like: 601 /// 602 /// %a = f(%x, %y) 603 /// %b = f(%a, %a) 604 /// %c = f(%b, %b) 605 /// 606 /// %d = f(%x, %y) 607 /// %e = f(%d, %d) 608 /// %f = f(%e, %e) 609 /// 610 /// CompareValueComplexity(%f, %c) 611 /// 612 /// Since we do not continue running this routine on expression trees once we 613 /// have seen unequal values, there is no need to track them in the cache. 614 static int 615 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue, 616 const LoopInfo *const LI, Value *LV, Value *RV, 617 unsigned Depth) { 618 if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV)) 619 return 0; 620 621 // Order pointer values after integer values. This helps SCEVExpander form 622 // GEPs. 623 bool LIsPointer = LV->getType()->isPointerTy(), 624 RIsPointer = RV->getType()->isPointerTy(); 625 if (LIsPointer != RIsPointer) 626 return (int)LIsPointer - (int)RIsPointer; 627 628 // Compare getValueID values. 629 unsigned LID = LV->getValueID(), RID = RV->getValueID(); 630 if (LID != RID) 631 return (int)LID - (int)RID; 632 633 // Sort arguments by their position. 634 if (const auto *LA = dyn_cast<Argument>(LV)) { 635 const auto *RA = cast<Argument>(RV); 636 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo(); 637 return (int)LArgNo - (int)RArgNo; 638 } 639 640 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) { 641 const auto *RGV = cast<GlobalValue>(RV); 642 643 const auto IsGVNameSemantic = [&](const GlobalValue *GV) { 644 auto LT = GV->getLinkage(); 645 return !(GlobalValue::isPrivateLinkage(LT) || 646 GlobalValue::isInternalLinkage(LT)); 647 }; 648 649 // Use the names to distinguish the two values, but only if the 650 // names are semantically important. 651 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV)) 652 return LGV->getName().compare(RGV->getName()); 653 } 654 655 // For instructions, compare their loop depth, and their operand count. This 656 // is pretty loose. 657 if (const auto *LInst = dyn_cast<Instruction>(LV)) { 658 const auto *RInst = cast<Instruction>(RV); 659 660 // Compare loop depths. 661 const BasicBlock *LParent = LInst->getParent(), 662 *RParent = RInst->getParent(); 663 if (LParent != RParent) { 664 unsigned LDepth = LI->getLoopDepth(LParent), 665 RDepth = LI->getLoopDepth(RParent); 666 if (LDepth != RDepth) 667 return (int)LDepth - (int)RDepth; 668 } 669 670 // Compare the number of operands. 671 unsigned LNumOps = LInst->getNumOperands(), 672 RNumOps = RInst->getNumOperands(); 673 if (LNumOps != RNumOps) 674 return (int)LNumOps - (int)RNumOps; 675 676 for (unsigned Idx : seq(0u, LNumOps)) { 677 int Result = 678 CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx), 679 RInst->getOperand(Idx), Depth + 1); 680 if (Result != 0) 681 return Result; 682 } 683 } 684 685 EqCacheValue.unionSets(LV, RV); 686 return 0; 687 } 688 689 // Return negative, zero, or positive, if LHS is less than, equal to, or greater 690 // than RHS, respectively. A three-way result allows recursive comparisons to be 691 // more efficient. 692 // If the max analysis depth was reached, return None, assuming we do not know 693 // if they are equivalent for sure. 694 static Optional<int> 695 CompareSCEVComplexity(EquivalenceClasses<const SCEV *> &EqCacheSCEV, 696 EquivalenceClasses<const Value *> &EqCacheValue, 697 const LoopInfo *const LI, const SCEV *LHS, 698 const SCEV *RHS, DominatorTree &DT, unsigned Depth = 0) { 699 // Fast-path: SCEVs are uniqued so we can do a quick equality check. 700 if (LHS == RHS) 701 return 0; 702 703 // Primarily, sort the SCEVs by their getSCEVType(). 704 SCEVTypes LType = LHS->getSCEVType(), RType = RHS->getSCEVType(); 705 if (LType != RType) 706 return (int)LType - (int)RType; 707 708 if (EqCacheSCEV.isEquivalent(LHS, RHS)) 709 return 0; 710 711 if (Depth > MaxSCEVCompareDepth) 712 return None; 713 714 // Aside from the getSCEVType() ordering, the particular ordering 715 // isn't very important except that it's beneficial to be consistent, 716 // so that (a + b) and (b + a) don't end up as different expressions. 717 switch (LType) { 718 case scUnknown: { 719 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS); 720 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); 721 722 int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(), 723 RU->getValue(), Depth + 1); 724 if (X == 0) 725 EqCacheSCEV.unionSets(LHS, RHS); 726 return X; 727 } 728 729 case scConstant: { 730 const SCEVConstant *LC = cast<SCEVConstant>(LHS); 731 const SCEVConstant *RC = cast<SCEVConstant>(RHS); 732 733 // Compare constant values. 734 const APInt &LA = LC->getAPInt(); 735 const APInt &RA = RC->getAPInt(); 736 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth(); 737 if (LBitWidth != RBitWidth) 738 return (int)LBitWidth - (int)RBitWidth; 739 return LA.ult(RA) ? -1 : 1; 740 } 741 742 case scAddRecExpr: { 743 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); 744 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); 745 746 // There is always a dominance between two recs that are used by one SCEV, 747 // so we can safely sort recs by loop header dominance. We require such 748 // order in getAddExpr. 749 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); 750 if (LLoop != RLoop) { 751 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader(); 752 assert(LHead != RHead && "Two loops share the same header?"); 753 if (DT.dominates(LHead, RHead)) 754 return 1; 755 else 756 assert(DT.dominates(RHead, LHead) && 757 "No dominance between recurrences used by one SCEV?"); 758 return -1; 759 } 760 761 // Addrec complexity grows with operand count. 762 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands(); 763 if (LNumOps != RNumOps) 764 return (int)LNumOps - (int)RNumOps; 765 766 // Lexicographically compare. 767 for (unsigned i = 0; i != LNumOps; ++i) { 768 auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 769 LA->getOperand(i), RA->getOperand(i), DT, 770 Depth + 1); 771 if (X != 0) 772 return X; 773 } 774 EqCacheSCEV.unionSets(LHS, RHS); 775 return 0; 776 } 777 778 case scAddExpr: 779 case scMulExpr: 780 case scSMaxExpr: 781 case scUMaxExpr: 782 case scSMinExpr: 783 case scUMinExpr: 784 case scSequentialUMinExpr: { 785 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); 786 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); 787 788 // Lexicographically compare n-ary expressions. 789 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); 790 if (LNumOps != RNumOps) 791 return (int)LNumOps - (int)RNumOps; 792 793 for (unsigned i = 0; i != LNumOps; ++i) { 794 auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 795 LC->getOperand(i), RC->getOperand(i), DT, 796 Depth + 1); 797 if (X != 0) 798 return X; 799 } 800 EqCacheSCEV.unionSets(LHS, RHS); 801 return 0; 802 } 803 804 case scUDivExpr: { 805 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); 806 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); 807 808 // Lexicographically compare udiv expressions. 809 auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(), 810 RC->getLHS(), DT, Depth + 1); 811 if (X != 0) 812 return X; 813 X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(), 814 RC->getRHS(), DT, Depth + 1); 815 if (X == 0) 816 EqCacheSCEV.unionSets(LHS, RHS); 817 return X; 818 } 819 820 case scPtrToInt: 821 case scTruncate: 822 case scZeroExtend: 823 case scSignExtend: { 824 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS); 825 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS); 826 827 // Compare cast expressions by operand. 828 auto X = 829 CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getOperand(), 830 RC->getOperand(), DT, Depth + 1); 831 if (X == 0) 832 EqCacheSCEV.unionSets(LHS, RHS); 833 return X; 834 } 835 836 case scCouldNotCompute: 837 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 838 } 839 llvm_unreachable("Unknown SCEV kind!"); 840 } 841 842 /// Given a list of SCEV objects, order them by their complexity, and group 843 /// objects of the same complexity together by value. When this routine is 844 /// finished, we know that any duplicates in the vector are consecutive and that 845 /// complexity is monotonically increasing. 846 /// 847 /// Note that we go take special precautions to ensure that we get deterministic 848 /// results from this routine. In other words, we don't want the results of 849 /// this to depend on where the addresses of various SCEV objects happened to 850 /// land in memory. 851 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, 852 LoopInfo *LI, DominatorTree &DT) { 853 if (Ops.size() < 2) return; // Noop 854 855 EquivalenceClasses<const SCEV *> EqCacheSCEV; 856 EquivalenceClasses<const Value *> EqCacheValue; 857 858 // Whether LHS has provably less complexity than RHS. 859 auto IsLessComplex = [&](const SCEV *LHS, const SCEV *RHS) { 860 auto Complexity = 861 CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT); 862 return Complexity && *Complexity < 0; 863 }; 864 if (Ops.size() == 2) { 865 // This is the common case, which also happens to be trivially simple. 866 // Special case it. 867 const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; 868 if (IsLessComplex(RHS, LHS)) 869 std::swap(LHS, RHS); 870 return; 871 } 872 873 // Do the rough sort by complexity. 874 llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) { 875 return IsLessComplex(LHS, RHS); 876 }); 877 878 // Now that we are sorted by complexity, group elements of the same 879 // complexity. Note that this is, at worst, N^2, but the vector is likely to 880 // be extremely short in practice. Note that we take this approach because we 881 // do not want to depend on the addresses of the objects we are grouping. 882 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { 883 const SCEV *S = Ops[i]; 884 unsigned Complexity = S->getSCEVType(); 885 886 // If there are any objects of the same complexity and same value as this 887 // one, group them. 888 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { 889 if (Ops[j] == S) { // Found a duplicate. 890 // Move it to immediately after i'th element. 891 std::swap(Ops[i+1], Ops[j]); 892 ++i; // no need to rescan it. 893 if (i == e-2) return; // Done! 894 } 895 } 896 } 897 } 898 899 /// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at 900 /// least HugeExprThreshold nodes). 901 static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) { 902 return any_of(Ops, [](const SCEV *S) { 903 return S->getExpressionSize() >= HugeExprThreshold; 904 }); 905 } 906 907 //===----------------------------------------------------------------------===// 908 // Simple SCEV method implementations 909 //===----------------------------------------------------------------------===// 910 911 /// Compute BC(It, K). The result has width W. Assume, K > 0. 912 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, 913 ScalarEvolution &SE, 914 Type *ResultTy) { 915 // Handle the simplest case efficiently. 916 if (K == 1) 917 return SE.getTruncateOrZeroExtend(It, ResultTy); 918 919 // We are using the following formula for BC(It, K): 920 // 921 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! 922 // 923 // Suppose, W is the bitwidth of the return value. We must be prepared for 924 // overflow. Hence, we must assure that the result of our computation is 925 // equal to the accurate one modulo 2^W. Unfortunately, division isn't 926 // safe in modular arithmetic. 927 // 928 // However, this code doesn't use exactly that formula; the formula it uses 929 // is something like the following, where T is the number of factors of 2 in 930 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is 931 // exponentiation: 932 // 933 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) 934 // 935 // This formula is trivially equivalent to the previous formula. However, 936 // this formula can be implemented much more efficiently. The trick is that 937 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular 938 // arithmetic. To do exact division in modular arithmetic, all we have 939 // to do is multiply by the inverse. Therefore, this step can be done at 940 // width W. 941 // 942 // The next issue is how to safely do the division by 2^T. The way this 943 // is done is by doing the multiplication step at a width of at least W + T 944 // bits. This way, the bottom W+T bits of the product are accurate. Then, 945 // when we perform the division by 2^T (which is equivalent to a right shift 946 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get 947 // truncated out after the division by 2^T. 948 // 949 // In comparison to just directly using the first formula, this technique 950 // is much more efficient; using the first formula requires W * K bits, 951 // but this formula less than W + K bits. Also, the first formula requires 952 // a division step, whereas this formula only requires multiplies and shifts. 953 // 954 // It doesn't matter whether the subtraction step is done in the calculation 955 // width or the input iteration count's width; if the subtraction overflows, 956 // the result must be zero anyway. We prefer here to do it in the width of 957 // the induction variable because it helps a lot for certain cases; CodeGen 958 // isn't smart enough to ignore the overflow, which leads to much less 959 // efficient code if the width of the subtraction is wider than the native 960 // register width. 961 // 962 // (It's possible to not widen at all by pulling out factors of 2 before 963 // the multiplication; for example, K=2 can be calculated as 964 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires 965 // extra arithmetic, so it's not an obvious win, and it gets 966 // much more complicated for K > 3.) 967 968 // Protection from insane SCEVs; this bound is conservative, 969 // but it probably doesn't matter. 970 if (K > 1000) 971 return SE.getCouldNotCompute(); 972 973 unsigned W = SE.getTypeSizeInBits(ResultTy); 974 975 // Calculate K! / 2^T and T; we divide out the factors of two before 976 // multiplying for calculating K! / 2^T to avoid overflow. 977 // Other overflow doesn't matter because we only care about the bottom 978 // W bits of the result. 979 APInt OddFactorial(W, 1); 980 unsigned T = 1; 981 for (unsigned i = 3; i <= K; ++i) { 982 APInt Mult(W, i); 983 unsigned TwoFactors = Mult.countTrailingZeros(); 984 T += TwoFactors; 985 Mult.lshrInPlace(TwoFactors); 986 OddFactorial *= Mult; 987 } 988 989 // We need at least W + T bits for the multiplication step 990 unsigned CalculationBits = W + T; 991 992 // Calculate 2^T, at width T+W. 993 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T); 994 995 // Calculate the multiplicative inverse of K! / 2^T; 996 // this multiplication factor will perform the exact division by 997 // K! / 2^T. 998 APInt Mod = APInt::getSignedMinValue(W+1); 999 APInt MultiplyFactor = OddFactorial.zext(W+1); 1000 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); 1001 MultiplyFactor = MultiplyFactor.trunc(W); 1002 1003 // Calculate the product, at width T+W 1004 IntegerType *CalculationTy = IntegerType::get(SE.getContext(), 1005 CalculationBits); 1006 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); 1007 for (unsigned i = 1; i != K; ++i) { 1008 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); 1009 Dividend = SE.getMulExpr(Dividend, 1010 SE.getTruncateOrZeroExtend(S, CalculationTy)); 1011 } 1012 1013 // Divide by 2^T 1014 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); 1015 1016 // Truncate the result, and divide by K! / 2^T. 1017 1018 return SE.getMulExpr(SE.getConstant(MultiplyFactor), 1019 SE.getTruncateOrZeroExtend(DivResult, ResultTy)); 1020 } 1021 1022 /// Return the value of this chain of recurrences at the specified iteration 1023 /// number. We can evaluate this recurrence by multiplying each element in the 1024 /// chain by the binomial coefficient corresponding to it. In other words, we 1025 /// can evaluate {A,+,B,+,C,+,D} as: 1026 /// 1027 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) 1028 /// 1029 /// where BC(It, k) stands for binomial coefficient. 1030 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, 1031 ScalarEvolution &SE) const { 1032 return evaluateAtIteration(makeArrayRef(op_begin(), op_end()), It, SE); 1033 } 1034 1035 const SCEV * 1036 SCEVAddRecExpr::evaluateAtIteration(ArrayRef<const SCEV *> Operands, 1037 const SCEV *It, ScalarEvolution &SE) { 1038 assert(Operands.size() > 0); 1039 const SCEV *Result = Operands[0]; 1040 for (unsigned i = 1, e = Operands.size(); i != e; ++i) { 1041 // The computation is correct in the face of overflow provided that the 1042 // multiplication is performed _after_ the evaluation of the binomial 1043 // coefficient. 1044 const SCEV *Coeff = BinomialCoefficient(It, i, SE, Result->getType()); 1045 if (isa<SCEVCouldNotCompute>(Coeff)) 1046 return Coeff; 1047 1048 Result = SE.getAddExpr(Result, SE.getMulExpr(Operands[i], Coeff)); 1049 } 1050 return Result; 1051 } 1052 1053 //===----------------------------------------------------------------------===// 1054 // SCEV Expression folder implementations 1055 //===----------------------------------------------------------------------===// 1056 1057 const SCEV *ScalarEvolution::getLosslessPtrToIntExpr(const SCEV *Op, 1058 unsigned Depth) { 1059 assert(Depth <= 1 && 1060 "getLosslessPtrToIntExpr() should self-recurse at most once."); 1061 1062 // We could be called with an integer-typed operands during SCEV rewrites. 1063 // Since the operand is an integer already, just perform zext/trunc/self cast. 1064 if (!Op->getType()->isPointerTy()) 1065 return Op; 1066 1067 // What would be an ID for such a SCEV cast expression? 1068 FoldingSetNodeID ID; 1069 ID.AddInteger(scPtrToInt); 1070 ID.AddPointer(Op); 1071 1072 void *IP = nullptr; 1073 1074 // Is there already an expression for such a cast? 1075 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 1076 return S; 1077 1078 // It isn't legal for optimizations to construct new ptrtoint expressions 1079 // for non-integral pointers. 1080 if (getDataLayout().isNonIntegralPointerType(Op->getType())) 1081 return getCouldNotCompute(); 1082 1083 Type *IntPtrTy = getDataLayout().getIntPtrType(Op->getType()); 1084 1085 // We can only trivially model ptrtoint if SCEV's effective (integer) type 1086 // is sufficiently wide to represent all possible pointer values. 1087 // We could theoretically teach SCEV to truncate wider pointers, but 1088 // that isn't implemented for now. 1089 if (getDataLayout().getTypeSizeInBits(getEffectiveSCEVType(Op->getType())) != 1090 getDataLayout().getTypeSizeInBits(IntPtrTy)) 1091 return getCouldNotCompute(); 1092 1093 // If not, is this expression something we can't reduce any further? 1094 if (auto *U = dyn_cast<SCEVUnknown>(Op)) { 1095 // Perform some basic constant folding. If the operand of the ptr2int cast 1096 // is a null pointer, don't create a ptr2int SCEV expression (that will be 1097 // left as-is), but produce a zero constant. 1098 // NOTE: We could handle a more general case, but lack motivational cases. 1099 if (isa<ConstantPointerNull>(U->getValue())) 1100 return getZero(IntPtrTy); 1101 1102 // Create an explicit cast node. 1103 // We can reuse the existing insert position since if we get here, 1104 // we won't have made any changes which would invalidate it. 1105 SCEV *S = new (SCEVAllocator) 1106 SCEVPtrToIntExpr(ID.Intern(SCEVAllocator), Op, IntPtrTy); 1107 UniqueSCEVs.InsertNode(S, IP); 1108 registerUser(S, Op); 1109 return S; 1110 } 1111 1112 assert(Depth == 0 && "getLosslessPtrToIntExpr() should not self-recurse for " 1113 "non-SCEVUnknown's."); 1114 1115 // Otherwise, we've got some expression that is more complex than just a 1116 // single SCEVUnknown. But we don't want to have a SCEVPtrToIntExpr of an 1117 // arbitrary expression, we want to have SCEVPtrToIntExpr of an SCEVUnknown 1118 // only, and the expressions must otherwise be integer-typed. 1119 // So sink the cast down to the SCEVUnknown's. 1120 1121 /// The SCEVPtrToIntSinkingRewriter takes a scalar evolution expression, 1122 /// which computes a pointer-typed value, and rewrites the whole expression 1123 /// tree so that *all* the computations are done on integers, and the only 1124 /// pointer-typed operands in the expression are SCEVUnknown. 1125 class SCEVPtrToIntSinkingRewriter 1126 : public SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter> { 1127 using Base = SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter>; 1128 1129 public: 1130 SCEVPtrToIntSinkingRewriter(ScalarEvolution &SE) : SCEVRewriteVisitor(SE) {} 1131 1132 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE) { 1133 SCEVPtrToIntSinkingRewriter Rewriter(SE); 1134 return Rewriter.visit(Scev); 1135 } 1136 1137 const SCEV *visit(const SCEV *S) { 1138 Type *STy = S->getType(); 1139 // If the expression is not pointer-typed, just keep it as-is. 1140 if (!STy->isPointerTy()) 1141 return S; 1142 // Else, recursively sink the cast down into it. 1143 return Base::visit(S); 1144 } 1145 1146 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) { 1147 SmallVector<const SCEV *, 2> Operands; 1148 bool Changed = false; 1149 for (auto *Op : Expr->operands()) { 1150 Operands.push_back(visit(Op)); 1151 Changed |= Op != Operands.back(); 1152 } 1153 return !Changed ? Expr : SE.getAddExpr(Operands, Expr->getNoWrapFlags()); 1154 } 1155 1156 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) { 1157 SmallVector<const SCEV *, 2> Operands; 1158 bool Changed = false; 1159 for (auto *Op : Expr->operands()) { 1160 Operands.push_back(visit(Op)); 1161 Changed |= Op != Operands.back(); 1162 } 1163 return !Changed ? Expr : SE.getMulExpr(Operands, Expr->getNoWrapFlags()); 1164 } 1165 1166 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 1167 assert(Expr->getType()->isPointerTy() && 1168 "Should only reach pointer-typed SCEVUnknown's."); 1169 return SE.getLosslessPtrToIntExpr(Expr, /*Depth=*/1); 1170 } 1171 }; 1172 1173 // And actually perform the cast sinking. 1174 const SCEV *IntOp = SCEVPtrToIntSinkingRewriter::rewrite(Op, *this); 1175 assert(IntOp->getType()->isIntegerTy() && 1176 "We must have succeeded in sinking the cast, " 1177 "and ending up with an integer-typed expression!"); 1178 return IntOp; 1179 } 1180 1181 const SCEV *ScalarEvolution::getPtrToIntExpr(const SCEV *Op, Type *Ty) { 1182 assert(Ty->isIntegerTy() && "Target type must be an integer type!"); 1183 1184 const SCEV *IntOp = getLosslessPtrToIntExpr(Op); 1185 if (isa<SCEVCouldNotCompute>(IntOp)) 1186 return IntOp; 1187 1188 return getTruncateOrZeroExtend(IntOp, Ty); 1189 } 1190 1191 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty, 1192 unsigned Depth) { 1193 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && 1194 "This is not a truncating conversion!"); 1195 assert(isSCEVable(Ty) && 1196 "This is not a conversion to a SCEVable type!"); 1197 assert(!Op->getType()->isPointerTy() && "Can't truncate pointer!"); 1198 Ty = getEffectiveSCEVType(Ty); 1199 1200 FoldingSetNodeID ID; 1201 ID.AddInteger(scTruncate); 1202 ID.AddPointer(Op); 1203 ID.AddPointer(Ty); 1204 void *IP = nullptr; 1205 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1206 1207 // Fold if the operand is constant. 1208 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1209 return getConstant( 1210 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); 1211 1212 // trunc(trunc(x)) --> trunc(x) 1213 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) 1214 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1); 1215 1216 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing 1217 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1218 return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1); 1219 1220 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing 1221 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1222 return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1); 1223 1224 if (Depth > MaxCastDepth) { 1225 SCEV *S = 1226 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty); 1227 UniqueSCEVs.InsertNode(S, IP); 1228 registerUser(S, Op); 1229 return S; 1230 } 1231 1232 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and 1233 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN), 1234 // if after transforming we have at most one truncate, not counting truncates 1235 // that replace other casts. 1236 if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) { 1237 auto *CommOp = cast<SCEVCommutativeExpr>(Op); 1238 SmallVector<const SCEV *, 4> Operands; 1239 unsigned numTruncs = 0; 1240 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2; 1241 ++i) { 1242 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1); 1243 if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) && 1244 isa<SCEVTruncateExpr>(S)) 1245 numTruncs++; 1246 Operands.push_back(S); 1247 } 1248 if (numTruncs < 2) { 1249 if (isa<SCEVAddExpr>(Op)) 1250 return getAddExpr(Operands); 1251 else if (isa<SCEVMulExpr>(Op)) 1252 return getMulExpr(Operands); 1253 else 1254 llvm_unreachable("Unexpected SCEV type for Op."); 1255 } 1256 // Although we checked in the beginning that ID is not in the cache, it is 1257 // possible that during recursion and different modification ID was inserted 1258 // into the cache. So if we find it, just return it. 1259 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 1260 return S; 1261 } 1262 1263 // If the input value is a chrec scev, truncate the chrec's operands. 1264 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 1265 SmallVector<const SCEV *, 4> Operands; 1266 for (const SCEV *Op : AddRec->operands()) 1267 Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1)); 1268 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap); 1269 } 1270 1271 // Return zero if truncating to known zeros. 1272 uint32_t MinTrailingZeros = GetMinTrailingZeros(Op); 1273 if (MinTrailingZeros >= getTypeSizeInBits(Ty)) 1274 return getZero(Ty); 1275 1276 // The cast wasn't folded; create an explicit cast node. We can reuse 1277 // the existing insert position since if we get here, we won't have 1278 // made any changes which would invalidate it. 1279 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), 1280 Op, Ty); 1281 UniqueSCEVs.InsertNode(S, IP); 1282 registerUser(S, Op); 1283 return S; 1284 } 1285 1286 // Get the limit of a recurrence such that incrementing by Step cannot cause 1287 // signed overflow as long as the value of the recurrence within the 1288 // loop does not exceed this limit before incrementing. 1289 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step, 1290 ICmpInst::Predicate *Pred, 1291 ScalarEvolution *SE) { 1292 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1293 if (SE->isKnownPositive(Step)) { 1294 *Pred = ICmpInst::ICMP_SLT; 1295 return SE->getConstant(APInt::getSignedMinValue(BitWidth) - 1296 SE->getSignedRangeMax(Step)); 1297 } 1298 if (SE->isKnownNegative(Step)) { 1299 *Pred = ICmpInst::ICMP_SGT; 1300 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - 1301 SE->getSignedRangeMin(Step)); 1302 } 1303 return nullptr; 1304 } 1305 1306 // Get the limit of a recurrence such that incrementing by Step cannot cause 1307 // unsigned overflow as long as the value of the recurrence within the loop does 1308 // not exceed this limit before incrementing. 1309 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step, 1310 ICmpInst::Predicate *Pred, 1311 ScalarEvolution *SE) { 1312 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1313 *Pred = ICmpInst::ICMP_ULT; 1314 1315 return SE->getConstant(APInt::getMinValue(BitWidth) - 1316 SE->getUnsignedRangeMax(Step)); 1317 } 1318 1319 namespace { 1320 1321 struct ExtendOpTraitsBase { 1322 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *, 1323 unsigned); 1324 }; 1325 1326 // Used to make code generic over signed and unsigned overflow. 1327 template <typename ExtendOp> struct ExtendOpTraits { 1328 // Members present: 1329 // 1330 // static const SCEV::NoWrapFlags WrapType; 1331 // 1332 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr; 1333 // 1334 // static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1335 // ICmpInst::Predicate *Pred, 1336 // ScalarEvolution *SE); 1337 }; 1338 1339 template <> 1340 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase { 1341 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW; 1342 1343 static const GetExtendExprTy GetExtendExpr; 1344 1345 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1346 ICmpInst::Predicate *Pred, 1347 ScalarEvolution *SE) { 1348 return getSignedOverflowLimitForStep(Step, Pred, SE); 1349 } 1350 }; 1351 1352 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1353 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr; 1354 1355 template <> 1356 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase { 1357 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW; 1358 1359 static const GetExtendExprTy GetExtendExpr; 1360 1361 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1362 ICmpInst::Predicate *Pred, 1363 ScalarEvolution *SE) { 1364 return getUnsignedOverflowLimitForStep(Step, Pred, SE); 1365 } 1366 }; 1367 1368 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1369 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr; 1370 1371 } // end anonymous namespace 1372 1373 // The recurrence AR has been shown to have no signed/unsigned wrap or something 1374 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as 1375 // easily prove NSW/NUW for its preincrement or postincrement sibling. This 1376 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step + 1377 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the 1378 // expression "Step + sext/zext(PreIncAR)" is congruent with 1379 // "sext/zext(PostIncAR)" 1380 template <typename ExtendOpTy> 1381 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, 1382 ScalarEvolution *SE, unsigned Depth) { 1383 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1384 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1385 1386 const Loop *L = AR->getLoop(); 1387 const SCEV *Start = AR->getStart(); 1388 const SCEV *Step = AR->getStepRecurrence(*SE); 1389 1390 // Check for a simple looking step prior to loop entry. 1391 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); 1392 if (!SA) 1393 return nullptr; 1394 1395 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV 1396 // subtraction is expensive. For this purpose, perform a quick and dirty 1397 // difference, by checking for Step in the operand list. 1398 SmallVector<const SCEV *, 4> DiffOps; 1399 for (const SCEV *Op : SA->operands()) 1400 if (Op != Step) 1401 DiffOps.push_back(Op); 1402 1403 if (DiffOps.size() == SA->getNumOperands()) 1404 return nullptr; 1405 1406 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` + 1407 // `Step`: 1408 1409 // 1. NSW/NUW flags on the step increment. 1410 auto PreStartFlags = 1411 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW); 1412 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags); 1413 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( 1414 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); 1415 1416 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies 1417 // "S+X does not sign/unsign-overflow". 1418 // 1419 1420 const SCEV *BECount = SE->getBackedgeTakenCount(L); 1421 if (PreAR && PreAR->getNoWrapFlags(WrapType) && 1422 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) 1423 return PreStart; 1424 1425 // 2. Direct overflow check on the step operation's expression. 1426 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); 1427 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); 1428 const SCEV *OperandExtendedStart = 1429 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth), 1430 (SE->*GetExtendExpr)(Step, WideTy, Depth)); 1431 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) { 1432 if (PreAR && AR->getNoWrapFlags(WrapType)) { 1433 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW 1434 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then 1435 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. 1436 SE->setNoWrapFlags(const_cast<SCEVAddRecExpr *>(PreAR), WrapType); 1437 } 1438 return PreStart; 1439 } 1440 1441 // 3. Loop precondition. 1442 ICmpInst::Predicate Pred; 1443 const SCEV *OverflowLimit = 1444 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); 1445 1446 if (OverflowLimit && 1447 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) 1448 return PreStart; 1449 1450 return nullptr; 1451 } 1452 1453 // Get the normalized zero or sign extended expression for this AddRec's Start. 1454 template <typename ExtendOpTy> 1455 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, 1456 ScalarEvolution *SE, 1457 unsigned Depth) { 1458 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1459 1460 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth); 1461 if (!PreStart) 1462 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth); 1463 1464 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty, 1465 Depth), 1466 (SE->*GetExtendExpr)(PreStart, Ty, Depth)); 1467 } 1468 1469 // Try to prove away overflow by looking at "nearby" add recurrences. A 1470 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it 1471 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. 1472 // 1473 // Formally: 1474 // 1475 // {S,+,X} == {S-T,+,X} + T 1476 // => Ext({S,+,X}) == Ext({S-T,+,X} + T) 1477 // 1478 // If ({S-T,+,X} + T) does not overflow ... (1) 1479 // 1480 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) 1481 // 1482 // If {S-T,+,X} does not overflow ... (2) 1483 // 1484 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) 1485 // == {Ext(S-T)+Ext(T),+,Ext(X)} 1486 // 1487 // If (S-T)+T does not overflow ... (3) 1488 // 1489 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} 1490 // == {Ext(S),+,Ext(X)} == LHS 1491 // 1492 // Thus, if (1), (2) and (3) are true for some T, then 1493 // Ext({S,+,X}) == {Ext(S),+,Ext(X)} 1494 // 1495 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) 1496 // does not overflow" restricted to the 0th iteration. Therefore we only need 1497 // to check for (1) and (2). 1498 // 1499 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T 1500 // is `Delta` (defined below). 1501 template <typename ExtendOpTy> 1502 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, 1503 const SCEV *Step, 1504 const Loop *L) { 1505 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1506 1507 // We restrict `Start` to a constant to prevent SCEV from spending too much 1508 // time here. It is correct (but more expensive) to continue with a 1509 // non-constant `Start` and do a general SCEV subtraction to compute 1510 // `PreStart` below. 1511 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); 1512 if (!StartC) 1513 return false; 1514 1515 APInt StartAI = StartC->getAPInt(); 1516 1517 for (unsigned Delta : {-2, -1, 1, 2}) { 1518 const SCEV *PreStart = getConstant(StartAI - Delta); 1519 1520 FoldingSetNodeID ID; 1521 ID.AddInteger(scAddRecExpr); 1522 ID.AddPointer(PreStart); 1523 ID.AddPointer(Step); 1524 ID.AddPointer(L); 1525 void *IP = nullptr; 1526 const auto *PreAR = 1527 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 1528 1529 // Give up if we don't already have the add recurrence we need because 1530 // actually constructing an add recurrence is relatively expensive. 1531 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2) 1532 const SCEV *DeltaS = getConstant(StartC->getType(), Delta); 1533 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; 1534 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep( 1535 DeltaS, &Pred, this); 1536 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1) 1537 return true; 1538 } 1539 } 1540 1541 return false; 1542 } 1543 1544 // Finds an integer D for an expression (C + x + y + ...) such that the top 1545 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or 1546 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is 1547 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and 1548 // the (C + x + y + ...) expression is \p WholeAddExpr. 1549 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1550 const SCEVConstant *ConstantTerm, 1551 const SCEVAddExpr *WholeAddExpr) { 1552 const APInt &C = ConstantTerm->getAPInt(); 1553 const unsigned BitWidth = C.getBitWidth(); 1554 // Find number of trailing zeros of (x + y + ...) w/o the C first: 1555 uint32_t TZ = BitWidth; 1556 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I) 1557 TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I))); 1558 if (TZ) { 1559 // Set D to be as many least significant bits of C as possible while still 1560 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap: 1561 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C; 1562 } 1563 return APInt(BitWidth, 0); 1564 } 1565 1566 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top 1567 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the 1568 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p 1569 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count. 1570 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1571 const APInt &ConstantStart, 1572 const SCEV *Step) { 1573 const unsigned BitWidth = ConstantStart.getBitWidth(); 1574 const uint32_t TZ = SE.GetMinTrailingZeros(Step); 1575 if (TZ) 1576 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth) 1577 : ConstantStart; 1578 return APInt(BitWidth, 0); 1579 } 1580 1581 const SCEV * 1582 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1583 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1584 "This is not an extending conversion!"); 1585 assert(isSCEVable(Ty) && 1586 "This is not a conversion to a SCEVable type!"); 1587 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!"); 1588 Ty = getEffectiveSCEVType(Ty); 1589 1590 // Fold if the operand is constant. 1591 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1592 return getConstant( 1593 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty))); 1594 1595 // zext(zext(x)) --> zext(x) 1596 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1597 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1598 1599 // Before doing any expensive analysis, check to see if we've already 1600 // computed a SCEV for this Op and Ty. 1601 FoldingSetNodeID ID; 1602 ID.AddInteger(scZeroExtend); 1603 ID.AddPointer(Op); 1604 ID.AddPointer(Ty); 1605 void *IP = nullptr; 1606 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1607 if (Depth > MaxCastDepth) { 1608 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1609 Op, Ty); 1610 UniqueSCEVs.InsertNode(S, IP); 1611 registerUser(S, Op); 1612 return S; 1613 } 1614 1615 // zext(trunc(x)) --> zext(x) or x or trunc(x) 1616 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1617 // It's possible the bits taken off by the truncate were all zero bits. If 1618 // so, we should be able to simplify this further. 1619 const SCEV *X = ST->getOperand(); 1620 ConstantRange CR = getUnsignedRange(X); 1621 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1622 unsigned NewBits = getTypeSizeInBits(Ty); 1623 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( 1624 CR.zextOrTrunc(NewBits))) 1625 return getTruncateOrZeroExtend(X, Ty, Depth); 1626 } 1627 1628 // If the input value is a chrec scev, and we can prove that the value 1629 // did not overflow the old, smaller, value, we can zero extend all of the 1630 // operands (often constants). This allows analysis of something like 1631 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } 1632 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1633 if (AR->isAffine()) { 1634 const SCEV *Start = AR->getStart(); 1635 const SCEV *Step = AR->getStepRecurrence(*this); 1636 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1637 const Loop *L = AR->getLoop(); 1638 1639 if (!AR->hasNoUnsignedWrap()) { 1640 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1641 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags); 1642 } 1643 1644 // If we have special knowledge that this addrec won't overflow, 1645 // we don't need to do any further analysis. 1646 if (AR->hasNoUnsignedWrap()) 1647 return getAddRecExpr( 1648 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1649 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1650 1651 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1652 // Note that this serves two purposes: It filters out loops that are 1653 // simply not analyzable, and it covers the case where this code is 1654 // being called from within backedge-taken count analysis, such that 1655 // attempting to ask for the backedge-taken count would likely result 1656 // in infinite recursion. In the later case, the analysis code will 1657 // cope with a conservative value, and it will take care to purge 1658 // that value once it has finished. 1659 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 1660 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1661 // Manually compute the final value for AR, checking for overflow. 1662 1663 // Check whether the backedge-taken count can be losslessly casted to 1664 // the addrec's type. The count is always unsigned. 1665 const SCEV *CastedMaxBECount = 1666 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 1667 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 1668 CastedMaxBECount, MaxBECount->getType(), Depth); 1669 if (MaxBECount == RecastedMaxBECount) { 1670 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1671 // Check whether Start+Step*MaxBECount has no unsigned overflow. 1672 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step, 1673 SCEV::FlagAnyWrap, Depth + 1); 1674 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul, 1675 SCEV::FlagAnyWrap, 1676 Depth + 1), 1677 WideTy, Depth + 1); 1678 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1); 1679 const SCEV *WideMaxBECount = 1680 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 1681 const SCEV *OperandExtendedAdd = 1682 getAddExpr(WideStart, 1683 getMulExpr(WideMaxBECount, 1684 getZeroExtendExpr(Step, WideTy, Depth + 1), 1685 SCEV::FlagAnyWrap, Depth + 1), 1686 SCEV::FlagAnyWrap, Depth + 1); 1687 if (ZAdd == OperandExtendedAdd) { 1688 // Cache knowledge of AR NUW, which is propagated to this AddRec. 1689 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW); 1690 // Return the expression with the addrec on the outside. 1691 return getAddRecExpr( 1692 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1693 Depth + 1), 1694 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1695 AR->getNoWrapFlags()); 1696 } 1697 // Similar to above, only this time treat the step value as signed. 1698 // This covers loops that count down. 1699 OperandExtendedAdd = 1700 getAddExpr(WideStart, 1701 getMulExpr(WideMaxBECount, 1702 getSignExtendExpr(Step, WideTy, Depth + 1), 1703 SCEV::FlagAnyWrap, Depth + 1), 1704 SCEV::FlagAnyWrap, Depth + 1); 1705 if (ZAdd == OperandExtendedAdd) { 1706 // Cache knowledge of AR NW, which is propagated to this AddRec. 1707 // Negative step causes unsigned wrap, but it still can't self-wrap. 1708 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW); 1709 // Return the expression with the addrec on the outside. 1710 return getAddRecExpr( 1711 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1712 Depth + 1), 1713 getSignExtendExpr(Step, Ty, Depth + 1), L, 1714 AR->getNoWrapFlags()); 1715 } 1716 } 1717 } 1718 1719 // Normally, in the cases we can prove no-overflow via a 1720 // backedge guarding condition, we can also compute a backedge 1721 // taken count for the loop. The exceptions are assumptions and 1722 // guards present in the loop -- SCEV is not great at exploiting 1723 // these to compute max backedge taken counts, but can still use 1724 // these to prove lack of overflow. Use this fact to avoid 1725 // doing extra work that may not pay off. 1726 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1727 !AC.assumptions().empty()) { 1728 1729 auto NewFlags = proveNoUnsignedWrapViaInduction(AR); 1730 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags); 1731 if (AR->hasNoUnsignedWrap()) { 1732 // Same as nuw case above - duplicated here to avoid a compile time 1733 // issue. It's not clear that the order of checks does matter, but 1734 // it's one of two issue possible causes for a change which was 1735 // reverted. Be conservative for the moment. 1736 return getAddRecExpr( 1737 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1738 Depth + 1), 1739 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1740 AR->getNoWrapFlags()); 1741 } 1742 1743 // For a negative step, we can extend the operands iff doing so only 1744 // traverses values in the range zext([0,UINT_MAX]). 1745 if (isKnownNegative(Step)) { 1746 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - 1747 getSignedRangeMin(Step)); 1748 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || 1749 isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) { 1750 // Cache knowledge of AR NW, which is propagated to this 1751 // AddRec. Negative step causes unsigned wrap, but it 1752 // still can't self-wrap. 1753 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW); 1754 // Return the expression with the addrec on the outside. 1755 return getAddRecExpr( 1756 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1757 Depth + 1), 1758 getSignExtendExpr(Step, Ty, Depth + 1), L, 1759 AR->getNoWrapFlags()); 1760 } 1761 } 1762 } 1763 1764 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw> 1765 // if D + (C - D + Step * n) could be proven to not unsigned wrap 1766 // where D maximizes the number of trailing zeros of (C - D + Step * n) 1767 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 1768 const APInt &C = SC->getAPInt(); 1769 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 1770 if (D != 0) { 1771 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1772 const SCEV *SResidual = 1773 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 1774 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1775 return getAddExpr(SZExtD, SZExtR, 1776 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1777 Depth + 1); 1778 } 1779 } 1780 1781 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { 1782 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW); 1783 return getAddRecExpr( 1784 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1785 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1786 } 1787 } 1788 1789 // zext(A % B) --> zext(A) % zext(B) 1790 { 1791 const SCEV *LHS; 1792 const SCEV *RHS; 1793 if (matchURem(Op, LHS, RHS)) 1794 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1), 1795 getZeroExtendExpr(RHS, Ty, Depth + 1)); 1796 } 1797 1798 // zext(A / B) --> zext(A) / zext(B). 1799 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op)) 1800 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1), 1801 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1)); 1802 1803 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1804 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> 1805 if (SA->hasNoUnsignedWrap()) { 1806 // If the addition does not unsign overflow then we can, by definition, 1807 // commute the zero extension with the addition operation. 1808 SmallVector<const SCEV *, 4> Ops; 1809 for (const auto *Op : SA->operands()) 1810 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1811 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1); 1812 } 1813 1814 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...)) 1815 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap 1816 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1817 // 1818 // Often address arithmetics contain expressions like 1819 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))). 1820 // This transformation is useful while proving that such expressions are 1821 // equal or differ by a small constant amount, see LoadStoreVectorizer pass. 1822 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1823 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1824 if (D != 0) { 1825 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1826 const SCEV *SResidual = 1827 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 1828 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1829 return getAddExpr(SZExtD, SZExtR, 1830 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1831 Depth + 1); 1832 } 1833 } 1834 } 1835 1836 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) { 1837 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw> 1838 if (SM->hasNoUnsignedWrap()) { 1839 // If the multiply does not unsign overflow then we can, by definition, 1840 // commute the zero extension with the multiply operation. 1841 SmallVector<const SCEV *, 4> Ops; 1842 for (const auto *Op : SM->operands()) 1843 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1844 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1); 1845 } 1846 1847 // zext(2^K * (trunc X to iN)) to iM -> 1848 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw> 1849 // 1850 // Proof: 1851 // 1852 // zext(2^K * (trunc X to iN)) to iM 1853 // = zext((trunc X to iN) << K) to iM 1854 // = zext((trunc X to i{N-K}) << K)<nuw> to iM 1855 // (because shl removes the top K bits) 1856 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM 1857 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>. 1858 // 1859 if (SM->getNumOperands() == 2) 1860 if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0))) 1861 if (MulLHS->getAPInt().isPowerOf2()) 1862 if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) { 1863 int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) - 1864 MulLHS->getAPInt().logBase2(); 1865 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits); 1866 return getMulExpr( 1867 getZeroExtendExpr(MulLHS, Ty), 1868 getZeroExtendExpr( 1869 getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty), 1870 SCEV::FlagNUW, Depth + 1); 1871 } 1872 } 1873 1874 // The cast wasn't folded; create an explicit cast node. 1875 // Recompute the insert position, as it may have been invalidated. 1876 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1877 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1878 Op, Ty); 1879 UniqueSCEVs.InsertNode(S, IP); 1880 registerUser(S, Op); 1881 return S; 1882 } 1883 1884 const SCEV * 1885 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1886 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1887 "This is not an extending conversion!"); 1888 assert(isSCEVable(Ty) && 1889 "This is not a conversion to a SCEVable type!"); 1890 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!"); 1891 Ty = getEffectiveSCEVType(Ty); 1892 1893 // Fold if the operand is constant. 1894 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1895 return getConstant( 1896 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); 1897 1898 // sext(sext(x)) --> sext(x) 1899 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1900 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1); 1901 1902 // sext(zext(x)) --> zext(x) 1903 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1904 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1905 1906 // Before doing any expensive analysis, check to see if we've already 1907 // computed a SCEV for this Op and Ty. 1908 FoldingSetNodeID ID; 1909 ID.AddInteger(scSignExtend); 1910 ID.AddPointer(Op); 1911 ID.AddPointer(Ty); 1912 void *IP = nullptr; 1913 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1914 // Limit recursion depth. 1915 if (Depth > MaxCastDepth) { 1916 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1917 Op, Ty); 1918 UniqueSCEVs.InsertNode(S, IP); 1919 registerUser(S, Op); 1920 return S; 1921 } 1922 1923 // sext(trunc(x)) --> sext(x) or x or trunc(x) 1924 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1925 // It's possible the bits taken off by the truncate were all sign bits. If 1926 // so, we should be able to simplify this further. 1927 const SCEV *X = ST->getOperand(); 1928 ConstantRange CR = getSignedRange(X); 1929 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1930 unsigned NewBits = getTypeSizeInBits(Ty); 1931 if (CR.truncate(TruncBits).signExtend(NewBits).contains( 1932 CR.sextOrTrunc(NewBits))) 1933 return getTruncateOrSignExtend(X, Ty, Depth); 1934 } 1935 1936 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1937 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 1938 if (SA->hasNoSignedWrap()) { 1939 // If the addition does not sign overflow then we can, by definition, 1940 // commute the sign extension with the addition operation. 1941 SmallVector<const SCEV *, 4> Ops; 1942 for (const auto *Op : SA->operands()) 1943 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1)); 1944 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1); 1945 } 1946 1947 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...)) 1948 // if D + (C - D + x + y + ...) could be proven to not signed wrap 1949 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1950 // 1951 // For instance, this will bring two seemingly different expressions: 1952 // 1 + sext(5 + 20 * %x + 24 * %y) and 1953 // sext(6 + 20 * %x + 24 * %y) 1954 // to the same form: 1955 // 2 + sext(4 + 20 * %x + 24 * %y) 1956 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1957 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1958 if (D != 0) { 1959 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 1960 const SCEV *SResidual = 1961 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 1962 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 1963 return getAddExpr(SSExtD, SSExtR, 1964 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1965 Depth + 1); 1966 } 1967 } 1968 } 1969 // If the input value is a chrec scev, and we can prove that the value 1970 // did not overflow the old, smaller, value, we can sign extend all of the 1971 // operands (often constants). This allows analysis of something like 1972 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 1973 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1974 if (AR->isAffine()) { 1975 const SCEV *Start = AR->getStart(); 1976 const SCEV *Step = AR->getStepRecurrence(*this); 1977 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1978 const Loop *L = AR->getLoop(); 1979 1980 if (!AR->hasNoSignedWrap()) { 1981 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1982 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags); 1983 } 1984 1985 // If we have special knowledge that this addrec won't overflow, 1986 // we don't need to do any further analysis. 1987 if (AR->hasNoSignedWrap()) 1988 return getAddRecExpr( 1989 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 1990 getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW); 1991 1992 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1993 // Note that this serves two purposes: It filters out loops that are 1994 // simply not analyzable, and it covers the case where this code is 1995 // being called from within backedge-taken count analysis, such that 1996 // attempting to ask for the backedge-taken count would likely result 1997 // in infinite recursion. In the later case, the analysis code will 1998 // cope with a conservative value, and it will take care to purge 1999 // that value once it has finished. 2000 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 2001 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 2002 // Manually compute the final value for AR, checking for 2003 // overflow. 2004 2005 // Check whether the backedge-taken count can be losslessly casted to 2006 // the addrec's type. The count is always unsigned. 2007 const SCEV *CastedMaxBECount = 2008 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 2009 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 2010 CastedMaxBECount, MaxBECount->getType(), Depth); 2011 if (MaxBECount == RecastedMaxBECount) { 2012 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 2013 // Check whether Start+Step*MaxBECount has no signed overflow. 2014 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step, 2015 SCEV::FlagAnyWrap, Depth + 1); 2016 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul, 2017 SCEV::FlagAnyWrap, 2018 Depth + 1), 2019 WideTy, Depth + 1); 2020 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1); 2021 const SCEV *WideMaxBECount = 2022 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 2023 const SCEV *OperandExtendedAdd = 2024 getAddExpr(WideStart, 2025 getMulExpr(WideMaxBECount, 2026 getSignExtendExpr(Step, WideTy, Depth + 1), 2027 SCEV::FlagAnyWrap, Depth + 1), 2028 SCEV::FlagAnyWrap, Depth + 1); 2029 if (SAdd == OperandExtendedAdd) { 2030 // Cache knowledge of AR NSW, which is propagated to this AddRec. 2031 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW); 2032 // Return the expression with the addrec on the outside. 2033 return getAddRecExpr( 2034 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2035 Depth + 1), 2036 getSignExtendExpr(Step, Ty, Depth + 1), L, 2037 AR->getNoWrapFlags()); 2038 } 2039 // Similar to above, only this time treat the step value as unsigned. 2040 // This covers loops that count up with an unsigned step. 2041 OperandExtendedAdd = 2042 getAddExpr(WideStart, 2043 getMulExpr(WideMaxBECount, 2044 getZeroExtendExpr(Step, WideTy, Depth + 1), 2045 SCEV::FlagAnyWrap, Depth + 1), 2046 SCEV::FlagAnyWrap, Depth + 1); 2047 if (SAdd == OperandExtendedAdd) { 2048 // If AR wraps around then 2049 // 2050 // abs(Step) * MaxBECount > unsigned-max(AR->getType()) 2051 // => SAdd != OperandExtendedAdd 2052 // 2053 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> 2054 // (SAdd == OperandExtendedAdd => AR is NW) 2055 2056 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW); 2057 2058 // Return the expression with the addrec on the outside. 2059 return getAddRecExpr( 2060 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2061 Depth + 1), 2062 getZeroExtendExpr(Step, Ty, Depth + 1), L, 2063 AR->getNoWrapFlags()); 2064 } 2065 } 2066 } 2067 2068 auto NewFlags = proveNoSignedWrapViaInduction(AR); 2069 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags); 2070 if (AR->hasNoSignedWrap()) { 2071 // Same as nsw case above - duplicated here to avoid a compile time 2072 // issue. It's not clear that the order of checks does matter, but 2073 // it's one of two issue possible causes for a change which was 2074 // reverted. Be conservative for the moment. 2075 return getAddRecExpr( 2076 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2077 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2078 } 2079 2080 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw> 2081 // if D + (C - D + Step * n) could be proven to not signed wrap 2082 // where D maximizes the number of trailing zeros of (C - D + Step * n) 2083 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 2084 const APInt &C = SC->getAPInt(); 2085 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 2086 if (D != 0) { 2087 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 2088 const SCEV *SResidual = 2089 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 2090 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 2091 return getAddExpr(SSExtD, SSExtR, 2092 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 2093 Depth + 1); 2094 } 2095 } 2096 2097 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { 2098 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW); 2099 return getAddRecExpr( 2100 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2101 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2102 } 2103 } 2104 2105 // If the input value is provably positive and we could not simplify 2106 // away the sext build a zext instead. 2107 if (isKnownNonNegative(Op)) 2108 return getZeroExtendExpr(Op, Ty, Depth + 1); 2109 2110 // The cast wasn't folded; create an explicit cast node. 2111 // Recompute the insert position, as it may have been invalidated. 2112 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 2113 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 2114 Op, Ty); 2115 UniqueSCEVs.InsertNode(S, IP); 2116 registerUser(S, { Op }); 2117 return S; 2118 } 2119 2120 const SCEV *ScalarEvolution::getCastExpr(SCEVTypes Kind, const SCEV *Op, 2121 Type *Ty) { 2122 switch (Kind) { 2123 case scTruncate: 2124 return getTruncateExpr(Op, Ty); 2125 case scZeroExtend: 2126 return getZeroExtendExpr(Op, Ty); 2127 case scSignExtend: 2128 return getSignExtendExpr(Op, Ty); 2129 case scPtrToInt: 2130 return getPtrToIntExpr(Op, Ty); 2131 default: 2132 llvm_unreachable("Not a SCEV cast expression!"); 2133 } 2134 } 2135 2136 /// getAnyExtendExpr - Return a SCEV for the given operand extended with 2137 /// unspecified bits out to the given type. 2138 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, 2139 Type *Ty) { 2140 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 2141 "This is not an extending conversion!"); 2142 assert(isSCEVable(Ty) && 2143 "This is not a conversion to a SCEVable type!"); 2144 Ty = getEffectiveSCEVType(Ty); 2145 2146 // Sign-extend negative constants. 2147 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 2148 if (SC->getAPInt().isNegative()) 2149 return getSignExtendExpr(Op, Ty); 2150 2151 // Peel off a truncate cast. 2152 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { 2153 const SCEV *NewOp = T->getOperand(); 2154 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) 2155 return getAnyExtendExpr(NewOp, Ty); 2156 return getTruncateOrNoop(NewOp, Ty); 2157 } 2158 2159 // Next try a zext cast. If the cast is folded, use it. 2160 const SCEV *ZExt = getZeroExtendExpr(Op, Ty); 2161 if (!isa<SCEVZeroExtendExpr>(ZExt)) 2162 return ZExt; 2163 2164 // Next try a sext cast. If the cast is folded, use it. 2165 const SCEV *SExt = getSignExtendExpr(Op, Ty); 2166 if (!isa<SCEVSignExtendExpr>(SExt)) 2167 return SExt; 2168 2169 // Force the cast to be folded into the operands of an addrec. 2170 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { 2171 SmallVector<const SCEV *, 4> Ops; 2172 for (const SCEV *Op : AR->operands()) 2173 Ops.push_back(getAnyExtendExpr(Op, Ty)); 2174 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); 2175 } 2176 2177 // If the expression is obviously signed, use the sext cast value. 2178 if (isa<SCEVSMaxExpr>(Op)) 2179 return SExt; 2180 2181 // Absent any other information, use the zext cast value. 2182 return ZExt; 2183 } 2184 2185 /// Process the given Ops list, which is a list of operands to be added under 2186 /// the given scale, update the given map. This is a helper function for 2187 /// getAddRecExpr. As an example of what it does, given a sequence of operands 2188 /// that would form an add expression like this: 2189 /// 2190 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r) 2191 /// 2192 /// where A and B are constants, update the map with these values: 2193 /// 2194 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) 2195 /// 2196 /// and add 13 + A*B*29 to AccumulatedConstant. 2197 /// This will allow getAddRecExpr to produce this: 2198 /// 2199 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) 2200 /// 2201 /// This form often exposes folding opportunities that are hidden in 2202 /// the original operand list. 2203 /// 2204 /// Return true iff it appears that any interesting folding opportunities 2205 /// may be exposed. This helps getAddRecExpr short-circuit extra work in 2206 /// the common case where no interesting opportunities are present, and 2207 /// is also used as a check to avoid infinite recursion. 2208 static bool 2209 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, 2210 SmallVectorImpl<const SCEV *> &NewOps, 2211 APInt &AccumulatedConstant, 2212 const SCEV *const *Ops, size_t NumOperands, 2213 const APInt &Scale, 2214 ScalarEvolution &SE) { 2215 bool Interesting = false; 2216 2217 // Iterate over the add operands. They are sorted, with constants first. 2218 unsigned i = 0; 2219 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2220 ++i; 2221 // Pull a buried constant out to the outside. 2222 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) 2223 Interesting = true; 2224 AccumulatedConstant += Scale * C->getAPInt(); 2225 } 2226 2227 // Next comes everything else. We're especially interested in multiplies 2228 // here, but they're in the middle, so just visit the rest with one loop. 2229 for (; i != NumOperands; ++i) { 2230 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); 2231 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { 2232 APInt NewScale = 2233 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); 2234 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { 2235 // A multiplication of a constant with another add; recurse. 2236 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); 2237 Interesting |= 2238 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2239 Add->op_begin(), Add->getNumOperands(), 2240 NewScale, SE); 2241 } else { 2242 // A multiplication of a constant with some other value. Update 2243 // the map. 2244 SmallVector<const SCEV *, 4> MulOps(drop_begin(Mul->operands())); 2245 const SCEV *Key = SE.getMulExpr(MulOps); 2246 auto Pair = M.insert({Key, NewScale}); 2247 if (Pair.second) { 2248 NewOps.push_back(Pair.first->first); 2249 } else { 2250 Pair.first->second += NewScale; 2251 // The map already had an entry for this value, which may indicate 2252 // a folding opportunity. 2253 Interesting = true; 2254 } 2255 } 2256 } else { 2257 // An ordinary operand. Update the map. 2258 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = 2259 M.insert({Ops[i], Scale}); 2260 if (Pair.second) { 2261 NewOps.push_back(Pair.first->first); 2262 } else { 2263 Pair.first->second += Scale; 2264 // The map already had an entry for this value, which may indicate 2265 // a folding opportunity. 2266 Interesting = true; 2267 } 2268 } 2269 } 2270 2271 return Interesting; 2272 } 2273 2274 bool ScalarEvolution::willNotOverflow(Instruction::BinaryOps BinOp, bool Signed, 2275 const SCEV *LHS, const SCEV *RHS) { 2276 const SCEV *(ScalarEvolution::*Operation)(const SCEV *, const SCEV *, 2277 SCEV::NoWrapFlags, unsigned); 2278 switch (BinOp) { 2279 default: 2280 llvm_unreachable("Unsupported binary op"); 2281 case Instruction::Add: 2282 Operation = &ScalarEvolution::getAddExpr; 2283 break; 2284 case Instruction::Sub: 2285 Operation = &ScalarEvolution::getMinusSCEV; 2286 break; 2287 case Instruction::Mul: 2288 Operation = &ScalarEvolution::getMulExpr; 2289 break; 2290 } 2291 2292 const SCEV *(ScalarEvolution::*Extension)(const SCEV *, Type *, unsigned) = 2293 Signed ? &ScalarEvolution::getSignExtendExpr 2294 : &ScalarEvolution::getZeroExtendExpr; 2295 2296 // Check ext(LHS op RHS) == ext(LHS) op ext(RHS) 2297 auto *NarrowTy = cast<IntegerType>(LHS->getType()); 2298 auto *WideTy = 2299 IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2); 2300 2301 const SCEV *A = (this->*Extension)( 2302 (this->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0), WideTy, 0); 2303 const SCEV *B = (this->*Operation)((this->*Extension)(LHS, WideTy, 0), 2304 (this->*Extension)(RHS, WideTy, 0), 2305 SCEV::FlagAnyWrap, 0); 2306 return A == B; 2307 } 2308 2309 std::pair<SCEV::NoWrapFlags, bool /*Deduced*/> 2310 ScalarEvolution::getStrengthenedNoWrapFlagsFromBinOp( 2311 const OverflowingBinaryOperator *OBO) { 2312 SCEV::NoWrapFlags Flags = SCEV::NoWrapFlags::FlagAnyWrap; 2313 2314 if (OBO->hasNoUnsignedWrap()) 2315 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2316 if (OBO->hasNoSignedWrap()) 2317 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2318 2319 bool Deduced = false; 2320 2321 if (OBO->hasNoUnsignedWrap() && OBO->hasNoSignedWrap()) 2322 return {Flags, Deduced}; 2323 2324 if (OBO->getOpcode() != Instruction::Add && 2325 OBO->getOpcode() != Instruction::Sub && 2326 OBO->getOpcode() != Instruction::Mul) 2327 return {Flags, Deduced}; 2328 2329 const SCEV *LHS = getSCEV(OBO->getOperand(0)); 2330 const SCEV *RHS = getSCEV(OBO->getOperand(1)); 2331 2332 if (!OBO->hasNoUnsignedWrap() && 2333 willNotOverflow((Instruction::BinaryOps)OBO->getOpcode(), 2334 /* Signed */ false, LHS, RHS)) { 2335 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2336 Deduced = true; 2337 } 2338 2339 if (!OBO->hasNoSignedWrap() && 2340 willNotOverflow((Instruction::BinaryOps)OBO->getOpcode(), 2341 /* Signed */ true, LHS, RHS)) { 2342 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2343 Deduced = true; 2344 } 2345 2346 return {Flags, Deduced}; 2347 } 2348 2349 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and 2350 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of 2351 // can't-overflow flags for the operation if possible. 2352 static SCEV::NoWrapFlags 2353 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, 2354 const ArrayRef<const SCEV *> Ops, 2355 SCEV::NoWrapFlags Flags) { 2356 using namespace std::placeholders; 2357 2358 using OBO = OverflowingBinaryOperator; 2359 2360 bool CanAnalyze = 2361 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; 2362 (void)CanAnalyze; 2363 assert(CanAnalyze && "don't call from other places!"); 2364 2365 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 2366 SCEV::NoWrapFlags SignOrUnsignWrap = 2367 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2368 2369 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 2370 auto IsKnownNonNegative = [&](const SCEV *S) { 2371 return SE->isKnownNonNegative(S); 2372 }; 2373 2374 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) 2375 Flags = 2376 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); 2377 2378 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2379 2380 if (SignOrUnsignWrap != SignOrUnsignMask && 2381 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 && 2382 isa<SCEVConstant>(Ops[0])) { 2383 2384 auto Opcode = [&] { 2385 switch (Type) { 2386 case scAddExpr: 2387 return Instruction::Add; 2388 case scMulExpr: 2389 return Instruction::Mul; 2390 default: 2391 llvm_unreachable("Unexpected SCEV op."); 2392 } 2393 }(); 2394 2395 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); 2396 2397 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow. 2398 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { 2399 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2400 Opcode, C, OBO::NoSignedWrap); 2401 if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) 2402 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2403 } 2404 2405 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow. 2406 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { 2407 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2408 Opcode, C, OBO::NoUnsignedWrap); 2409 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) 2410 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2411 } 2412 } 2413 2414 // <0,+,nonnegative><nw> is also nuw 2415 // TODO: Add corresponding nsw case 2416 if (Type == scAddRecExpr && ScalarEvolution::hasFlags(Flags, SCEV::FlagNW) && 2417 !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) && Ops.size() == 2 && 2418 Ops[0]->isZero() && IsKnownNonNegative(Ops[1])) 2419 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2420 2421 // both (udiv X, Y) * Y and Y * (udiv X, Y) are always NUW 2422 if (Type == scMulExpr && !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) && 2423 Ops.size() == 2) { 2424 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[0])) 2425 if (UDiv->getOperand(1) == Ops[1]) 2426 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2427 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[1])) 2428 if (UDiv->getOperand(1) == Ops[0]) 2429 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2430 } 2431 2432 return Flags; 2433 } 2434 2435 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) { 2436 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader()); 2437 } 2438 2439 /// Get a canonical add expression, or something simpler if possible. 2440 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2441 SCEV::NoWrapFlags OrigFlags, 2442 unsigned Depth) { 2443 assert(!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && 2444 "only nuw or nsw allowed"); 2445 assert(!Ops.empty() && "Cannot get empty add!"); 2446 if (Ops.size() == 1) return Ops[0]; 2447 #ifndef NDEBUG 2448 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2449 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2450 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2451 "SCEVAddExpr operand types don't match!"); 2452 unsigned NumPtrs = count_if( 2453 Ops, [](const SCEV *Op) { return Op->getType()->isPointerTy(); }); 2454 assert(NumPtrs <= 1 && "add has at most one pointer operand"); 2455 #endif 2456 2457 // Sort by complexity, this groups all similar expression types together. 2458 GroupByComplexity(Ops, &LI, DT); 2459 2460 // If there are any constants, fold them together. 2461 unsigned Idx = 0; 2462 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2463 ++Idx; 2464 assert(Idx < Ops.size()); 2465 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2466 // We found two constants, fold them together! 2467 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); 2468 if (Ops.size() == 2) return Ops[0]; 2469 Ops.erase(Ops.begin()+1); // Erase the folded element 2470 LHSC = cast<SCEVConstant>(Ops[0]); 2471 } 2472 2473 // If we are left with a constant zero being added, strip it off. 2474 if (LHSC->getValue()->isZero()) { 2475 Ops.erase(Ops.begin()); 2476 --Idx; 2477 } 2478 2479 if (Ops.size() == 1) return Ops[0]; 2480 } 2481 2482 // Delay expensive flag strengthening until necessary. 2483 auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) { 2484 return StrengthenNoWrapFlags(this, scAddExpr, Ops, OrigFlags); 2485 }; 2486 2487 // Limit recursion calls depth. 2488 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 2489 return getOrCreateAddExpr(Ops, ComputeFlags(Ops)); 2490 2491 if (SCEV *S = findExistingSCEVInCache(scAddExpr, Ops)) { 2492 // Don't strengthen flags if we have no new information. 2493 SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S); 2494 if (Add->getNoWrapFlags(OrigFlags) != OrigFlags) 2495 Add->setNoWrapFlags(ComputeFlags(Ops)); 2496 return S; 2497 } 2498 2499 // Okay, check to see if the same value occurs in the operand list more than 2500 // once. If so, merge them together into an multiply expression. Since we 2501 // sorted the list, these values are required to be adjacent. 2502 Type *Ty = Ops[0]->getType(); 2503 bool FoundMatch = false; 2504 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 2505 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 2506 // Scan ahead to count how many equal operands there are. 2507 unsigned Count = 2; 2508 while (i+Count != e && Ops[i+Count] == Ops[i]) 2509 ++Count; 2510 // Merge the values into a multiply. 2511 const SCEV *Scale = getConstant(Ty, Count); 2512 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1); 2513 if (Ops.size() == Count) 2514 return Mul; 2515 Ops[i] = Mul; 2516 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 2517 --i; e -= Count - 1; 2518 FoundMatch = true; 2519 } 2520 if (FoundMatch) 2521 return getAddExpr(Ops, OrigFlags, Depth + 1); 2522 2523 // Check for truncates. If all the operands are truncated from the same 2524 // type, see if factoring out the truncate would permit the result to be 2525 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y) 2526 // if the contents of the resulting outer trunc fold to something simple. 2527 auto FindTruncSrcType = [&]() -> Type * { 2528 // We're ultimately looking to fold an addrec of truncs and muls of only 2529 // constants and truncs, so if we find any other types of SCEV 2530 // as operands of the addrec then we bail and return nullptr here. 2531 // Otherwise, we return the type of the operand of a trunc that we find. 2532 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx])) 2533 return T->getOperand()->getType(); 2534 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2535 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1); 2536 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp)) 2537 return T->getOperand()->getType(); 2538 } 2539 return nullptr; 2540 }; 2541 if (auto *SrcType = FindTruncSrcType()) { 2542 SmallVector<const SCEV *, 8> LargeOps; 2543 bool Ok = true; 2544 // Check all the operands to see if they can be represented in the 2545 // source type of the truncate. 2546 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 2547 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 2548 if (T->getOperand()->getType() != SrcType) { 2549 Ok = false; 2550 break; 2551 } 2552 LargeOps.push_back(T->getOperand()); 2553 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2554 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 2555 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 2556 SmallVector<const SCEV *, 8> LargeMulOps; 2557 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 2558 if (const SCEVTruncateExpr *T = 2559 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 2560 if (T->getOperand()->getType() != SrcType) { 2561 Ok = false; 2562 break; 2563 } 2564 LargeMulOps.push_back(T->getOperand()); 2565 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { 2566 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 2567 } else { 2568 Ok = false; 2569 break; 2570 } 2571 } 2572 if (Ok) 2573 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1)); 2574 } else { 2575 Ok = false; 2576 break; 2577 } 2578 } 2579 if (Ok) { 2580 // Evaluate the expression in the larger type. 2581 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1); 2582 // If it folds to something simple, use it. Otherwise, don't. 2583 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 2584 return getTruncateExpr(Fold, Ty); 2585 } 2586 } 2587 2588 if (Ops.size() == 2) { 2589 // Check if we have an expression of the form ((X + C1) - C2), where C1 and 2590 // C2 can be folded in a way that allows retaining wrapping flags of (X + 2591 // C1). 2592 const SCEV *A = Ops[0]; 2593 const SCEV *B = Ops[1]; 2594 auto *AddExpr = dyn_cast<SCEVAddExpr>(B); 2595 auto *C = dyn_cast<SCEVConstant>(A); 2596 if (AddExpr && C && isa<SCEVConstant>(AddExpr->getOperand(0))) { 2597 auto C1 = cast<SCEVConstant>(AddExpr->getOperand(0))->getAPInt(); 2598 auto C2 = C->getAPInt(); 2599 SCEV::NoWrapFlags PreservedFlags = SCEV::FlagAnyWrap; 2600 2601 APInt ConstAdd = C1 + C2; 2602 auto AddFlags = AddExpr->getNoWrapFlags(); 2603 // Adding a smaller constant is NUW if the original AddExpr was NUW. 2604 if (ScalarEvolution::hasFlags(AddFlags, SCEV::FlagNUW) && 2605 ConstAdd.ule(C1)) { 2606 PreservedFlags = 2607 ScalarEvolution::setFlags(PreservedFlags, SCEV::FlagNUW); 2608 } 2609 2610 // Adding a constant with the same sign and small magnitude is NSW, if the 2611 // original AddExpr was NSW. 2612 if (ScalarEvolution::hasFlags(AddFlags, SCEV::FlagNSW) && 2613 C1.isSignBitSet() == ConstAdd.isSignBitSet() && 2614 ConstAdd.abs().ule(C1.abs())) { 2615 PreservedFlags = 2616 ScalarEvolution::setFlags(PreservedFlags, SCEV::FlagNSW); 2617 } 2618 2619 if (PreservedFlags != SCEV::FlagAnyWrap) { 2620 SmallVector<const SCEV *, 4> NewOps(AddExpr->operands()); 2621 NewOps[0] = getConstant(ConstAdd); 2622 return getAddExpr(NewOps, PreservedFlags); 2623 } 2624 } 2625 } 2626 2627 // Canonicalize (-1 * urem X, Y) + X --> (Y * X/Y) 2628 if (Ops.size() == 2) { 2629 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[0]); 2630 if (Mul && Mul->getNumOperands() == 2 && 2631 Mul->getOperand(0)->isAllOnesValue()) { 2632 const SCEV *X; 2633 const SCEV *Y; 2634 if (matchURem(Mul->getOperand(1), X, Y) && X == Ops[1]) { 2635 return getMulExpr(Y, getUDivExpr(X, Y)); 2636 } 2637 } 2638 } 2639 2640 // Skip past any other cast SCEVs. 2641 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 2642 ++Idx; 2643 2644 // If there are add operands they would be next. 2645 if (Idx < Ops.size()) { 2646 bool DeletedAdd = false; 2647 // If the original flags and all inlined SCEVAddExprs are NUW, use the 2648 // common NUW flag for expression after inlining. Other flags cannot be 2649 // preserved, because they may depend on the original order of operations. 2650 SCEV::NoWrapFlags CommonFlags = maskFlags(OrigFlags, SCEV::FlagNUW); 2651 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2652 if (Ops.size() > AddOpsInlineThreshold || 2653 Add->getNumOperands() > AddOpsInlineThreshold) 2654 break; 2655 // If we have an add, expand the add operands onto the end of the operands 2656 // list. 2657 Ops.erase(Ops.begin()+Idx); 2658 Ops.append(Add->op_begin(), Add->op_end()); 2659 DeletedAdd = true; 2660 CommonFlags = maskFlags(CommonFlags, Add->getNoWrapFlags()); 2661 } 2662 2663 // If we deleted at least one add, we added operands to the end of the list, 2664 // and they are not necessarily sorted. Recurse to resort and resimplify 2665 // any operands we just acquired. 2666 if (DeletedAdd) 2667 return getAddExpr(Ops, CommonFlags, Depth + 1); 2668 } 2669 2670 // Skip over the add expression until we get to a multiply. 2671 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2672 ++Idx; 2673 2674 // Check to see if there are any folding opportunities present with 2675 // operands multiplied by constant values. 2676 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2677 uint64_t BitWidth = getTypeSizeInBits(Ty); 2678 DenseMap<const SCEV *, APInt> M; 2679 SmallVector<const SCEV *, 8> NewOps; 2680 APInt AccumulatedConstant(BitWidth, 0); 2681 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2682 Ops.data(), Ops.size(), 2683 APInt(BitWidth, 1), *this)) { 2684 struct APIntCompare { 2685 bool operator()(const APInt &LHS, const APInt &RHS) const { 2686 return LHS.ult(RHS); 2687 } 2688 }; 2689 2690 // Some interesting folding opportunity is present, so its worthwhile to 2691 // re-generate the operands list. Group the operands by constant scale, 2692 // to avoid multiplying by the same constant scale multiple times. 2693 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2694 for (const SCEV *NewOp : NewOps) 2695 MulOpLists[M.find(NewOp)->second].push_back(NewOp); 2696 // Re-generate the operands list. 2697 Ops.clear(); 2698 if (AccumulatedConstant != 0) 2699 Ops.push_back(getConstant(AccumulatedConstant)); 2700 for (auto &MulOp : MulOpLists) { 2701 if (MulOp.first == 1) { 2702 Ops.push_back(getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1)); 2703 } else if (MulOp.first != 0) { 2704 Ops.push_back(getMulExpr( 2705 getConstant(MulOp.first), 2706 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1), 2707 SCEV::FlagAnyWrap, Depth + 1)); 2708 } 2709 } 2710 if (Ops.empty()) 2711 return getZero(Ty); 2712 if (Ops.size() == 1) 2713 return Ops[0]; 2714 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2715 } 2716 } 2717 2718 // If we are adding something to a multiply expression, make sure the 2719 // something is not already an operand of the multiply. If so, merge it into 2720 // the multiply. 2721 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2722 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2723 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2724 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2725 if (isa<SCEVConstant>(MulOpSCEV)) 2726 continue; 2727 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2728 if (MulOpSCEV == Ops[AddOp]) { 2729 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2730 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2731 if (Mul->getNumOperands() != 2) { 2732 // If the multiply has more than two operands, we must get the 2733 // Y*Z term. 2734 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2735 Mul->op_begin()+MulOp); 2736 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2737 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2738 } 2739 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul}; 2740 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2741 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV, 2742 SCEV::FlagAnyWrap, Depth + 1); 2743 if (Ops.size() == 2) return OuterMul; 2744 if (AddOp < Idx) { 2745 Ops.erase(Ops.begin()+AddOp); 2746 Ops.erase(Ops.begin()+Idx-1); 2747 } else { 2748 Ops.erase(Ops.begin()+Idx); 2749 Ops.erase(Ops.begin()+AddOp-1); 2750 } 2751 Ops.push_back(OuterMul); 2752 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2753 } 2754 2755 // Check this multiply against other multiplies being added together. 2756 for (unsigned OtherMulIdx = Idx+1; 2757 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2758 ++OtherMulIdx) { 2759 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2760 // If MulOp occurs in OtherMul, we can fold the two multiplies 2761 // together. 2762 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2763 OMulOp != e; ++OMulOp) 2764 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2765 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2766 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2767 if (Mul->getNumOperands() != 2) { 2768 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2769 Mul->op_begin()+MulOp); 2770 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2771 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2772 } 2773 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2774 if (OtherMul->getNumOperands() != 2) { 2775 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2776 OtherMul->op_begin()+OMulOp); 2777 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2778 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2779 } 2780 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2}; 2781 const SCEV *InnerMulSum = 2782 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2783 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum, 2784 SCEV::FlagAnyWrap, Depth + 1); 2785 if (Ops.size() == 2) return OuterMul; 2786 Ops.erase(Ops.begin()+Idx); 2787 Ops.erase(Ops.begin()+OtherMulIdx-1); 2788 Ops.push_back(OuterMul); 2789 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2790 } 2791 } 2792 } 2793 } 2794 2795 // If there are any add recurrences in the operands list, see if any other 2796 // added values are loop invariant. If so, we can fold them into the 2797 // recurrence. 2798 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2799 ++Idx; 2800 2801 // Scan over all recurrences, trying to fold loop invariants into them. 2802 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2803 // Scan all of the other operands to this add and add them to the vector if 2804 // they are loop invariant w.r.t. the recurrence. 2805 SmallVector<const SCEV *, 8> LIOps; 2806 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2807 const Loop *AddRecLoop = AddRec->getLoop(); 2808 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2809 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2810 LIOps.push_back(Ops[i]); 2811 Ops.erase(Ops.begin()+i); 2812 --i; --e; 2813 } 2814 2815 // If we found some loop invariants, fold them into the recurrence. 2816 if (!LIOps.empty()) { 2817 // Compute nowrap flags for the addition of the loop-invariant ops and 2818 // the addrec. Temporarily push it as an operand for that purpose. These 2819 // flags are valid in the scope of the addrec only. 2820 LIOps.push_back(AddRec); 2821 SCEV::NoWrapFlags Flags = ComputeFlags(LIOps); 2822 LIOps.pop_back(); 2823 2824 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2825 LIOps.push_back(AddRec->getStart()); 2826 2827 SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands()); 2828 2829 // It is not in general safe to propagate flags valid on an add within 2830 // the addrec scope to one outside it. We must prove that the inner 2831 // scope is guaranteed to execute if the outer one does to be able to 2832 // safely propagate. We know the program is undefined if poison is 2833 // produced on the inner scoped addrec. We also know that *for this use* 2834 // the outer scoped add can't overflow (because of the flags we just 2835 // computed for the inner scoped add) without the program being undefined. 2836 // Proving that entry to the outer scope neccesitates entry to the inner 2837 // scope, thus proves the program undefined if the flags would be violated 2838 // in the outer scope. 2839 SCEV::NoWrapFlags AddFlags = Flags; 2840 if (AddFlags != SCEV::FlagAnyWrap) { 2841 auto *DefI = getDefiningScopeBound(LIOps); 2842 auto *ReachI = &*AddRecLoop->getHeader()->begin(); 2843 if (!isGuaranteedToTransferExecutionTo(DefI, ReachI)) 2844 AddFlags = SCEV::FlagAnyWrap; 2845 } 2846 AddRecOps[0] = getAddExpr(LIOps, AddFlags, Depth + 1); 2847 2848 // Build the new addrec. Propagate the NUW and NSW flags if both the 2849 // outer add and the inner addrec are guaranteed to have no overflow. 2850 // Always propagate NW. 2851 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2852 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2853 2854 // If all of the other operands were loop invariant, we are done. 2855 if (Ops.size() == 1) return NewRec; 2856 2857 // Otherwise, add the folded AddRec by the non-invariant parts. 2858 for (unsigned i = 0;; ++i) 2859 if (Ops[i] == AddRec) { 2860 Ops[i] = NewRec; 2861 break; 2862 } 2863 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2864 } 2865 2866 // Okay, if there weren't any loop invariants to be folded, check to see if 2867 // there are multiple AddRec's with the same loop induction variable being 2868 // added together. If so, we can fold them. 2869 for (unsigned OtherIdx = Idx+1; 2870 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2871 ++OtherIdx) { 2872 // We expect the AddRecExpr's to be sorted in reverse dominance order, 2873 // so that the 1st found AddRecExpr is dominated by all others. 2874 assert(DT.dominates( 2875 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), 2876 AddRec->getLoop()->getHeader()) && 2877 "AddRecExprs are not sorted in reverse dominance order?"); 2878 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2879 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2880 SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands()); 2881 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2882 ++OtherIdx) { 2883 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2884 if (OtherAddRec->getLoop() == AddRecLoop) { 2885 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2886 i != e; ++i) { 2887 if (i >= AddRecOps.size()) { 2888 AddRecOps.append(OtherAddRec->op_begin()+i, 2889 OtherAddRec->op_end()); 2890 break; 2891 } 2892 SmallVector<const SCEV *, 2> TwoOps = { 2893 AddRecOps[i], OtherAddRec->getOperand(i)}; 2894 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2895 } 2896 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2897 } 2898 } 2899 // Step size has changed, so we cannot guarantee no self-wraparound. 2900 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2901 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2902 } 2903 } 2904 2905 // Otherwise couldn't fold anything into this recurrence. Move onto the 2906 // next one. 2907 } 2908 2909 // Okay, it looks like we really DO need an add expr. Check to see if we 2910 // already have one, otherwise create a new one. 2911 return getOrCreateAddExpr(Ops, ComputeFlags(Ops)); 2912 } 2913 2914 const SCEV * 2915 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops, 2916 SCEV::NoWrapFlags Flags) { 2917 FoldingSetNodeID ID; 2918 ID.AddInteger(scAddExpr); 2919 for (const SCEV *Op : Ops) 2920 ID.AddPointer(Op); 2921 void *IP = nullptr; 2922 SCEVAddExpr *S = 2923 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2924 if (!S) { 2925 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2926 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2927 S = new (SCEVAllocator) 2928 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size()); 2929 UniqueSCEVs.InsertNode(S, IP); 2930 registerUser(S, Ops); 2931 } 2932 S->setNoWrapFlags(Flags); 2933 return S; 2934 } 2935 2936 const SCEV * 2937 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops, 2938 const Loop *L, SCEV::NoWrapFlags Flags) { 2939 FoldingSetNodeID ID; 2940 ID.AddInteger(scAddRecExpr); 2941 for (const SCEV *Op : Ops) 2942 ID.AddPointer(Op); 2943 ID.AddPointer(L); 2944 void *IP = nullptr; 2945 SCEVAddRecExpr *S = 2946 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2947 if (!S) { 2948 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2949 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2950 S = new (SCEVAllocator) 2951 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L); 2952 UniqueSCEVs.InsertNode(S, IP); 2953 LoopUsers[L].push_back(S); 2954 registerUser(S, Ops); 2955 } 2956 setNoWrapFlags(S, Flags); 2957 return S; 2958 } 2959 2960 const SCEV * 2961 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops, 2962 SCEV::NoWrapFlags Flags) { 2963 FoldingSetNodeID ID; 2964 ID.AddInteger(scMulExpr); 2965 for (const SCEV *Op : Ops) 2966 ID.AddPointer(Op); 2967 void *IP = nullptr; 2968 SCEVMulExpr *S = 2969 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2970 if (!S) { 2971 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2972 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2973 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2974 O, Ops.size()); 2975 UniqueSCEVs.InsertNode(S, IP); 2976 registerUser(S, Ops); 2977 } 2978 S->setNoWrapFlags(Flags); 2979 return S; 2980 } 2981 2982 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2983 uint64_t k = i*j; 2984 if (j > 1 && k / j != i) Overflow = true; 2985 return k; 2986 } 2987 2988 /// Compute the result of "n choose k", the binomial coefficient. If an 2989 /// intermediate computation overflows, Overflow will be set and the return will 2990 /// be garbage. Overflow is not cleared on absence of overflow. 2991 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 2992 // We use the multiplicative formula: 2993 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 2994 // At each iteration, we take the n-th term of the numeral and divide by the 2995 // (k-n)th term of the denominator. This division will always produce an 2996 // integral result, and helps reduce the chance of overflow in the 2997 // intermediate computations. However, we can still overflow even when the 2998 // final result would fit. 2999 3000 if (n == 0 || n == k) return 1; 3001 if (k > n) return 0; 3002 3003 if (k > n/2) 3004 k = n-k; 3005 3006 uint64_t r = 1; 3007 for (uint64_t i = 1; i <= k; ++i) { 3008 r = umul_ov(r, n-(i-1), Overflow); 3009 r /= i; 3010 } 3011 return r; 3012 } 3013 3014 /// Determine if any of the operands in this SCEV are a constant or if 3015 /// any of the add or multiply expressions in this SCEV contain a constant. 3016 static bool containsConstantInAddMulChain(const SCEV *StartExpr) { 3017 struct FindConstantInAddMulChain { 3018 bool FoundConstant = false; 3019 3020 bool follow(const SCEV *S) { 3021 FoundConstant |= isa<SCEVConstant>(S); 3022 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S); 3023 } 3024 3025 bool isDone() const { 3026 return FoundConstant; 3027 } 3028 }; 3029 3030 FindConstantInAddMulChain F; 3031 SCEVTraversal<FindConstantInAddMulChain> ST(F); 3032 ST.visitAll(StartExpr); 3033 return F.FoundConstant; 3034 } 3035 3036 /// Get a canonical multiply expression, or something simpler if possible. 3037 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 3038 SCEV::NoWrapFlags OrigFlags, 3039 unsigned Depth) { 3040 assert(OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) && 3041 "only nuw or nsw allowed"); 3042 assert(!Ops.empty() && "Cannot get empty mul!"); 3043 if (Ops.size() == 1) return Ops[0]; 3044 #ifndef NDEBUG 3045 Type *ETy = Ops[0]->getType(); 3046 assert(!ETy->isPointerTy()); 3047 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3048 assert(Ops[i]->getType() == ETy && 3049 "SCEVMulExpr operand types don't match!"); 3050 #endif 3051 3052 // Sort by complexity, this groups all similar expression types together. 3053 GroupByComplexity(Ops, &LI, DT); 3054 3055 // If there are any constants, fold them together. 3056 unsigned Idx = 0; 3057 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3058 ++Idx; 3059 assert(Idx < Ops.size()); 3060 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3061 // We found two constants, fold them together! 3062 Ops[0] = getConstant(LHSC->getAPInt() * RHSC->getAPInt()); 3063 if (Ops.size() == 2) return Ops[0]; 3064 Ops.erase(Ops.begin()+1); // Erase the folded element 3065 LHSC = cast<SCEVConstant>(Ops[0]); 3066 } 3067 3068 // If we have a multiply of zero, it will always be zero. 3069 if (LHSC->getValue()->isZero()) 3070 return LHSC; 3071 3072 // If we are left with a constant one being multiplied, strip it off. 3073 if (LHSC->getValue()->isOne()) { 3074 Ops.erase(Ops.begin()); 3075 --Idx; 3076 } 3077 3078 if (Ops.size() == 1) 3079 return Ops[0]; 3080 } 3081 3082 // Delay expensive flag strengthening until necessary. 3083 auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) { 3084 return StrengthenNoWrapFlags(this, scMulExpr, Ops, OrigFlags); 3085 }; 3086 3087 // Limit recursion calls depth. 3088 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 3089 return getOrCreateMulExpr(Ops, ComputeFlags(Ops)); 3090 3091 if (SCEV *S = findExistingSCEVInCache(scMulExpr, Ops)) { 3092 // Don't strengthen flags if we have no new information. 3093 SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S); 3094 if (Mul->getNoWrapFlags(OrigFlags) != OrigFlags) 3095 Mul->setNoWrapFlags(ComputeFlags(Ops)); 3096 return S; 3097 } 3098 3099 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3100 if (Ops.size() == 2) { 3101 // C1*(C2+V) -> C1*C2 + C1*V 3102 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 3103 // If any of Add's ops are Adds or Muls with a constant, apply this 3104 // transformation as well. 3105 // 3106 // TODO: There are some cases where this transformation is not 3107 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of 3108 // this transformation should be narrowed down. 3109 if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add)) 3110 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0), 3111 SCEV::FlagAnyWrap, Depth + 1), 3112 getMulExpr(LHSC, Add->getOperand(1), 3113 SCEV::FlagAnyWrap, Depth + 1), 3114 SCEV::FlagAnyWrap, Depth + 1); 3115 3116 if (Ops[0]->isAllOnesValue()) { 3117 // If we have a mul by -1 of an add, try distributing the -1 among the 3118 // add operands. 3119 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 3120 SmallVector<const SCEV *, 4> NewOps; 3121 bool AnyFolded = false; 3122 for (const SCEV *AddOp : Add->operands()) { 3123 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap, 3124 Depth + 1); 3125 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 3126 NewOps.push_back(Mul); 3127 } 3128 if (AnyFolded) 3129 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1); 3130 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 3131 // Negation preserves a recurrence's no self-wrap property. 3132 SmallVector<const SCEV *, 4> Operands; 3133 for (const SCEV *AddRecOp : AddRec->operands()) 3134 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap, 3135 Depth + 1)); 3136 3137 return getAddRecExpr(Operands, AddRec->getLoop(), 3138 AddRec->getNoWrapFlags(SCEV::FlagNW)); 3139 } 3140 } 3141 } 3142 } 3143 3144 // Skip over the add expression until we get to a multiply. 3145 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 3146 ++Idx; 3147 3148 // If there are mul operands inline them all into this expression. 3149 if (Idx < Ops.size()) { 3150 bool DeletedMul = false; 3151 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 3152 if (Ops.size() > MulOpsInlineThreshold) 3153 break; 3154 // If we have an mul, expand the mul operands onto the end of the 3155 // operands list. 3156 Ops.erase(Ops.begin()+Idx); 3157 Ops.append(Mul->op_begin(), Mul->op_end()); 3158 DeletedMul = true; 3159 } 3160 3161 // If we deleted at least one mul, we added operands to the end of the 3162 // list, and they are not necessarily sorted. Recurse to resort and 3163 // resimplify any operands we just acquired. 3164 if (DeletedMul) 3165 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3166 } 3167 3168 // If there are any add recurrences in the operands list, see if any other 3169 // added values are loop invariant. If so, we can fold them into the 3170 // recurrence. 3171 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 3172 ++Idx; 3173 3174 // Scan over all recurrences, trying to fold loop invariants into them. 3175 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 3176 // Scan all of the other operands to this mul and add them to the vector 3177 // if they are loop invariant w.r.t. the recurrence. 3178 SmallVector<const SCEV *, 8> LIOps; 3179 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 3180 const Loop *AddRecLoop = AddRec->getLoop(); 3181 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3182 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 3183 LIOps.push_back(Ops[i]); 3184 Ops.erase(Ops.begin()+i); 3185 --i; --e; 3186 } 3187 3188 // If we found some loop invariants, fold them into the recurrence. 3189 if (!LIOps.empty()) { 3190 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 3191 SmallVector<const SCEV *, 4> NewOps; 3192 NewOps.reserve(AddRec->getNumOperands()); 3193 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1); 3194 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 3195 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i), 3196 SCEV::FlagAnyWrap, Depth + 1)); 3197 3198 // Build the new addrec. Propagate the NUW and NSW flags if both the 3199 // outer mul and the inner addrec are guaranteed to have no overflow. 3200 // 3201 // No self-wrap cannot be guaranteed after changing the step size, but 3202 // will be inferred if either NUW or NSW is true. 3203 SCEV::NoWrapFlags Flags = ComputeFlags({Scale, AddRec}); 3204 const SCEV *NewRec = getAddRecExpr( 3205 NewOps, AddRecLoop, AddRec->getNoWrapFlags(Flags)); 3206 3207 // If all of the other operands were loop invariant, we are done. 3208 if (Ops.size() == 1) return NewRec; 3209 3210 // Otherwise, multiply the folded AddRec by the non-invariant parts. 3211 for (unsigned i = 0;; ++i) 3212 if (Ops[i] == AddRec) { 3213 Ops[i] = NewRec; 3214 break; 3215 } 3216 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3217 } 3218 3219 // Okay, if there weren't any loop invariants to be folded, check to see 3220 // if there are multiple AddRec's with the same loop induction variable 3221 // being multiplied together. If so, we can fold them. 3222 3223 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 3224 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 3225 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 3226 // ]]],+,...up to x=2n}. 3227 // Note that the arguments to choose() are always integers with values 3228 // known at compile time, never SCEV objects. 3229 // 3230 // The implementation avoids pointless extra computations when the two 3231 // addrec's are of different length (mathematically, it's equivalent to 3232 // an infinite stream of zeros on the right). 3233 bool OpsModified = false; 3234 for (unsigned OtherIdx = Idx+1; 3235 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 3236 ++OtherIdx) { 3237 const SCEVAddRecExpr *OtherAddRec = 3238 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 3239 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 3240 continue; 3241 3242 // Limit max number of arguments to avoid creation of unreasonably big 3243 // SCEVAddRecs with very complex operands. 3244 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 > 3245 MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec})) 3246 continue; 3247 3248 bool Overflow = false; 3249 Type *Ty = AddRec->getType(); 3250 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 3251 SmallVector<const SCEV*, 7> AddRecOps; 3252 for (int x = 0, xe = AddRec->getNumOperands() + 3253 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 3254 SmallVector <const SCEV *, 7> SumOps; 3255 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 3256 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 3257 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 3258 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 3259 z < ze && !Overflow; ++z) { 3260 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 3261 uint64_t Coeff; 3262 if (LargerThan64Bits) 3263 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 3264 else 3265 Coeff = Coeff1*Coeff2; 3266 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 3267 const SCEV *Term1 = AddRec->getOperand(y-z); 3268 const SCEV *Term2 = OtherAddRec->getOperand(z); 3269 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2, 3270 SCEV::FlagAnyWrap, Depth + 1)); 3271 } 3272 } 3273 if (SumOps.empty()) 3274 SumOps.push_back(getZero(Ty)); 3275 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1)); 3276 } 3277 if (!Overflow) { 3278 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop, 3279 SCEV::FlagAnyWrap); 3280 if (Ops.size() == 2) return NewAddRec; 3281 Ops[Idx] = NewAddRec; 3282 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 3283 OpsModified = true; 3284 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 3285 if (!AddRec) 3286 break; 3287 } 3288 } 3289 if (OpsModified) 3290 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3291 3292 // Otherwise couldn't fold anything into this recurrence. Move onto the 3293 // next one. 3294 } 3295 3296 // Okay, it looks like we really DO need an mul expr. Check to see if we 3297 // already have one, otherwise create a new one. 3298 return getOrCreateMulExpr(Ops, ComputeFlags(Ops)); 3299 } 3300 3301 /// Represents an unsigned remainder expression based on unsigned division. 3302 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS, 3303 const SCEV *RHS) { 3304 assert(getEffectiveSCEVType(LHS->getType()) == 3305 getEffectiveSCEVType(RHS->getType()) && 3306 "SCEVURemExpr operand types don't match!"); 3307 3308 // Short-circuit easy cases 3309 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3310 // If constant is one, the result is trivial 3311 if (RHSC->getValue()->isOne()) 3312 return getZero(LHS->getType()); // X urem 1 --> 0 3313 3314 // If constant is a power of two, fold into a zext(trunc(LHS)). 3315 if (RHSC->getAPInt().isPowerOf2()) { 3316 Type *FullTy = LHS->getType(); 3317 Type *TruncTy = 3318 IntegerType::get(getContext(), RHSC->getAPInt().logBase2()); 3319 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy); 3320 } 3321 } 3322 3323 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y) 3324 const SCEV *UDiv = getUDivExpr(LHS, RHS); 3325 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW); 3326 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW); 3327 } 3328 3329 /// Get a canonical unsigned division expression, or something simpler if 3330 /// possible. 3331 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 3332 const SCEV *RHS) { 3333 assert(!LHS->getType()->isPointerTy() && 3334 "SCEVUDivExpr operand can't be pointer!"); 3335 assert(LHS->getType() == RHS->getType() && 3336 "SCEVUDivExpr operand types don't match!"); 3337 3338 FoldingSetNodeID ID; 3339 ID.AddInteger(scUDivExpr); 3340 ID.AddPointer(LHS); 3341 ID.AddPointer(RHS); 3342 void *IP = nullptr; 3343 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 3344 return S; 3345 3346 // 0 udiv Y == 0 3347 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) 3348 if (LHSC->getValue()->isZero()) 3349 return LHS; 3350 3351 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3352 if (RHSC->getValue()->isOne()) 3353 return LHS; // X udiv 1 --> x 3354 // If the denominator is zero, the result of the udiv is undefined. Don't 3355 // try to analyze it, because the resolution chosen here may differ from 3356 // the resolution chosen in other parts of the compiler. 3357 if (!RHSC->getValue()->isZero()) { 3358 // Determine if the division can be folded into the operands of 3359 // its operands. 3360 // TODO: Generalize this to non-constants by using known-bits information. 3361 Type *Ty = LHS->getType(); 3362 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 3363 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 3364 // For non-power-of-two values, effectively round the value up to the 3365 // nearest power of two. 3366 if (!RHSC->getAPInt().isPowerOf2()) 3367 ++MaxShiftAmt; 3368 IntegerType *ExtTy = 3369 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 3370 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 3371 if (const SCEVConstant *Step = 3372 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 3373 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 3374 const APInt &StepInt = Step->getAPInt(); 3375 const APInt &DivInt = RHSC->getAPInt(); 3376 if (!StepInt.urem(DivInt) && 3377 getZeroExtendExpr(AR, ExtTy) == 3378 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3379 getZeroExtendExpr(Step, ExtTy), 3380 AR->getLoop(), SCEV::FlagAnyWrap)) { 3381 SmallVector<const SCEV *, 4> Operands; 3382 for (const SCEV *Op : AR->operands()) 3383 Operands.push_back(getUDivExpr(Op, RHS)); 3384 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 3385 } 3386 /// Get a canonical UDivExpr for a recurrence. 3387 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 3388 // We can currently only fold X%N if X is constant. 3389 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 3390 if (StartC && !DivInt.urem(StepInt) && 3391 getZeroExtendExpr(AR, ExtTy) == 3392 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3393 getZeroExtendExpr(Step, ExtTy), 3394 AR->getLoop(), SCEV::FlagAnyWrap)) { 3395 const APInt &StartInt = StartC->getAPInt(); 3396 const APInt &StartRem = StartInt.urem(StepInt); 3397 if (StartRem != 0) { 3398 const SCEV *NewLHS = 3399 getAddRecExpr(getConstant(StartInt - StartRem), Step, 3400 AR->getLoop(), SCEV::FlagNW); 3401 if (LHS != NewLHS) { 3402 LHS = NewLHS; 3403 3404 // Reset the ID to include the new LHS, and check if it is 3405 // already cached. 3406 ID.clear(); 3407 ID.AddInteger(scUDivExpr); 3408 ID.AddPointer(LHS); 3409 ID.AddPointer(RHS); 3410 IP = nullptr; 3411 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 3412 return S; 3413 } 3414 } 3415 } 3416 } 3417 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 3418 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 3419 SmallVector<const SCEV *, 4> Operands; 3420 for (const SCEV *Op : M->operands()) 3421 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3422 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 3423 // Find an operand that's safely divisible. 3424 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 3425 const SCEV *Op = M->getOperand(i); 3426 const SCEV *Div = getUDivExpr(Op, RHSC); 3427 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 3428 Operands = SmallVector<const SCEV *, 4>(M->operands()); 3429 Operands[i] = Div; 3430 return getMulExpr(Operands); 3431 } 3432 } 3433 } 3434 3435 // (A/B)/C --> A/(B*C) if safe and B*C can be folded. 3436 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) { 3437 if (auto *DivisorConstant = 3438 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) { 3439 bool Overflow = false; 3440 APInt NewRHS = 3441 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow); 3442 if (Overflow) { 3443 return getConstant(RHSC->getType(), 0, false); 3444 } 3445 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS)); 3446 } 3447 } 3448 3449 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 3450 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 3451 SmallVector<const SCEV *, 4> Operands; 3452 for (const SCEV *Op : A->operands()) 3453 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3454 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 3455 Operands.clear(); 3456 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 3457 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 3458 if (isa<SCEVUDivExpr>(Op) || 3459 getMulExpr(Op, RHS) != A->getOperand(i)) 3460 break; 3461 Operands.push_back(Op); 3462 } 3463 if (Operands.size() == A->getNumOperands()) 3464 return getAddExpr(Operands); 3465 } 3466 } 3467 3468 // Fold if both operands are constant. 3469 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 3470 Constant *LHSCV = LHSC->getValue(); 3471 Constant *RHSCV = RHSC->getValue(); 3472 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 3473 RHSCV))); 3474 } 3475 } 3476 } 3477 3478 // The Insertion Point (IP) might be invalid by now (due to UniqueSCEVs 3479 // changes). Make sure we get a new one. 3480 IP = nullptr; 3481 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3482 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 3483 LHS, RHS); 3484 UniqueSCEVs.InsertNode(S, IP); 3485 registerUser(S, {LHS, RHS}); 3486 return S; 3487 } 3488 3489 APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 3490 APInt A = C1->getAPInt().abs(); 3491 APInt B = C2->getAPInt().abs(); 3492 uint32_t ABW = A.getBitWidth(); 3493 uint32_t BBW = B.getBitWidth(); 3494 3495 if (ABW > BBW) 3496 B = B.zext(ABW); 3497 else if (ABW < BBW) 3498 A = A.zext(BBW); 3499 3500 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B)); 3501 } 3502 3503 /// Get a canonical unsigned division expression, or something simpler if 3504 /// possible. There is no representation for an exact udiv in SCEV IR, but we 3505 /// can attempt to remove factors from the LHS and RHS. We can't do this when 3506 /// it's not exact because the udiv may be clearing bits. 3507 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 3508 const SCEV *RHS) { 3509 // TODO: we could try to find factors in all sorts of things, but for now we 3510 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 3511 // end of this file for inspiration. 3512 3513 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 3514 if (!Mul || !Mul->hasNoUnsignedWrap()) 3515 return getUDivExpr(LHS, RHS); 3516 3517 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 3518 // If the mulexpr multiplies by a constant, then that constant must be the 3519 // first element of the mulexpr. 3520 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 3521 if (LHSCst == RHSCst) { 3522 SmallVector<const SCEV *, 2> Operands(drop_begin(Mul->operands())); 3523 return getMulExpr(Operands); 3524 } 3525 3526 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 3527 // that there's a factor provided by one of the other terms. We need to 3528 // check. 3529 APInt Factor = gcd(LHSCst, RHSCst); 3530 if (!Factor.isIntN(1)) { 3531 LHSCst = 3532 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 3533 RHSCst = 3534 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 3535 SmallVector<const SCEV *, 2> Operands; 3536 Operands.push_back(LHSCst); 3537 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3538 LHS = getMulExpr(Operands); 3539 RHS = RHSCst; 3540 Mul = dyn_cast<SCEVMulExpr>(LHS); 3541 if (!Mul) 3542 return getUDivExactExpr(LHS, RHS); 3543 } 3544 } 3545 } 3546 3547 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 3548 if (Mul->getOperand(i) == RHS) { 3549 SmallVector<const SCEV *, 2> Operands; 3550 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 3551 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 3552 return getMulExpr(Operands); 3553 } 3554 } 3555 3556 return getUDivExpr(LHS, RHS); 3557 } 3558 3559 /// Get an add recurrence expression for the specified loop. Simplify the 3560 /// expression as much as possible. 3561 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 3562 const Loop *L, 3563 SCEV::NoWrapFlags Flags) { 3564 SmallVector<const SCEV *, 4> Operands; 3565 Operands.push_back(Start); 3566 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 3567 if (StepChrec->getLoop() == L) { 3568 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 3569 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 3570 } 3571 3572 Operands.push_back(Step); 3573 return getAddRecExpr(Operands, L, Flags); 3574 } 3575 3576 /// Get an add recurrence expression for the specified loop. Simplify the 3577 /// expression as much as possible. 3578 const SCEV * 3579 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 3580 const Loop *L, SCEV::NoWrapFlags Flags) { 3581 if (Operands.size() == 1) return Operands[0]; 3582 #ifndef NDEBUG 3583 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 3584 for (unsigned i = 1, e = Operands.size(); i != e; ++i) { 3585 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 3586 "SCEVAddRecExpr operand types don't match!"); 3587 assert(!Operands[i]->getType()->isPointerTy() && "Step must be integer"); 3588 } 3589 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3590 assert(isLoopInvariant(Operands[i], L) && 3591 "SCEVAddRecExpr operand is not loop-invariant!"); 3592 #endif 3593 3594 if (Operands.back()->isZero()) { 3595 Operands.pop_back(); 3596 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 3597 } 3598 3599 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and 3600 // use that information to infer NUW and NSW flags. However, computing a 3601 // BE count requires calling getAddRecExpr, so we may not yet have a 3602 // meaningful BE count at this point (and if we don't, we'd be stuck 3603 // with a SCEVCouldNotCompute as the cached BE count). 3604 3605 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 3606 3607 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 3608 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 3609 const Loop *NestedLoop = NestedAR->getLoop(); 3610 if (L->contains(NestedLoop) 3611 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 3612 : (!NestedLoop->contains(L) && 3613 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 3614 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->operands()); 3615 Operands[0] = NestedAR->getStart(); 3616 // AddRecs require their operands be loop-invariant with respect to their 3617 // loops. Don't perform this transformation if it would break this 3618 // requirement. 3619 bool AllInvariant = all_of( 3620 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 3621 3622 if (AllInvariant) { 3623 // Create a recurrence for the outer loop with the same step size. 3624 // 3625 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 3626 // inner recurrence has the same property. 3627 SCEV::NoWrapFlags OuterFlags = 3628 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 3629 3630 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 3631 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 3632 return isLoopInvariant(Op, NestedLoop); 3633 }); 3634 3635 if (AllInvariant) { 3636 // Ok, both add recurrences are valid after the transformation. 3637 // 3638 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 3639 // the outer recurrence has the same property. 3640 SCEV::NoWrapFlags InnerFlags = 3641 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 3642 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 3643 } 3644 } 3645 // Reset Operands to its original state. 3646 Operands[0] = NestedAR; 3647 } 3648 } 3649 3650 // Okay, it looks like we really DO need an addrec expr. Check to see if we 3651 // already have one, otherwise create a new one. 3652 return getOrCreateAddRecExpr(Operands, L, Flags); 3653 } 3654 3655 const SCEV * 3656 ScalarEvolution::getGEPExpr(GEPOperator *GEP, 3657 const SmallVectorImpl<const SCEV *> &IndexExprs) { 3658 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand()); 3659 // getSCEV(Base)->getType() has the same address space as Base->getType() 3660 // because SCEV::getType() preserves the address space. 3661 Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType()); 3662 const bool AssumeInBoundsFlags = [&]() { 3663 if (!GEP->isInBounds()) 3664 return false; 3665 3666 // We'd like to propagate flags from the IR to the corresponding SCEV nodes, 3667 // but to do that, we have to ensure that said flag is valid in the entire 3668 // defined scope of the SCEV. 3669 auto *GEPI = dyn_cast<Instruction>(GEP); 3670 // TODO: non-instructions have global scope. We might be able to prove 3671 // some global scope cases 3672 return GEPI && isSCEVExprNeverPoison(GEPI); 3673 }(); 3674 3675 SCEV::NoWrapFlags OffsetWrap = 3676 AssumeInBoundsFlags ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3677 3678 Type *CurTy = GEP->getType(); 3679 bool FirstIter = true; 3680 SmallVector<const SCEV *, 4> Offsets; 3681 for (const SCEV *IndexExpr : IndexExprs) { 3682 // Compute the (potentially symbolic) offset in bytes for this index. 3683 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 3684 // For a struct, add the member offset. 3685 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 3686 unsigned FieldNo = Index->getZExtValue(); 3687 const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo); 3688 Offsets.push_back(FieldOffset); 3689 3690 // Update CurTy to the type of the field at Index. 3691 CurTy = STy->getTypeAtIndex(Index); 3692 } else { 3693 // Update CurTy to its element type. 3694 if (FirstIter) { 3695 assert(isa<PointerType>(CurTy) && 3696 "The first index of a GEP indexes a pointer"); 3697 CurTy = GEP->getSourceElementType(); 3698 FirstIter = false; 3699 } else { 3700 CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0); 3701 } 3702 // For an array, add the element offset, explicitly scaled. 3703 const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy); 3704 // Getelementptr indices are signed. 3705 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy); 3706 3707 // Multiply the index by the element size to compute the element offset. 3708 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap); 3709 Offsets.push_back(LocalOffset); 3710 } 3711 } 3712 3713 // Handle degenerate case of GEP without offsets. 3714 if (Offsets.empty()) 3715 return BaseExpr; 3716 3717 // Add the offsets together, assuming nsw if inbounds. 3718 const SCEV *Offset = getAddExpr(Offsets, OffsetWrap); 3719 // Add the base address and the offset. We cannot use the nsw flag, as the 3720 // base address is unsigned. However, if we know that the offset is 3721 // non-negative, we can use nuw. 3722 SCEV::NoWrapFlags BaseWrap = AssumeInBoundsFlags && isKnownNonNegative(Offset) 3723 ? SCEV::FlagNUW : SCEV::FlagAnyWrap; 3724 auto *GEPExpr = getAddExpr(BaseExpr, Offset, BaseWrap); 3725 assert(BaseExpr->getType() == GEPExpr->getType() && 3726 "GEP should not change type mid-flight."); 3727 return GEPExpr; 3728 } 3729 3730 SCEV *ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType, 3731 ArrayRef<const SCEV *> Ops) { 3732 FoldingSetNodeID ID; 3733 ID.AddInteger(SCEVType); 3734 for (const SCEV *Op : Ops) 3735 ID.AddPointer(Op); 3736 void *IP = nullptr; 3737 return UniqueSCEVs.FindNodeOrInsertPos(ID, IP); 3738 } 3739 3740 const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) { 3741 SCEV::NoWrapFlags Flags = IsNSW ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3742 return getSMaxExpr(Op, getNegativeSCEV(Op, Flags)); 3743 } 3744 3745 const SCEV *ScalarEvolution::getMinMaxExpr(SCEVTypes Kind, 3746 SmallVectorImpl<const SCEV *> &Ops) { 3747 assert(SCEVMinMaxExpr::isMinMaxType(Kind) && "Not a SCEVMinMaxExpr!"); 3748 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!"); 3749 if (Ops.size() == 1) return Ops[0]; 3750 #ifndef NDEBUG 3751 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3752 for (unsigned i = 1, e = Ops.size(); i != e; ++i) { 3753 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3754 "Operand types don't match!"); 3755 assert(Ops[0]->getType()->isPointerTy() == 3756 Ops[i]->getType()->isPointerTy() && 3757 "min/max should be consistently pointerish"); 3758 } 3759 #endif 3760 3761 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr; 3762 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr; 3763 3764 // Sort by complexity, this groups all similar expression types together. 3765 GroupByComplexity(Ops, &LI, DT); 3766 3767 // Check if we have created the same expression before. 3768 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops)) { 3769 return S; 3770 } 3771 3772 // If there are any constants, fold them together. 3773 unsigned Idx = 0; 3774 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3775 ++Idx; 3776 assert(Idx < Ops.size()); 3777 auto FoldOp = [&](const APInt &LHS, const APInt &RHS) { 3778 if (Kind == scSMaxExpr) 3779 return APIntOps::smax(LHS, RHS); 3780 else if (Kind == scSMinExpr) 3781 return APIntOps::smin(LHS, RHS); 3782 else if (Kind == scUMaxExpr) 3783 return APIntOps::umax(LHS, RHS); 3784 else if (Kind == scUMinExpr) 3785 return APIntOps::umin(LHS, RHS); 3786 llvm_unreachable("Unknown SCEV min/max opcode"); 3787 }; 3788 3789 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3790 // We found two constants, fold them together! 3791 ConstantInt *Fold = ConstantInt::get( 3792 getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt())); 3793 Ops[0] = getConstant(Fold); 3794 Ops.erase(Ops.begin()+1); // Erase the folded element 3795 if (Ops.size() == 1) return Ops[0]; 3796 LHSC = cast<SCEVConstant>(Ops[0]); 3797 } 3798 3799 bool IsMinV = LHSC->getValue()->isMinValue(IsSigned); 3800 bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned); 3801 3802 if (IsMax ? IsMinV : IsMaxV) { 3803 // If we are left with a constant minimum(/maximum)-int, strip it off. 3804 Ops.erase(Ops.begin()); 3805 --Idx; 3806 } else if (IsMax ? IsMaxV : IsMinV) { 3807 // If we have a max(/min) with a constant maximum(/minimum)-int, 3808 // it will always be the extremum. 3809 return LHSC; 3810 } 3811 3812 if (Ops.size() == 1) return Ops[0]; 3813 } 3814 3815 // Find the first operation of the same kind 3816 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind) 3817 ++Idx; 3818 3819 // Check to see if one of the operands is of the same kind. If so, expand its 3820 // operands onto our operand list, and recurse to simplify. 3821 if (Idx < Ops.size()) { 3822 bool DeletedAny = false; 3823 while (Ops[Idx]->getSCEVType() == Kind) { 3824 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]); 3825 Ops.erase(Ops.begin()+Idx); 3826 Ops.append(SMME->op_begin(), SMME->op_end()); 3827 DeletedAny = true; 3828 } 3829 3830 if (DeletedAny) 3831 return getMinMaxExpr(Kind, Ops); 3832 } 3833 3834 // Okay, check to see if the same value occurs in the operand list twice. If 3835 // so, delete one. Since we sorted the list, these values are required to 3836 // be adjacent. 3837 llvm::CmpInst::Predicate GEPred = 3838 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 3839 llvm::CmpInst::Predicate LEPred = 3840 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 3841 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred; 3842 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred; 3843 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) { 3844 if (Ops[i] == Ops[i + 1] || 3845 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) { 3846 // X op Y op Y --> X op Y 3847 // X op Y --> X, if we know X, Y are ordered appropriately 3848 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2); 3849 --i; 3850 --e; 3851 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i], 3852 Ops[i + 1])) { 3853 // X op Y --> Y, if we know X, Y are ordered appropriately 3854 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1); 3855 --i; 3856 --e; 3857 } 3858 } 3859 3860 if (Ops.size() == 1) return Ops[0]; 3861 3862 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3863 3864 // Okay, it looks like we really DO need an expr. Check to see if we 3865 // already have one, otherwise create a new one. 3866 FoldingSetNodeID ID; 3867 ID.AddInteger(Kind); 3868 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3869 ID.AddPointer(Ops[i]); 3870 void *IP = nullptr; 3871 const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP); 3872 if (ExistingSCEV) 3873 return ExistingSCEV; 3874 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3875 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3876 SCEV *S = new (SCEVAllocator) 3877 SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size()); 3878 3879 UniqueSCEVs.InsertNode(S, IP); 3880 registerUser(S, Ops); 3881 return S; 3882 } 3883 3884 namespace { 3885 3886 class SCEVSequentialMinMaxDeduplicatingVisitor final 3887 : public SCEVVisitor<SCEVSequentialMinMaxDeduplicatingVisitor, 3888 Optional<const SCEV *>> { 3889 using RetVal = Optional<const SCEV *>; 3890 using Base = SCEVVisitor<SCEVSequentialMinMaxDeduplicatingVisitor, RetVal>; 3891 3892 ScalarEvolution &SE; 3893 const SCEVTypes RootKind; // Must be a sequential min/max expression. 3894 const SCEVTypes NonSequentialRootKind; // Non-sequential variant of RootKind. 3895 SmallPtrSet<const SCEV *, 16> SeenOps; 3896 3897 bool canRecurseInto(SCEVTypes Kind) const { 3898 // We can only recurse into the SCEV expression of the same effective type 3899 // as the type of our root SCEV expression. 3900 return RootKind == Kind || NonSequentialRootKind == Kind; 3901 }; 3902 3903 RetVal visitAnyMinMaxExpr(const SCEV *S) { 3904 assert((isa<SCEVMinMaxExpr>(S) || isa<SCEVSequentialMinMaxExpr>(S)) && 3905 "Only for min/max expressions."); 3906 SCEVTypes Kind = S->getSCEVType(); 3907 3908 if (!canRecurseInto(Kind)) 3909 return S; 3910 3911 auto *NAry = cast<SCEVNAryExpr>(S); 3912 SmallVector<const SCEV *> NewOps; 3913 bool Changed = 3914 visit(Kind, makeArrayRef(NAry->op_begin(), NAry->op_end()), NewOps); 3915 3916 if (!Changed) 3917 return S; 3918 if (NewOps.empty()) 3919 return None; 3920 3921 return isa<SCEVSequentialMinMaxExpr>(S) 3922 ? SE.getSequentialMinMaxExpr(Kind, NewOps) 3923 : SE.getMinMaxExpr(Kind, NewOps); 3924 } 3925 3926 RetVal visit(const SCEV *S) { 3927 // Has the whole operand been seen already? 3928 if (!SeenOps.insert(S).second) 3929 return None; 3930 return Base::visit(S); 3931 } 3932 3933 public: 3934 SCEVSequentialMinMaxDeduplicatingVisitor(ScalarEvolution &SE, 3935 SCEVTypes RootKind) 3936 : SE(SE), RootKind(RootKind), 3937 NonSequentialRootKind( 3938 SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType( 3939 RootKind)) {} 3940 3941 bool /*Changed*/ visit(SCEVTypes Kind, ArrayRef<const SCEV *> OrigOps, 3942 SmallVectorImpl<const SCEV *> &NewOps) { 3943 bool Changed = false; 3944 SmallVector<const SCEV *> Ops; 3945 Ops.reserve(OrigOps.size()); 3946 3947 for (const SCEV *Op : OrigOps) { 3948 RetVal NewOp = visit(Op); 3949 if (NewOp != Op) 3950 Changed = true; 3951 if (NewOp) 3952 Ops.emplace_back(*NewOp); 3953 } 3954 3955 if (Changed) 3956 NewOps = std::move(Ops); 3957 return Changed; 3958 } 3959 3960 RetVal visitConstant(const SCEVConstant *Constant) { return Constant; } 3961 3962 RetVal visitPtrToIntExpr(const SCEVPtrToIntExpr *Expr) { return Expr; } 3963 3964 RetVal visitTruncateExpr(const SCEVTruncateExpr *Expr) { return Expr; } 3965 3966 RetVal visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { return Expr; } 3967 3968 RetVal visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { return Expr; } 3969 3970 RetVal visitAddExpr(const SCEVAddExpr *Expr) { return Expr; } 3971 3972 RetVal visitMulExpr(const SCEVMulExpr *Expr) { return Expr; } 3973 3974 RetVal visitUDivExpr(const SCEVUDivExpr *Expr) { return Expr; } 3975 3976 RetVal visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; } 3977 3978 RetVal visitSMaxExpr(const SCEVSMaxExpr *Expr) { 3979 return visitAnyMinMaxExpr(Expr); 3980 } 3981 3982 RetVal visitUMaxExpr(const SCEVUMaxExpr *Expr) { 3983 return visitAnyMinMaxExpr(Expr); 3984 } 3985 3986 RetVal visitSMinExpr(const SCEVSMinExpr *Expr) { 3987 return visitAnyMinMaxExpr(Expr); 3988 } 3989 3990 RetVal visitUMinExpr(const SCEVUMinExpr *Expr) { 3991 return visitAnyMinMaxExpr(Expr); 3992 } 3993 3994 RetVal visitSequentialUMinExpr(const SCEVSequentialUMinExpr *Expr) { 3995 return visitAnyMinMaxExpr(Expr); 3996 } 3997 3998 RetVal visitUnknown(const SCEVUnknown *Expr) { return Expr; } 3999 4000 RetVal visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { return Expr; } 4001 }; 4002 4003 } // namespace 4004 4005 const SCEV * 4006 ScalarEvolution::getSequentialMinMaxExpr(SCEVTypes Kind, 4007 SmallVectorImpl<const SCEV *> &Ops) { 4008 assert(SCEVSequentialMinMaxExpr::isSequentialMinMaxType(Kind) && 4009 "Not a SCEVSequentialMinMaxExpr!"); 4010 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!"); 4011 if (Ops.size() == 1) 4012 return Ops[0]; 4013 if (Ops.size() == 2 && 4014 any_of(Ops, [](const SCEV *Op) { return isa<SCEVConstant>(Op); })) 4015 return getMinMaxExpr( 4016 SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(Kind), 4017 Ops); 4018 #ifndef NDEBUG 4019 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 4020 for (unsigned i = 1, e = Ops.size(); i != e; ++i) { 4021 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 4022 "Operand types don't match!"); 4023 assert(Ops[0]->getType()->isPointerTy() == 4024 Ops[i]->getType()->isPointerTy() && 4025 "min/max should be consistently pointerish"); 4026 } 4027 #endif 4028 4029 // Note that SCEVSequentialMinMaxExpr is *NOT* commutative, 4030 // so we can *NOT* do any kind of sorting of the expressions! 4031 4032 // Check if we have created the same expression before. 4033 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops)) 4034 return S; 4035 4036 // FIXME: there are *some* simplifications that we can do here. 4037 4038 // Keep only the first instance of an operand. 4039 { 4040 SCEVSequentialMinMaxDeduplicatingVisitor Deduplicator(*this, Kind); 4041 bool Changed = Deduplicator.visit(Kind, Ops, Ops); 4042 if (Changed) 4043 return getSequentialMinMaxExpr(Kind, Ops); 4044 } 4045 4046 // Check to see if one of the operands is of the same kind. If so, expand its 4047 // operands onto our operand list, and recurse to simplify. 4048 { 4049 unsigned Idx = 0; 4050 bool DeletedAny = false; 4051 while (Idx < Ops.size()) { 4052 if (Ops[Idx]->getSCEVType() != Kind) { 4053 ++Idx; 4054 continue; 4055 } 4056 const auto *SMME = cast<SCEVSequentialMinMaxExpr>(Ops[Idx]); 4057 Ops.erase(Ops.begin() + Idx); 4058 Ops.insert(Ops.begin() + Idx, SMME->op_begin(), SMME->op_end()); 4059 DeletedAny = true; 4060 } 4061 4062 if (DeletedAny) 4063 return getSequentialMinMaxExpr(Kind, Ops); 4064 } 4065 4066 // Okay, it looks like we really DO need an expr. Check to see if we 4067 // already have one, otherwise create a new one. 4068 FoldingSetNodeID ID; 4069 ID.AddInteger(Kind); 4070 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 4071 ID.AddPointer(Ops[i]); 4072 void *IP = nullptr; 4073 const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP); 4074 if (ExistingSCEV) 4075 return ExistingSCEV; 4076 4077 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 4078 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 4079 SCEV *S = new (SCEVAllocator) 4080 SCEVSequentialMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size()); 4081 4082 UniqueSCEVs.InsertNode(S, IP); 4083 registerUser(S, Ops); 4084 return S; 4085 } 4086 4087 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) { 4088 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 4089 return getSMaxExpr(Ops); 4090 } 4091 4092 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 4093 return getMinMaxExpr(scSMaxExpr, Ops); 4094 } 4095 4096 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) { 4097 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 4098 return getUMaxExpr(Ops); 4099 } 4100 4101 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 4102 return getMinMaxExpr(scUMaxExpr, Ops); 4103 } 4104 4105 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 4106 const SCEV *RHS) { 4107 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 4108 return getSMinExpr(Ops); 4109 } 4110 4111 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 4112 return getMinMaxExpr(scSMinExpr, Ops); 4113 } 4114 4115 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, const SCEV *RHS, 4116 bool Sequential) { 4117 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 4118 return getUMinExpr(Ops, Sequential); 4119 } 4120 4121 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops, 4122 bool Sequential) { 4123 return Sequential ? getSequentialMinMaxExpr(scSequentialUMinExpr, Ops) 4124 : getMinMaxExpr(scUMinExpr, Ops); 4125 } 4126 4127 const SCEV * 4128 ScalarEvolution::getSizeOfScalableVectorExpr(Type *IntTy, 4129 ScalableVectorType *ScalableTy) { 4130 Constant *NullPtr = Constant::getNullValue(ScalableTy->getPointerTo()); 4131 Constant *One = ConstantInt::get(IntTy, 1); 4132 Constant *GEP = ConstantExpr::getGetElementPtr(ScalableTy, NullPtr, One); 4133 // Note that the expression we created is the final expression, we don't 4134 // want to simplify it any further Also, if we call a normal getSCEV(), 4135 // we'll end up in an endless recursion. So just create an SCEVUnknown. 4136 return getUnknown(ConstantExpr::getPtrToInt(GEP, IntTy)); 4137 } 4138 4139 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 4140 if (auto *ScalableAllocTy = dyn_cast<ScalableVectorType>(AllocTy)) 4141 return getSizeOfScalableVectorExpr(IntTy, ScalableAllocTy); 4142 // We can bypass creating a target-independent constant expression and then 4143 // folding it back into a ConstantInt. This is just a compile-time 4144 // optimization. 4145 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 4146 } 4147 4148 const SCEV *ScalarEvolution::getStoreSizeOfExpr(Type *IntTy, Type *StoreTy) { 4149 if (auto *ScalableStoreTy = dyn_cast<ScalableVectorType>(StoreTy)) 4150 return getSizeOfScalableVectorExpr(IntTy, ScalableStoreTy); 4151 // We can bypass creating a target-independent constant expression and then 4152 // folding it back into a ConstantInt. This is just a compile-time 4153 // optimization. 4154 return getConstant(IntTy, getDataLayout().getTypeStoreSize(StoreTy)); 4155 } 4156 4157 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 4158 StructType *STy, 4159 unsigned FieldNo) { 4160 // We can bypass creating a target-independent constant expression and then 4161 // folding it back into a ConstantInt. This is just a compile-time 4162 // optimization. 4163 return getConstant( 4164 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 4165 } 4166 4167 const SCEV *ScalarEvolution::getUnknown(Value *V) { 4168 // Don't attempt to do anything other than create a SCEVUnknown object 4169 // here. createSCEV only calls getUnknown after checking for all other 4170 // interesting possibilities, and any other code that calls getUnknown 4171 // is doing so in order to hide a value from SCEV canonicalization. 4172 4173 FoldingSetNodeID ID; 4174 ID.AddInteger(scUnknown); 4175 ID.AddPointer(V); 4176 void *IP = nullptr; 4177 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 4178 assert(cast<SCEVUnknown>(S)->getValue() == V && 4179 "Stale SCEVUnknown in uniquing map!"); 4180 return S; 4181 } 4182 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 4183 FirstUnknown); 4184 FirstUnknown = cast<SCEVUnknown>(S); 4185 UniqueSCEVs.InsertNode(S, IP); 4186 return S; 4187 } 4188 4189 //===----------------------------------------------------------------------===// 4190 // Basic SCEV Analysis and PHI Idiom Recognition Code 4191 // 4192 4193 /// Test if values of the given type are analyzable within the SCEV 4194 /// framework. This primarily includes integer types, and it can optionally 4195 /// include pointer types if the ScalarEvolution class has access to 4196 /// target-specific information. 4197 bool ScalarEvolution::isSCEVable(Type *Ty) const { 4198 // Integers and pointers are always SCEVable. 4199 return Ty->isIntOrPtrTy(); 4200 } 4201 4202 /// Return the size in bits of the specified type, for which isSCEVable must 4203 /// return true. 4204 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 4205 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 4206 if (Ty->isPointerTy()) 4207 return getDataLayout().getIndexTypeSizeInBits(Ty); 4208 return getDataLayout().getTypeSizeInBits(Ty); 4209 } 4210 4211 /// Return a type with the same bitwidth as the given type and which represents 4212 /// how SCEV will treat the given type, for which isSCEVable must return 4213 /// true. For pointer types, this is the pointer index sized integer type. 4214 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 4215 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 4216 4217 if (Ty->isIntegerTy()) 4218 return Ty; 4219 4220 // The only other support type is pointer. 4221 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 4222 return getDataLayout().getIndexType(Ty); 4223 } 4224 4225 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const { 4226 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2; 4227 } 4228 4229 bool ScalarEvolution::instructionCouldExistWitthOperands(const SCEV *A, 4230 const SCEV *B) { 4231 /// For a valid use point to exist, the defining scope of one operand 4232 /// must dominate the other. 4233 bool PreciseA, PreciseB; 4234 auto *ScopeA = getDefiningScopeBound({A}, PreciseA); 4235 auto *ScopeB = getDefiningScopeBound({B}, PreciseB); 4236 if (!PreciseA || !PreciseB) 4237 // Can't tell. 4238 return false; 4239 return (ScopeA == ScopeB) || DT.dominates(ScopeA, ScopeB) || 4240 DT.dominates(ScopeB, ScopeA); 4241 } 4242 4243 4244 const SCEV *ScalarEvolution::getCouldNotCompute() { 4245 return CouldNotCompute.get(); 4246 } 4247 4248 bool ScalarEvolution::checkValidity(const SCEV *S) const { 4249 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) { 4250 auto *SU = dyn_cast<SCEVUnknown>(S); 4251 return SU && SU->getValue() == nullptr; 4252 }); 4253 4254 return !ContainsNulls; 4255 } 4256 4257 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 4258 HasRecMapType::iterator I = HasRecMap.find(S); 4259 if (I != HasRecMap.end()) 4260 return I->second; 4261 4262 bool FoundAddRec = 4263 SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); }); 4264 HasRecMap.insert({S, FoundAddRec}); 4265 return FoundAddRec; 4266 } 4267 4268 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. 4269 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an 4270 /// offset I, then return {S', I}, else return {\p S, nullptr}. 4271 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { 4272 const auto *Add = dyn_cast<SCEVAddExpr>(S); 4273 if (!Add) 4274 return {S, nullptr}; 4275 4276 if (Add->getNumOperands() != 2) 4277 return {S, nullptr}; 4278 4279 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); 4280 if (!ConstOp) 4281 return {S, nullptr}; 4282 4283 return {Add->getOperand(1), ConstOp->getValue()}; 4284 } 4285 4286 /// Return the ValueOffsetPair set for \p S. \p S can be represented 4287 /// by the value and offset from any ValueOffsetPair in the set. 4288 ScalarEvolution::ValueOffsetPairSetVector * 4289 ScalarEvolution::getSCEVValues(const SCEV *S) { 4290 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 4291 if (SI == ExprValueMap.end()) 4292 return nullptr; 4293 #ifndef NDEBUG 4294 if (VerifySCEVMap) { 4295 // Check there is no dangling Value in the set returned. 4296 for (const auto &VE : SI->second) 4297 assert(ValueExprMap.count(VE.first)); 4298 } 4299 #endif 4300 return &SI->second; 4301 } 4302 4303 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) 4304 /// cannot be used separately. eraseValueFromMap should be used to remove 4305 /// V from ValueExprMap and ExprValueMap at the same time. 4306 void ScalarEvolution::eraseValueFromMap(Value *V) { 4307 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 4308 if (I != ValueExprMap.end()) { 4309 const SCEV *S = I->second; 4310 // Remove {V, 0} from the set of ExprValueMap[S] 4311 if (auto *SV = getSCEVValues(S)) 4312 SV->remove({V, nullptr}); 4313 4314 // Remove {V, Offset} from the set of ExprValueMap[Stripped] 4315 const SCEV *Stripped; 4316 ConstantInt *Offset; 4317 std::tie(Stripped, Offset) = splitAddExpr(S); 4318 if (Offset != nullptr) { 4319 if (auto *SV = getSCEVValues(Stripped)) 4320 SV->remove({V, Offset}); 4321 } 4322 ValueExprMap.erase(V); 4323 } 4324 } 4325 4326 void ScalarEvolution::insertValueToMap(Value *V, const SCEV *S) { 4327 // A recursive query may have already computed the SCEV. It should be 4328 // equivalent, but may not necessarily be exactly the same, e.g. due to lazily 4329 // inferred nowrap flags. 4330 auto It = ValueExprMap.find_as(V); 4331 if (It == ValueExprMap.end()) { 4332 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 4333 ExprValueMap[S].insert({V, nullptr}); 4334 } 4335 } 4336 4337 /// Return an existing SCEV if it exists, otherwise analyze the expression and 4338 /// create a new one. 4339 const SCEV *ScalarEvolution::getSCEV(Value *V) { 4340 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 4341 4342 const SCEV *S = getExistingSCEV(V); 4343 if (S == nullptr) { 4344 S = createSCEV(V); 4345 // During PHI resolution, it is possible to create two SCEVs for the same 4346 // V, so it is needed to double check whether V->S is inserted into 4347 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 4348 std::pair<ValueExprMapType::iterator, bool> Pair = 4349 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 4350 if (Pair.second) { 4351 ExprValueMap[S].insert({V, nullptr}); 4352 4353 // If S == Stripped + Offset, add Stripped -> {V, Offset} into 4354 // ExprValueMap. 4355 const SCEV *Stripped = S; 4356 ConstantInt *Offset = nullptr; 4357 std::tie(Stripped, Offset) = splitAddExpr(S); 4358 // If stripped is SCEVUnknown, don't bother to save 4359 // Stripped -> {V, offset}. It doesn't simplify and sometimes even 4360 // increase the complexity of the expansion code. 4361 // If V is GetElementPtrInst, don't save Stripped -> {V, offset} 4362 // because it may generate add/sub instead of GEP in SCEV expansion. 4363 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && 4364 !isa<GetElementPtrInst>(V)) 4365 ExprValueMap[Stripped].insert({V, Offset}); 4366 } 4367 } 4368 return S; 4369 } 4370 4371 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 4372 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 4373 4374 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 4375 if (I != ValueExprMap.end()) { 4376 const SCEV *S = I->second; 4377 assert(checkValidity(S) && 4378 "existing SCEV has not been properly invalidated"); 4379 return S; 4380 } 4381 return nullptr; 4382 } 4383 4384 /// Return a SCEV corresponding to -V = -1*V 4385 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 4386 SCEV::NoWrapFlags Flags) { 4387 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 4388 return getConstant( 4389 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 4390 4391 Type *Ty = V->getType(); 4392 Ty = getEffectiveSCEVType(Ty); 4393 return getMulExpr(V, getMinusOne(Ty), Flags); 4394 } 4395 4396 /// If Expr computes ~A, return A else return nullptr 4397 static const SCEV *MatchNotExpr(const SCEV *Expr) { 4398 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 4399 if (!Add || Add->getNumOperands() != 2 || 4400 !Add->getOperand(0)->isAllOnesValue()) 4401 return nullptr; 4402 4403 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 4404 if (!AddRHS || AddRHS->getNumOperands() != 2 || 4405 !AddRHS->getOperand(0)->isAllOnesValue()) 4406 return nullptr; 4407 4408 return AddRHS->getOperand(1); 4409 } 4410 4411 /// Return a SCEV corresponding to ~V = -1-V 4412 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 4413 assert(!V->getType()->isPointerTy() && "Can't negate pointer"); 4414 4415 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 4416 return getConstant( 4417 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 4418 4419 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y) 4420 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) { 4421 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) { 4422 SmallVector<const SCEV *, 2> MatchedOperands; 4423 for (const SCEV *Operand : MME->operands()) { 4424 const SCEV *Matched = MatchNotExpr(Operand); 4425 if (!Matched) 4426 return (const SCEV *)nullptr; 4427 MatchedOperands.push_back(Matched); 4428 } 4429 return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()), 4430 MatchedOperands); 4431 }; 4432 if (const SCEV *Replaced = MatchMinMaxNegation(MME)) 4433 return Replaced; 4434 } 4435 4436 Type *Ty = V->getType(); 4437 Ty = getEffectiveSCEVType(Ty); 4438 return getMinusSCEV(getMinusOne(Ty), V); 4439 } 4440 4441 const SCEV *ScalarEvolution::removePointerBase(const SCEV *P) { 4442 assert(P->getType()->isPointerTy()); 4443 4444 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(P)) { 4445 // The base of an AddRec is the first operand. 4446 SmallVector<const SCEV *> Ops{AddRec->operands()}; 4447 Ops[0] = removePointerBase(Ops[0]); 4448 // Don't try to transfer nowrap flags for now. We could in some cases 4449 // (for example, if pointer operand of the AddRec is a SCEVUnknown). 4450 return getAddRecExpr(Ops, AddRec->getLoop(), SCEV::FlagAnyWrap); 4451 } 4452 if (auto *Add = dyn_cast<SCEVAddExpr>(P)) { 4453 // The base of an Add is the pointer operand. 4454 SmallVector<const SCEV *> Ops{Add->operands()}; 4455 const SCEV **PtrOp = nullptr; 4456 for (const SCEV *&AddOp : Ops) { 4457 if (AddOp->getType()->isPointerTy()) { 4458 assert(!PtrOp && "Cannot have multiple pointer ops"); 4459 PtrOp = &AddOp; 4460 } 4461 } 4462 *PtrOp = removePointerBase(*PtrOp); 4463 // Don't try to transfer nowrap flags for now. We could in some cases 4464 // (for example, if the pointer operand of the Add is a SCEVUnknown). 4465 return getAddExpr(Ops); 4466 } 4467 // Any other expression must be a pointer base. 4468 return getZero(P->getType()); 4469 } 4470 4471 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 4472 SCEV::NoWrapFlags Flags, 4473 unsigned Depth) { 4474 // Fast path: X - X --> 0. 4475 if (LHS == RHS) 4476 return getZero(LHS->getType()); 4477 4478 // If we subtract two pointers with different pointer bases, bail. 4479 // Eventually, we're going to add an assertion to getMulExpr that we 4480 // can't multiply by a pointer. 4481 if (RHS->getType()->isPointerTy()) { 4482 if (!LHS->getType()->isPointerTy() || 4483 getPointerBase(LHS) != getPointerBase(RHS)) 4484 return getCouldNotCompute(); 4485 LHS = removePointerBase(LHS); 4486 RHS = removePointerBase(RHS); 4487 } 4488 4489 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 4490 // makes it so that we cannot make much use of NUW. 4491 auto AddFlags = SCEV::FlagAnyWrap; 4492 const bool RHSIsNotMinSigned = 4493 !getSignedRangeMin(RHS).isMinSignedValue(); 4494 if (hasFlags(Flags, SCEV::FlagNSW)) { 4495 // Let M be the minimum representable signed value. Then (-1)*RHS 4496 // signed-wraps if and only if RHS is M. That can happen even for 4497 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 4498 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 4499 // (-1)*RHS, we need to prove that RHS != M. 4500 // 4501 // If LHS is non-negative and we know that LHS - RHS does not 4502 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 4503 // either by proving that RHS > M or that LHS >= 0. 4504 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 4505 AddFlags = SCEV::FlagNSW; 4506 } 4507 } 4508 4509 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 4510 // RHS is NSW and LHS >= 0. 4511 // 4512 // The difficulty here is that the NSW flag may have been proven 4513 // relative to a loop that is to be found in a recurrence in LHS and 4514 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 4515 // larger scope than intended. 4516 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 4517 4518 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth); 4519 } 4520 4521 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty, 4522 unsigned Depth) { 4523 Type *SrcTy = V->getType(); 4524 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4525 "Cannot truncate or zero extend with non-integer arguments!"); 4526 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4527 return V; // No conversion 4528 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4529 return getTruncateExpr(V, Ty, Depth); 4530 return getZeroExtendExpr(V, Ty, Depth); 4531 } 4532 4533 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty, 4534 unsigned Depth) { 4535 Type *SrcTy = V->getType(); 4536 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4537 "Cannot truncate or zero extend with non-integer arguments!"); 4538 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4539 return V; // No conversion 4540 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4541 return getTruncateExpr(V, Ty, Depth); 4542 return getSignExtendExpr(V, Ty, Depth); 4543 } 4544 4545 const SCEV * 4546 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 4547 Type *SrcTy = V->getType(); 4548 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4549 "Cannot noop or zero extend with non-integer arguments!"); 4550 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4551 "getNoopOrZeroExtend cannot truncate!"); 4552 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4553 return V; // No conversion 4554 return getZeroExtendExpr(V, Ty); 4555 } 4556 4557 const SCEV * 4558 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 4559 Type *SrcTy = V->getType(); 4560 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4561 "Cannot noop or sign extend with non-integer arguments!"); 4562 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4563 "getNoopOrSignExtend cannot truncate!"); 4564 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4565 return V; // No conversion 4566 return getSignExtendExpr(V, Ty); 4567 } 4568 4569 const SCEV * 4570 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 4571 Type *SrcTy = V->getType(); 4572 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4573 "Cannot noop or any extend with non-integer arguments!"); 4574 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4575 "getNoopOrAnyExtend cannot truncate!"); 4576 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4577 return V; // No conversion 4578 return getAnyExtendExpr(V, Ty); 4579 } 4580 4581 const SCEV * 4582 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 4583 Type *SrcTy = V->getType(); 4584 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4585 "Cannot truncate or noop with non-integer arguments!"); 4586 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 4587 "getTruncateOrNoop cannot extend!"); 4588 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4589 return V; // No conversion 4590 return getTruncateExpr(V, Ty); 4591 } 4592 4593 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 4594 const SCEV *RHS) { 4595 const SCEV *PromotedLHS = LHS; 4596 const SCEV *PromotedRHS = RHS; 4597 4598 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 4599 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 4600 else 4601 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 4602 4603 return getUMaxExpr(PromotedLHS, PromotedRHS); 4604 } 4605 4606 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 4607 const SCEV *RHS, 4608 bool Sequential) { 4609 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 4610 return getUMinFromMismatchedTypes(Ops, Sequential); 4611 } 4612 4613 const SCEV * 4614 ScalarEvolution::getUMinFromMismatchedTypes(SmallVectorImpl<const SCEV *> &Ops, 4615 bool Sequential) { 4616 assert(!Ops.empty() && "At least one operand must be!"); 4617 // Trivial case. 4618 if (Ops.size() == 1) 4619 return Ops[0]; 4620 4621 // Find the max type first. 4622 Type *MaxType = nullptr; 4623 for (auto *S : Ops) 4624 if (MaxType) 4625 MaxType = getWiderType(MaxType, S->getType()); 4626 else 4627 MaxType = S->getType(); 4628 assert(MaxType && "Failed to find maximum type!"); 4629 4630 // Extend all ops to max type. 4631 SmallVector<const SCEV *, 2> PromotedOps; 4632 for (auto *S : Ops) 4633 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType)); 4634 4635 // Generate umin. 4636 return getUMinExpr(PromotedOps, Sequential); 4637 } 4638 4639 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 4640 // A pointer operand may evaluate to a nonpointer expression, such as null. 4641 if (!V->getType()->isPointerTy()) 4642 return V; 4643 4644 while (true) { 4645 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 4646 V = AddRec->getStart(); 4647 } else if (auto *Add = dyn_cast<SCEVAddExpr>(V)) { 4648 const SCEV *PtrOp = nullptr; 4649 for (const SCEV *AddOp : Add->operands()) { 4650 if (AddOp->getType()->isPointerTy()) { 4651 assert(!PtrOp && "Cannot have multiple pointer ops"); 4652 PtrOp = AddOp; 4653 } 4654 } 4655 assert(PtrOp && "Must have pointer op"); 4656 V = PtrOp; 4657 } else // Not something we can look further into. 4658 return V; 4659 } 4660 } 4661 4662 /// Push users of the given Instruction onto the given Worklist. 4663 static void PushDefUseChildren(Instruction *I, 4664 SmallVectorImpl<Instruction *> &Worklist, 4665 SmallPtrSetImpl<Instruction *> &Visited) { 4666 // Push the def-use children onto the Worklist stack. 4667 for (User *U : I->users()) { 4668 auto *UserInsn = cast<Instruction>(U); 4669 if (Visited.insert(UserInsn).second) 4670 Worklist.push_back(UserInsn); 4671 } 4672 } 4673 4674 namespace { 4675 4676 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start 4677 /// expression in case its Loop is L. If it is not L then 4678 /// if IgnoreOtherLoops is true then use AddRec itself 4679 /// otherwise rewrite cannot be done. 4680 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4681 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 4682 public: 4683 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 4684 bool IgnoreOtherLoops = true) { 4685 SCEVInitRewriter Rewriter(L, SE); 4686 const SCEV *Result = Rewriter.visit(S); 4687 if (Rewriter.hasSeenLoopVariantSCEVUnknown()) 4688 return SE.getCouldNotCompute(); 4689 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops 4690 ? SE.getCouldNotCompute() 4691 : Result; 4692 } 4693 4694 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4695 if (!SE.isLoopInvariant(Expr, L)) 4696 SeenLoopVariantSCEVUnknown = true; 4697 return Expr; 4698 } 4699 4700 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4701 // Only re-write AddRecExprs for this loop. 4702 if (Expr->getLoop() == L) 4703 return Expr->getStart(); 4704 SeenOtherLoops = true; 4705 return Expr; 4706 } 4707 4708 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4709 4710 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4711 4712 private: 4713 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 4714 : SCEVRewriteVisitor(SE), L(L) {} 4715 4716 const Loop *L; 4717 bool SeenLoopVariantSCEVUnknown = false; 4718 bool SeenOtherLoops = false; 4719 }; 4720 4721 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post 4722 /// increment expression in case its Loop is L. If it is not L then 4723 /// use AddRec itself. 4724 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4725 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> { 4726 public: 4727 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) { 4728 SCEVPostIncRewriter Rewriter(L, SE); 4729 const SCEV *Result = Rewriter.visit(S); 4730 return Rewriter.hasSeenLoopVariantSCEVUnknown() 4731 ? SE.getCouldNotCompute() 4732 : Result; 4733 } 4734 4735 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4736 if (!SE.isLoopInvariant(Expr, L)) 4737 SeenLoopVariantSCEVUnknown = true; 4738 return Expr; 4739 } 4740 4741 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4742 // Only re-write AddRecExprs for this loop. 4743 if (Expr->getLoop() == L) 4744 return Expr->getPostIncExpr(SE); 4745 SeenOtherLoops = true; 4746 return Expr; 4747 } 4748 4749 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4750 4751 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4752 4753 private: 4754 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE) 4755 : SCEVRewriteVisitor(SE), L(L) {} 4756 4757 const Loop *L; 4758 bool SeenLoopVariantSCEVUnknown = false; 4759 bool SeenOtherLoops = false; 4760 }; 4761 4762 /// This class evaluates the compare condition by matching it against the 4763 /// condition of loop latch. If there is a match we assume a true value 4764 /// for the condition while building SCEV nodes. 4765 class SCEVBackedgeConditionFolder 4766 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> { 4767 public: 4768 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4769 ScalarEvolution &SE) { 4770 bool IsPosBECond = false; 4771 Value *BECond = nullptr; 4772 if (BasicBlock *Latch = L->getLoopLatch()) { 4773 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator()); 4774 if (BI && BI->isConditional()) { 4775 assert(BI->getSuccessor(0) != BI->getSuccessor(1) && 4776 "Both outgoing branches should not target same header!"); 4777 BECond = BI->getCondition(); 4778 IsPosBECond = BI->getSuccessor(0) == L->getHeader(); 4779 } else { 4780 return S; 4781 } 4782 } 4783 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE); 4784 return Rewriter.visit(S); 4785 } 4786 4787 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4788 const SCEV *Result = Expr; 4789 bool InvariantF = SE.isLoopInvariant(Expr, L); 4790 4791 if (!InvariantF) { 4792 Instruction *I = cast<Instruction>(Expr->getValue()); 4793 switch (I->getOpcode()) { 4794 case Instruction::Select: { 4795 SelectInst *SI = cast<SelectInst>(I); 4796 Optional<const SCEV *> Res = 4797 compareWithBackedgeCondition(SI->getCondition()); 4798 if (Res.hasValue()) { 4799 bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne(); 4800 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue()); 4801 } 4802 break; 4803 } 4804 default: { 4805 Optional<const SCEV *> Res = compareWithBackedgeCondition(I); 4806 if (Res.hasValue()) 4807 Result = Res.getValue(); 4808 break; 4809 } 4810 } 4811 } 4812 return Result; 4813 } 4814 4815 private: 4816 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond, 4817 bool IsPosBECond, ScalarEvolution &SE) 4818 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond), 4819 IsPositiveBECond(IsPosBECond) {} 4820 4821 Optional<const SCEV *> compareWithBackedgeCondition(Value *IC); 4822 4823 const Loop *L; 4824 /// Loop back condition. 4825 Value *BackedgeCond = nullptr; 4826 /// Set to true if loop back is on positive branch condition. 4827 bool IsPositiveBECond; 4828 }; 4829 4830 Optional<const SCEV *> 4831 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) { 4832 4833 // If value matches the backedge condition for loop latch, 4834 // then return a constant evolution node based on loopback 4835 // branch taken. 4836 if (BackedgeCond == IC) 4837 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext())) 4838 : SE.getZero(Type::getInt1Ty(SE.getContext())); 4839 return None; 4840 } 4841 4842 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 4843 public: 4844 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4845 ScalarEvolution &SE) { 4846 SCEVShiftRewriter Rewriter(L, SE); 4847 const SCEV *Result = Rewriter.visit(S); 4848 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 4849 } 4850 4851 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4852 // Only allow AddRecExprs for this loop. 4853 if (!SE.isLoopInvariant(Expr, L)) 4854 Valid = false; 4855 return Expr; 4856 } 4857 4858 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4859 if (Expr->getLoop() == L && Expr->isAffine()) 4860 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 4861 Valid = false; 4862 return Expr; 4863 } 4864 4865 bool isValid() { return Valid; } 4866 4867 private: 4868 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 4869 : SCEVRewriteVisitor(SE), L(L) {} 4870 4871 const Loop *L; 4872 bool Valid = true; 4873 }; 4874 4875 } // end anonymous namespace 4876 4877 SCEV::NoWrapFlags 4878 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 4879 if (!AR->isAffine()) 4880 return SCEV::FlagAnyWrap; 4881 4882 using OBO = OverflowingBinaryOperator; 4883 4884 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 4885 4886 if (!AR->hasNoSignedWrap()) { 4887 ConstantRange AddRecRange = getSignedRange(AR); 4888 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 4889 4890 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4891 Instruction::Add, IncRange, OBO::NoSignedWrap); 4892 if (NSWRegion.contains(AddRecRange)) 4893 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 4894 } 4895 4896 if (!AR->hasNoUnsignedWrap()) { 4897 ConstantRange AddRecRange = getUnsignedRange(AR); 4898 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 4899 4900 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4901 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 4902 if (NUWRegion.contains(AddRecRange)) 4903 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 4904 } 4905 4906 return Result; 4907 } 4908 4909 SCEV::NoWrapFlags 4910 ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) { 4911 SCEV::NoWrapFlags Result = AR->getNoWrapFlags(); 4912 4913 if (AR->hasNoSignedWrap()) 4914 return Result; 4915 4916 if (!AR->isAffine()) 4917 return Result; 4918 4919 const SCEV *Step = AR->getStepRecurrence(*this); 4920 const Loop *L = AR->getLoop(); 4921 4922 // Check whether the backedge-taken count is SCEVCouldNotCompute. 4923 // Note that this serves two purposes: It filters out loops that are 4924 // simply not analyzable, and it covers the case where this code is 4925 // being called from within backedge-taken count analysis, such that 4926 // attempting to ask for the backedge-taken count would likely result 4927 // in infinite recursion. In the later case, the analysis code will 4928 // cope with a conservative value, and it will take care to purge 4929 // that value once it has finished. 4930 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 4931 4932 // Normally, in the cases we can prove no-overflow via a 4933 // backedge guarding condition, we can also compute a backedge 4934 // taken count for the loop. The exceptions are assumptions and 4935 // guards present in the loop -- SCEV is not great at exploiting 4936 // these to compute max backedge taken counts, but can still use 4937 // these to prove lack of overflow. Use this fact to avoid 4938 // doing extra work that may not pay off. 4939 4940 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards && 4941 AC.assumptions().empty()) 4942 return Result; 4943 4944 // If the backedge is guarded by a comparison with the pre-inc value the 4945 // addrec is safe. Also, if the entry is guarded by a comparison with the 4946 // start value and the backedge is guarded by a comparison with the post-inc 4947 // value, the addrec is safe. 4948 ICmpInst::Predicate Pred; 4949 const SCEV *OverflowLimit = 4950 getSignedOverflowLimitForStep(Step, &Pred, this); 4951 if (OverflowLimit && 4952 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 4953 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) { 4954 Result = setFlags(Result, SCEV::FlagNSW); 4955 } 4956 return Result; 4957 } 4958 SCEV::NoWrapFlags 4959 ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) { 4960 SCEV::NoWrapFlags Result = AR->getNoWrapFlags(); 4961 4962 if (AR->hasNoUnsignedWrap()) 4963 return Result; 4964 4965 if (!AR->isAffine()) 4966 return Result; 4967 4968 const SCEV *Step = AR->getStepRecurrence(*this); 4969 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 4970 const Loop *L = AR->getLoop(); 4971 4972 // Check whether the backedge-taken count is SCEVCouldNotCompute. 4973 // Note that this serves two purposes: It filters out loops that are 4974 // simply not analyzable, and it covers the case where this code is 4975 // being called from within backedge-taken count analysis, such that 4976 // attempting to ask for the backedge-taken count would likely result 4977 // in infinite recursion. In the later case, the analysis code will 4978 // cope with a conservative value, and it will take care to purge 4979 // that value once it has finished. 4980 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 4981 4982 // Normally, in the cases we can prove no-overflow via a 4983 // backedge guarding condition, we can also compute a backedge 4984 // taken count for the loop. The exceptions are assumptions and 4985 // guards present in the loop -- SCEV is not great at exploiting 4986 // these to compute max backedge taken counts, but can still use 4987 // these to prove lack of overflow. Use this fact to avoid 4988 // doing extra work that may not pay off. 4989 4990 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards && 4991 AC.assumptions().empty()) 4992 return Result; 4993 4994 // If the backedge is guarded by a comparison with the pre-inc value the 4995 // addrec is safe. Also, if the entry is guarded by a comparison with the 4996 // start value and the backedge is guarded by a comparison with the post-inc 4997 // value, the addrec is safe. 4998 if (isKnownPositive(Step)) { 4999 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 5000 getUnsignedRangeMax(Step)); 5001 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 5002 isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) { 5003 Result = setFlags(Result, SCEV::FlagNUW); 5004 } 5005 } 5006 5007 return Result; 5008 } 5009 5010 namespace { 5011 5012 /// Represents an abstract binary operation. This may exist as a 5013 /// normal instruction or constant expression, or may have been 5014 /// derived from an expression tree. 5015 struct BinaryOp { 5016 unsigned Opcode; 5017 Value *LHS; 5018 Value *RHS; 5019 bool IsNSW = false; 5020 bool IsNUW = false; 5021 5022 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 5023 /// constant expression. 5024 Operator *Op = nullptr; 5025 5026 explicit BinaryOp(Operator *Op) 5027 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 5028 Op(Op) { 5029 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 5030 IsNSW = OBO->hasNoSignedWrap(); 5031 IsNUW = OBO->hasNoUnsignedWrap(); 5032 } 5033 } 5034 5035 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 5036 bool IsNUW = false) 5037 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {} 5038 }; 5039 5040 } // end anonymous namespace 5041 5042 /// Try to map \p V into a BinaryOp, and return \c None on failure. 5043 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 5044 auto *Op = dyn_cast<Operator>(V); 5045 if (!Op) 5046 return None; 5047 5048 // Implementation detail: all the cleverness here should happen without 5049 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 5050 // SCEV expressions when possible, and we should not break that. 5051 5052 switch (Op->getOpcode()) { 5053 case Instruction::Add: 5054 case Instruction::Sub: 5055 case Instruction::Mul: 5056 case Instruction::UDiv: 5057 case Instruction::URem: 5058 case Instruction::And: 5059 case Instruction::Or: 5060 case Instruction::AShr: 5061 case Instruction::Shl: 5062 return BinaryOp(Op); 5063 5064 case Instruction::Xor: 5065 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 5066 // If the RHS of the xor is a signmask, then this is just an add. 5067 // Instcombine turns add of signmask into xor as a strength reduction step. 5068 if (RHSC->getValue().isSignMask()) 5069 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 5070 // Binary `xor` is a bit-wise `add`. 5071 if (V->getType()->isIntegerTy(1)) 5072 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 5073 return BinaryOp(Op); 5074 5075 case Instruction::LShr: 5076 // Turn logical shift right of a constant into a unsigned divide. 5077 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 5078 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 5079 5080 // If the shift count is not less than the bitwidth, the result of 5081 // the shift is undefined. Don't try to analyze it, because the 5082 // resolution chosen here may differ from the resolution chosen in 5083 // other parts of the compiler. 5084 if (SA->getValue().ult(BitWidth)) { 5085 Constant *X = 5086 ConstantInt::get(SA->getContext(), 5087 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 5088 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 5089 } 5090 } 5091 return BinaryOp(Op); 5092 5093 case Instruction::ExtractValue: { 5094 auto *EVI = cast<ExtractValueInst>(Op); 5095 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 5096 break; 5097 5098 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()); 5099 if (!WO) 5100 break; 5101 5102 Instruction::BinaryOps BinOp = WO->getBinaryOp(); 5103 bool Signed = WO->isSigned(); 5104 // TODO: Should add nuw/nsw flags for mul as well. 5105 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT)) 5106 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS()); 5107 5108 // Now that we know that all uses of the arithmetic-result component of 5109 // CI are guarded by the overflow check, we can go ahead and pretend 5110 // that the arithmetic is non-overflowing. 5111 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(), 5112 /* IsNSW = */ Signed, /* IsNUW = */ !Signed); 5113 } 5114 5115 default: 5116 break; 5117 } 5118 5119 // Recognise intrinsic loop.decrement.reg, and as this has exactly the same 5120 // semantics as a Sub, return a binary sub expression. 5121 if (auto *II = dyn_cast<IntrinsicInst>(V)) 5122 if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg) 5123 return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1)); 5124 5125 return None; 5126 } 5127 5128 /// Helper function to createAddRecFromPHIWithCasts. We have a phi 5129 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via 5130 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the 5131 /// way. This function checks if \p Op, an operand of this SCEVAddExpr, 5132 /// follows one of the following patterns: 5133 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 5134 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 5135 /// If the SCEV expression of \p Op conforms with one of the expected patterns 5136 /// we return the type of the truncation operation, and indicate whether the 5137 /// truncated type should be treated as signed/unsigned by setting 5138 /// \p Signed to true/false, respectively. 5139 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, 5140 bool &Signed, ScalarEvolution &SE) { 5141 // The case where Op == SymbolicPHI (that is, with no type conversions on 5142 // the way) is handled by the regular add recurrence creating logic and 5143 // would have already been triggered in createAddRecForPHI. Reaching it here 5144 // means that createAddRecFromPHI had failed for this PHI before (e.g., 5145 // because one of the other operands of the SCEVAddExpr updating this PHI is 5146 // not invariant). 5147 // 5148 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in 5149 // this case predicates that allow us to prove that Op == SymbolicPHI will 5150 // be added. 5151 if (Op == SymbolicPHI) 5152 return nullptr; 5153 5154 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType()); 5155 unsigned NewBits = SE.getTypeSizeInBits(Op->getType()); 5156 if (SourceBits != NewBits) 5157 return nullptr; 5158 5159 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op); 5160 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op); 5161 if (!SExt && !ZExt) 5162 return nullptr; 5163 const SCEVTruncateExpr *Trunc = 5164 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand()) 5165 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand()); 5166 if (!Trunc) 5167 return nullptr; 5168 const SCEV *X = Trunc->getOperand(); 5169 if (X != SymbolicPHI) 5170 return nullptr; 5171 Signed = SExt != nullptr; 5172 return Trunc->getType(); 5173 } 5174 5175 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) { 5176 if (!PN->getType()->isIntegerTy()) 5177 return nullptr; 5178 const Loop *L = LI.getLoopFor(PN->getParent()); 5179 if (!L || L->getHeader() != PN->getParent()) 5180 return nullptr; 5181 return L; 5182 } 5183 5184 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the 5185 // computation that updates the phi follows the following pattern: 5186 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum 5187 // which correspond to a phi->trunc->sext/zext->add->phi update chain. 5188 // If so, try to see if it can be rewritten as an AddRecExpr under some 5189 // Predicates. If successful, return them as a pair. Also cache the results 5190 // of the analysis. 5191 // 5192 // Example usage scenario: 5193 // Say the Rewriter is called for the following SCEV: 5194 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 5195 // where: 5196 // %X = phi i64 (%Start, %BEValue) 5197 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X), 5198 // and call this function with %SymbolicPHI = %X. 5199 // 5200 // The analysis will find that the value coming around the backedge has 5201 // the following SCEV: 5202 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 5203 // Upon concluding that this matches the desired pattern, the function 5204 // will return the pair {NewAddRec, SmallPredsVec} where: 5205 // NewAddRec = {%Start,+,%Step} 5206 // SmallPredsVec = {P1, P2, P3} as follows: 5207 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw> 5208 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64) 5209 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64) 5210 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec 5211 // under the predicates {P1,P2,P3}. 5212 // This predicated rewrite will be cached in PredicatedSCEVRewrites: 5213 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)} 5214 // 5215 // TODO's: 5216 // 5217 // 1) Extend the Induction descriptor to also support inductions that involve 5218 // casts: When needed (namely, when we are called in the context of the 5219 // vectorizer induction analysis), a Set of cast instructions will be 5220 // populated by this method, and provided back to isInductionPHI. This is 5221 // needed to allow the vectorizer to properly record them to be ignored by 5222 // the cost model and to avoid vectorizing them (otherwise these casts, 5223 // which are redundant under the runtime overflow checks, will be 5224 // vectorized, which can be costly). 5225 // 5226 // 2) Support additional induction/PHISCEV patterns: We also want to support 5227 // inductions where the sext-trunc / zext-trunc operations (partly) occur 5228 // after the induction update operation (the induction increment): 5229 // 5230 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix) 5231 // which correspond to a phi->add->trunc->sext/zext->phi update chain. 5232 // 5233 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix) 5234 // which correspond to a phi->trunc->add->sext/zext->phi update chain. 5235 // 5236 // 3) Outline common code with createAddRecFromPHI to avoid duplication. 5237 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 5238 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) { 5239 SmallVector<const SCEVPredicate *, 3> Predicates; 5240 5241 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can 5242 // return an AddRec expression under some predicate. 5243 5244 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 5245 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 5246 assert(L && "Expecting an integer loop header phi"); 5247 5248 // The loop may have multiple entrances or multiple exits; we can analyze 5249 // this phi as an addrec if it has a unique entry value and a unique 5250 // backedge value. 5251 Value *BEValueV = nullptr, *StartValueV = nullptr; 5252 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 5253 Value *V = PN->getIncomingValue(i); 5254 if (L->contains(PN->getIncomingBlock(i))) { 5255 if (!BEValueV) { 5256 BEValueV = V; 5257 } else if (BEValueV != V) { 5258 BEValueV = nullptr; 5259 break; 5260 } 5261 } else if (!StartValueV) { 5262 StartValueV = V; 5263 } else if (StartValueV != V) { 5264 StartValueV = nullptr; 5265 break; 5266 } 5267 } 5268 if (!BEValueV || !StartValueV) 5269 return None; 5270 5271 const SCEV *BEValue = getSCEV(BEValueV); 5272 5273 // If the value coming around the backedge is an add with the symbolic 5274 // value we just inserted, possibly with casts that we can ignore under 5275 // an appropriate runtime guard, then we found a simple induction variable! 5276 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue); 5277 if (!Add) 5278 return None; 5279 5280 // If there is a single occurrence of the symbolic value, possibly 5281 // casted, replace it with a recurrence. 5282 unsigned FoundIndex = Add->getNumOperands(); 5283 Type *TruncTy = nullptr; 5284 bool Signed; 5285 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5286 if ((TruncTy = 5287 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this))) 5288 if (FoundIndex == e) { 5289 FoundIndex = i; 5290 break; 5291 } 5292 5293 if (FoundIndex == Add->getNumOperands()) 5294 return None; 5295 5296 // Create an add with everything but the specified operand. 5297 SmallVector<const SCEV *, 8> Ops; 5298 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5299 if (i != FoundIndex) 5300 Ops.push_back(Add->getOperand(i)); 5301 const SCEV *Accum = getAddExpr(Ops); 5302 5303 // The runtime checks will not be valid if the step amount is 5304 // varying inside the loop. 5305 if (!isLoopInvariant(Accum, L)) 5306 return None; 5307 5308 // *** Part2: Create the predicates 5309 5310 // Analysis was successful: we have a phi-with-cast pattern for which we 5311 // can return an AddRec expression under the following predicates: 5312 // 5313 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum) 5314 // fits within the truncated type (does not overflow) for i = 0 to n-1. 5315 // P2: An Equal predicate that guarantees that 5316 // Start = (Ext ix (Trunc iy (Start) to ix) to iy) 5317 // P3: An Equal predicate that guarantees that 5318 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy) 5319 // 5320 // As we next prove, the above predicates guarantee that: 5321 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy) 5322 // 5323 // 5324 // More formally, we want to prove that: 5325 // Expr(i+1) = Start + (i+1) * Accum 5326 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 5327 // 5328 // Given that: 5329 // 1) Expr(0) = Start 5330 // 2) Expr(1) = Start + Accum 5331 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2 5332 // 3) Induction hypothesis (step i): 5333 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum 5334 // 5335 // Proof: 5336 // Expr(i+1) = 5337 // = Start + (i+1)*Accum 5338 // = (Start + i*Accum) + Accum 5339 // = Expr(i) + Accum 5340 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum 5341 // :: from step i 5342 // 5343 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum 5344 // 5345 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) 5346 // + (Ext ix (Trunc iy (Accum) to ix) to iy) 5347 // + Accum :: from P3 5348 // 5349 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy) 5350 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y) 5351 // 5352 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum 5353 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 5354 // 5355 // By induction, the same applies to all iterations 1<=i<n: 5356 // 5357 5358 // Create a truncated addrec for which we will add a no overflow check (P1). 5359 const SCEV *StartVal = getSCEV(StartValueV); 5360 const SCEV *PHISCEV = 5361 getAddRecExpr(getTruncateExpr(StartVal, TruncTy), 5362 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap); 5363 5364 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr. 5365 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV 5366 // will be constant. 5367 // 5368 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't 5369 // add P1. 5370 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) { 5371 SCEVWrapPredicate::IncrementWrapFlags AddedFlags = 5372 Signed ? SCEVWrapPredicate::IncrementNSSW 5373 : SCEVWrapPredicate::IncrementNUSW; 5374 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags); 5375 Predicates.push_back(AddRecPred); 5376 } 5377 5378 // Create the Equal Predicates P2,P3: 5379 5380 // It is possible that the predicates P2 and/or P3 are computable at 5381 // compile time due to StartVal and/or Accum being constants. 5382 // If either one is, then we can check that now and escape if either P2 5383 // or P3 is false. 5384 5385 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy) 5386 // for each of StartVal and Accum 5387 auto getExtendedExpr = [&](const SCEV *Expr, 5388 bool CreateSignExtend) -> const SCEV * { 5389 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant"); 5390 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy); 5391 const SCEV *ExtendedExpr = 5392 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType()) 5393 : getZeroExtendExpr(TruncatedExpr, Expr->getType()); 5394 return ExtendedExpr; 5395 }; 5396 5397 // Given: 5398 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy 5399 // = getExtendedExpr(Expr) 5400 // Determine whether the predicate P: Expr == ExtendedExpr 5401 // is known to be false at compile time 5402 auto PredIsKnownFalse = [&](const SCEV *Expr, 5403 const SCEV *ExtendedExpr) -> bool { 5404 return Expr != ExtendedExpr && 5405 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr); 5406 }; 5407 5408 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed); 5409 if (PredIsKnownFalse(StartVal, StartExtended)) { 5410 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";); 5411 return None; 5412 } 5413 5414 // The Step is always Signed (because the overflow checks are either 5415 // NSSW or NUSW) 5416 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true); 5417 if (PredIsKnownFalse(Accum, AccumExtended)) { 5418 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";); 5419 return None; 5420 } 5421 5422 auto AppendPredicate = [&](const SCEV *Expr, 5423 const SCEV *ExtendedExpr) -> void { 5424 if (Expr != ExtendedExpr && 5425 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) { 5426 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr); 5427 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred); 5428 Predicates.push_back(Pred); 5429 } 5430 }; 5431 5432 AppendPredicate(StartVal, StartExtended); 5433 AppendPredicate(Accum, AccumExtended); 5434 5435 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in 5436 // which the casts had been folded away. The caller can rewrite SymbolicPHI 5437 // into NewAR if it will also add the runtime overflow checks specified in 5438 // Predicates. 5439 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap); 5440 5441 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite = 5442 std::make_pair(NewAR, Predicates); 5443 // Remember the result of the analysis for this SCEV at this locayyytion. 5444 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite; 5445 return PredRewrite; 5446 } 5447 5448 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 5449 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) { 5450 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 5451 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 5452 if (!L) 5453 return None; 5454 5455 // Check to see if we already analyzed this PHI. 5456 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L}); 5457 if (I != PredicatedSCEVRewrites.end()) { 5458 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite = 5459 I->second; 5460 // Analysis was done before and failed to create an AddRec: 5461 if (Rewrite.first == SymbolicPHI) 5462 return None; 5463 // Analysis was done before and succeeded to create an AddRec under 5464 // a predicate: 5465 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec"); 5466 assert(!(Rewrite.second).empty() && "Expected to find Predicates"); 5467 return Rewrite; 5468 } 5469 5470 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 5471 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI); 5472 5473 // Record in the cache that the analysis failed 5474 if (!Rewrite) { 5475 SmallVector<const SCEVPredicate *, 3> Predicates; 5476 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates}; 5477 return None; 5478 } 5479 5480 return Rewrite; 5481 } 5482 5483 // FIXME: This utility is currently required because the Rewriter currently 5484 // does not rewrite this expression: 5485 // {0, +, (sext ix (trunc iy to ix) to iy)} 5486 // into {0, +, %step}, 5487 // even when the following Equal predicate exists: 5488 // "%step == (sext ix (trunc iy to ix) to iy)". 5489 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds( 5490 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const { 5491 if (AR1 == AR2) 5492 return true; 5493 5494 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool { 5495 if (Expr1 != Expr2 && !Preds->implies(SE.getEqualPredicate(Expr1, Expr2)) && 5496 !Preds->implies(SE.getEqualPredicate(Expr2, Expr1))) 5497 return false; 5498 return true; 5499 }; 5500 5501 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) || 5502 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE))) 5503 return false; 5504 return true; 5505 } 5506 5507 /// A helper function for createAddRecFromPHI to handle simple cases. 5508 /// 5509 /// This function tries to find an AddRec expression for the simplest (yet most 5510 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)). 5511 /// If it fails, createAddRecFromPHI will use a more general, but slow, 5512 /// technique for finding the AddRec expression. 5513 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN, 5514 Value *BEValueV, 5515 Value *StartValueV) { 5516 const Loop *L = LI.getLoopFor(PN->getParent()); 5517 assert(L && L->getHeader() == PN->getParent()); 5518 assert(BEValueV && StartValueV); 5519 5520 auto BO = MatchBinaryOp(BEValueV, DT); 5521 if (!BO) 5522 return nullptr; 5523 5524 if (BO->Opcode != Instruction::Add) 5525 return nullptr; 5526 5527 const SCEV *Accum = nullptr; 5528 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS)) 5529 Accum = getSCEV(BO->RHS); 5530 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS)) 5531 Accum = getSCEV(BO->LHS); 5532 5533 if (!Accum) 5534 return nullptr; 5535 5536 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5537 if (BO->IsNUW) 5538 Flags = setFlags(Flags, SCEV::FlagNUW); 5539 if (BO->IsNSW) 5540 Flags = setFlags(Flags, SCEV::FlagNSW); 5541 5542 const SCEV *StartVal = getSCEV(StartValueV); 5543 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5544 insertValueToMap(PN, PHISCEV); 5545 5546 // We can add Flags to the post-inc expression only if we 5547 // know that it is *undefined behavior* for BEValueV to 5548 // overflow. 5549 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) { 5550 assert(isLoopInvariant(Accum, L) && 5551 "Accum is defined outside L, but is not invariant?"); 5552 if (isAddRecNeverPoison(BEInst, L)) 5553 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5554 } 5555 5556 return PHISCEV; 5557 } 5558 5559 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 5560 const Loop *L = LI.getLoopFor(PN->getParent()); 5561 if (!L || L->getHeader() != PN->getParent()) 5562 return nullptr; 5563 5564 // The loop may have multiple entrances or multiple exits; we can analyze 5565 // this phi as an addrec if it has a unique entry value and a unique 5566 // backedge value. 5567 Value *BEValueV = nullptr, *StartValueV = nullptr; 5568 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 5569 Value *V = PN->getIncomingValue(i); 5570 if (L->contains(PN->getIncomingBlock(i))) { 5571 if (!BEValueV) { 5572 BEValueV = V; 5573 } else if (BEValueV != V) { 5574 BEValueV = nullptr; 5575 break; 5576 } 5577 } else if (!StartValueV) { 5578 StartValueV = V; 5579 } else if (StartValueV != V) { 5580 StartValueV = nullptr; 5581 break; 5582 } 5583 } 5584 if (!BEValueV || !StartValueV) 5585 return nullptr; 5586 5587 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 5588 "PHI node already processed?"); 5589 5590 // First, try to find AddRec expression without creating a fictituos symbolic 5591 // value for PN. 5592 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV)) 5593 return S; 5594 5595 // Handle PHI node value symbolically. 5596 const SCEV *SymbolicName = getUnknown(PN); 5597 insertValueToMap(PN, SymbolicName); 5598 5599 // Using this symbolic name for the PHI, analyze the value coming around 5600 // the back-edge. 5601 const SCEV *BEValue = getSCEV(BEValueV); 5602 5603 // NOTE: If BEValue is loop invariant, we know that the PHI node just 5604 // has a special value for the first iteration of the loop. 5605 5606 // If the value coming around the backedge is an add with the symbolic 5607 // value we just inserted, then we found a simple induction variable! 5608 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 5609 // If there is a single occurrence of the symbolic value, replace it 5610 // with a recurrence. 5611 unsigned FoundIndex = Add->getNumOperands(); 5612 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5613 if (Add->getOperand(i) == SymbolicName) 5614 if (FoundIndex == e) { 5615 FoundIndex = i; 5616 break; 5617 } 5618 5619 if (FoundIndex != Add->getNumOperands()) { 5620 // Create an add with everything but the specified operand. 5621 SmallVector<const SCEV *, 8> Ops; 5622 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5623 if (i != FoundIndex) 5624 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i), 5625 L, *this)); 5626 const SCEV *Accum = getAddExpr(Ops); 5627 5628 // This is not a valid addrec if the step amount is varying each 5629 // loop iteration, but is not itself an addrec in this loop. 5630 if (isLoopInvariant(Accum, L) || 5631 (isa<SCEVAddRecExpr>(Accum) && 5632 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 5633 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5634 5635 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 5636 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 5637 if (BO->IsNUW) 5638 Flags = setFlags(Flags, SCEV::FlagNUW); 5639 if (BO->IsNSW) 5640 Flags = setFlags(Flags, SCEV::FlagNSW); 5641 } 5642 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 5643 // If the increment is an inbounds GEP, then we know the address 5644 // space cannot be wrapped around. We cannot make any guarantee 5645 // about signed or unsigned overflow because pointers are 5646 // unsigned but we may have a negative index from the base 5647 // pointer. We can guarantee that no unsigned wrap occurs if the 5648 // indices form a positive value. 5649 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 5650 Flags = setFlags(Flags, SCEV::FlagNW); 5651 5652 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 5653 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 5654 Flags = setFlags(Flags, SCEV::FlagNUW); 5655 } 5656 5657 // We cannot transfer nuw and nsw flags from subtraction 5658 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 5659 // for instance. 5660 } 5661 5662 const SCEV *StartVal = getSCEV(StartValueV); 5663 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5664 5665 // Okay, for the entire analysis of this edge we assumed the PHI 5666 // to be symbolic. We now need to go back and purge all of the 5667 // entries for the scalars that use the symbolic expression. 5668 forgetMemoizedResults(SymbolicName); 5669 insertValueToMap(PN, PHISCEV); 5670 5671 // We can add Flags to the post-inc expression only if we 5672 // know that it is *undefined behavior* for BEValueV to 5673 // overflow. 5674 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5675 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5676 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5677 5678 return PHISCEV; 5679 } 5680 } 5681 } else { 5682 // Otherwise, this could be a loop like this: 5683 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 5684 // In this case, j = {1,+,1} and BEValue is j. 5685 // Because the other in-value of i (0) fits the evolution of BEValue 5686 // i really is an addrec evolution. 5687 // 5688 // We can generalize this saying that i is the shifted value of BEValue 5689 // by one iteration: 5690 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 5691 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 5692 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false); 5693 if (Shifted != getCouldNotCompute() && 5694 Start != getCouldNotCompute()) { 5695 const SCEV *StartVal = getSCEV(StartValueV); 5696 if (Start == StartVal) { 5697 // Okay, for the entire analysis of this edge we assumed the PHI 5698 // to be symbolic. We now need to go back and purge all of the 5699 // entries for the scalars that use the symbolic expression. 5700 forgetMemoizedResults(SymbolicName); 5701 insertValueToMap(PN, Shifted); 5702 return Shifted; 5703 } 5704 } 5705 } 5706 5707 // Remove the temporary PHI node SCEV that has been inserted while intending 5708 // to create an AddRecExpr for this PHI node. We can not keep this temporary 5709 // as it will prevent later (possibly simpler) SCEV expressions to be added 5710 // to the ValueExprMap. 5711 eraseValueFromMap(PN); 5712 5713 return nullptr; 5714 } 5715 5716 // Checks if the SCEV S is available at BB. S is considered available at BB 5717 // if S can be materialized at BB without introducing a fault. 5718 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 5719 BasicBlock *BB) { 5720 struct CheckAvailable { 5721 bool TraversalDone = false; 5722 bool Available = true; 5723 5724 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 5725 BasicBlock *BB = nullptr; 5726 DominatorTree &DT; 5727 5728 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 5729 : L(L), BB(BB), DT(DT) {} 5730 5731 bool setUnavailable() { 5732 TraversalDone = true; 5733 Available = false; 5734 return false; 5735 } 5736 5737 bool follow(const SCEV *S) { 5738 switch (S->getSCEVType()) { 5739 case scConstant: 5740 case scPtrToInt: 5741 case scTruncate: 5742 case scZeroExtend: 5743 case scSignExtend: 5744 case scAddExpr: 5745 case scMulExpr: 5746 case scUMaxExpr: 5747 case scSMaxExpr: 5748 case scUMinExpr: 5749 case scSMinExpr: 5750 case scSequentialUMinExpr: 5751 // These expressions are available if their operand(s) is/are. 5752 return true; 5753 5754 case scAddRecExpr: { 5755 // We allow add recurrences that are on the loop BB is in, or some 5756 // outer loop. This guarantees availability because the value of the 5757 // add recurrence at BB is simply the "current" value of the induction 5758 // variable. We can relax this in the future; for instance an add 5759 // recurrence on a sibling dominating loop is also available at BB. 5760 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 5761 if (L && (ARLoop == L || ARLoop->contains(L))) 5762 return true; 5763 5764 return setUnavailable(); 5765 } 5766 5767 case scUnknown: { 5768 // For SCEVUnknown, we check for simple dominance. 5769 const auto *SU = cast<SCEVUnknown>(S); 5770 Value *V = SU->getValue(); 5771 5772 if (isa<Argument>(V)) 5773 return false; 5774 5775 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 5776 return false; 5777 5778 return setUnavailable(); 5779 } 5780 5781 case scUDivExpr: 5782 case scCouldNotCompute: 5783 // We do not try to smart about these at all. 5784 return setUnavailable(); 5785 } 5786 llvm_unreachable("Unknown SCEV kind!"); 5787 } 5788 5789 bool isDone() { return TraversalDone; } 5790 }; 5791 5792 CheckAvailable CA(L, BB, DT); 5793 SCEVTraversal<CheckAvailable> ST(CA); 5794 5795 ST.visitAll(S); 5796 return CA.Available; 5797 } 5798 5799 // Try to match a control flow sequence that branches out at BI and merges back 5800 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 5801 // match. 5802 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 5803 Value *&C, Value *&LHS, Value *&RHS) { 5804 C = BI->getCondition(); 5805 5806 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 5807 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 5808 5809 if (!LeftEdge.isSingleEdge()) 5810 return false; 5811 5812 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 5813 5814 Use &LeftUse = Merge->getOperandUse(0); 5815 Use &RightUse = Merge->getOperandUse(1); 5816 5817 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 5818 LHS = LeftUse; 5819 RHS = RightUse; 5820 return true; 5821 } 5822 5823 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 5824 LHS = RightUse; 5825 RHS = LeftUse; 5826 return true; 5827 } 5828 5829 return false; 5830 } 5831 5832 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 5833 auto IsReachable = 5834 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 5835 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 5836 const Loop *L = LI.getLoopFor(PN->getParent()); 5837 5838 // We don't want to break LCSSA, even in a SCEV expression tree. 5839 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 5840 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 5841 return nullptr; 5842 5843 // Try to match 5844 // 5845 // br %cond, label %left, label %right 5846 // left: 5847 // br label %merge 5848 // right: 5849 // br label %merge 5850 // merge: 5851 // V = phi [ %x, %left ], [ %y, %right ] 5852 // 5853 // as "select %cond, %x, %y" 5854 5855 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 5856 assert(IDom && "At least the entry block should dominate PN"); 5857 5858 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 5859 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 5860 5861 if (BI && BI->isConditional() && 5862 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 5863 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 5864 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 5865 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 5866 } 5867 5868 return nullptr; 5869 } 5870 5871 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 5872 if (const SCEV *S = createAddRecFromPHI(PN)) 5873 return S; 5874 5875 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 5876 return S; 5877 5878 // If the PHI has a single incoming value, follow that value, unless the 5879 // PHI's incoming blocks are in a different loop, in which case doing so 5880 // risks breaking LCSSA form. Instcombine would normally zap these, but 5881 // it doesn't have DominatorTree information, so it may miss cases. 5882 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC})) 5883 if (LI.replacementPreservesLCSSAForm(PN, V)) 5884 return getSCEV(V); 5885 5886 // If it's not a loop phi, we can't handle it yet. 5887 return getUnknown(PN); 5888 } 5889 5890 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, 5891 Value *Cond, 5892 Value *TrueVal, 5893 Value *FalseVal) { 5894 // Handle "constant" branch or select. This can occur for instance when a 5895 // loop pass transforms an inner loop and moves on to process the outer loop. 5896 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 5897 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 5898 5899 // Try to match some simple smax or umax patterns. 5900 auto *ICI = dyn_cast<ICmpInst>(Cond); 5901 if (!ICI) 5902 return getUnknown(I); 5903 5904 Value *LHS = ICI->getOperand(0); 5905 Value *RHS = ICI->getOperand(1); 5906 5907 switch (ICI->getPredicate()) { 5908 case ICmpInst::ICMP_SLT: 5909 case ICmpInst::ICMP_SLE: 5910 case ICmpInst::ICMP_ULT: 5911 case ICmpInst::ICMP_ULE: 5912 std::swap(LHS, RHS); 5913 LLVM_FALLTHROUGH; 5914 case ICmpInst::ICMP_SGT: 5915 case ICmpInst::ICMP_SGE: 5916 case ICmpInst::ICMP_UGT: 5917 case ICmpInst::ICMP_UGE: 5918 // a > b ? a+x : b+x -> max(a, b)+x 5919 // a > b ? b+x : a+x -> min(a, b)+x 5920 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5921 bool Signed = ICI->isSigned(); 5922 const SCEV *LA = getSCEV(TrueVal); 5923 const SCEV *RA = getSCEV(FalseVal); 5924 const SCEV *LS = getSCEV(LHS); 5925 const SCEV *RS = getSCEV(RHS); 5926 if (LA->getType()->isPointerTy()) { 5927 // FIXME: Handle cases where LS/RS are pointers not equal to LA/RA. 5928 // Need to make sure we can't produce weird expressions involving 5929 // negated pointers. 5930 if (LA == LS && RA == RS) 5931 return Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS); 5932 if (LA == RS && RA == LS) 5933 return Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS); 5934 } 5935 auto CoerceOperand = [&](const SCEV *Op) -> const SCEV * { 5936 if (Op->getType()->isPointerTy()) { 5937 Op = getLosslessPtrToIntExpr(Op); 5938 if (isa<SCEVCouldNotCompute>(Op)) 5939 return Op; 5940 } 5941 if (Signed) 5942 Op = getNoopOrSignExtend(Op, I->getType()); 5943 else 5944 Op = getNoopOrZeroExtend(Op, I->getType()); 5945 return Op; 5946 }; 5947 LS = CoerceOperand(LS); 5948 RS = CoerceOperand(RS); 5949 if (isa<SCEVCouldNotCompute>(LS) || isa<SCEVCouldNotCompute>(RS)) 5950 break; 5951 const SCEV *LDiff = getMinusSCEV(LA, LS); 5952 const SCEV *RDiff = getMinusSCEV(RA, RS); 5953 if (LDiff == RDiff) 5954 return getAddExpr(Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS), 5955 LDiff); 5956 LDiff = getMinusSCEV(LA, RS); 5957 RDiff = getMinusSCEV(RA, LS); 5958 if (LDiff == RDiff) 5959 return getAddExpr(Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS), 5960 LDiff); 5961 } 5962 break; 5963 case ICmpInst::ICMP_NE: 5964 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 5965 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5966 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5967 const SCEV *One = getOne(I->getType()); 5968 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5969 const SCEV *LA = getSCEV(TrueVal); 5970 const SCEV *RA = getSCEV(FalseVal); 5971 const SCEV *LDiff = getMinusSCEV(LA, LS); 5972 const SCEV *RDiff = getMinusSCEV(RA, One); 5973 if (LDiff == RDiff) 5974 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5975 } 5976 break; 5977 case ICmpInst::ICMP_EQ: 5978 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 5979 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5980 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5981 const SCEV *One = getOne(I->getType()); 5982 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5983 const SCEV *LA = getSCEV(TrueVal); 5984 const SCEV *RA = getSCEV(FalseVal); 5985 const SCEV *LDiff = getMinusSCEV(LA, One); 5986 const SCEV *RDiff = getMinusSCEV(RA, LS); 5987 if (LDiff == RDiff) 5988 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5989 } 5990 break; 5991 default: 5992 break; 5993 } 5994 5995 return getUnknown(I); 5996 } 5997 5998 /// Expand GEP instructions into add and multiply operations. This allows them 5999 /// to be analyzed by regular SCEV code. 6000 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 6001 // Don't attempt to analyze GEPs over unsized objects. 6002 if (!GEP->getSourceElementType()->isSized()) 6003 return getUnknown(GEP); 6004 6005 SmallVector<const SCEV *, 4> IndexExprs; 6006 for (Value *Index : GEP->indices()) 6007 IndexExprs.push_back(getSCEV(Index)); 6008 return getGEPExpr(GEP, IndexExprs); 6009 } 6010 6011 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) { 6012 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 6013 return C->getAPInt().countTrailingZeros(); 6014 6015 if (const SCEVPtrToIntExpr *I = dyn_cast<SCEVPtrToIntExpr>(S)) 6016 return GetMinTrailingZeros(I->getOperand()); 6017 6018 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 6019 return std::min(GetMinTrailingZeros(T->getOperand()), 6020 (uint32_t)getTypeSizeInBits(T->getType())); 6021 6022 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 6023 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 6024 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 6025 ? getTypeSizeInBits(E->getType()) 6026 : OpRes; 6027 } 6028 6029 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 6030 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 6031 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 6032 ? getTypeSizeInBits(E->getType()) 6033 : OpRes; 6034 } 6035 6036 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 6037 // The result is the min of all operands results. 6038 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 6039 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 6040 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 6041 return MinOpRes; 6042 } 6043 6044 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 6045 // The result is the sum of all operands results. 6046 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 6047 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 6048 for (unsigned i = 1, e = M->getNumOperands(); 6049 SumOpRes != BitWidth && i != e; ++i) 6050 SumOpRes = 6051 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth); 6052 return SumOpRes; 6053 } 6054 6055 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 6056 // The result is the min of all operands results. 6057 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 6058 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 6059 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 6060 return MinOpRes; 6061 } 6062 6063 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 6064 // The result is the min of all operands results. 6065 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 6066 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 6067 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 6068 return MinOpRes; 6069 } 6070 6071 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 6072 // The result is the min of all operands results. 6073 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 6074 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 6075 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 6076 return MinOpRes; 6077 } 6078 6079 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 6080 // For a SCEVUnknown, ask ValueTracking. 6081 KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT); 6082 return Known.countMinTrailingZeros(); 6083 } 6084 6085 // SCEVUDivExpr 6086 return 0; 6087 } 6088 6089 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 6090 auto I = MinTrailingZerosCache.find(S); 6091 if (I != MinTrailingZerosCache.end()) 6092 return I->second; 6093 6094 uint32_t Result = GetMinTrailingZerosImpl(S); 6095 auto InsertPair = MinTrailingZerosCache.insert({S, Result}); 6096 assert(InsertPair.second && "Should insert a new key"); 6097 return InsertPair.first->second; 6098 } 6099 6100 /// Helper method to assign a range to V from metadata present in the IR. 6101 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 6102 if (Instruction *I = dyn_cast<Instruction>(V)) 6103 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 6104 return getConstantRangeFromMetadata(*MD); 6105 6106 return None; 6107 } 6108 6109 void ScalarEvolution::setNoWrapFlags(SCEVAddRecExpr *AddRec, 6110 SCEV::NoWrapFlags Flags) { 6111 if (AddRec->getNoWrapFlags(Flags) != Flags) { 6112 AddRec->setNoWrapFlags(Flags); 6113 UnsignedRanges.erase(AddRec); 6114 SignedRanges.erase(AddRec); 6115 } 6116 } 6117 6118 ConstantRange ScalarEvolution:: 6119 getRangeForUnknownRecurrence(const SCEVUnknown *U) { 6120 const DataLayout &DL = getDataLayout(); 6121 6122 unsigned BitWidth = getTypeSizeInBits(U->getType()); 6123 const ConstantRange FullSet(BitWidth, /*isFullSet=*/true); 6124 6125 // Match a simple recurrence of the form: <start, ShiftOp, Step>, and then 6126 // use information about the trip count to improve our available range. Note 6127 // that the trip count independent cases are already handled by known bits. 6128 // WARNING: The definition of recurrence used here is subtly different than 6129 // the one used by AddRec (and thus most of this file). Step is allowed to 6130 // be arbitrarily loop varying here, where AddRec allows only loop invariant 6131 // and other addrecs in the same loop (for non-affine addrecs). The code 6132 // below intentionally handles the case where step is not loop invariant. 6133 auto *P = dyn_cast<PHINode>(U->getValue()); 6134 if (!P) 6135 return FullSet; 6136 6137 // Make sure that no Phi input comes from an unreachable block. Otherwise, 6138 // even the values that are not available in these blocks may come from them, 6139 // and this leads to false-positive recurrence test. 6140 for (auto *Pred : predecessors(P->getParent())) 6141 if (!DT.isReachableFromEntry(Pred)) 6142 return FullSet; 6143 6144 BinaryOperator *BO; 6145 Value *Start, *Step; 6146 if (!matchSimpleRecurrence(P, BO, Start, Step)) 6147 return FullSet; 6148 6149 // If we found a recurrence in reachable code, we must be in a loop. Note 6150 // that BO might be in some subloop of L, and that's completely okay. 6151 auto *L = LI.getLoopFor(P->getParent()); 6152 assert(L && L->getHeader() == P->getParent()); 6153 if (!L->contains(BO->getParent())) 6154 // NOTE: This bailout should be an assert instead. However, asserting 6155 // the condition here exposes a case where LoopFusion is querying SCEV 6156 // with malformed loop information during the midst of the transform. 6157 // There doesn't appear to be an obvious fix, so for the moment bailout 6158 // until the caller issue can be fixed. PR49566 tracks the bug. 6159 return FullSet; 6160 6161 // TODO: Extend to other opcodes such as mul, and div 6162 switch (BO->getOpcode()) { 6163 default: 6164 return FullSet; 6165 case Instruction::AShr: 6166 case Instruction::LShr: 6167 case Instruction::Shl: 6168 break; 6169 }; 6170 6171 if (BO->getOperand(0) != P) 6172 // TODO: Handle the power function forms some day. 6173 return FullSet; 6174 6175 unsigned TC = getSmallConstantMaxTripCount(L); 6176 if (!TC || TC >= BitWidth) 6177 return FullSet; 6178 6179 auto KnownStart = computeKnownBits(Start, DL, 0, &AC, nullptr, &DT); 6180 auto KnownStep = computeKnownBits(Step, DL, 0, &AC, nullptr, &DT); 6181 assert(KnownStart.getBitWidth() == BitWidth && 6182 KnownStep.getBitWidth() == BitWidth); 6183 6184 // Compute total shift amount, being careful of overflow and bitwidths. 6185 auto MaxShiftAmt = KnownStep.getMaxValue(); 6186 APInt TCAP(BitWidth, TC-1); 6187 bool Overflow = false; 6188 auto TotalShift = MaxShiftAmt.umul_ov(TCAP, Overflow); 6189 if (Overflow) 6190 return FullSet; 6191 6192 switch (BO->getOpcode()) { 6193 default: 6194 llvm_unreachable("filtered out above"); 6195 case Instruction::AShr: { 6196 // For each ashr, three cases: 6197 // shift = 0 => unchanged value 6198 // saturation => 0 or -1 6199 // other => a value closer to zero (of the same sign) 6200 // Thus, the end value is closer to zero than the start. 6201 auto KnownEnd = KnownBits::ashr(KnownStart, 6202 KnownBits::makeConstant(TotalShift)); 6203 if (KnownStart.isNonNegative()) 6204 // Analogous to lshr (simply not yet canonicalized) 6205 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(), 6206 KnownStart.getMaxValue() + 1); 6207 if (KnownStart.isNegative()) 6208 // End >=u Start && End <=s Start 6209 return ConstantRange::getNonEmpty(KnownStart.getMinValue(), 6210 KnownEnd.getMaxValue() + 1); 6211 break; 6212 } 6213 case Instruction::LShr: { 6214 // For each lshr, three cases: 6215 // shift = 0 => unchanged value 6216 // saturation => 0 6217 // other => a smaller positive number 6218 // Thus, the low end of the unsigned range is the last value produced. 6219 auto KnownEnd = KnownBits::lshr(KnownStart, 6220 KnownBits::makeConstant(TotalShift)); 6221 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(), 6222 KnownStart.getMaxValue() + 1); 6223 } 6224 case Instruction::Shl: { 6225 // Iff no bits are shifted out, value increases on every shift. 6226 auto KnownEnd = KnownBits::shl(KnownStart, 6227 KnownBits::makeConstant(TotalShift)); 6228 if (TotalShift.ult(KnownStart.countMinLeadingZeros())) 6229 return ConstantRange(KnownStart.getMinValue(), 6230 KnownEnd.getMaxValue() + 1); 6231 break; 6232 } 6233 }; 6234 return FullSet; 6235 } 6236 6237 /// Determine the range for a particular SCEV. If SignHint is 6238 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 6239 /// with a "cleaner" unsigned (resp. signed) representation. 6240 const ConstantRange & 6241 ScalarEvolution::getRangeRef(const SCEV *S, 6242 ScalarEvolution::RangeSignHint SignHint) { 6243 DenseMap<const SCEV *, ConstantRange> &Cache = 6244 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 6245 : SignedRanges; 6246 ConstantRange::PreferredRangeType RangeType = 6247 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED 6248 ? ConstantRange::Unsigned : ConstantRange::Signed; 6249 6250 // See if we've computed this range already. 6251 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 6252 if (I != Cache.end()) 6253 return I->second; 6254 6255 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 6256 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 6257 6258 unsigned BitWidth = getTypeSizeInBits(S->getType()); 6259 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 6260 using OBO = OverflowingBinaryOperator; 6261 6262 // If the value has known zeros, the maximum value will have those known zeros 6263 // as well. 6264 uint32_t TZ = GetMinTrailingZeros(S); 6265 if (TZ != 0) { 6266 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 6267 ConservativeResult = 6268 ConstantRange(APInt::getMinValue(BitWidth), 6269 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 6270 else 6271 ConservativeResult = ConstantRange( 6272 APInt::getSignedMinValue(BitWidth), 6273 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 6274 } 6275 6276 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 6277 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint); 6278 unsigned WrapType = OBO::AnyWrap; 6279 if (Add->hasNoSignedWrap()) 6280 WrapType |= OBO::NoSignedWrap; 6281 if (Add->hasNoUnsignedWrap()) 6282 WrapType |= OBO::NoUnsignedWrap; 6283 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 6284 X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint), 6285 WrapType, RangeType); 6286 return setRange(Add, SignHint, 6287 ConservativeResult.intersectWith(X, RangeType)); 6288 } 6289 6290 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 6291 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint); 6292 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 6293 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint)); 6294 return setRange(Mul, SignHint, 6295 ConservativeResult.intersectWith(X, RangeType)); 6296 } 6297 6298 if (isa<SCEVMinMaxExpr>(S) || isa<SCEVSequentialMinMaxExpr>(S)) { 6299 Intrinsic::ID ID; 6300 switch (S->getSCEVType()) { 6301 case scUMaxExpr: 6302 ID = Intrinsic::umax; 6303 break; 6304 case scSMaxExpr: 6305 ID = Intrinsic::smax; 6306 break; 6307 case scUMinExpr: 6308 case scSequentialUMinExpr: 6309 ID = Intrinsic::umin; 6310 break; 6311 case scSMinExpr: 6312 ID = Intrinsic::smin; 6313 break; 6314 default: 6315 llvm_unreachable("Unknown SCEVMinMaxExpr/SCEVSequentialMinMaxExpr."); 6316 } 6317 6318 const auto *NAry = cast<SCEVNAryExpr>(S); 6319 ConstantRange X = getRangeRef(NAry->getOperand(0), SignHint); 6320 for (unsigned i = 1, e = NAry->getNumOperands(); i != e; ++i) 6321 X = X.intrinsic(ID, {X, getRangeRef(NAry->getOperand(i), SignHint)}); 6322 return setRange(S, SignHint, 6323 ConservativeResult.intersectWith(X, RangeType)); 6324 } 6325 6326 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 6327 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint); 6328 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint); 6329 return setRange(UDiv, SignHint, 6330 ConservativeResult.intersectWith(X.udiv(Y), RangeType)); 6331 } 6332 6333 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 6334 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint); 6335 return setRange(ZExt, SignHint, 6336 ConservativeResult.intersectWith(X.zeroExtend(BitWidth), 6337 RangeType)); 6338 } 6339 6340 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 6341 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint); 6342 return setRange(SExt, SignHint, 6343 ConservativeResult.intersectWith(X.signExtend(BitWidth), 6344 RangeType)); 6345 } 6346 6347 if (const SCEVPtrToIntExpr *PtrToInt = dyn_cast<SCEVPtrToIntExpr>(S)) { 6348 ConstantRange X = getRangeRef(PtrToInt->getOperand(), SignHint); 6349 return setRange(PtrToInt, SignHint, X); 6350 } 6351 6352 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 6353 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint); 6354 return setRange(Trunc, SignHint, 6355 ConservativeResult.intersectWith(X.truncate(BitWidth), 6356 RangeType)); 6357 } 6358 6359 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 6360 // If there's no unsigned wrap, the value will never be less than its 6361 // initial value. 6362 if (AddRec->hasNoUnsignedWrap()) { 6363 APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart()); 6364 if (!UnsignedMinValue.isZero()) 6365 ConservativeResult = ConservativeResult.intersectWith( 6366 ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType); 6367 } 6368 6369 // If there's no signed wrap, and all the operands except initial value have 6370 // the same sign or zero, the value won't ever be: 6371 // 1: smaller than initial value if operands are non negative, 6372 // 2: bigger than initial value if operands are non positive. 6373 // For both cases, value can not cross signed min/max boundary. 6374 if (AddRec->hasNoSignedWrap()) { 6375 bool AllNonNeg = true; 6376 bool AllNonPos = true; 6377 for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) { 6378 if (!isKnownNonNegative(AddRec->getOperand(i))) 6379 AllNonNeg = false; 6380 if (!isKnownNonPositive(AddRec->getOperand(i))) 6381 AllNonPos = false; 6382 } 6383 if (AllNonNeg) 6384 ConservativeResult = ConservativeResult.intersectWith( 6385 ConstantRange::getNonEmpty(getSignedRangeMin(AddRec->getStart()), 6386 APInt::getSignedMinValue(BitWidth)), 6387 RangeType); 6388 else if (AllNonPos) 6389 ConservativeResult = ConservativeResult.intersectWith( 6390 ConstantRange::getNonEmpty( 6391 APInt::getSignedMinValue(BitWidth), 6392 getSignedRangeMax(AddRec->getStart()) + 1), 6393 RangeType); 6394 } 6395 6396 // TODO: non-affine addrec 6397 if (AddRec->isAffine()) { 6398 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop()); 6399 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 6400 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 6401 auto RangeFromAffine = getRangeForAffineAR( 6402 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 6403 BitWidth); 6404 ConservativeResult = 6405 ConservativeResult.intersectWith(RangeFromAffine, RangeType); 6406 6407 auto RangeFromFactoring = getRangeViaFactoring( 6408 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 6409 BitWidth); 6410 ConservativeResult = 6411 ConservativeResult.intersectWith(RangeFromFactoring, RangeType); 6412 } 6413 6414 // Now try symbolic BE count and more powerful methods. 6415 if (UseExpensiveRangeSharpening) { 6416 const SCEV *SymbolicMaxBECount = 6417 getSymbolicMaxBackedgeTakenCount(AddRec->getLoop()); 6418 if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) && 6419 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 6420 AddRec->hasNoSelfWrap()) { 6421 auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR( 6422 AddRec, SymbolicMaxBECount, BitWidth, SignHint); 6423 ConservativeResult = 6424 ConservativeResult.intersectWith(RangeFromAffineNew, RangeType); 6425 } 6426 } 6427 } 6428 6429 return setRange(AddRec, SignHint, std::move(ConservativeResult)); 6430 } 6431 6432 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 6433 6434 // Check if the IR explicitly contains !range metadata. 6435 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 6436 if (MDRange.hasValue()) 6437 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(), 6438 RangeType); 6439 6440 // Use facts about recurrences in the underlying IR. Note that add 6441 // recurrences are AddRecExprs and thus don't hit this path. This 6442 // primarily handles shift recurrences. 6443 auto CR = getRangeForUnknownRecurrence(U); 6444 ConservativeResult = ConservativeResult.intersectWith(CR); 6445 6446 // See if ValueTracking can give us a useful range. 6447 const DataLayout &DL = getDataLayout(); 6448 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 6449 if (Known.getBitWidth() != BitWidth) 6450 Known = Known.zextOrTrunc(BitWidth); 6451 6452 // ValueTracking may be able to compute a tighter result for the number of 6453 // sign bits than for the value of those sign bits. 6454 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 6455 if (U->getType()->isPointerTy()) { 6456 // If the pointer size is larger than the index size type, this can cause 6457 // NS to be larger than BitWidth. So compensate for this. 6458 unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType()); 6459 int ptrIdxDiff = ptrSize - BitWidth; 6460 if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff) 6461 NS -= ptrIdxDiff; 6462 } 6463 6464 if (NS > 1) { 6465 // If we know any of the sign bits, we know all of the sign bits. 6466 if (!Known.Zero.getHiBits(NS).isZero()) 6467 Known.Zero.setHighBits(NS); 6468 if (!Known.One.getHiBits(NS).isZero()) 6469 Known.One.setHighBits(NS); 6470 } 6471 6472 if (Known.getMinValue() != Known.getMaxValue() + 1) 6473 ConservativeResult = ConservativeResult.intersectWith( 6474 ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1), 6475 RangeType); 6476 if (NS > 1) 6477 ConservativeResult = ConservativeResult.intersectWith( 6478 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 6479 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1), 6480 RangeType); 6481 6482 // A range of Phi is a subset of union of all ranges of its input. 6483 if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) { 6484 // Make sure that we do not run over cycled Phis. 6485 if (PendingPhiRanges.insert(Phi).second) { 6486 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false); 6487 for (auto &Op : Phi->operands()) { 6488 auto OpRange = getRangeRef(getSCEV(Op), SignHint); 6489 RangeFromOps = RangeFromOps.unionWith(OpRange); 6490 // No point to continue if we already have a full set. 6491 if (RangeFromOps.isFullSet()) 6492 break; 6493 } 6494 ConservativeResult = 6495 ConservativeResult.intersectWith(RangeFromOps, RangeType); 6496 bool Erased = PendingPhiRanges.erase(Phi); 6497 assert(Erased && "Failed to erase Phi properly?"); 6498 (void) Erased; 6499 } 6500 } 6501 6502 return setRange(U, SignHint, std::move(ConservativeResult)); 6503 } 6504 6505 return setRange(S, SignHint, std::move(ConservativeResult)); 6506 } 6507 6508 // Given a StartRange, Step and MaxBECount for an expression compute a range of 6509 // values that the expression can take. Initially, the expression has a value 6510 // from StartRange and then is changed by Step up to MaxBECount times. Signed 6511 // argument defines if we treat Step as signed or unsigned. 6512 static ConstantRange getRangeForAffineARHelper(APInt Step, 6513 const ConstantRange &StartRange, 6514 const APInt &MaxBECount, 6515 unsigned BitWidth, bool Signed) { 6516 // If either Step or MaxBECount is 0, then the expression won't change, and we 6517 // just need to return the initial range. 6518 if (Step == 0 || MaxBECount == 0) 6519 return StartRange; 6520 6521 // If we don't know anything about the initial value (i.e. StartRange is 6522 // FullRange), then we don't know anything about the final range either. 6523 // Return FullRange. 6524 if (StartRange.isFullSet()) 6525 return ConstantRange::getFull(BitWidth); 6526 6527 // If Step is signed and negative, then we use its absolute value, but we also 6528 // note that we're moving in the opposite direction. 6529 bool Descending = Signed && Step.isNegative(); 6530 6531 if (Signed) 6532 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this: 6533 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128. 6534 // This equations hold true due to the well-defined wrap-around behavior of 6535 // APInt. 6536 Step = Step.abs(); 6537 6538 // Check if Offset is more than full span of BitWidth. If it is, the 6539 // expression is guaranteed to overflow. 6540 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount)) 6541 return ConstantRange::getFull(BitWidth); 6542 6543 // Offset is by how much the expression can change. Checks above guarantee no 6544 // overflow here. 6545 APInt Offset = Step * MaxBECount; 6546 6547 // Minimum value of the final range will match the minimal value of StartRange 6548 // if the expression is increasing and will be decreased by Offset otherwise. 6549 // Maximum value of the final range will match the maximal value of StartRange 6550 // if the expression is decreasing and will be increased by Offset otherwise. 6551 APInt StartLower = StartRange.getLower(); 6552 APInt StartUpper = StartRange.getUpper() - 1; 6553 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset)) 6554 : (StartUpper + std::move(Offset)); 6555 6556 // It's possible that the new minimum/maximum value will fall into the initial 6557 // range (due to wrap around). This means that the expression can take any 6558 // value in this bitwidth, and we have to return full range. 6559 if (StartRange.contains(MovedBoundary)) 6560 return ConstantRange::getFull(BitWidth); 6561 6562 APInt NewLower = 6563 Descending ? std::move(MovedBoundary) : std::move(StartLower); 6564 APInt NewUpper = 6565 Descending ? std::move(StartUpper) : std::move(MovedBoundary); 6566 NewUpper += 1; 6567 6568 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range. 6569 return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper)); 6570 } 6571 6572 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 6573 const SCEV *Step, 6574 const SCEV *MaxBECount, 6575 unsigned BitWidth) { 6576 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 6577 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 6578 "Precondition!"); 6579 6580 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 6581 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount); 6582 6583 // First, consider step signed. 6584 ConstantRange StartSRange = getSignedRange(Start); 6585 ConstantRange StepSRange = getSignedRange(Step); 6586 6587 // If Step can be both positive and negative, we need to find ranges for the 6588 // maximum absolute step values in both directions and union them. 6589 ConstantRange SR = 6590 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange, 6591 MaxBECountValue, BitWidth, /* Signed = */ true); 6592 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(), 6593 StartSRange, MaxBECountValue, 6594 BitWidth, /* Signed = */ true)); 6595 6596 // Next, consider step unsigned. 6597 ConstantRange UR = getRangeForAffineARHelper( 6598 getUnsignedRangeMax(Step), getUnsignedRange(Start), 6599 MaxBECountValue, BitWidth, /* Signed = */ false); 6600 6601 // Finally, intersect signed and unsigned ranges. 6602 return SR.intersectWith(UR, ConstantRange::Smallest); 6603 } 6604 6605 ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR( 6606 const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth, 6607 ScalarEvolution::RangeSignHint SignHint) { 6608 assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n"); 6609 assert(AddRec->hasNoSelfWrap() && 6610 "This only works for non-self-wrapping AddRecs!"); 6611 const bool IsSigned = SignHint == HINT_RANGE_SIGNED; 6612 const SCEV *Step = AddRec->getStepRecurrence(*this); 6613 // Only deal with constant step to save compile time. 6614 if (!isa<SCEVConstant>(Step)) 6615 return ConstantRange::getFull(BitWidth); 6616 // Let's make sure that we can prove that we do not self-wrap during 6617 // MaxBECount iterations. We need this because MaxBECount is a maximum 6618 // iteration count estimate, and we might infer nw from some exit for which we 6619 // do not know max exit count (or any other side reasoning). 6620 // TODO: Turn into assert at some point. 6621 if (getTypeSizeInBits(MaxBECount->getType()) > 6622 getTypeSizeInBits(AddRec->getType())) 6623 return ConstantRange::getFull(BitWidth); 6624 MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType()); 6625 const SCEV *RangeWidth = getMinusOne(AddRec->getType()); 6626 const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step)); 6627 const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs); 6628 if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount, 6629 MaxItersWithoutWrap)) 6630 return ConstantRange::getFull(BitWidth); 6631 6632 ICmpInst::Predicate LEPred = 6633 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 6634 ICmpInst::Predicate GEPred = 6635 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 6636 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this); 6637 6638 // We know that there is no self-wrap. Let's take Start and End values and 6639 // look at all intermediate values V1, V2, ..., Vn that IndVar takes during 6640 // the iteration. They either lie inside the range [Min(Start, End), 6641 // Max(Start, End)] or outside it: 6642 // 6643 // Case 1: RangeMin ... Start V1 ... VN End ... RangeMax; 6644 // Case 2: RangeMin Vk ... V1 Start ... End Vn ... Vk + 1 RangeMax; 6645 // 6646 // No self wrap flag guarantees that the intermediate values cannot be BOTH 6647 // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that 6648 // knowledge, let's try to prove that we are dealing with Case 1. It is so if 6649 // Start <= End and step is positive, or Start >= End and step is negative. 6650 const SCEV *Start = AddRec->getStart(); 6651 ConstantRange StartRange = getRangeRef(Start, SignHint); 6652 ConstantRange EndRange = getRangeRef(End, SignHint); 6653 ConstantRange RangeBetween = StartRange.unionWith(EndRange); 6654 // If they already cover full iteration space, we will know nothing useful 6655 // even if we prove what we want to prove. 6656 if (RangeBetween.isFullSet()) 6657 return RangeBetween; 6658 // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax). 6659 bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet() 6660 : RangeBetween.isWrappedSet(); 6661 if (IsWrappedSet) 6662 return ConstantRange::getFull(BitWidth); 6663 6664 if (isKnownPositive(Step) && 6665 isKnownPredicateViaConstantRanges(LEPred, Start, End)) 6666 return RangeBetween; 6667 else if (isKnownNegative(Step) && 6668 isKnownPredicateViaConstantRanges(GEPred, Start, End)) 6669 return RangeBetween; 6670 return ConstantRange::getFull(BitWidth); 6671 } 6672 6673 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 6674 const SCEV *Step, 6675 const SCEV *MaxBECount, 6676 unsigned BitWidth) { 6677 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 6678 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 6679 6680 struct SelectPattern { 6681 Value *Condition = nullptr; 6682 APInt TrueValue; 6683 APInt FalseValue; 6684 6685 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 6686 const SCEV *S) { 6687 Optional<unsigned> CastOp; 6688 APInt Offset(BitWidth, 0); 6689 6690 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 6691 "Should be!"); 6692 6693 // Peel off a constant offset: 6694 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 6695 // In the future we could consider being smarter here and handle 6696 // {Start+Step,+,Step} too. 6697 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 6698 return; 6699 6700 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 6701 S = SA->getOperand(1); 6702 } 6703 6704 // Peel off a cast operation 6705 if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) { 6706 CastOp = SCast->getSCEVType(); 6707 S = SCast->getOperand(); 6708 } 6709 6710 using namespace llvm::PatternMatch; 6711 6712 auto *SU = dyn_cast<SCEVUnknown>(S); 6713 const APInt *TrueVal, *FalseVal; 6714 if (!SU || 6715 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 6716 m_APInt(FalseVal)))) { 6717 Condition = nullptr; 6718 return; 6719 } 6720 6721 TrueValue = *TrueVal; 6722 FalseValue = *FalseVal; 6723 6724 // Re-apply the cast we peeled off earlier 6725 if (CastOp.hasValue()) 6726 switch (*CastOp) { 6727 default: 6728 llvm_unreachable("Unknown SCEV cast type!"); 6729 6730 case scTruncate: 6731 TrueValue = TrueValue.trunc(BitWidth); 6732 FalseValue = FalseValue.trunc(BitWidth); 6733 break; 6734 case scZeroExtend: 6735 TrueValue = TrueValue.zext(BitWidth); 6736 FalseValue = FalseValue.zext(BitWidth); 6737 break; 6738 case scSignExtend: 6739 TrueValue = TrueValue.sext(BitWidth); 6740 FalseValue = FalseValue.sext(BitWidth); 6741 break; 6742 } 6743 6744 // Re-apply the constant offset we peeled off earlier 6745 TrueValue += Offset; 6746 FalseValue += Offset; 6747 } 6748 6749 bool isRecognized() { return Condition != nullptr; } 6750 }; 6751 6752 SelectPattern StartPattern(*this, BitWidth, Start); 6753 if (!StartPattern.isRecognized()) 6754 return ConstantRange::getFull(BitWidth); 6755 6756 SelectPattern StepPattern(*this, BitWidth, Step); 6757 if (!StepPattern.isRecognized()) 6758 return ConstantRange::getFull(BitWidth); 6759 6760 if (StartPattern.Condition != StepPattern.Condition) { 6761 // We don't handle this case today; but we could, by considering four 6762 // possibilities below instead of two. I'm not sure if there are cases where 6763 // that will help over what getRange already does, though. 6764 return ConstantRange::getFull(BitWidth); 6765 } 6766 6767 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 6768 // construct arbitrary general SCEV expressions here. This function is called 6769 // from deep in the call stack, and calling getSCEV (on a sext instruction, 6770 // say) can end up caching a suboptimal value. 6771 6772 // FIXME: without the explicit `this` receiver below, MSVC errors out with 6773 // C2352 and C2512 (otherwise it isn't needed). 6774 6775 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 6776 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 6777 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 6778 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 6779 6780 ConstantRange TrueRange = 6781 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 6782 ConstantRange FalseRange = 6783 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 6784 6785 return TrueRange.unionWith(FalseRange); 6786 } 6787 6788 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 6789 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 6790 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 6791 6792 // Return early if there are no flags to propagate to the SCEV. 6793 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6794 if (BinOp->hasNoUnsignedWrap()) 6795 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 6796 if (BinOp->hasNoSignedWrap()) 6797 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 6798 if (Flags == SCEV::FlagAnyWrap) 6799 return SCEV::FlagAnyWrap; 6800 6801 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 6802 } 6803 6804 const Instruction * 6805 ScalarEvolution::getNonTrivialDefiningScopeBound(const SCEV *S) { 6806 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S)) 6807 return &*AddRec->getLoop()->getHeader()->begin(); 6808 if (auto *U = dyn_cast<SCEVUnknown>(S)) 6809 if (auto *I = dyn_cast<Instruction>(U->getValue())) 6810 return I; 6811 return nullptr; 6812 } 6813 6814 /// Fills \p Ops with unique operands of \p S, if it has operands. If not, 6815 /// \p Ops remains unmodified. 6816 static void collectUniqueOps(const SCEV *S, 6817 SmallVectorImpl<const SCEV *> &Ops) { 6818 SmallPtrSet<const SCEV *, 4> Unique; 6819 auto InsertUnique = [&](const SCEV *S) { 6820 if (Unique.insert(S).second) 6821 Ops.push_back(S); 6822 }; 6823 if (auto *S2 = dyn_cast<SCEVCastExpr>(S)) 6824 for (auto *Op : S2->operands()) 6825 InsertUnique(Op); 6826 else if (auto *S2 = dyn_cast<SCEVNAryExpr>(S)) 6827 for (auto *Op : S2->operands()) 6828 InsertUnique(Op); 6829 else if (auto *S2 = dyn_cast<SCEVUDivExpr>(S)) 6830 for (auto *Op : S2->operands()) 6831 InsertUnique(Op); 6832 } 6833 6834 const Instruction * 6835 ScalarEvolution::getDefiningScopeBound(ArrayRef<const SCEV *> Ops, 6836 bool &Precise) { 6837 Precise = true; 6838 // Do a bounded search of the def relation of the requested SCEVs. 6839 SmallSet<const SCEV *, 16> Visited; 6840 SmallVector<const SCEV *> Worklist; 6841 auto pushOp = [&](const SCEV *S) { 6842 if (!Visited.insert(S).second) 6843 return; 6844 // Threshold of 30 here is arbitrary. 6845 if (Visited.size() > 30) { 6846 Precise = false; 6847 return; 6848 } 6849 Worklist.push_back(S); 6850 }; 6851 6852 for (auto *S : Ops) 6853 pushOp(S); 6854 6855 const Instruction *Bound = nullptr; 6856 while (!Worklist.empty()) { 6857 auto *S = Worklist.pop_back_val(); 6858 if (auto *DefI = getNonTrivialDefiningScopeBound(S)) { 6859 if (!Bound || DT.dominates(Bound, DefI)) 6860 Bound = DefI; 6861 } else { 6862 SmallVector<const SCEV *, 4> Ops; 6863 collectUniqueOps(S, Ops); 6864 for (auto *Op : Ops) 6865 pushOp(Op); 6866 } 6867 } 6868 return Bound ? Bound : &*F.getEntryBlock().begin(); 6869 } 6870 6871 const Instruction * 6872 ScalarEvolution::getDefiningScopeBound(ArrayRef<const SCEV *> Ops) { 6873 bool Discard; 6874 return getDefiningScopeBound(Ops, Discard); 6875 } 6876 6877 bool ScalarEvolution::isGuaranteedToTransferExecutionTo(const Instruction *A, 6878 const Instruction *B) { 6879 if (A->getParent() == B->getParent() && 6880 isGuaranteedToTransferExecutionToSuccessor(A->getIterator(), 6881 B->getIterator())) 6882 return true; 6883 6884 auto *BLoop = LI.getLoopFor(B->getParent()); 6885 if (BLoop && BLoop->getHeader() == B->getParent() && 6886 BLoop->getLoopPreheader() == A->getParent() && 6887 isGuaranteedToTransferExecutionToSuccessor(A->getIterator(), 6888 A->getParent()->end()) && 6889 isGuaranteedToTransferExecutionToSuccessor(B->getParent()->begin(), 6890 B->getIterator())) 6891 return true; 6892 return false; 6893 } 6894 6895 6896 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 6897 // Only proceed if we can prove that I does not yield poison. 6898 if (!programUndefinedIfPoison(I)) 6899 return false; 6900 6901 // At this point we know that if I is executed, then it does not wrap 6902 // according to at least one of NSW or NUW. If I is not executed, then we do 6903 // not know if the calculation that I represents would wrap. Multiple 6904 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 6905 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 6906 // derived from other instructions that map to the same SCEV. We cannot make 6907 // that guarantee for cases where I is not executed. So we need to find a 6908 // upper bound on the defining scope for the SCEV, and prove that I is 6909 // executed every time we enter that scope. When the bounding scope is a 6910 // loop (the common case), this is equivalent to proving I executes on every 6911 // iteration of that loop. 6912 SmallVector<const SCEV *> SCEVOps; 6913 for (const Use &Op : I->operands()) { 6914 // I could be an extractvalue from a call to an overflow intrinsic. 6915 // TODO: We can do better here in some cases. 6916 if (isSCEVable(Op->getType())) 6917 SCEVOps.push_back(getSCEV(Op)); 6918 } 6919 auto *DefI = getDefiningScopeBound(SCEVOps); 6920 return isGuaranteedToTransferExecutionTo(DefI, I); 6921 } 6922 6923 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 6924 // If we know that \c I can never be poison period, then that's enough. 6925 if (isSCEVExprNeverPoison(I)) 6926 return true; 6927 6928 // For an add recurrence specifically, we assume that infinite loops without 6929 // side effects are undefined behavior, and then reason as follows: 6930 // 6931 // If the add recurrence is poison in any iteration, it is poison on all 6932 // future iterations (since incrementing poison yields poison). If the result 6933 // of the add recurrence is fed into the loop latch condition and the loop 6934 // does not contain any throws or exiting blocks other than the latch, we now 6935 // have the ability to "choose" whether the backedge is taken or not (by 6936 // choosing a sufficiently evil value for the poison feeding into the branch) 6937 // for every iteration including and after the one in which \p I first became 6938 // poison. There are two possibilities (let's call the iteration in which \p 6939 // I first became poison as K): 6940 // 6941 // 1. In the set of iterations including and after K, the loop body executes 6942 // no side effects. In this case executing the backege an infinte number 6943 // of times will yield undefined behavior. 6944 // 6945 // 2. In the set of iterations including and after K, the loop body executes 6946 // at least one side effect. In this case, that specific instance of side 6947 // effect is control dependent on poison, which also yields undefined 6948 // behavior. 6949 6950 auto *ExitingBB = L->getExitingBlock(); 6951 auto *LatchBB = L->getLoopLatch(); 6952 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 6953 return false; 6954 6955 SmallPtrSet<const Instruction *, 16> Pushed; 6956 SmallVector<const Instruction *, 8> PoisonStack; 6957 6958 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 6959 // things that are known to be poison under that assumption go on the 6960 // PoisonStack. 6961 Pushed.insert(I); 6962 PoisonStack.push_back(I); 6963 6964 bool LatchControlDependentOnPoison = false; 6965 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 6966 const Instruction *Poison = PoisonStack.pop_back_val(); 6967 6968 for (auto *PoisonUser : Poison->users()) { 6969 if (propagatesPoison(cast<Operator>(PoisonUser))) { 6970 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 6971 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 6972 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 6973 assert(BI->isConditional() && "Only possibility!"); 6974 if (BI->getParent() == LatchBB) { 6975 LatchControlDependentOnPoison = true; 6976 break; 6977 } 6978 } 6979 } 6980 } 6981 6982 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 6983 } 6984 6985 ScalarEvolution::LoopProperties 6986 ScalarEvolution::getLoopProperties(const Loop *L) { 6987 using LoopProperties = ScalarEvolution::LoopProperties; 6988 6989 auto Itr = LoopPropertiesCache.find(L); 6990 if (Itr == LoopPropertiesCache.end()) { 6991 auto HasSideEffects = [](Instruction *I) { 6992 if (auto *SI = dyn_cast<StoreInst>(I)) 6993 return !SI->isSimple(); 6994 6995 return I->mayThrow() || I->mayWriteToMemory(); 6996 }; 6997 6998 LoopProperties LP = {/* HasNoAbnormalExits */ true, 6999 /*HasNoSideEffects*/ true}; 7000 7001 for (auto *BB : L->getBlocks()) 7002 for (auto &I : *BB) { 7003 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 7004 LP.HasNoAbnormalExits = false; 7005 if (HasSideEffects(&I)) 7006 LP.HasNoSideEffects = false; 7007 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 7008 break; // We're already as pessimistic as we can get. 7009 } 7010 7011 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 7012 assert(InsertPair.second && "We just checked!"); 7013 Itr = InsertPair.first; 7014 } 7015 7016 return Itr->second; 7017 } 7018 7019 bool ScalarEvolution::loopIsFiniteByAssumption(const Loop *L) { 7020 // A mustprogress loop without side effects must be finite. 7021 // TODO: The check used here is very conservative. It's only *specific* 7022 // side effects which are well defined in infinite loops. 7023 return isFinite(L) || (isMustProgress(L) && loopHasNoSideEffects(L)); 7024 } 7025 7026 const SCEV *ScalarEvolution::createSCEV(Value *V) { 7027 if (!isSCEVable(V->getType())) 7028 return getUnknown(V); 7029 7030 if (Instruction *I = dyn_cast<Instruction>(V)) { 7031 // Don't attempt to analyze instructions in blocks that aren't 7032 // reachable. Such instructions don't matter, and they aren't required 7033 // to obey basic rules for definitions dominating uses which this 7034 // analysis depends on. 7035 if (!DT.isReachableFromEntry(I->getParent())) 7036 return getUnknown(UndefValue::get(V->getType())); 7037 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 7038 return getConstant(CI); 7039 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 7040 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 7041 else if (!isa<ConstantExpr>(V)) 7042 return getUnknown(V); 7043 7044 Operator *U = cast<Operator>(V); 7045 if (auto BO = MatchBinaryOp(U, DT)) { 7046 switch (BO->Opcode) { 7047 case Instruction::Add: { 7048 // The simple thing to do would be to just call getSCEV on both operands 7049 // and call getAddExpr with the result. However if we're looking at a 7050 // bunch of things all added together, this can be quite inefficient, 7051 // because it leads to N-1 getAddExpr calls for N ultimate operands. 7052 // Instead, gather up all the operands and make a single getAddExpr call. 7053 // LLVM IR canonical form means we need only traverse the left operands. 7054 SmallVector<const SCEV *, 4> AddOps; 7055 do { 7056 if (BO->Op) { 7057 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 7058 AddOps.push_back(OpSCEV); 7059 break; 7060 } 7061 7062 // If a NUW or NSW flag can be applied to the SCEV for this 7063 // addition, then compute the SCEV for this addition by itself 7064 // with a separate call to getAddExpr. We need to do that 7065 // instead of pushing the operands of the addition onto AddOps, 7066 // since the flags are only known to apply to this particular 7067 // addition - they may not apply to other additions that can be 7068 // formed with operands from AddOps. 7069 const SCEV *RHS = getSCEV(BO->RHS); 7070 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 7071 if (Flags != SCEV::FlagAnyWrap) { 7072 const SCEV *LHS = getSCEV(BO->LHS); 7073 if (BO->Opcode == Instruction::Sub) 7074 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 7075 else 7076 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 7077 break; 7078 } 7079 } 7080 7081 if (BO->Opcode == Instruction::Sub) 7082 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 7083 else 7084 AddOps.push_back(getSCEV(BO->RHS)); 7085 7086 auto NewBO = MatchBinaryOp(BO->LHS, DT); 7087 if (!NewBO || (NewBO->Opcode != Instruction::Add && 7088 NewBO->Opcode != Instruction::Sub)) { 7089 AddOps.push_back(getSCEV(BO->LHS)); 7090 break; 7091 } 7092 BO = NewBO; 7093 } while (true); 7094 7095 return getAddExpr(AddOps); 7096 } 7097 7098 case Instruction::Mul: { 7099 SmallVector<const SCEV *, 4> MulOps; 7100 do { 7101 if (BO->Op) { 7102 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 7103 MulOps.push_back(OpSCEV); 7104 break; 7105 } 7106 7107 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 7108 if (Flags != SCEV::FlagAnyWrap) { 7109 MulOps.push_back( 7110 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 7111 break; 7112 } 7113 } 7114 7115 MulOps.push_back(getSCEV(BO->RHS)); 7116 auto NewBO = MatchBinaryOp(BO->LHS, DT); 7117 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 7118 MulOps.push_back(getSCEV(BO->LHS)); 7119 break; 7120 } 7121 BO = NewBO; 7122 } while (true); 7123 7124 return getMulExpr(MulOps); 7125 } 7126 case Instruction::UDiv: 7127 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 7128 case Instruction::URem: 7129 return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 7130 case Instruction::Sub: { 7131 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 7132 if (BO->Op) 7133 Flags = getNoWrapFlagsFromUB(BO->Op); 7134 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 7135 } 7136 case Instruction::And: 7137 // For an expression like x&255 that merely masks off the high bits, 7138 // use zext(trunc(x)) as the SCEV expression. 7139 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 7140 if (CI->isZero()) 7141 return getSCEV(BO->RHS); 7142 if (CI->isMinusOne()) 7143 return getSCEV(BO->LHS); 7144 const APInt &A = CI->getValue(); 7145 7146 // Instcombine's ShrinkDemandedConstant may strip bits out of 7147 // constants, obscuring what would otherwise be a low-bits mask. 7148 // Use computeKnownBits to compute what ShrinkDemandedConstant 7149 // knew about to reconstruct a low-bits mask value. 7150 unsigned LZ = A.countLeadingZeros(); 7151 unsigned TZ = A.countTrailingZeros(); 7152 unsigned BitWidth = A.getBitWidth(); 7153 KnownBits Known(BitWidth); 7154 computeKnownBits(BO->LHS, Known, getDataLayout(), 7155 0, &AC, nullptr, &DT); 7156 7157 APInt EffectiveMask = 7158 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 7159 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) { 7160 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ)); 7161 const SCEV *LHS = getSCEV(BO->LHS); 7162 const SCEV *ShiftedLHS = nullptr; 7163 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) { 7164 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) { 7165 // For an expression like (x * 8) & 8, simplify the multiply. 7166 unsigned MulZeros = OpC->getAPInt().countTrailingZeros(); 7167 unsigned GCD = std::min(MulZeros, TZ); 7168 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD); 7169 SmallVector<const SCEV*, 4> MulOps; 7170 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD))); 7171 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end()); 7172 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags()); 7173 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt)); 7174 } 7175 } 7176 if (!ShiftedLHS) 7177 ShiftedLHS = getUDivExpr(LHS, MulCount); 7178 return getMulExpr( 7179 getZeroExtendExpr( 7180 getTruncateExpr(ShiftedLHS, 7181 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 7182 BO->LHS->getType()), 7183 MulCount); 7184 } 7185 } 7186 // Binary `and` is a bit-wise `umin`. 7187 if (BO->LHS->getType()->isIntegerTy(1)) 7188 return getUMinExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 7189 break; 7190 7191 case Instruction::Or: 7192 // If the RHS of the Or is a constant, we may have something like: 7193 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 7194 // optimizations will transparently handle this case. 7195 // 7196 // In order for this transformation to be safe, the LHS must be of the 7197 // form X*(2^n) and the Or constant must be less than 2^n. 7198 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 7199 const SCEV *LHS = getSCEV(BO->LHS); 7200 const APInt &CIVal = CI->getValue(); 7201 if (GetMinTrailingZeros(LHS) >= 7202 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 7203 // Build a plain add SCEV. 7204 return getAddExpr(LHS, getSCEV(CI), 7205 (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW)); 7206 } 7207 } 7208 // Binary `or` is a bit-wise `umax`. 7209 if (BO->LHS->getType()->isIntegerTy(1)) 7210 return getUMaxExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 7211 break; 7212 7213 case Instruction::Xor: 7214 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 7215 // If the RHS of xor is -1, then this is a not operation. 7216 if (CI->isMinusOne()) 7217 return getNotSCEV(getSCEV(BO->LHS)); 7218 7219 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 7220 // This is a variant of the check for xor with -1, and it handles 7221 // the case where instcombine has trimmed non-demanded bits out 7222 // of an xor with -1. 7223 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 7224 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 7225 if (LBO->getOpcode() == Instruction::And && 7226 LCI->getValue() == CI->getValue()) 7227 if (const SCEVZeroExtendExpr *Z = 7228 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 7229 Type *UTy = BO->LHS->getType(); 7230 const SCEV *Z0 = Z->getOperand(); 7231 Type *Z0Ty = Z0->getType(); 7232 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 7233 7234 // If C is a low-bits mask, the zero extend is serving to 7235 // mask off the high bits. Complement the operand and 7236 // re-apply the zext. 7237 if (CI->getValue().isMask(Z0TySize)) 7238 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 7239 7240 // If C is a single bit, it may be in the sign-bit position 7241 // before the zero-extend. In this case, represent the xor 7242 // using an add, which is equivalent, and re-apply the zext. 7243 APInt Trunc = CI->getValue().trunc(Z0TySize); 7244 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 7245 Trunc.isSignMask()) 7246 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 7247 UTy); 7248 } 7249 } 7250 break; 7251 7252 case Instruction::Shl: 7253 // Turn shift left of a constant amount into a multiply. 7254 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 7255 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 7256 7257 // If the shift count is not less than the bitwidth, the result of 7258 // the shift is undefined. Don't try to analyze it, because the 7259 // resolution chosen here may differ from the resolution chosen in 7260 // other parts of the compiler. 7261 if (SA->getValue().uge(BitWidth)) 7262 break; 7263 7264 // We can safely preserve the nuw flag in all cases. It's also safe to 7265 // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation 7266 // requires special handling. It can be preserved as long as we're not 7267 // left shifting by bitwidth - 1. 7268 auto Flags = SCEV::FlagAnyWrap; 7269 if (BO->Op) { 7270 auto MulFlags = getNoWrapFlagsFromUB(BO->Op); 7271 if ((MulFlags & SCEV::FlagNSW) && 7272 ((MulFlags & SCEV::FlagNUW) || SA->getValue().ult(BitWidth - 1))) 7273 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNSW); 7274 if (MulFlags & SCEV::FlagNUW) 7275 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNUW); 7276 } 7277 7278 Constant *X = ConstantInt::get( 7279 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 7280 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 7281 } 7282 break; 7283 7284 case Instruction::AShr: { 7285 // AShr X, C, where C is a constant. 7286 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS); 7287 if (!CI) 7288 break; 7289 7290 Type *OuterTy = BO->LHS->getType(); 7291 uint64_t BitWidth = getTypeSizeInBits(OuterTy); 7292 // If the shift count is not less than the bitwidth, the result of 7293 // the shift is undefined. Don't try to analyze it, because the 7294 // resolution chosen here may differ from the resolution chosen in 7295 // other parts of the compiler. 7296 if (CI->getValue().uge(BitWidth)) 7297 break; 7298 7299 if (CI->isZero()) 7300 return getSCEV(BO->LHS); // shift by zero --> noop 7301 7302 uint64_t AShrAmt = CI->getZExtValue(); 7303 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt); 7304 7305 Operator *L = dyn_cast<Operator>(BO->LHS); 7306 if (L && L->getOpcode() == Instruction::Shl) { 7307 // X = Shl A, n 7308 // Y = AShr X, m 7309 // Both n and m are constant. 7310 7311 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0)); 7312 if (L->getOperand(1) == BO->RHS) 7313 // For a two-shift sext-inreg, i.e. n = m, 7314 // use sext(trunc(x)) as the SCEV expression. 7315 return getSignExtendExpr( 7316 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy); 7317 7318 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1)); 7319 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) { 7320 uint64_t ShlAmt = ShlAmtCI->getZExtValue(); 7321 if (ShlAmt > AShrAmt) { 7322 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV 7323 // expression. We already checked that ShlAmt < BitWidth, so 7324 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as 7325 // ShlAmt - AShrAmt < Amt. 7326 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt, 7327 ShlAmt - AShrAmt); 7328 return getSignExtendExpr( 7329 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy), 7330 getConstant(Mul)), OuterTy); 7331 } 7332 } 7333 } 7334 break; 7335 } 7336 } 7337 } 7338 7339 switch (U->getOpcode()) { 7340 case Instruction::Trunc: 7341 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 7342 7343 case Instruction::ZExt: 7344 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 7345 7346 case Instruction::SExt: 7347 if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) { 7348 // The NSW flag of a subtract does not always survive the conversion to 7349 // A + (-1)*B. By pushing sign extension onto its operands we are much 7350 // more likely to preserve NSW and allow later AddRec optimisations. 7351 // 7352 // NOTE: This is effectively duplicating this logic from getSignExtend: 7353 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 7354 // but by that point the NSW information has potentially been lost. 7355 if (BO->Opcode == Instruction::Sub && BO->IsNSW) { 7356 Type *Ty = U->getType(); 7357 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty); 7358 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty); 7359 return getMinusSCEV(V1, V2, SCEV::FlagNSW); 7360 } 7361 } 7362 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 7363 7364 case Instruction::BitCast: 7365 // BitCasts are no-op casts so we just eliminate the cast. 7366 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 7367 return getSCEV(U->getOperand(0)); 7368 break; 7369 7370 case Instruction::PtrToInt: { 7371 // Pointer to integer cast is straight-forward, so do model it. 7372 const SCEV *Op = getSCEV(U->getOperand(0)); 7373 Type *DstIntTy = U->getType(); 7374 // But only if effective SCEV (integer) type is wide enough to represent 7375 // all possible pointer values. 7376 const SCEV *IntOp = getPtrToIntExpr(Op, DstIntTy); 7377 if (isa<SCEVCouldNotCompute>(IntOp)) 7378 return getUnknown(V); 7379 return IntOp; 7380 } 7381 case Instruction::IntToPtr: 7382 // Just don't deal with inttoptr casts. 7383 return getUnknown(V); 7384 7385 case Instruction::SDiv: 7386 // If both operands are non-negative, this is just an udiv. 7387 if (isKnownNonNegative(getSCEV(U->getOperand(0))) && 7388 isKnownNonNegative(getSCEV(U->getOperand(1)))) 7389 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1))); 7390 break; 7391 7392 case Instruction::SRem: 7393 // If both operands are non-negative, this is just an urem. 7394 if (isKnownNonNegative(getSCEV(U->getOperand(0))) && 7395 isKnownNonNegative(getSCEV(U->getOperand(1)))) 7396 return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1))); 7397 break; 7398 7399 case Instruction::GetElementPtr: 7400 return createNodeForGEP(cast<GEPOperator>(U)); 7401 7402 case Instruction::PHI: 7403 return createNodeForPHI(cast<PHINode>(U)); 7404 7405 case Instruction::Select: 7406 // U can also be a select constant expr, which let fall through. Since 7407 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 7408 // constant expressions cannot have instructions as operands, we'd have 7409 // returned getUnknown for a select constant expressions anyway. 7410 if (isa<Instruction>(U)) 7411 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 7412 U->getOperand(1), U->getOperand(2)); 7413 break; 7414 7415 case Instruction::Call: 7416 case Instruction::Invoke: 7417 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand()) 7418 return getSCEV(RV); 7419 7420 if (auto *II = dyn_cast<IntrinsicInst>(U)) { 7421 switch (II->getIntrinsicID()) { 7422 case Intrinsic::abs: 7423 return getAbsExpr( 7424 getSCEV(II->getArgOperand(0)), 7425 /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne()); 7426 case Intrinsic::umax: 7427 return getUMaxExpr(getSCEV(II->getArgOperand(0)), 7428 getSCEV(II->getArgOperand(1))); 7429 case Intrinsic::umin: 7430 return getUMinExpr(getSCEV(II->getArgOperand(0)), 7431 getSCEV(II->getArgOperand(1))); 7432 case Intrinsic::smax: 7433 return getSMaxExpr(getSCEV(II->getArgOperand(0)), 7434 getSCEV(II->getArgOperand(1))); 7435 case Intrinsic::smin: 7436 return getSMinExpr(getSCEV(II->getArgOperand(0)), 7437 getSCEV(II->getArgOperand(1))); 7438 case Intrinsic::usub_sat: { 7439 const SCEV *X = getSCEV(II->getArgOperand(0)); 7440 const SCEV *Y = getSCEV(II->getArgOperand(1)); 7441 const SCEV *ClampedY = getUMinExpr(X, Y); 7442 return getMinusSCEV(X, ClampedY, SCEV::FlagNUW); 7443 } 7444 case Intrinsic::uadd_sat: { 7445 const SCEV *X = getSCEV(II->getArgOperand(0)); 7446 const SCEV *Y = getSCEV(II->getArgOperand(1)); 7447 const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y)); 7448 return getAddExpr(ClampedX, Y, SCEV::FlagNUW); 7449 } 7450 case Intrinsic::start_loop_iterations: 7451 // A start_loop_iterations is just equivalent to the first operand for 7452 // SCEV purposes. 7453 return getSCEV(II->getArgOperand(0)); 7454 default: 7455 break; 7456 } 7457 } 7458 break; 7459 } 7460 7461 return getUnknown(V); 7462 } 7463 7464 //===----------------------------------------------------------------------===// 7465 // Iteration Count Computation Code 7466 // 7467 7468 const SCEV *ScalarEvolution::getTripCountFromExitCount(const SCEV *ExitCount, 7469 bool Extend) { 7470 if (isa<SCEVCouldNotCompute>(ExitCount)) 7471 return getCouldNotCompute(); 7472 7473 auto *ExitCountType = ExitCount->getType(); 7474 assert(ExitCountType->isIntegerTy()); 7475 7476 if (!Extend) 7477 return getAddExpr(ExitCount, getOne(ExitCountType)); 7478 7479 auto *WiderType = Type::getIntNTy(ExitCountType->getContext(), 7480 1 + ExitCountType->getScalarSizeInBits()); 7481 return getAddExpr(getNoopOrZeroExtend(ExitCount, WiderType), 7482 getOne(WiderType)); 7483 } 7484 7485 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 7486 if (!ExitCount) 7487 return 0; 7488 7489 ConstantInt *ExitConst = ExitCount->getValue(); 7490 7491 // Guard against huge trip counts. 7492 if (ExitConst->getValue().getActiveBits() > 32) 7493 return 0; 7494 7495 // In case of integer overflow, this returns 0, which is correct. 7496 return ((unsigned)ExitConst->getZExtValue()) + 1; 7497 } 7498 7499 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) { 7500 auto *ExitCount = dyn_cast<SCEVConstant>(getBackedgeTakenCount(L, Exact)); 7501 return getConstantTripCount(ExitCount); 7502 } 7503 7504 unsigned 7505 ScalarEvolution::getSmallConstantTripCount(const Loop *L, 7506 const BasicBlock *ExitingBlock) { 7507 assert(ExitingBlock && "Must pass a non-null exiting block!"); 7508 assert(L->isLoopExiting(ExitingBlock) && 7509 "Exiting block must actually branch out of the loop!"); 7510 const SCEVConstant *ExitCount = 7511 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 7512 return getConstantTripCount(ExitCount); 7513 } 7514 7515 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) { 7516 const auto *MaxExitCount = 7517 dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L)); 7518 return getConstantTripCount(MaxExitCount); 7519 } 7520 7521 const SCEV *ScalarEvolution::getConstantMaxTripCountFromArray(const Loop *L) { 7522 // We can't infer from Array in Irregular Loop. 7523 // FIXME: It's hard to infer loop bound from array operated in Nested Loop. 7524 if (!L->isLoopSimplifyForm() || !L->isInnermost()) 7525 return getCouldNotCompute(); 7526 7527 // FIXME: To make the scene more typical, we only analysis loops that have 7528 // one exiting block and that block must be the latch. To make it easier to 7529 // capture loops that have memory access and memory access will be executed 7530 // in each iteration. 7531 const BasicBlock *LoopLatch = L->getLoopLatch(); 7532 assert(LoopLatch && "See defination of simplify form loop."); 7533 if (L->getExitingBlock() != LoopLatch) 7534 return getCouldNotCompute(); 7535 7536 const DataLayout &DL = getDataLayout(); 7537 SmallVector<const SCEV *> InferCountColl; 7538 for (auto *BB : L->getBlocks()) { 7539 // Go here, we can know that Loop is a single exiting and simplified form 7540 // loop. Make sure that infer from Memory Operation in those BBs must be 7541 // executed in loop. First step, we can make sure that max execution time 7542 // of MemAccessBB in loop represents latch max excution time. 7543 // If MemAccessBB does not dom Latch, skip. 7544 // Entry 7545 // │ 7546 // ┌─────▼─────┐ 7547 // │Loop Header◄─────┐ 7548 // └──┬──────┬─┘ │ 7549 // │ │ │ 7550 // ┌────────▼──┐ ┌─▼─────┐ │ 7551 // │MemAccessBB│ │OtherBB│ │ 7552 // └────────┬──┘ └─┬─────┘ │ 7553 // │ │ │ 7554 // ┌─▼──────▼─┐ │ 7555 // │Loop Latch├─────┘ 7556 // └────┬─────┘ 7557 // ▼ 7558 // Exit 7559 if (!DT.dominates(BB, LoopLatch)) 7560 continue; 7561 7562 for (Instruction &Inst : *BB) { 7563 // Find Memory Operation Instruction. 7564 auto *GEP = getLoadStorePointerOperand(&Inst); 7565 if (!GEP) 7566 continue; 7567 7568 auto *ElemSize = dyn_cast<SCEVConstant>(getElementSize(&Inst)); 7569 // Do not infer from scalar type, eg."ElemSize = sizeof()". 7570 if (!ElemSize) 7571 continue; 7572 7573 // Use a existing polynomial recurrence on the trip count. 7574 auto *AddRec = dyn_cast<SCEVAddRecExpr>(getSCEV(GEP)); 7575 if (!AddRec) 7576 continue; 7577 auto *ArrBase = dyn_cast<SCEVUnknown>(getPointerBase(AddRec)); 7578 auto *Step = dyn_cast<SCEVConstant>(AddRec->getStepRecurrence(*this)); 7579 if (!ArrBase || !Step) 7580 continue; 7581 assert(isLoopInvariant(ArrBase, L) && "See addrec definition"); 7582 7583 // Only handle { %array + step }, 7584 // FIXME: {(SCEVAddRecExpr) + step } could not be analysed here. 7585 if (AddRec->getStart() != ArrBase) 7586 continue; 7587 7588 // Memory operation pattern which have gaps. 7589 // Or repeat memory opreation. 7590 // And index of GEP wraps arround. 7591 if (Step->getAPInt().getActiveBits() > 32 || 7592 Step->getAPInt().getZExtValue() != 7593 ElemSize->getAPInt().getZExtValue() || 7594 Step->isZero() || Step->getAPInt().isNegative()) 7595 continue; 7596 7597 // Only infer from stack array which has certain size. 7598 // Make sure alloca instruction is not excuted in loop. 7599 AllocaInst *AllocateInst = dyn_cast<AllocaInst>(ArrBase->getValue()); 7600 if (!AllocateInst || L->contains(AllocateInst->getParent())) 7601 continue; 7602 7603 // Make sure only handle normal array. 7604 auto *Ty = dyn_cast<ArrayType>(AllocateInst->getAllocatedType()); 7605 auto *ArrSize = dyn_cast<ConstantInt>(AllocateInst->getArraySize()); 7606 if (!Ty || !ArrSize || !ArrSize->isOne()) 7607 continue; 7608 7609 // FIXME: Since gep indices are silently zext to the indexing type, 7610 // we will have a narrow gep index which wraps around rather than 7611 // increasing strictly, we shoule ensure that step is increasing 7612 // strictly by the loop iteration. 7613 // Now we can infer a max execution time by MemLength/StepLength. 7614 const SCEV *MemSize = 7615 getConstant(Step->getType(), DL.getTypeAllocSize(Ty)); 7616 auto *MaxExeCount = 7617 dyn_cast<SCEVConstant>(getUDivCeilSCEV(MemSize, Step)); 7618 if (!MaxExeCount || MaxExeCount->getAPInt().getActiveBits() > 32) 7619 continue; 7620 7621 // If the loop reaches the maximum number of executions, we can not 7622 // access bytes starting outside the statically allocated size without 7623 // being immediate UB. But it is allowed to enter loop header one more 7624 // time. 7625 auto *InferCount = dyn_cast<SCEVConstant>( 7626 getAddExpr(MaxExeCount, getOne(MaxExeCount->getType()))); 7627 // Discard the maximum number of execution times under 32bits. 7628 if (!InferCount || InferCount->getAPInt().getActiveBits() > 32) 7629 continue; 7630 7631 InferCountColl.push_back(InferCount); 7632 } 7633 } 7634 7635 if (InferCountColl.size() == 0) 7636 return getCouldNotCompute(); 7637 7638 return getUMinFromMismatchedTypes(InferCountColl); 7639 } 7640 7641 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) { 7642 SmallVector<BasicBlock *, 8> ExitingBlocks; 7643 L->getExitingBlocks(ExitingBlocks); 7644 7645 Optional<unsigned> Res = None; 7646 for (auto *ExitingBB : ExitingBlocks) { 7647 unsigned Multiple = getSmallConstantTripMultiple(L, ExitingBB); 7648 if (!Res) 7649 Res = Multiple; 7650 Res = (unsigned)GreatestCommonDivisor64(*Res, Multiple); 7651 } 7652 return Res.getValueOr(1); 7653 } 7654 7655 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 7656 const SCEV *ExitCount) { 7657 if (ExitCount == getCouldNotCompute()) 7658 return 1; 7659 7660 // Get the trip count 7661 const SCEV *TCExpr = getTripCountFromExitCount(ExitCount); 7662 7663 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr); 7664 if (!TC) 7665 // Attempt to factor more general cases. Returns the greatest power of 7666 // two divisor. If overflow happens, the trip count expression is still 7667 // divisible by the greatest power of 2 divisor returned. 7668 return 1U << std::min((uint32_t)31, 7669 GetMinTrailingZeros(applyLoopGuards(TCExpr, L))); 7670 7671 ConstantInt *Result = TC->getValue(); 7672 7673 // Guard against huge trip counts (this requires checking 7674 // for zero to handle the case where the trip count == -1 and the 7675 // addition wraps). 7676 if (!Result || Result->getValue().getActiveBits() > 32 || 7677 Result->getValue().getActiveBits() == 0) 7678 return 1; 7679 7680 return (unsigned)Result->getZExtValue(); 7681 } 7682 7683 /// Returns the largest constant divisor of the trip count of this loop as a 7684 /// normal unsigned value, if possible. This means that the actual trip count is 7685 /// always a multiple of the returned value (don't forget the trip count could 7686 /// very well be zero as well!). 7687 /// 7688 /// Returns 1 if the trip count is unknown or not guaranteed to be the 7689 /// multiple of a constant (which is also the case if the trip count is simply 7690 /// constant, use getSmallConstantTripCount for that case), Will also return 1 7691 /// if the trip count is very large (>= 2^32). 7692 /// 7693 /// As explained in the comments for getSmallConstantTripCount, this assumes 7694 /// that control exits the loop via ExitingBlock. 7695 unsigned 7696 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 7697 const BasicBlock *ExitingBlock) { 7698 assert(ExitingBlock && "Must pass a non-null exiting block!"); 7699 assert(L->isLoopExiting(ExitingBlock) && 7700 "Exiting block must actually branch out of the loop!"); 7701 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 7702 return getSmallConstantTripMultiple(L, ExitCount); 7703 } 7704 7705 const SCEV *ScalarEvolution::getExitCount(const Loop *L, 7706 const BasicBlock *ExitingBlock, 7707 ExitCountKind Kind) { 7708 switch (Kind) { 7709 case Exact: 7710 case SymbolicMaximum: 7711 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 7712 case ConstantMaximum: 7713 return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this); 7714 }; 7715 llvm_unreachable("Invalid ExitCountKind!"); 7716 } 7717 7718 const SCEV * 7719 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 7720 SmallVector<const SCEVPredicate *, 4> &Preds) { 7721 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds); 7722 } 7723 7724 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L, 7725 ExitCountKind Kind) { 7726 switch (Kind) { 7727 case Exact: 7728 return getBackedgeTakenInfo(L).getExact(L, this); 7729 case ConstantMaximum: 7730 return getBackedgeTakenInfo(L).getConstantMax(this); 7731 case SymbolicMaximum: 7732 return getBackedgeTakenInfo(L).getSymbolicMax(L, this); 7733 }; 7734 llvm_unreachable("Invalid ExitCountKind!"); 7735 } 7736 7737 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 7738 return getBackedgeTakenInfo(L).isConstantMaxOrZero(this); 7739 } 7740 7741 /// Push PHI nodes in the header of the given loop onto the given Worklist. 7742 static void PushLoopPHIs(const Loop *L, 7743 SmallVectorImpl<Instruction *> &Worklist, 7744 SmallPtrSetImpl<Instruction *> &Visited) { 7745 BasicBlock *Header = L->getHeader(); 7746 7747 // Push all Loop-header PHIs onto the Worklist stack. 7748 for (PHINode &PN : Header->phis()) 7749 if (Visited.insert(&PN).second) 7750 Worklist.push_back(&PN); 7751 } 7752 7753 const ScalarEvolution::BackedgeTakenInfo & 7754 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 7755 auto &BTI = getBackedgeTakenInfo(L); 7756 if (BTI.hasFullInfo()) 7757 return BTI; 7758 7759 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 7760 7761 if (!Pair.second) 7762 return Pair.first->second; 7763 7764 BackedgeTakenInfo Result = 7765 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 7766 7767 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 7768 } 7769 7770 ScalarEvolution::BackedgeTakenInfo & 7771 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 7772 // Initially insert an invalid entry for this loop. If the insertion 7773 // succeeds, proceed to actually compute a backedge-taken count and 7774 // update the value. The temporary CouldNotCompute value tells SCEV 7775 // code elsewhere that it shouldn't attempt to request a new 7776 // backedge-taken count, which could result in infinite recursion. 7777 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 7778 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 7779 if (!Pair.second) 7780 return Pair.first->second; 7781 7782 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 7783 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 7784 // must be cleared in this scope. 7785 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 7786 7787 // In product build, there are no usage of statistic. 7788 (void)NumTripCountsComputed; 7789 (void)NumTripCountsNotComputed; 7790 #if LLVM_ENABLE_STATS || !defined(NDEBUG) 7791 const SCEV *BEExact = Result.getExact(L, this); 7792 if (BEExact != getCouldNotCompute()) { 7793 assert(isLoopInvariant(BEExact, L) && 7794 isLoopInvariant(Result.getConstantMax(this), L) && 7795 "Computed backedge-taken count isn't loop invariant for loop!"); 7796 ++NumTripCountsComputed; 7797 } else if (Result.getConstantMax(this) == getCouldNotCompute() && 7798 isa<PHINode>(L->getHeader()->begin())) { 7799 // Only count loops that have phi nodes as not being computable. 7800 ++NumTripCountsNotComputed; 7801 } 7802 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG) 7803 7804 // Now that we know more about the trip count for this loop, forget any 7805 // existing SCEV values for PHI nodes in this loop since they are only 7806 // conservative estimates made without the benefit of trip count 7807 // information. This invalidation is not necessary for correctness, and is 7808 // only done to produce more precise results. 7809 if (Result.hasAnyInfo()) { 7810 // Invalidate any expression using an addrec in this loop. 7811 SmallVector<const SCEV *, 8> ToForget; 7812 auto LoopUsersIt = LoopUsers.find(L); 7813 if (LoopUsersIt != LoopUsers.end()) 7814 append_range(ToForget, LoopUsersIt->second); 7815 forgetMemoizedResults(ToForget); 7816 7817 // Invalidate constant-evolved loop header phis. 7818 for (PHINode &PN : L->getHeader()->phis()) 7819 ConstantEvolutionLoopExitValue.erase(&PN); 7820 } 7821 7822 // Re-lookup the insert position, since the call to 7823 // computeBackedgeTakenCount above could result in a 7824 // recusive call to getBackedgeTakenInfo (on a different 7825 // loop), which would invalidate the iterator computed 7826 // earlier. 7827 return BackedgeTakenCounts.find(L)->second = std::move(Result); 7828 } 7829 7830 void ScalarEvolution::forgetAllLoops() { 7831 // This method is intended to forget all info about loops. It should 7832 // invalidate caches as if the following happened: 7833 // - The trip counts of all loops have changed arbitrarily 7834 // - Every llvm::Value has been updated in place to produce a different 7835 // result. 7836 BackedgeTakenCounts.clear(); 7837 PredicatedBackedgeTakenCounts.clear(); 7838 BECountUsers.clear(); 7839 LoopPropertiesCache.clear(); 7840 ConstantEvolutionLoopExitValue.clear(); 7841 ValueExprMap.clear(); 7842 ValuesAtScopes.clear(); 7843 ValuesAtScopesUsers.clear(); 7844 LoopDispositions.clear(); 7845 BlockDispositions.clear(); 7846 UnsignedRanges.clear(); 7847 SignedRanges.clear(); 7848 ExprValueMap.clear(); 7849 HasRecMap.clear(); 7850 MinTrailingZerosCache.clear(); 7851 PredicatedSCEVRewrites.clear(); 7852 } 7853 7854 void ScalarEvolution::forgetLoop(const Loop *L) { 7855 SmallVector<const Loop *, 16> LoopWorklist(1, L); 7856 SmallVector<Instruction *, 32> Worklist; 7857 SmallPtrSet<Instruction *, 16> Visited; 7858 SmallVector<const SCEV *, 16> ToForget; 7859 7860 // Iterate over all the loops and sub-loops to drop SCEV information. 7861 while (!LoopWorklist.empty()) { 7862 auto *CurrL = LoopWorklist.pop_back_val(); 7863 7864 // Drop any stored trip count value. 7865 forgetBackedgeTakenCounts(CurrL, /* Predicated */ false); 7866 forgetBackedgeTakenCounts(CurrL, /* Predicated */ true); 7867 7868 // Drop information about predicated SCEV rewrites for this loop. 7869 for (auto I = PredicatedSCEVRewrites.begin(); 7870 I != PredicatedSCEVRewrites.end();) { 7871 std::pair<const SCEV *, const Loop *> Entry = I->first; 7872 if (Entry.second == CurrL) 7873 PredicatedSCEVRewrites.erase(I++); 7874 else 7875 ++I; 7876 } 7877 7878 auto LoopUsersItr = LoopUsers.find(CurrL); 7879 if (LoopUsersItr != LoopUsers.end()) { 7880 ToForget.insert(ToForget.end(), LoopUsersItr->second.begin(), 7881 LoopUsersItr->second.end()); 7882 LoopUsers.erase(LoopUsersItr); 7883 } 7884 7885 // Drop information about expressions based on loop-header PHIs. 7886 PushLoopPHIs(CurrL, Worklist, Visited); 7887 7888 while (!Worklist.empty()) { 7889 Instruction *I = Worklist.pop_back_val(); 7890 7891 ValueExprMapType::iterator It = 7892 ValueExprMap.find_as(static_cast<Value *>(I)); 7893 if (It != ValueExprMap.end()) { 7894 eraseValueFromMap(It->first); 7895 ToForget.push_back(It->second); 7896 if (PHINode *PN = dyn_cast<PHINode>(I)) 7897 ConstantEvolutionLoopExitValue.erase(PN); 7898 } 7899 7900 PushDefUseChildren(I, Worklist, Visited); 7901 } 7902 7903 LoopPropertiesCache.erase(CurrL); 7904 // Forget all contained loops too, to avoid dangling entries in the 7905 // ValuesAtScopes map. 7906 LoopWorklist.append(CurrL->begin(), CurrL->end()); 7907 } 7908 forgetMemoizedResults(ToForget); 7909 } 7910 7911 void ScalarEvolution::forgetTopmostLoop(const Loop *L) { 7912 while (Loop *Parent = L->getParentLoop()) 7913 L = Parent; 7914 forgetLoop(L); 7915 } 7916 7917 void ScalarEvolution::forgetValue(Value *V) { 7918 Instruction *I = dyn_cast<Instruction>(V); 7919 if (!I) return; 7920 7921 // Drop information about expressions based on loop-header PHIs. 7922 SmallVector<Instruction *, 16> Worklist; 7923 SmallPtrSet<Instruction *, 8> Visited; 7924 SmallVector<const SCEV *, 8> ToForget; 7925 Worklist.push_back(I); 7926 Visited.insert(I); 7927 7928 while (!Worklist.empty()) { 7929 I = Worklist.pop_back_val(); 7930 ValueExprMapType::iterator It = 7931 ValueExprMap.find_as(static_cast<Value *>(I)); 7932 if (It != ValueExprMap.end()) { 7933 eraseValueFromMap(It->first); 7934 ToForget.push_back(It->second); 7935 if (PHINode *PN = dyn_cast<PHINode>(I)) 7936 ConstantEvolutionLoopExitValue.erase(PN); 7937 } 7938 7939 PushDefUseChildren(I, Worklist, Visited); 7940 } 7941 forgetMemoizedResults(ToForget); 7942 } 7943 7944 void ScalarEvolution::forgetLoopDispositions(const Loop *L) { 7945 LoopDispositions.clear(); 7946 } 7947 7948 /// Get the exact loop backedge taken count considering all loop exits. A 7949 /// computable result can only be returned for loops with all exiting blocks 7950 /// dominating the latch. howFarToZero assumes that the limit of each loop test 7951 /// is never skipped. This is a valid assumption as long as the loop exits via 7952 /// that test. For precise results, it is the caller's responsibility to specify 7953 /// the relevant loop exiting block using getExact(ExitingBlock, SE). 7954 const SCEV * 7955 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE, 7956 SmallVector<const SCEVPredicate *, 4> *Preds) const { 7957 // If any exits were not computable, the loop is not computable. 7958 if (!isComplete() || ExitNotTaken.empty()) 7959 return SE->getCouldNotCompute(); 7960 7961 const BasicBlock *Latch = L->getLoopLatch(); 7962 // All exiting blocks we have collected must dominate the only backedge. 7963 if (!Latch) 7964 return SE->getCouldNotCompute(); 7965 7966 // All exiting blocks we have gathered dominate loop's latch, so exact trip 7967 // count is simply a minimum out of all these calculated exit counts. 7968 SmallVector<const SCEV *, 2> Ops; 7969 for (auto &ENT : ExitNotTaken) { 7970 const SCEV *BECount = ENT.ExactNotTaken; 7971 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!"); 7972 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) && 7973 "We should only have known counts for exiting blocks that dominate " 7974 "latch!"); 7975 7976 Ops.push_back(BECount); 7977 7978 if (Preds) 7979 for (auto *P : ENT.Predicates) 7980 Preds->push_back(P); 7981 7982 assert((Preds || ENT.hasAlwaysTruePredicate()) && 7983 "Predicate should be always true!"); 7984 } 7985 7986 return SE->getUMinFromMismatchedTypes(Ops); 7987 } 7988 7989 /// Get the exact not taken count for this loop exit. 7990 const SCEV * 7991 ScalarEvolution::BackedgeTakenInfo::getExact(const BasicBlock *ExitingBlock, 7992 ScalarEvolution *SE) const { 7993 for (auto &ENT : ExitNotTaken) 7994 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 7995 return ENT.ExactNotTaken; 7996 7997 return SE->getCouldNotCompute(); 7998 } 7999 8000 const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax( 8001 const BasicBlock *ExitingBlock, ScalarEvolution *SE) const { 8002 for (auto &ENT : ExitNotTaken) 8003 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 8004 return ENT.MaxNotTaken; 8005 8006 return SE->getCouldNotCompute(); 8007 } 8008 8009 /// getConstantMax - Get the constant max backedge taken count for the loop. 8010 const SCEV * 8011 ScalarEvolution::BackedgeTakenInfo::getConstantMax(ScalarEvolution *SE) const { 8012 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 8013 return !ENT.hasAlwaysTruePredicate(); 8014 }; 8015 8016 if (!getConstantMax() || any_of(ExitNotTaken, PredicateNotAlwaysTrue)) 8017 return SE->getCouldNotCompute(); 8018 8019 assert((isa<SCEVCouldNotCompute>(getConstantMax()) || 8020 isa<SCEVConstant>(getConstantMax())) && 8021 "No point in having a non-constant max backedge taken count!"); 8022 return getConstantMax(); 8023 } 8024 8025 const SCEV * 8026 ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(const Loop *L, 8027 ScalarEvolution *SE) { 8028 if (!SymbolicMax) 8029 SymbolicMax = SE->computeSymbolicMaxBackedgeTakenCount(L); 8030 return SymbolicMax; 8031 } 8032 8033 bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero( 8034 ScalarEvolution *SE) const { 8035 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 8036 return !ENT.hasAlwaysTruePredicate(); 8037 }; 8038 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 8039 } 8040 8041 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E) 8042 : ExitLimit(E, E, false, None) { 8043 } 8044 8045 ScalarEvolution::ExitLimit::ExitLimit( 8046 const SCEV *E, const SCEV *M, bool MaxOrZero, 8047 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList) 8048 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) { 8049 // If we prove the max count is zero, so is the symbolic bound. This happens 8050 // in practice due to differences in a) how context sensitive we've chosen 8051 // to be and b) how we reason about bounds impied by UB. 8052 if (MaxNotTaken->isZero()) 8053 ExactNotTaken = MaxNotTaken; 8054 8055 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) || 8056 !isa<SCEVCouldNotCompute>(MaxNotTaken)) && 8057 "Exact is not allowed to be less precise than Max"); 8058 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 8059 isa<SCEVConstant>(MaxNotTaken)) && 8060 "No point in having a non-constant max backedge taken count!"); 8061 for (auto *PredSet : PredSetList) 8062 for (auto *P : *PredSet) 8063 addPredicate(P); 8064 assert((isa<SCEVCouldNotCompute>(E) || !E->getType()->isPointerTy()) && 8065 "Backedge count should be int"); 8066 assert((isa<SCEVCouldNotCompute>(M) || !M->getType()->isPointerTy()) && 8067 "Max backedge count should be int"); 8068 } 8069 8070 ScalarEvolution::ExitLimit::ExitLimit( 8071 const SCEV *E, const SCEV *M, bool MaxOrZero, 8072 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet) 8073 : ExitLimit(E, M, MaxOrZero, {&PredSet}) { 8074 } 8075 8076 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M, 8077 bool MaxOrZero) 8078 : ExitLimit(E, M, MaxOrZero, None) { 8079 } 8080 8081 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 8082 /// computable exit into a persistent ExitNotTakenInfo array. 8083 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 8084 ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> ExitCounts, 8085 bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero) 8086 : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) { 8087 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 8088 8089 ExitNotTaken.reserve(ExitCounts.size()); 8090 std::transform( 8091 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 8092 [&](const EdgeExitInfo &EEI) { 8093 BasicBlock *ExitBB = EEI.first; 8094 const ExitLimit &EL = EEI.second; 8095 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 8096 EL.Predicates); 8097 }); 8098 assert((isa<SCEVCouldNotCompute>(ConstantMax) || 8099 isa<SCEVConstant>(ConstantMax)) && 8100 "No point in having a non-constant max backedge taken count!"); 8101 } 8102 8103 /// Compute the number of times the backedge of the specified loop will execute. 8104 ScalarEvolution::BackedgeTakenInfo 8105 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 8106 bool AllowPredicates) { 8107 SmallVector<BasicBlock *, 8> ExitingBlocks; 8108 L->getExitingBlocks(ExitingBlocks); 8109 8110 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 8111 8112 SmallVector<EdgeExitInfo, 4> ExitCounts; 8113 bool CouldComputeBECount = true; 8114 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 8115 const SCEV *MustExitMaxBECount = nullptr; 8116 const SCEV *MayExitMaxBECount = nullptr; 8117 bool MustExitMaxOrZero = false; 8118 8119 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 8120 // and compute maxBECount. 8121 // Do a union of all the predicates here. 8122 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 8123 BasicBlock *ExitBB = ExitingBlocks[i]; 8124 8125 // We canonicalize untaken exits to br (constant), ignore them so that 8126 // proving an exit untaken doesn't negatively impact our ability to reason 8127 // about the loop as whole. 8128 if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator())) 8129 if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) { 8130 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 8131 if (ExitIfTrue == CI->isZero()) 8132 continue; 8133 } 8134 8135 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 8136 8137 assert((AllowPredicates || EL.Predicates.empty()) && 8138 "Predicated exit limit when predicates are not allowed!"); 8139 8140 // 1. For each exit that can be computed, add an entry to ExitCounts. 8141 // CouldComputeBECount is true only if all exits can be computed. 8142 if (EL.ExactNotTaken == getCouldNotCompute()) 8143 // We couldn't compute an exact value for this exit, so 8144 // we won't be able to compute an exact value for the loop. 8145 CouldComputeBECount = false; 8146 else 8147 ExitCounts.emplace_back(ExitBB, EL); 8148 8149 // 2. Derive the loop's MaxBECount from each exit's max number of 8150 // non-exiting iterations. Partition the loop exits into two kinds: 8151 // LoopMustExits and LoopMayExits. 8152 // 8153 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 8154 // is a LoopMayExit. If any computable LoopMustExit is found, then 8155 // MaxBECount is the minimum EL.MaxNotTaken of computable 8156 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 8157 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 8158 // computable EL.MaxNotTaken. 8159 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 8160 DT.dominates(ExitBB, Latch)) { 8161 if (!MustExitMaxBECount) { 8162 MustExitMaxBECount = EL.MaxNotTaken; 8163 MustExitMaxOrZero = EL.MaxOrZero; 8164 } else { 8165 MustExitMaxBECount = 8166 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 8167 } 8168 } else if (MayExitMaxBECount != getCouldNotCompute()) { 8169 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 8170 MayExitMaxBECount = EL.MaxNotTaken; 8171 else { 8172 MayExitMaxBECount = 8173 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 8174 } 8175 } 8176 } 8177 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 8178 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 8179 // The loop backedge will be taken the maximum or zero times if there's 8180 // a single exit that must be taken the maximum or zero times. 8181 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 8182 8183 // Remember which SCEVs are used in exit limits for invalidation purposes. 8184 // We only care about non-constant SCEVs here, so we can ignore EL.MaxNotTaken 8185 // and MaxBECount, which must be SCEVConstant. 8186 for (const auto &Pair : ExitCounts) 8187 if (!isa<SCEVConstant>(Pair.second.ExactNotTaken)) 8188 BECountUsers[Pair.second.ExactNotTaken].insert({L, AllowPredicates}); 8189 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 8190 MaxBECount, MaxOrZero); 8191 } 8192 8193 ScalarEvolution::ExitLimit 8194 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 8195 bool AllowPredicates) { 8196 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?"); 8197 // If our exiting block does not dominate the latch, then its connection with 8198 // loop's exit limit may be far from trivial. 8199 const BasicBlock *Latch = L->getLoopLatch(); 8200 if (!Latch || !DT.dominates(ExitingBlock, Latch)) 8201 return getCouldNotCompute(); 8202 8203 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 8204 Instruction *Term = ExitingBlock->getTerminator(); 8205 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 8206 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 8207 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 8208 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) && 8209 "It should have one successor in loop and one exit block!"); 8210 // Proceed to the next level to examine the exit condition expression. 8211 return computeExitLimitFromCond( 8212 L, BI->getCondition(), ExitIfTrue, 8213 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 8214 } 8215 8216 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) { 8217 // For switch, make sure that there is a single exit from the loop. 8218 BasicBlock *Exit = nullptr; 8219 for (auto *SBB : successors(ExitingBlock)) 8220 if (!L->contains(SBB)) { 8221 if (Exit) // Multiple exit successors. 8222 return getCouldNotCompute(); 8223 Exit = SBB; 8224 } 8225 assert(Exit && "Exiting block must have at least one exit"); 8226 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 8227 /*ControlsExit=*/IsOnlyExit); 8228 } 8229 8230 return getCouldNotCompute(); 8231 } 8232 8233 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond( 8234 const Loop *L, Value *ExitCond, bool ExitIfTrue, 8235 bool ControlsExit, bool AllowPredicates) { 8236 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates); 8237 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue, 8238 ControlsExit, AllowPredicates); 8239 } 8240 8241 Optional<ScalarEvolution::ExitLimit> 8242 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond, 8243 bool ExitIfTrue, bool ControlsExit, 8244 bool AllowPredicates) { 8245 (void)this->L; 8246 (void)this->ExitIfTrue; 8247 (void)this->AllowPredicates; 8248 8249 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 8250 this->AllowPredicates == AllowPredicates && 8251 "Variance in assumed invariant key components!"); 8252 auto Itr = TripCountMap.find({ExitCond, ControlsExit}); 8253 if (Itr == TripCountMap.end()) 8254 return None; 8255 return Itr->second; 8256 } 8257 8258 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond, 8259 bool ExitIfTrue, 8260 bool ControlsExit, 8261 bool AllowPredicates, 8262 const ExitLimit &EL) { 8263 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 8264 this->AllowPredicates == AllowPredicates && 8265 "Variance in assumed invariant key components!"); 8266 8267 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL}); 8268 assert(InsertResult.second && "Expected successful insertion!"); 8269 (void)InsertResult; 8270 (void)ExitIfTrue; 8271 } 8272 8273 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached( 8274 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 8275 bool ControlsExit, bool AllowPredicates) { 8276 8277 if (auto MaybeEL = 8278 Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 8279 return *MaybeEL; 8280 8281 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue, 8282 ControlsExit, AllowPredicates); 8283 Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL); 8284 return EL; 8285 } 8286 8287 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl( 8288 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 8289 bool ControlsExit, bool AllowPredicates) { 8290 // Handle BinOp conditions (And, Or). 8291 if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp( 8292 Cache, L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 8293 return *LimitFromBinOp; 8294 8295 // With an icmp, it may be feasible to compute an exact backedge-taken count. 8296 // Proceed to the next level to examine the icmp. 8297 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 8298 ExitLimit EL = 8299 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit); 8300 if (EL.hasFullInfo() || !AllowPredicates) 8301 return EL; 8302 8303 // Try again, but use SCEV predicates this time. 8304 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit, 8305 /*AllowPredicates=*/true); 8306 } 8307 8308 // Check for a constant condition. These are normally stripped out by 8309 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 8310 // preserve the CFG and is temporarily leaving constant conditions 8311 // in place. 8312 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 8313 if (ExitIfTrue == !CI->getZExtValue()) 8314 // The backedge is always taken. 8315 return getCouldNotCompute(); 8316 else 8317 // The backedge is never taken. 8318 return getZero(CI->getType()); 8319 } 8320 8321 // If we're exiting based on the overflow flag of an x.with.overflow intrinsic 8322 // with a constant step, we can form an equivalent icmp predicate and figure 8323 // out how many iterations will be taken before we exit. 8324 const WithOverflowInst *WO; 8325 const APInt *C; 8326 if (match(ExitCond, m_ExtractValue<1>(m_WithOverflowInst(WO))) && 8327 match(WO->getRHS(), m_APInt(C))) { 8328 ConstantRange NWR = 8329 ConstantRange::makeExactNoWrapRegion(WO->getBinaryOp(), *C, 8330 WO->getNoWrapKind()); 8331 CmpInst::Predicate Pred; 8332 APInt NewRHSC, Offset; 8333 NWR.getEquivalentICmp(Pred, NewRHSC, Offset); 8334 if (!ExitIfTrue) 8335 Pred = ICmpInst::getInversePredicate(Pred); 8336 auto *LHS = getSCEV(WO->getLHS()); 8337 if (Offset != 0) 8338 LHS = getAddExpr(LHS, getConstant(Offset)); 8339 auto EL = computeExitLimitFromICmp(L, Pred, LHS, getConstant(NewRHSC), 8340 ControlsExit, AllowPredicates); 8341 if (EL.hasAnyInfo()) return EL; 8342 } 8343 8344 // If it's not an integer or pointer comparison then compute it the hard way. 8345 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 8346 } 8347 8348 Optional<ScalarEvolution::ExitLimit> 8349 ScalarEvolution::computeExitLimitFromCondFromBinOp( 8350 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 8351 bool ControlsExit, bool AllowPredicates) { 8352 // Check if the controlling expression for this loop is an And or Or. 8353 Value *Op0, *Op1; 8354 bool IsAnd = false; 8355 if (match(ExitCond, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) 8356 IsAnd = true; 8357 else if (match(ExitCond, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) 8358 IsAnd = false; 8359 else 8360 return None; 8361 8362 // EitherMayExit is true in these two cases: 8363 // br (and Op0 Op1), loop, exit 8364 // br (or Op0 Op1), exit, loop 8365 bool EitherMayExit = IsAnd ^ ExitIfTrue; 8366 ExitLimit EL0 = computeExitLimitFromCondCached(Cache, L, Op0, ExitIfTrue, 8367 ControlsExit && !EitherMayExit, 8368 AllowPredicates); 8369 ExitLimit EL1 = computeExitLimitFromCondCached(Cache, L, Op1, ExitIfTrue, 8370 ControlsExit && !EitherMayExit, 8371 AllowPredicates); 8372 8373 // Be robust against unsimplified IR for the form "op i1 X, NeutralElement" 8374 const Constant *NeutralElement = ConstantInt::get(ExitCond->getType(), IsAnd); 8375 if (isa<ConstantInt>(Op1)) 8376 return Op1 == NeutralElement ? EL0 : EL1; 8377 if (isa<ConstantInt>(Op0)) 8378 return Op0 == NeutralElement ? EL1 : EL0; 8379 8380 const SCEV *BECount = getCouldNotCompute(); 8381 const SCEV *MaxBECount = getCouldNotCompute(); 8382 if (EitherMayExit) { 8383 // Both conditions must be same for the loop to continue executing. 8384 // Choose the less conservative count. 8385 if (EL0.ExactNotTaken != getCouldNotCompute() && 8386 EL1.ExactNotTaken != getCouldNotCompute()) { 8387 BECount = getUMinFromMismatchedTypes( 8388 EL0.ExactNotTaken, EL1.ExactNotTaken, 8389 /*Sequential=*/!isa<BinaryOperator>(ExitCond)); 8390 8391 // If EL0.ExactNotTaken was zero and ExitCond was a short-circuit form, 8392 // it should have been simplified to zero (see the condition (3) above) 8393 assert(!isa<BinaryOperator>(ExitCond) || !EL0.ExactNotTaken->isZero() || 8394 BECount->isZero()); 8395 } 8396 if (EL0.MaxNotTaken == getCouldNotCompute()) 8397 MaxBECount = EL1.MaxNotTaken; 8398 else if (EL1.MaxNotTaken == getCouldNotCompute()) 8399 MaxBECount = EL0.MaxNotTaken; 8400 else 8401 MaxBECount = getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 8402 } else { 8403 // Both conditions must be same at the same time for the loop to exit. 8404 // For now, be conservative. 8405 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 8406 BECount = EL0.ExactNotTaken; 8407 } 8408 8409 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 8410 // to be more aggressive when computing BECount than when computing 8411 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 8412 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 8413 // to not. 8414 if (isa<SCEVCouldNotCompute>(MaxBECount) && 8415 !isa<SCEVCouldNotCompute>(BECount)) 8416 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 8417 8418 return ExitLimit(BECount, MaxBECount, false, 8419 { &EL0.Predicates, &EL1.Predicates }); 8420 } 8421 8422 ScalarEvolution::ExitLimit 8423 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 8424 ICmpInst *ExitCond, 8425 bool ExitIfTrue, 8426 bool ControlsExit, 8427 bool AllowPredicates) { 8428 // If the condition was exit on true, convert the condition to exit on false 8429 ICmpInst::Predicate Pred; 8430 if (!ExitIfTrue) 8431 Pred = ExitCond->getPredicate(); 8432 else 8433 Pred = ExitCond->getInversePredicate(); 8434 const ICmpInst::Predicate OriginalPred = Pred; 8435 8436 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 8437 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 8438 8439 ExitLimit EL = computeExitLimitFromICmp(L, Pred, LHS, RHS, ControlsExit, 8440 AllowPredicates); 8441 if (EL.hasAnyInfo()) return EL; 8442 8443 auto *ExhaustiveCount = 8444 computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 8445 8446 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 8447 return ExhaustiveCount; 8448 8449 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 8450 ExitCond->getOperand(1), L, OriginalPred); 8451 } 8452 ScalarEvolution::ExitLimit 8453 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 8454 ICmpInst::Predicate Pred, 8455 const SCEV *LHS, const SCEV *RHS, 8456 bool ControlsExit, 8457 bool AllowPredicates) { 8458 8459 // Try to evaluate any dependencies out of the loop. 8460 LHS = getSCEVAtScope(LHS, L); 8461 RHS = getSCEVAtScope(RHS, L); 8462 8463 // At this point, we would like to compute how many iterations of the 8464 // loop the predicate will return true for these inputs. 8465 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 8466 // If there is a loop-invariant, force it into the RHS. 8467 std::swap(LHS, RHS); 8468 Pred = ICmpInst::getSwappedPredicate(Pred); 8469 } 8470 8471 bool ControllingFiniteLoop = 8472 ControlsExit && loopHasNoAbnormalExits(L) && loopIsFiniteByAssumption(L); 8473 // Simplify the operands before analyzing them. 8474 (void)SimplifyICmpOperands(Pred, LHS, RHS, /*Depth=*/0, 8475 ControllingFiniteLoop); 8476 8477 // If we have a comparison of a chrec against a constant, try to use value 8478 // ranges to answer this query. 8479 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 8480 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 8481 if (AddRec->getLoop() == L) { 8482 // Form the constant range. 8483 ConstantRange CompRange = 8484 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt()); 8485 8486 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 8487 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 8488 } 8489 8490 // If this loop must exit based on this condition (or execute undefined 8491 // behaviour), and we can prove the test sequence produced must repeat 8492 // the same values on self-wrap of the IV, then we can infer that IV 8493 // doesn't self wrap because if it did, we'd have an infinite (undefined) 8494 // loop. 8495 if (ControllingFiniteLoop && isLoopInvariant(RHS, L)) { 8496 // TODO: We can peel off any functions which are invertible *in L*. Loop 8497 // invariant terms are effectively constants for our purposes here. 8498 auto *InnerLHS = LHS; 8499 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS)) 8500 InnerLHS = ZExt->getOperand(); 8501 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(InnerLHS)) { 8502 auto *StrideC = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)); 8503 if (!AR->hasNoSelfWrap() && AR->getLoop() == L && AR->isAffine() && 8504 StrideC && StrideC->getAPInt().isPowerOf2()) { 8505 auto Flags = AR->getNoWrapFlags(); 8506 Flags = setFlags(Flags, SCEV::FlagNW); 8507 SmallVector<const SCEV*> Operands{AR->operands()}; 8508 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 8509 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags); 8510 } 8511 } 8512 } 8513 8514 switch (Pred) { 8515 case ICmpInst::ICMP_NE: { // while (X != Y) 8516 // Convert to: while (X-Y != 0) 8517 if (LHS->getType()->isPointerTy()) { 8518 LHS = getLosslessPtrToIntExpr(LHS); 8519 if (isa<SCEVCouldNotCompute>(LHS)) 8520 return LHS; 8521 } 8522 if (RHS->getType()->isPointerTy()) { 8523 RHS = getLosslessPtrToIntExpr(RHS); 8524 if (isa<SCEVCouldNotCompute>(RHS)) 8525 return RHS; 8526 } 8527 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 8528 AllowPredicates); 8529 if (EL.hasAnyInfo()) return EL; 8530 break; 8531 } 8532 case ICmpInst::ICMP_EQ: { // while (X == Y) 8533 // Convert to: while (X-Y == 0) 8534 if (LHS->getType()->isPointerTy()) { 8535 LHS = getLosslessPtrToIntExpr(LHS); 8536 if (isa<SCEVCouldNotCompute>(LHS)) 8537 return LHS; 8538 } 8539 if (RHS->getType()->isPointerTy()) { 8540 RHS = getLosslessPtrToIntExpr(RHS); 8541 if (isa<SCEVCouldNotCompute>(RHS)) 8542 return RHS; 8543 } 8544 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 8545 if (EL.hasAnyInfo()) return EL; 8546 break; 8547 } 8548 case ICmpInst::ICMP_SLT: 8549 case ICmpInst::ICMP_ULT: { // while (X < Y) 8550 bool IsSigned = Pred == ICmpInst::ICMP_SLT; 8551 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 8552 AllowPredicates); 8553 if (EL.hasAnyInfo()) return EL; 8554 break; 8555 } 8556 case ICmpInst::ICMP_SGT: 8557 case ICmpInst::ICMP_UGT: { // while (X > Y) 8558 bool IsSigned = Pred == ICmpInst::ICMP_SGT; 8559 ExitLimit EL = 8560 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 8561 AllowPredicates); 8562 if (EL.hasAnyInfo()) return EL; 8563 break; 8564 } 8565 default: 8566 break; 8567 } 8568 8569 return getCouldNotCompute(); 8570 } 8571 8572 ScalarEvolution::ExitLimit 8573 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 8574 SwitchInst *Switch, 8575 BasicBlock *ExitingBlock, 8576 bool ControlsExit) { 8577 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 8578 8579 // Give up if the exit is the default dest of a switch. 8580 if (Switch->getDefaultDest() == ExitingBlock) 8581 return getCouldNotCompute(); 8582 8583 assert(L->contains(Switch->getDefaultDest()) && 8584 "Default case must not exit the loop!"); 8585 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 8586 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 8587 8588 // while (X != Y) --> while (X-Y != 0) 8589 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 8590 if (EL.hasAnyInfo()) 8591 return EL; 8592 8593 return getCouldNotCompute(); 8594 } 8595 8596 static ConstantInt * 8597 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 8598 ScalarEvolution &SE) { 8599 const SCEV *InVal = SE.getConstant(C); 8600 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 8601 assert(isa<SCEVConstant>(Val) && 8602 "Evaluation of SCEV at constant didn't fold correctly?"); 8603 return cast<SCEVConstant>(Val)->getValue(); 8604 } 8605 8606 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 8607 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 8608 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 8609 if (!RHS) 8610 return getCouldNotCompute(); 8611 8612 const BasicBlock *Latch = L->getLoopLatch(); 8613 if (!Latch) 8614 return getCouldNotCompute(); 8615 8616 const BasicBlock *Predecessor = L->getLoopPredecessor(); 8617 if (!Predecessor) 8618 return getCouldNotCompute(); 8619 8620 // Return true if V is of the form "LHS `shift_op` <positive constant>". 8621 // Return LHS in OutLHS and shift_opt in OutOpCode. 8622 auto MatchPositiveShift = 8623 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 8624 8625 using namespace PatternMatch; 8626 8627 ConstantInt *ShiftAmt; 8628 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 8629 OutOpCode = Instruction::LShr; 8630 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 8631 OutOpCode = Instruction::AShr; 8632 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 8633 OutOpCode = Instruction::Shl; 8634 else 8635 return false; 8636 8637 return ShiftAmt->getValue().isStrictlyPositive(); 8638 }; 8639 8640 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 8641 // 8642 // loop: 8643 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 8644 // %iv.shifted = lshr i32 %iv, <positive constant> 8645 // 8646 // Return true on a successful match. Return the corresponding PHI node (%iv 8647 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 8648 auto MatchShiftRecurrence = 8649 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 8650 Optional<Instruction::BinaryOps> PostShiftOpCode; 8651 8652 { 8653 Instruction::BinaryOps OpC; 8654 Value *V; 8655 8656 // If we encounter a shift instruction, "peel off" the shift operation, 8657 // and remember that we did so. Later when we inspect %iv's backedge 8658 // value, we will make sure that the backedge value uses the same 8659 // operation. 8660 // 8661 // Note: the peeled shift operation does not have to be the same 8662 // instruction as the one feeding into the PHI's backedge value. We only 8663 // really care about it being the same *kind* of shift instruction -- 8664 // that's all that is required for our later inferences to hold. 8665 if (MatchPositiveShift(LHS, V, OpC)) { 8666 PostShiftOpCode = OpC; 8667 LHS = V; 8668 } 8669 } 8670 8671 PNOut = dyn_cast<PHINode>(LHS); 8672 if (!PNOut || PNOut->getParent() != L->getHeader()) 8673 return false; 8674 8675 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 8676 Value *OpLHS; 8677 8678 return 8679 // The backedge value for the PHI node must be a shift by a positive 8680 // amount 8681 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 8682 8683 // of the PHI node itself 8684 OpLHS == PNOut && 8685 8686 // and the kind of shift should be match the kind of shift we peeled 8687 // off, if any. 8688 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 8689 }; 8690 8691 PHINode *PN; 8692 Instruction::BinaryOps OpCode; 8693 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 8694 return getCouldNotCompute(); 8695 8696 const DataLayout &DL = getDataLayout(); 8697 8698 // The key rationale for this optimization is that for some kinds of shift 8699 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 8700 // within a finite number of iterations. If the condition guarding the 8701 // backedge (in the sense that the backedge is taken if the condition is true) 8702 // is false for the value the shift recurrence stabilizes to, then we know 8703 // that the backedge is taken only a finite number of times. 8704 8705 ConstantInt *StableValue = nullptr; 8706 switch (OpCode) { 8707 default: 8708 llvm_unreachable("Impossible case!"); 8709 8710 case Instruction::AShr: { 8711 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 8712 // bitwidth(K) iterations. 8713 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 8714 KnownBits Known = computeKnownBits(FirstValue, DL, 0, &AC, 8715 Predecessor->getTerminator(), &DT); 8716 auto *Ty = cast<IntegerType>(RHS->getType()); 8717 if (Known.isNonNegative()) 8718 StableValue = ConstantInt::get(Ty, 0); 8719 else if (Known.isNegative()) 8720 StableValue = ConstantInt::get(Ty, -1, true); 8721 else 8722 return getCouldNotCompute(); 8723 8724 break; 8725 } 8726 case Instruction::LShr: 8727 case Instruction::Shl: 8728 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 8729 // stabilize to 0 in at most bitwidth(K) iterations. 8730 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 8731 break; 8732 } 8733 8734 auto *Result = 8735 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 8736 assert(Result->getType()->isIntegerTy(1) && 8737 "Otherwise cannot be an operand to a branch instruction"); 8738 8739 if (Result->isZeroValue()) { 8740 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 8741 const SCEV *UpperBound = 8742 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 8743 return ExitLimit(getCouldNotCompute(), UpperBound, false); 8744 } 8745 8746 return getCouldNotCompute(); 8747 } 8748 8749 /// Return true if we can constant fold an instruction of the specified type, 8750 /// assuming that all operands were constants. 8751 static bool CanConstantFold(const Instruction *I) { 8752 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 8753 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 8754 isa<LoadInst>(I) || isa<ExtractValueInst>(I)) 8755 return true; 8756 8757 if (const CallInst *CI = dyn_cast<CallInst>(I)) 8758 if (const Function *F = CI->getCalledFunction()) 8759 return canConstantFoldCallTo(CI, F); 8760 return false; 8761 } 8762 8763 /// Determine whether this instruction can constant evolve within this loop 8764 /// assuming its operands can all constant evolve. 8765 static bool canConstantEvolve(Instruction *I, const Loop *L) { 8766 // An instruction outside of the loop can't be derived from a loop PHI. 8767 if (!L->contains(I)) return false; 8768 8769 if (isa<PHINode>(I)) { 8770 // We don't currently keep track of the control flow needed to evaluate 8771 // PHIs, so we cannot handle PHIs inside of loops. 8772 return L->getHeader() == I->getParent(); 8773 } 8774 8775 // If we won't be able to constant fold this expression even if the operands 8776 // are constants, bail early. 8777 return CanConstantFold(I); 8778 } 8779 8780 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 8781 /// recursing through each instruction operand until reaching a loop header phi. 8782 static PHINode * 8783 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 8784 DenseMap<Instruction *, PHINode *> &PHIMap, 8785 unsigned Depth) { 8786 if (Depth > MaxConstantEvolvingDepth) 8787 return nullptr; 8788 8789 // Otherwise, we can evaluate this instruction if all of its operands are 8790 // constant or derived from a PHI node themselves. 8791 PHINode *PHI = nullptr; 8792 for (Value *Op : UseInst->operands()) { 8793 if (isa<Constant>(Op)) continue; 8794 8795 Instruction *OpInst = dyn_cast<Instruction>(Op); 8796 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 8797 8798 PHINode *P = dyn_cast<PHINode>(OpInst); 8799 if (!P) 8800 // If this operand is already visited, reuse the prior result. 8801 // We may have P != PHI if this is the deepest point at which the 8802 // inconsistent paths meet. 8803 P = PHIMap.lookup(OpInst); 8804 if (!P) { 8805 // Recurse and memoize the results, whether a phi is found or not. 8806 // This recursive call invalidates pointers into PHIMap. 8807 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1); 8808 PHIMap[OpInst] = P; 8809 } 8810 if (!P) 8811 return nullptr; // Not evolving from PHI 8812 if (PHI && PHI != P) 8813 return nullptr; // Evolving from multiple different PHIs. 8814 PHI = P; 8815 } 8816 // This is a expression evolving from a constant PHI! 8817 return PHI; 8818 } 8819 8820 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 8821 /// in the loop that V is derived from. We allow arbitrary operations along the 8822 /// way, but the operands of an operation must either be constants or a value 8823 /// derived from a constant PHI. If this expression does not fit with these 8824 /// constraints, return null. 8825 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 8826 Instruction *I = dyn_cast<Instruction>(V); 8827 if (!I || !canConstantEvolve(I, L)) return nullptr; 8828 8829 if (PHINode *PN = dyn_cast<PHINode>(I)) 8830 return PN; 8831 8832 // Record non-constant instructions contained by the loop. 8833 DenseMap<Instruction *, PHINode *> PHIMap; 8834 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0); 8835 } 8836 8837 /// EvaluateExpression - Given an expression that passes the 8838 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 8839 /// in the loop has the value PHIVal. If we can't fold this expression for some 8840 /// reason, return null. 8841 static Constant *EvaluateExpression(Value *V, const Loop *L, 8842 DenseMap<Instruction *, Constant *> &Vals, 8843 const DataLayout &DL, 8844 const TargetLibraryInfo *TLI) { 8845 // Convenient constant check, but redundant for recursive calls. 8846 if (Constant *C = dyn_cast<Constant>(V)) return C; 8847 Instruction *I = dyn_cast<Instruction>(V); 8848 if (!I) return nullptr; 8849 8850 if (Constant *C = Vals.lookup(I)) return C; 8851 8852 // An instruction inside the loop depends on a value outside the loop that we 8853 // weren't given a mapping for, or a value such as a call inside the loop. 8854 if (!canConstantEvolve(I, L)) return nullptr; 8855 8856 // An unmapped PHI can be due to a branch or another loop inside this loop, 8857 // or due to this not being the initial iteration through a loop where we 8858 // couldn't compute the evolution of this particular PHI last time. 8859 if (isa<PHINode>(I)) return nullptr; 8860 8861 std::vector<Constant*> Operands(I->getNumOperands()); 8862 8863 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 8864 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 8865 if (!Operand) { 8866 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 8867 if (!Operands[i]) return nullptr; 8868 continue; 8869 } 8870 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 8871 Vals[Operand] = C; 8872 if (!C) return nullptr; 8873 Operands[i] = C; 8874 } 8875 8876 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 8877 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8878 Operands[1], DL, TLI); 8879 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 8880 if (!LI->isVolatile()) 8881 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 8882 } 8883 return ConstantFoldInstOperands(I, Operands, DL, TLI); 8884 } 8885 8886 8887 // If every incoming value to PN except the one for BB is a specific Constant, 8888 // return that, else return nullptr. 8889 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 8890 Constant *IncomingVal = nullptr; 8891 8892 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 8893 if (PN->getIncomingBlock(i) == BB) 8894 continue; 8895 8896 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 8897 if (!CurrentVal) 8898 return nullptr; 8899 8900 if (IncomingVal != CurrentVal) { 8901 if (IncomingVal) 8902 return nullptr; 8903 IncomingVal = CurrentVal; 8904 } 8905 } 8906 8907 return IncomingVal; 8908 } 8909 8910 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 8911 /// in the header of its containing loop, we know the loop executes a 8912 /// constant number of times, and the PHI node is just a recurrence 8913 /// involving constants, fold it. 8914 Constant * 8915 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 8916 const APInt &BEs, 8917 const Loop *L) { 8918 auto I = ConstantEvolutionLoopExitValue.find(PN); 8919 if (I != ConstantEvolutionLoopExitValue.end()) 8920 return I->second; 8921 8922 if (BEs.ugt(MaxBruteForceIterations)) 8923 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 8924 8925 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 8926 8927 DenseMap<Instruction *, Constant *> CurrentIterVals; 8928 BasicBlock *Header = L->getHeader(); 8929 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 8930 8931 BasicBlock *Latch = L->getLoopLatch(); 8932 if (!Latch) 8933 return nullptr; 8934 8935 for (PHINode &PHI : Header->phis()) { 8936 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 8937 CurrentIterVals[&PHI] = StartCST; 8938 } 8939 if (!CurrentIterVals.count(PN)) 8940 return RetVal = nullptr; 8941 8942 Value *BEValue = PN->getIncomingValueForBlock(Latch); 8943 8944 // Execute the loop symbolically to determine the exit value. 8945 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) && 8946 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!"); 8947 8948 unsigned NumIterations = BEs.getZExtValue(); // must be in range 8949 unsigned IterationNum = 0; 8950 const DataLayout &DL = getDataLayout(); 8951 for (; ; ++IterationNum) { 8952 if (IterationNum == NumIterations) 8953 return RetVal = CurrentIterVals[PN]; // Got exit value! 8954 8955 // Compute the value of the PHIs for the next iteration. 8956 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 8957 DenseMap<Instruction *, Constant *> NextIterVals; 8958 Constant *NextPHI = 8959 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8960 if (!NextPHI) 8961 return nullptr; // Couldn't evaluate! 8962 NextIterVals[PN] = NextPHI; 8963 8964 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 8965 8966 // Also evaluate the other PHI nodes. However, we don't get to stop if we 8967 // cease to be able to evaluate one of them or if they stop evolving, 8968 // because that doesn't necessarily prevent us from computing PN. 8969 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 8970 for (const auto &I : CurrentIterVals) { 8971 PHINode *PHI = dyn_cast<PHINode>(I.first); 8972 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 8973 PHIsToCompute.emplace_back(PHI, I.second); 8974 } 8975 // We use two distinct loops because EvaluateExpression may invalidate any 8976 // iterators into CurrentIterVals. 8977 for (const auto &I : PHIsToCompute) { 8978 PHINode *PHI = I.first; 8979 Constant *&NextPHI = NextIterVals[PHI]; 8980 if (!NextPHI) { // Not already computed. 8981 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 8982 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8983 } 8984 if (NextPHI != I.second) 8985 StoppedEvolving = false; 8986 } 8987 8988 // If all entries in CurrentIterVals == NextIterVals then we can stop 8989 // iterating, the loop can't continue to change. 8990 if (StoppedEvolving) 8991 return RetVal = CurrentIterVals[PN]; 8992 8993 CurrentIterVals.swap(NextIterVals); 8994 } 8995 } 8996 8997 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 8998 Value *Cond, 8999 bool ExitWhen) { 9000 PHINode *PN = getConstantEvolvingPHI(Cond, L); 9001 if (!PN) return getCouldNotCompute(); 9002 9003 // If the loop is canonicalized, the PHI will have exactly two entries. 9004 // That's the only form we support here. 9005 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 9006 9007 DenseMap<Instruction *, Constant *> CurrentIterVals; 9008 BasicBlock *Header = L->getHeader(); 9009 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 9010 9011 BasicBlock *Latch = L->getLoopLatch(); 9012 assert(Latch && "Should follow from NumIncomingValues == 2!"); 9013 9014 for (PHINode &PHI : Header->phis()) { 9015 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 9016 CurrentIterVals[&PHI] = StartCST; 9017 } 9018 if (!CurrentIterVals.count(PN)) 9019 return getCouldNotCompute(); 9020 9021 // Okay, we find a PHI node that defines the trip count of this loop. Execute 9022 // the loop symbolically to determine when the condition gets a value of 9023 // "ExitWhen". 9024 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 9025 const DataLayout &DL = getDataLayout(); 9026 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 9027 auto *CondVal = dyn_cast_or_null<ConstantInt>( 9028 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 9029 9030 // Couldn't symbolically evaluate. 9031 if (!CondVal) return getCouldNotCompute(); 9032 9033 if (CondVal->getValue() == uint64_t(ExitWhen)) { 9034 ++NumBruteForceTripCountsComputed; 9035 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 9036 } 9037 9038 // Update all the PHI nodes for the next iteration. 9039 DenseMap<Instruction *, Constant *> NextIterVals; 9040 9041 // Create a list of which PHIs we need to compute. We want to do this before 9042 // calling EvaluateExpression on them because that may invalidate iterators 9043 // into CurrentIterVals. 9044 SmallVector<PHINode *, 8> PHIsToCompute; 9045 for (const auto &I : CurrentIterVals) { 9046 PHINode *PHI = dyn_cast<PHINode>(I.first); 9047 if (!PHI || PHI->getParent() != Header) continue; 9048 PHIsToCompute.push_back(PHI); 9049 } 9050 for (PHINode *PHI : PHIsToCompute) { 9051 Constant *&NextPHI = NextIterVals[PHI]; 9052 if (NextPHI) continue; // Already computed! 9053 9054 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 9055 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 9056 } 9057 CurrentIterVals.swap(NextIterVals); 9058 } 9059 9060 // Too many iterations were needed to evaluate. 9061 return getCouldNotCompute(); 9062 } 9063 9064 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 9065 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 9066 ValuesAtScopes[V]; 9067 // Check to see if we've folded this expression at this loop before. 9068 for (auto &LS : Values) 9069 if (LS.first == L) 9070 return LS.second ? LS.second : V; 9071 9072 Values.emplace_back(L, nullptr); 9073 9074 // Otherwise compute it. 9075 const SCEV *C = computeSCEVAtScope(V, L); 9076 for (auto &LS : reverse(ValuesAtScopes[V])) 9077 if (LS.first == L) { 9078 LS.second = C; 9079 if (!isa<SCEVConstant>(C)) 9080 ValuesAtScopesUsers[C].push_back({L, V}); 9081 break; 9082 } 9083 return C; 9084 } 9085 9086 /// This builds up a Constant using the ConstantExpr interface. That way, we 9087 /// will return Constants for objects which aren't represented by a 9088 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 9089 /// Returns NULL if the SCEV isn't representable as a Constant. 9090 static Constant *BuildConstantFromSCEV(const SCEV *V) { 9091 switch (V->getSCEVType()) { 9092 case scCouldNotCompute: 9093 case scAddRecExpr: 9094 return nullptr; 9095 case scConstant: 9096 return cast<SCEVConstant>(V)->getValue(); 9097 case scUnknown: 9098 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 9099 case scSignExtend: { 9100 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 9101 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 9102 return ConstantExpr::getSExt(CastOp, SS->getType()); 9103 return nullptr; 9104 } 9105 case scZeroExtend: { 9106 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 9107 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 9108 return ConstantExpr::getZExt(CastOp, SZ->getType()); 9109 return nullptr; 9110 } 9111 case scPtrToInt: { 9112 const SCEVPtrToIntExpr *P2I = cast<SCEVPtrToIntExpr>(V); 9113 if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand())) 9114 return ConstantExpr::getPtrToInt(CastOp, P2I->getType()); 9115 9116 return nullptr; 9117 } 9118 case scTruncate: { 9119 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 9120 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 9121 return ConstantExpr::getTrunc(CastOp, ST->getType()); 9122 return nullptr; 9123 } 9124 case scAddExpr: { 9125 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 9126 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 9127 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 9128 unsigned AS = PTy->getAddressSpace(); 9129 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 9130 C = ConstantExpr::getBitCast(C, DestPtrTy); 9131 } 9132 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 9133 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 9134 if (!C2) 9135 return nullptr; 9136 9137 // First pointer! 9138 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 9139 unsigned AS = C2->getType()->getPointerAddressSpace(); 9140 std::swap(C, C2); 9141 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 9142 // The offsets have been converted to bytes. We can add bytes to an 9143 // i8* by GEP with the byte count in the first index. 9144 C = ConstantExpr::getBitCast(C, DestPtrTy); 9145 } 9146 9147 // Don't bother trying to sum two pointers. We probably can't 9148 // statically compute a load that results from it anyway. 9149 if (C2->getType()->isPointerTy()) 9150 return nullptr; 9151 9152 if (C->getType()->isPointerTy()) { 9153 C = ConstantExpr::getGetElementPtr(Type::getInt8Ty(C->getContext()), 9154 C, C2); 9155 } else { 9156 C = ConstantExpr::getAdd(C, C2); 9157 } 9158 } 9159 return C; 9160 } 9161 return nullptr; 9162 } 9163 case scMulExpr: { 9164 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 9165 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 9166 // Don't bother with pointers at all. 9167 if (C->getType()->isPointerTy()) 9168 return nullptr; 9169 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 9170 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 9171 if (!C2 || C2->getType()->isPointerTy()) 9172 return nullptr; 9173 C = ConstantExpr::getMul(C, C2); 9174 } 9175 return C; 9176 } 9177 return nullptr; 9178 } 9179 case scUDivExpr: { 9180 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 9181 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 9182 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 9183 if (LHS->getType() == RHS->getType()) 9184 return ConstantExpr::getUDiv(LHS, RHS); 9185 return nullptr; 9186 } 9187 case scSMaxExpr: 9188 case scUMaxExpr: 9189 case scSMinExpr: 9190 case scUMinExpr: 9191 case scSequentialUMinExpr: 9192 return nullptr; // TODO: smax, umax, smin, umax, umin_seq. 9193 } 9194 llvm_unreachable("Unknown SCEV kind!"); 9195 } 9196 9197 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 9198 if (isa<SCEVConstant>(V)) return V; 9199 9200 // If this instruction is evolved from a constant-evolving PHI, compute the 9201 // exit value from the loop without using SCEVs. 9202 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 9203 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 9204 if (PHINode *PN = dyn_cast<PHINode>(I)) { 9205 const Loop *CurrLoop = this->LI[I->getParent()]; 9206 // Looking for loop exit value. 9207 if (CurrLoop && CurrLoop->getParentLoop() == L && 9208 PN->getParent() == CurrLoop->getHeader()) { 9209 // Okay, there is no closed form solution for the PHI node. Check 9210 // to see if the loop that contains it has a known backedge-taken 9211 // count. If so, we may be able to force computation of the exit 9212 // value. 9213 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop); 9214 // This trivial case can show up in some degenerate cases where 9215 // the incoming IR has not yet been fully simplified. 9216 if (BackedgeTakenCount->isZero()) { 9217 Value *InitValue = nullptr; 9218 bool MultipleInitValues = false; 9219 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { 9220 if (!CurrLoop->contains(PN->getIncomingBlock(i))) { 9221 if (!InitValue) 9222 InitValue = PN->getIncomingValue(i); 9223 else if (InitValue != PN->getIncomingValue(i)) { 9224 MultipleInitValues = true; 9225 break; 9226 } 9227 } 9228 } 9229 if (!MultipleInitValues && InitValue) 9230 return getSCEV(InitValue); 9231 } 9232 // Do we have a loop invariant value flowing around the backedge 9233 // for a loop which must execute the backedge? 9234 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) && 9235 isKnownPositive(BackedgeTakenCount) && 9236 PN->getNumIncomingValues() == 2) { 9237 9238 unsigned InLoopPred = 9239 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1; 9240 Value *BackedgeVal = PN->getIncomingValue(InLoopPred); 9241 if (CurrLoop->isLoopInvariant(BackedgeVal)) 9242 return getSCEV(BackedgeVal); 9243 } 9244 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 9245 // Okay, we know how many times the containing loop executes. If 9246 // this is a constant evolving PHI node, get the final value at 9247 // the specified iteration number. 9248 Constant *RV = getConstantEvolutionLoopExitValue( 9249 PN, BTCC->getAPInt(), CurrLoop); 9250 if (RV) return getSCEV(RV); 9251 } 9252 } 9253 9254 // If there is a single-input Phi, evaluate it at our scope. If we can 9255 // prove that this replacement does not break LCSSA form, use new value. 9256 if (PN->getNumOperands() == 1) { 9257 const SCEV *Input = getSCEV(PN->getOperand(0)); 9258 const SCEV *InputAtScope = getSCEVAtScope(Input, L); 9259 // TODO: We can generalize it using LI.replacementPreservesLCSSAForm, 9260 // for the simplest case just support constants. 9261 if (isa<SCEVConstant>(InputAtScope)) return InputAtScope; 9262 } 9263 } 9264 9265 // Okay, this is an expression that we cannot symbolically evaluate 9266 // into a SCEV. Check to see if it's possible to symbolically evaluate 9267 // the arguments into constants, and if so, try to constant propagate the 9268 // result. This is particularly useful for computing loop exit values. 9269 if (CanConstantFold(I)) { 9270 SmallVector<Constant *, 4> Operands; 9271 bool MadeImprovement = false; 9272 for (Value *Op : I->operands()) { 9273 if (Constant *C = dyn_cast<Constant>(Op)) { 9274 Operands.push_back(C); 9275 continue; 9276 } 9277 9278 // If any of the operands is non-constant and if they are 9279 // non-integer and non-pointer, don't even try to analyze them 9280 // with scev techniques. 9281 if (!isSCEVable(Op->getType())) 9282 return V; 9283 9284 const SCEV *OrigV = getSCEV(Op); 9285 const SCEV *OpV = getSCEVAtScope(OrigV, L); 9286 MadeImprovement |= OrigV != OpV; 9287 9288 Constant *C = BuildConstantFromSCEV(OpV); 9289 if (!C) return V; 9290 if (C->getType() != Op->getType()) 9291 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 9292 Op->getType(), 9293 false), 9294 C, Op->getType()); 9295 Operands.push_back(C); 9296 } 9297 9298 // Check to see if getSCEVAtScope actually made an improvement. 9299 if (MadeImprovement) { 9300 Constant *C = nullptr; 9301 const DataLayout &DL = getDataLayout(); 9302 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 9303 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 9304 Operands[1], DL, &TLI); 9305 else if (const LoadInst *Load = dyn_cast<LoadInst>(I)) { 9306 if (!Load->isVolatile()) 9307 C = ConstantFoldLoadFromConstPtr(Operands[0], Load->getType(), 9308 DL); 9309 } else 9310 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 9311 if (!C) return V; 9312 return getSCEV(C); 9313 } 9314 } 9315 } 9316 9317 // This is some other type of SCEVUnknown, just return it. 9318 return V; 9319 } 9320 9321 if (isa<SCEVCommutativeExpr>(V) || isa<SCEVSequentialMinMaxExpr>(V)) { 9322 const auto *Comm = cast<SCEVNAryExpr>(V); 9323 // Avoid performing the look-up in the common case where the specified 9324 // expression has no loop-variant portions. 9325 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 9326 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 9327 if (OpAtScope != Comm->getOperand(i)) { 9328 // Okay, at least one of these operands is loop variant but might be 9329 // foldable. Build a new instance of the folded commutative expression. 9330 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 9331 Comm->op_begin()+i); 9332 NewOps.push_back(OpAtScope); 9333 9334 for (++i; i != e; ++i) { 9335 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 9336 NewOps.push_back(OpAtScope); 9337 } 9338 if (isa<SCEVAddExpr>(Comm)) 9339 return getAddExpr(NewOps, Comm->getNoWrapFlags()); 9340 if (isa<SCEVMulExpr>(Comm)) 9341 return getMulExpr(NewOps, Comm->getNoWrapFlags()); 9342 if (isa<SCEVMinMaxExpr>(Comm)) 9343 return getMinMaxExpr(Comm->getSCEVType(), NewOps); 9344 if (isa<SCEVSequentialMinMaxExpr>(Comm)) 9345 return getSequentialMinMaxExpr(Comm->getSCEVType(), NewOps); 9346 llvm_unreachable("Unknown commutative / sequential min/max SCEV type!"); 9347 } 9348 } 9349 // If we got here, all operands are loop invariant. 9350 return Comm; 9351 } 9352 9353 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 9354 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 9355 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 9356 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 9357 return Div; // must be loop invariant 9358 return getUDivExpr(LHS, RHS); 9359 } 9360 9361 // If this is a loop recurrence for a loop that does not contain L, then we 9362 // are dealing with the final value computed by the loop. 9363 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 9364 // First, attempt to evaluate each operand. 9365 // Avoid performing the look-up in the common case where the specified 9366 // expression has no loop-variant portions. 9367 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 9368 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 9369 if (OpAtScope == AddRec->getOperand(i)) 9370 continue; 9371 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(AddRec->op_begin(), 9375 AddRec->op_begin()+i); 9376 NewOps.push_back(OpAtScope); 9377 for (++i; i != e; ++i) 9378 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 9379 9380 const SCEV *FoldedRec = 9381 getAddRecExpr(NewOps, AddRec->getLoop(), 9382 AddRec->getNoWrapFlags(SCEV::FlagNW)); 9383 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 9384 // The addrec may be folded to a nonrecurrence, for example, if the 9385 // induction variable is multiplied by zero after constant folding. Go 9386 // ahead and return the folded value. 9387 if (!AddRec) 9388 return FoldedRec; 9389 break; 9390 } 9391 9392 // If the scope is outside the addrec's loop, evaluate it by using the 9393 // loop exit value of the addrec. 9394 if (!AddRec->getLoop()->contains(L)) { 9395 // To evaluate this recurrence, we need to know how many times the AddRec 9396 // loop iterates. Compute this now. 9397 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 9398 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 9399 9400 // Then, evaluate the AddRec. 9401 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 9402 } 9403 9404 return AddRec; 9405 } 9406 9407 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) { 9408 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 9409 if (Op == Cast->getOperand()) 9410 return Cast; // must be loop invariant 9411 return getCastExpr(Cast->getSCEVType(), Op, Cast->getType()); 9412 } 9413 9414 llvm_unreachable("Unknown SCEV type!"); 9415 } 9416 9417 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 9418 return getSCEVAtScope(getSCEV(V), L); 9419 } 9420 9421 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const { 9422 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) 9423 return stripInjectiveFunctions(ZExt->getOperand()); 9424 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) 9425 return stripInjectiveFunctions(SExt->getOperand()); 9426 return S; 9427 } 9428 9429 /// Finds the minimum unsigned root of the following equation: 9430 /// 9431 /// A * X = B (mod N) 9432 /// 9433 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 9434 /// A and B isn't important. 9435 /// 9436 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 9437 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, 9438 ScalarEvolution &SE) { 9439 uint32_t BW = A.getBitWidth(); 9440 assert(BW == SE.getTypeSizeInBits(B->getType())); 9441 assert(A != 0 && "A must be non-zero."); 9442 9443 // 1. D = gcd(A, N) 9444 // 9445 // The gcd of A and N may have only one prime factor: 2. The number of 9446 // trailing zeros in A is its multiplicity 9447 uint32_t Mult2 = A.countTrailingZeros(); 9448 // D = 2^Mult2 9449 9450 // 2. Check if B is divisible by D. 9451 // 9452 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 9453 // is not less than multiplicity of this prime factor for D. 9454 if (SE.GetMinTrailingZeros(B) < Mult2) 9455 return SE.getCouldNotCompute(); 9456 9457 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 9458 // modulo (N / D). 9459 // 9460 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent 9461 // (N / D) in general. The inverse itself always fits into BW bits, though, 9462 // so we immediately truncate it. 9463 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 9464 APInt Mod(BW + 1, 0); 9465 Mod.setBit(BW - Mult2); // Mod = N / D 9466 APInt I = AD.multiplicativeInverse(Mod).trunc(BW); 9467 9468 // 4. Compute the minimum unsigned root of the equation: 9469 // I * (B / D) mod (N / D) 9470 // To simplify the computation, we factor out the divide by D: 9471 // (I * B mod N) / D 9472 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2)); 9473 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D); 9474 } 9475 9476 /// For a given quadratic addrec, generate coefficients of the corresponding 9477 /// quadratic equation, multiplied by a common value to ensure that they are 9478 /// integers. 9479 /// The returned value is a tuple { A, B, C, M, BitWidth }, where 9480 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C 9481 /// were multiplied by, and BitWidth is the bit width of the original addrec 9482 /// coefficients. 9483 /// This function returns None if the addrec coefficients are not compile- 9484 /// time constants. 9485 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>> 9486 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) { 9487 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 9488 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 9489 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 9490 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 9491 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: " 9492 << *AddRec << '\n'); 9493 9494 // We currently can only solve this if the coefficients are constants. 9495 if (!LC || !MC || !NC) { 9496 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n"); 9497 return None; 9498 } 9499 9500 APInt L = LC->getAPInt(); 9501 APInt M = MC->getAPInt(); 9502 APInt N = NC->getAPInt(); 9503 assert(!N.isZero() && "This is not a quadratic addrec"); 9504 9505 unsigned BitWidth = LC->getAPInt().getBitWidth(); 9506 unsigned NewWidth = BitWidth + 1; 9507 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: " 9508 << BitWidth << '\n'); 9509 // The sign-extension (as opposed to a zero-extension) here matches the 9510 // extension used in SolveQuadraticEquationWrap (with the same motivation). 9511 N = N.sext(NewWidth); 9512 M = M.sext(NewWidth); 9513 L = L.sext(NewWidth); 9514 9515 // The increments are M, M+N, M+2N, ..., so the accumulated values are 9516 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is, 9517 // L+M, L+2M+N, L+3M+3N, ... 9518 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N. 9519 // 9520 // The equation Acc = 0 is then 9521 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0. 9522 // In a quadratic form it becomes: 9523 // N n^2 + (2M-N) n + 2L = 0. 9524 9525 APInt A = N; 9526 APInt B = 2 * M - A; 9527 APInt C = 2 * L; 9528 APInt T = APInt(NewWidth, 2); 9529 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B 9530 << "x + " << C << ", coeff bw: " << NewWidth 9531 << ", multiplied by " << T << '\n'); 9532 return std::make_tuple(A, B, C, T, BitWidth); 9533 } 9534 9535 /// Helper function to compare optional APInts: 9536 /// (a) if X and Y both exist, return min(X, Y), 9537 /// (b) if neither X nor Y exist, return None, 9538 /// (c) if exactly one of X and Y exists, return that value. 9539 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) { 9540 if (X.hasValue() && Y.hasValue()) { 9541 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth()); 9542 APInt XW = X->sextOrSelf(W); 9543 APInt YW = Y->sextOrSelf(W); 9544 return XW.slt(YW) ? *X : *Y; 9545 } 9546 if (!X.hasValue() && !Y.hasValue()) 9547 return None; 9548 return X.hasValue() ? *X : *Y; 9549 } 9550 9551 /// Helper function to truncate an optional APInt to a given BitWidth. 9552 /// When solving addrec-related equations, it is preferable to return a value 9553 /// that has the same bit width as the original addrec's coefficients. If the 9554 /// solution fits in the original bit width, truncate it (except for i1). 9555 /// Returning a value of a different bit width may inhibit some optimizations. 9556 /// 9557 /// In general, a solution to a quadratic equation generated from an addrec 9558 /// may require BW+1 bits, where BW is the bit width of the addrec's 9559 /// coefficients. The reason is that the coefficients of the quadratic 9560 /// equation are BW+1 bits wide (to avoid truncation when converting from 9561 /// the addrec to the equation). 9562 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) { 9563 if (!X.hasValue()) 9564 return None; 9565 unsigned W = X->getBitWidth(); 9566 if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth)) 9567 return X->trunc(BitWidth); 9568 return X; 9569 } 9570 9571 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n 9572 /// iterations. The values L, M, N are assumed to be signed, and they 9573 /// should all have the same bit widths. 9574 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW, 9575 /// where BW is the bit width of the addrec's coefficients. 9576 /// If the calculated value is a BW-bit integer (for BW > 1), it will be 9577 /// returned as such, otherwise the bit width of the returned value may 9578 /// be greater than BW. 9579 /// 9580 /// This function returns None if 9581 /// (a) the addrec coefficients are not constant, or 9582 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases 9583 /// like x^2 = 5, no integer solutions exist, in other cases an integer 9584 /// solution may exist, but SolveQuadraticEquationWrap may fail to find it. 9585 static Optional<APInt> 9586 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 9587 APInt A, B, C, M; 9588 unsigned BitWidth; 9589 auto T = GetQuadraticEquation(AddRec); 9590 if (!T.hasValue()) 9591 return None; 9592 9593 std::tie(A, B, C, M, BitWidth) = *T; 9594 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n"); 9595 Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1); 9596 if (!X.hasValue()) 9597 return None; 9598 9599 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X); 9600 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE); 9601 if (!V->isZero()) 9602 return None; 9603 9604 return TruncIfPossible(X, BitWidth); 9605 } 9606 9607 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n 9608 /// iterations. The values M, N are assumed to be signed, and they 9609 /// should all have the same bit widths. 9610 /// Find the least n such that c(n) does not belong to the given range, 9611 /// while c(n-1) does. 9612 /// 9613 /// This function returns None if 9614 /// (a) the addrec coefficients are not constant, or 9615 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the 9616 /// bounds of the range. 9617 static Optional<APInt> 9618 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec, 9619 const ConstantRange &Range, ScalarEvolution &SE) { 9620 assert(AddRec->getOperand(0)->isZero() && 9621 "Starting value of addrec should be 0"); 9622 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range " 9623 << Range << ", addrec " << *AddRec << '\n'); 9624 // This case is handled in getNumIterationsInRange. Here we can assume that 9625 // we start in the range. 9626 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) && 9627 "Addrec's initial value should be in range"); 9628 9629 APInt A, B, C, M; 9630 unsigned BitWidth; 9631 auto T = GetQuadraticEquation(AddRec); 9632 if (!T.hasValue()) 9633 return None; 9634 9635 // Be careful about the return value: there can be two reasons for not 9636 // returning an actual number. First, if no solutions to the equations 9637 // were found, and second, if the solutions don't leave the given range. 9638 // The first case means that the actual solution is "unknown", the second 9639 // means that it's known, but not valid. If the solution is unknown, we 9640 // cannot make any conclusions. 9641 // Return a pair: the optional solution and a flag indicating if the 9642 // solution was found. 9643 auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> { 9644 // Solve for signed overflow and unsigned overflow, pick the lower 9645 // solution. 9646 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary " 9647 << Bound << " (before multiplying by " << M << ")\n"); 9648 Bound *= M; // The quadratic equation multiplier. 9649 9650 Optional<APInt> SO = None; 9651 if (BitWidth > 1) { 9652 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 9653 "signed overflow\n"); 9654 SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth); 9655 } 9656 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 9657 "unsigned overflow\n"); 9658 Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, 9659 BitWidth+1); 9660 9661 auto LeavesRange = [&] (const APInt &X) { 9662 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X); 9663 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE); 9664 if (Range.contains(V0->getValue())) 9665 return false; 9666 // X should be at least 1, so X-1 is non-negative. 9667 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1); 9668 ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE); 9669 if (Range.contains(V1->getValue())) 9670 return true; 9671 return false; 9672 }; 9673 9674 // If SolveQuadraticEquationWrap returns None, it means that there can 9675 // be a solution, but the function failed to find it. We cannot treat it 9676 // as "no solution". 9677 if (!SO.hasValue() || !UO.hasValue()) 9678 return { None, false }; 9679 9680 // Check the smaller value first to see if it leaves the range. 9681 // At this point, both SO and UO must have values. 9682 Optional<APInt> Min = MinOptional(SO, UO); 9683 if (LeavesRange(*Min)) 9684 return { Min, true }; 9685 Optional<APInt> Max = Min == SO ? UO : SO; 9686 if (LeavesRange(*Max)) 9687 return { Max, true }; 9688 9689 // Solutions were found, but were eliminated, hence the "true". 9690 return { None, true }; 9691 }; 9692 9693 std::tie(A, B, C, M, BitWidth) = *T; 9694 // Lower bound is inclusive, subtract 1 to represent the exiting value. 9695 APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1; 9696 APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth()); 9697 auto SL = SolveForBoundary(Lower); 9698 auto SU = SolveForBoundary(Upper); 9699 // If any of the solutions was unknown, no meaninigful conclusions can 9700 // be made. 9701 if (!SL.second || !SU.second) 9702 return None; 9703 9704 // Claim: The correct solution is not some value between Min and Max. 9705 // 9706 // Justification: Assuming that Min and Max are different values, one of 9707 // them is when the first signed overflow happens, the other is when the 9708 // first unsigned overflow happens. Crossing the range boundary is only 9709 // possible via an overflow (treating 0 as a special case of it, modeling 9710 // an overflow as crossing k*2^W for some k). 9711 // 9712 // The interesting case here is when Min was eliminated as an invalid 9713 // solution, but Max was not. The argument is that if there was another 9714 // overflow between Min and Max, it would also have been eliminated if 9715 // it was considered. 9716 // 9717 // For a given boundary, it is possible to have two overflows of the same 9718 // type (signed/unsigned) without having the other type in between: this 9719 // can happen when the vertex of the parabola is between the iterations 9720 // corresponding to the overflows. This is only possible when the two 9721 // overflows cross k*2^W for the same k. In such case, if the second one 9722 // left the range (and was the first one to do so), the first overflow 9723 // would have to enter the range, which would mean that either we had left 9724 // the range before or that we started outside of it. Both of these cases 9725 // are contradictions. 9726 // 9727 // Claim: In the case where SolveForBoundary returns None, the correct 9728 // solution is not some value between the Max for this boundary and the 9729 // Min of the other boundary. 9730 // 9731 // Justification: Assume that we had such Max_A and Min_B corresponding 9732 // to range boundaries A and B and such that Max_A < Min_B. If there was 9733 // a solution between Max_A and Min_B, it would have to be caused by an 9734 // overflow corresponding to either A or B. It cannot correspond to B, 9735 // since Min_B is the first occurrence of such an overflow. If it 9736 // corresponded to A, it would have to be either a signed or an unsigned 9737 // overflow that is larger than both eliminated overflows for A. But 9738 // between the eliminated overflows and this overflow, the values would 9739 // cover the entire value space, thus crossing the other boundary, which 9740 // is a contradiction. 9741 9742 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth); 9743 } 9744 9745 ScalarEvolution::ExitLimit 9746 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 9747 bool AllowPredicates) { 9748 9749 // This is only used for loops with a "x != y" exit test. The exit condition 9750 // is now expressed as a single expression, V = x-y. So the exit test is 9751 // effectively V != 0. We know and take advantage of the fact that this 9752 // expression only being used in a comparison by zero context. 9753 9754 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 9755 // If the value is a constant 9756 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 9757 // If the value is already zero, the branch will execute zero times. 9758 if (C->getValue()->isZero()) return C; 9759 return getCouldNotCompute(); // Otherwise it will loop infinitely. 9760 } 9761 9762 const SCEVAddRecExpr *AddRec = 9763 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V)); 9764 9765 if (!AddRec && AllowPredicates) 9766 // Try to make this an AddRec using runtime tests, in the first X 9767 // iterations of this loop, where X is the SCEV expression found by the 9768 // algorithm below. 9769 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 9770 9771 if (!AddRec || AddRec->getLoop() != L) 9772 return getCouldNotCompute(); 9773 9774 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 9775 // the quadratic equation to solve it. 9776 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 9777 // We can only use this value if the chrec ends up with an exact zero 9778 // value at this index. When solving for "X*X != 5", for example, we 9779 // should not accept a root of 2. 9780 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) { 9781 const auto *R = cast<SCEVConstant>(getConstant(S.getValue())); 9782 return ExitLimit(R, R, false, Predicates); 9783 } 9784 return getCouldNotCompute(); 9785 } 9786 9787 // Otherwise we can only handle this if it is affine. 9788 if (!AddRec->isAffine()) 9789 return getCouldNotCompute(); 9790 9791 // If this is an affine expression, the execution count of this branch is 9792 // the minimum unsigned root of the following equation: 9793 // 9794 // Start + Step*N = 0 (mod 2^BW) 9795 // 9796 // equivalent to: 9797 // 9798 // Step*N = -Start (mod 2^BW) 9799 // 9800 // where BW is the common bit width of Start and Step. 9801 9802 // Get the initial value for the loop. 9803 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 9804 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 9805 9806 // For now we handle only constant steps. 9807 // 9808 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 9809 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 9810 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 9811 // We have not yet seen any such cases. 9812 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 9813 if (!StepC || StepC->getValue()->isZero()) 9814 return getCouldNotCompute(); 9815 9816 // For positive steps (counting up until unsigned overflow): 9817 // N = -Start/Step (as unsigned) 9818 // For negative steps (counting down to zero): 9819 // N = Start/-Step 9820 // First compute the unsigned distance from zero in the direction of Step. 9821 bool CountDown = StepC->getAPInt().isNegative(); 9822 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 9823 9824 // Handle unitary steps, which cannot wraparound. 9825 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 9826 // N = Distance (as unsigned) 9827 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) { 9828 APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, L)); 9829 MaxBECount = APIntOps::umin(MaxBECount, getUnsignedRangeMax(Distance)); 9830 9831 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated, 9832 // we end up with a loop whose backedge-taken count is n - 1. Detect this 9833 // case, and see if we can improve the bound. 9834 // 9835 // Explicitly handling this here is necessary because getUnsignedRange 9836 // isn't context-sensitive; it doesn't know that we only care about the 9837 // range inside the loop. 9838 const SCEV *Zero = getZero(Distance->getType()); 9839 const SCEV *One = getOne(Distance->getType()); 9840 const SCEV *DistancePlusOne = getAddExpr(Distance, One); 9841 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) { 9842 // If Distance + 1 doesn't overflow, we can compute the maximum distance 9843 // as "unsigned_max(Distance + 1) - 1". 9844 ConstantRange CR = getUnsignedRange(DistancePlusOne); 9845 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1); 9846 } 9847 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates); 9848 } 9849 9850 // If the condition controls loop exit (the loop exits only if the expression 9851 // is true) and the addition is no-wrap we can use unsigned divide to 9852 // compute the backedge count. In this case, the step may not divide the 9853 // distance, but we don't care because if the condition is "missed" the loop 9854 // will have undefined behavior due to wrapping. 9855 if (ControlsExit && AddRec->hasNoSelfWrap() && 9856 loopHasNoAbnormalExits(AddRec->getLoop())) { 9857 const SCEV *Exact = 9858 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 9859 const SCEV *Max = getCouldNotCompute(); 9860 if (Exact != getCouldNotCompute()) { 9861 APInt MaxInt = getUnsignedRangeMax(applyLoopGuards(Exact, L)); 9862 Max = getConstant(APIntOps::umin(MaxInt, getUnsignedRangeMax(Exact))); 9863 } 9864 return ExitLimit(Exact, Max, false, Predicates); 9865 } 9866 9867 // Solve the general equation. 9868 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(), 9869 getNegativeSCEV(Start), *this); 9870 9871 const SCEV *M = E; 9872 if (E != getCouldNotCompute()) { 9873 APInt MaxWithGuards = getUnsignedRangeMax(applyLoopGuards(E, L)); 9874 M = getConstant(APIntOps::umin(MaxWithGuards, getUnsignedRangeMax(E))); 9875 } 9876 return ExitLimit(E, M, false, Predicates); 9877 } 9878 9879 ScalarEvolution::ExitLimit 9880 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 9881 // Loops that look like: while (X == 0) are very strange indeed. We don't 9882 // handle them yet except for the trivial case. This could be expanded in the 9883 // future as needed. 9884 9885 // If the value is a constant, check to see if it is known to be non-zero 9886 // already. If so, the backedge will execute zero times. 9887 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 9888 if (!C->getValue()->isZero()) 9889 return getZero(C->getType()); 9890 return getCouldNotCompute(); // Otherwise it will loop infinitely. 9891 } 9892 9893 // We could implement others, but I really doubt anyone writes loops like 9894 // this, and if they did, they would already be constant folded. 9895 return getCouldNotCompute(); 9896 } 9897 9898 std::pair<const BasicBlock *, const BasicBlock *> 9899 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB) 9900 const { 9901 // If the block has a unique predecessor, then there is no path from the 9902 // predecessor to the block that does not go through the direct edge 9903 // from the predecessor to the block. 9904 if (const BasicBlock *Pred = BB->getSinglePredecessor()) 9905 return {Pred, BB}; 9906 9907 // A loop's header is defined to be a block that dominates the loop. 9908 // If the header has a unique predecessor outside the loop, it must be 9909 // a block that has exactly one successor that can reach the loop. 9910 if (const Loop *L = LI.getLoopFor(BB)) 9911 return {L->getLoopPredecessor(), L->getHeader()}; 9912 9913 return {nullptr, nullptr}; 9914 } 9915 9916 /// SCEV structural equivalence is usually sufficient for testing whether two 9917 /// expressions are equal, however for the purposes of looking for a condition 9918 /// guarding a loop, it can be useful to be a little more general, since a 9919 /// front-end may have replicated the controlling expression. 9920 static bool HasSameValue(const SCEV *A, const SCEV *B) { 9921 // Quick check to see if they are the same SCEV. 9922 if (A == B) return true; 9923 9924 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 9925 // Not all instructions that are "identical" compute the same value. For 9926 // instance, two distinct alloca instructions allocating the same type are 9927 // identical and do not read memory; but compute distinct values. 9928 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 9929 }; 9930 9931 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 9932 // two different instructions with the same value. Check for this case. 9933 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 9934 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 9935 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 9936 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 9937 if (ComputesEqualValues(AI, BI)) 9938 return true; 9939 9940 // Otherwise assume they may have a different value. 9941 return false; 9942 } 9943 9944 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 9945 const SCEV *&LHS, const SCEV *&RHS, 9946 unsigned Depth, 9947 bool ControllingFiniteLoop) { 9948 bool Changed = false; 9949 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or 9950 // '0 != 0'. 9951 auto TrivialCase = [&](bool TriviallyTrue) { 9952 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 9953 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE; 9954 return true; 9955 }; 9956 // If we hit the max recursion limit bail out. 9957 if (Depth >= 3) 9958 return false; 9959 9960 // Canonicalize a constant to the right side. 9961 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 9962 // Check for both operands constant. 9963 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 9964 if (ConstantExpr::getICmp(Pred, 9965 LHSC->getValue(), 9966 RHSC->getValue())->isNullValue()) 9967 return TrivialCase(false); 9968 else 9969 return TrivialCase(true); 9970 } 9971 // Otherwise swap the operands to put the constant on the right. 9972 std::swap(LHS, RHS); 9973 Pred = ICmpInst::getSwappedPredicate(Pred); 9974 Changed = true; 9975 } 9976 9977 // If we're comparing an addrec with a value which is loop-invariant in the 9978 // addrec's loop, put the addrec on the left. Also make a dominance check, 9979 // as both operands could be addrecs loop-invariant in each other's loop. 9980 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 9981 const Loop *L = AR->getLoop(); 9982 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 9983 std::swap(LHS, RHS); 9984 Pred = ICmpInst::getSwappedPredicate(Pred); 9985 Changed = true; 9986 } 9987 } 9988 9989 // If there's a constant operand, canonicalize comparisons with boundary 9990 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 9991 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 9992 const APInt &RA = RC->getAPInt(); 9993 9994 bool SimplifiedByConstantRange = false; 9995 9996 if (!ICmpInst::isEquality(Pred)) { 9997 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 9998 if (ExactCR.isFullSet()) 9999 return TrivialCase(true); 10000 else if (ExactCR.isEmptySet()) 10001 return TrivialCase(false); 10002 10003 APInt NewRHS; 10004 CmpInst::Predicate NewPred; 10005 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 10006 ICmpInst::isEquality(NewPred)) { 10007 // We were able to convert an inequality to an equality. 10008 Pred = NewPred; 10009 RHS = getConstant(NewRHS); 10010 Changed = SimplifiedByConstantRange = true; 10011 } 10012 } 10013 10014 if (!SimplifiedByConstantRange) { 10015 switch (Pred) { 10016 default: 10017 break; 10018 case ICmpInst::ICMP_EQ: 10019 case ICmpInst::ICMP_NE: 10020 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 10021 if (!RA) 10022 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 10023 if (const SCEVMulExpr *ME = 10024 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 10025 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 10026 ME->getOperand(0)->isAllOnesValue()) { 10027 RHS = AE->getOperand(1); 10028 LHS = ME->getOperand(1); 10029 Changed = true; 10030 } 10031 break; 10032 10033 10034 // The "Should have been caught earlier!" messages refer to the fact 10035 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 10036 // should have fired on the corresponding cases, and canonicalized the 10037 // check to trivial case. 10038 10039 case ICmpInst::ICMP_UGE: 10040 assert(!RA.isMinValue() && "Should have been caught earlier!"); 10041 Pred = ICmpInst::ICMP_UGT; 10042 RHS = getConstant(RA - 1); 10043 Changed = true; 10044 break; 10045 case ICmpInst::ICMP_ULE: 10046 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 10047 Pred = ICmpInst::ICMP_ULT; 10048 RHS = getConstant(RA + 1); 10049 Changed = true; 10050 break; 10051 case ICmpInst::ICMP_SGE: 10052 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 10053 Pred = ICmpInst::ICMP_SGT; 10054 RHS = getConstant(RA - 1); 10055 Changed = true; 10056 break; 10057 case ICmpInst::ICMP_SLE: 10058 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 10059 Pred = ICmpInst::ICMP_SLT; 10060 RHS = getConstant(RA + 1); 10061 Changed = true; 10062 break; 10063 } 10064 } 10065 } 10066 10067 // Check for obvious equality. 10068 if (HasSameValue(LHS, RHS)) { 10069 if (ICmpInst::isTrueWhenEqual(Pred)) 10070 return TrivialCase(true); 10071 if (ICmpInst::isFalseWhenEqual(Pred)) 10072 return TrivialCase(false); 10073 } 10074 10075 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 10076 // adding or subtracting 1 from one of the operands. This can be done for 10077 // one of two reasons: 10078 // 1) The range of the RHS does not include the (signed/unsigned) boundaries 10079 // 2) The loop is finite, with this comparison controlling the exit. Since the 10080 // loop is finite, the bound cannot include the corresponding boundary 10081 // (otherwise it would loop forever). 10082 switch (Pred) { 10083 case ICmpInst::ICMP_SLE: 10084 if (ControllingFiniteLoop || !getSignedRangeMax(RHS).isMaxSignedValue()) { 10085 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 10086 SCEV::FlagNSW); 10087 Pred = ICmpInst::ICMP_SLT; 10088 Changed = true; 10089 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) { 10090 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 10091 SCEV::FlagNSW); 10092 Pred = ICmpInst::ICMP_SLT; 10093 Changed = true; 10094 } 10095 break; 10096 case ICmpInst::ICMP_SGE: 10097 if (ControllingFiniteLoop || !getSignedRangeMin(RHS).isMinSignedValue()) { 10098 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 10099 SCEV::FlagNSW); 10100 Pred = ICmpInst::ICMP_SGT; 10101 Changed = true; 10102 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) { 10103 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 10104 SCEV::FlagNSW); 10105 Pred = ICmpInst::ICMP_SGT; 10106 Changed = true; 10107 } 10108 break; 10109 case ICmpInst::ICMP_ULE: 10110 if (ControllingFiniteLoop || !getUnsignedRangeMax(RHS).isMaxValue()) { 10111 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 10112 SCEV::FlagNUW); 10113 Pred = ICmpInst::ICMP_ULT; 10114 Changed = true; 10115 } else if (!getUnsignedRangeMin(LHS).isMinValue()) { 10116 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 10117 Pred = ICmpInst::ICMP_ULT; 10118 Changed = true; 10119 } 10120 break; 10121 case ICmpInst::ICMP_UGE: 10122 if (ControllingFiniteLoop || !getUnsignedRangeMin(RHS).isMinValue()) { 10123 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 10124 Pred = ICmpInst::ICMP_UGT; 10125 Changed = true; 10126 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) { 10127 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 10128 SCEV::FlagNUW); 10129 Pred = ICmpInst::ICMP_UGT; 10130 Changed = true; 10131 } 10132 break; 10133 default: 10134 break; 10135 } 10136 10137 // TODO: More simplifications are possible here. 10138 10139 // Recursively simplify until we either hit a recursion limit or nothing 10140 // changes. 10141 if (Changed) 10142 return SimplifyICmpOperands(Pred, LHS, RHS, Depth + 1, 10143 ControllingFiniteLoop); 10144 10145 return Changed; 10146 } 10147 10148 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 10149 return getSignedRangeMax(S).isNegative(); 10150 } 10151 10152 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 10153 return getSignedRangeMin(S).isStrictlyPositive(); 10154 } 10155 10156 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 10157 return !getSignedRangeMin(S).isNegative(); 10158 } 10159 10160 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 10161 return !getSignedRangeMax(S).isStrictlyPositive(); 10162 } 10163 10164 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 10165 return getUnsignedRangeMin(S) != 0; 10166 } 10167 10168 std::pair<const SCEV *, const SCEV *> 10169 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) { 10170 // Compute SCEV on entry of loop L. 10171 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this); 10172 if (Start == getCouldNotCompute()) 10173 return { Start, Start }; 10174 // Compute post increment SCEV for loop L. 10175 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this); 10176 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute"); 10177 return { Start, PostInc }; 10178 } 10179 10180 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred, 10181 const SCEV *LHS, const SCEV *RHS) { 10182 // First collect all loops. 10183 SmallPtrSet<const Loop *, 8> LoopsUsed; 10184 getUsedLoops(LHS, LoopsUsed); 10185 getUsedLoops(RHS, LoopsUsed); 10186 10187 if (LoopsUsed.empty()) 10188 return false; 10189 10190 // Domination relationship must be a linear order on collected loops. 10191 #ifndef NDEBUG 10192 for (auto *L1 : LoopsUsed) 10193 for (auto *L2 : LoopsUsed) 10194 assert((DT.dominates(L1->getHeader(), L2->getHeader()) || 10195 DT.dominates(L2->getHeader(), L1->getHeader())) && 10196 "Domination relationship is not a linear order"); 10197 #endif 10198 10199 const Loop *MDL = 10200 *std::max_element(LoopsUsed.begin(), LoopsUsed.end(), 10201 [&](const Loop *L1, const Loop *L2) { 10202 return DT.properlyDominates(L1->getHeader(), L2->getHeader()); 10203 }); 10204 10205 // Get init and post increment value for LHS. 10206 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS); 10207 // if LHS contains unknown non-invariant SCEV then bail out. 10208 if (SplitLHS.first == getCouldNotCompute()) 10209 return false; 10210 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC"); 10211 // Get init and post increment value for RHS. 10212 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS); 10213 // if RHS contains unknown non-invariant SCEV then bail out. 10214 if (SplitRHS.first == getCouldNotCompute()) 10215 return false; 10216 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC"); 10217 // It is possible that init SCEV contains an invariant load but it does 10218 // not dominate MDL and is not available at MDL loop entry, so we should 10219 // check it here. 10220 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) || 10221 !isAvailableAtLoopEntry(SplitRHS.first, MDL)) 10222 return false; 10223 10224 // It seems backedge guard check is faster than entry one so in some cases 10225 // it can speed up whole estimation by short circuit 10226 return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second, 10227 SplitRHS.second) && 10228 isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first); 10229 } 10230 10231 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 10232 const SCEV *LHS, const SCEV *RHS) { 10233 // Canonicalize the inputs first. 10234 (void)SimplifyICmpOperands(Pred, LHS, RHS); 10235 10236 if (isKnownViaInduction(Pred, LHS, RHS)) 10237 return true; 10238 10239 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 10240 return true; 10241 10242 // Otherwise see what can be done with some simple reasoning. 10243 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS); 10244 } 10245 10246 Optional<bool> ScalarEvolution::evaluatePredicate(ICmpInst::Predicate Pred, 10247 const SCEV *LHS, 10248 const SCEV *RHS) { 10249 if (isKnownPredicate(Pred, LHS, RHS)) 10250 return true; 10251 else if (isKnownPredicate(ICmpInst::getInversePredicate(Pred), LHS, RHS)) 10252 return false; 10253 return None; 10254 } 10255 10256 bool ScalarEvolution::isKnownPredicateAt(ICmpInst::Predicate Pred, 10257 const SCEV *LHS, const SCEV *RHS, 10258 const Instruction *CtxI) { 10259 // TODO: Analyze guards and assumes from Context's block. 10260 return isKnownPredicate(Pred, LHS, RHS) || 10261 isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS); 10262 } 10263 10264 Optional<bool> ScalarEvolution::evaluatePredicateAt(ICmpInst::Predicate Pred, 10265 const SCEV *LHS, 10266 const SCEV *RHS, 10267 const Instruction *CtxI) { 10268 Optional<bool> KnownWithoutContext = evaluatePredicate(Pred, LHS, RHS); 10269 if (KnownWithoutContext) 10270 return KnownWithoutContext; 10271 10272 if (isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS)) 10273 return true; 10274 else if (isBasicBlockEntryGuardedByCond(CtxI->getParent(), 10275 ICmpInst::getInversePredicate(Pred), 10276 LHS, RHS)) 10277 return false; 10278 return None; 10279 } 10280 10281 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred, 10282 const SCEVAddRecExpr *LHS, 10283 const SCEV *RHS) { 10284 const Loop *L = LHS->getLoop(); 10285 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) && 10286 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS); 10287 } 10288 10289 Optional<ScalarEvolution::MonotonicPredicateType> 10290 ScalarEvolution::getMonotonicPredicateType(const SCEVAddRecExpr *LHS, 10291 ICmpInst::Predicate Pred) { 10292 auto Result = getMonotonicPredicateTypeImpl(LHS, Pred); 10293 10294 #ifndef NDEBUG 10295 // Verify an invariant: inverting the predicate should turn a monotonically 10296 // increasing change to a monotonically decreasing one, and vice versa. 10297 if (Result) { 10298 auto ResultSwapped = 10299 getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred)); 10300 10301 assert(ResultSwapped.hasValue() && "should be able to analyze both!"); 10302 assert(ResultSwapped.getValue() != Result.getValue() && 10303 "monotonicity should flip as we flip the predicate"); 10304 } 10305 #endif 10306 10307 return Result; 10308 } 10309 10310 Optional<ScalarEvolution::MonotonicPredicateType> 10311 ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS, 10312 ICmpInst::Predicate Pred) { 10313 // A zero step value for LHS means the induction variable is essentially a 10314 // loop invariant value. We don't really depend on the predicate actually 10315 // flipping from false to true (for increasing predicates, and the other way 10316 // around for decreasing predicates), all we care about is that *if* the 10317 // predicate changes then it only changes from false to true. 10318 // 10319 // A zero step value in itself is not very useful, but there may be places 10320 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 10321 // as general as possible. 10322 10323 // Only handle LE/LT/GE/GT predicates. 10324 if (!ICmpInst::isRelational(Pred)) 10325 return None; 10326 10327 bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred); 10328 assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) && 10329 "Should be greater or less!"); 10330 10331 // Check that AR does not wrap. 10332 if (ICmpInst::isUnsigned(Pred)) { 10333 if (!LHS->hasNoUnsignedWrap()) 10334 return None; 10335 return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 10336 } else { 10337 assert(ICmpInst::isSigned(Pred) && 10338 "Relational predicate is either signed or unsigned!"); 10339 if (!LHS->hasNoSignedWrap()) 10340 return None; 10341 10342 const SCEV *Step = LHS->getStepRecurrence(*this); 10343 10344 if (isKnownNonNegative(Step)) 10345 return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 10346 10347 if (isKnownNonPositive(Step)) 10348 return !IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 10349 10350 return None; 10351 } 10352 } 10353 10354 Optional<ScalarEvolution::LoopInvariantPredicate> 10355 ScalarEvolution::getLoopInvariantPredicate(ICmpInst::Predicate Pred, 10356 const SCEV *LHS, const SCEV *RHS, 10357 const Loop *L) { 10358 10359 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 10360 if (!isLoopInvariant(RHS, L)) { 10361 if (!isLoopInvariant(LHS, L)) 10362 return None; 10363 10364 std::swap(LHS, RHS); 10365 Pred = ICmpInst::getSwappedPredicate(Pred); 10366 } 10367 10368 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 10369 if (!ArLHS || ArLHS->getLoop() != L) 10370 return None; 10371 10372 auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred); 10373 if (!MonotonicType) 10374 return None; 10375 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 10376 // true as the loop iterates, and the backedge is control dependent on 10377 // "ArLHS `Pred` RHS" == true then we can reason as follows: 10378 // 10379 // * if the predicate was false in the first iteration then the predicate 10380 // is never evaluated again, since the loop exits without taking the 10381 // backedge. 10382 // * if the predicate was true in the first iteration then it will 10383 // continue to be true for all future iterations since it is 10384 // monotonically increasing. 10385 // 10386 // For both the above possibilities, we can replace the loop varying 10387 // predicate with its value on the first iteration of the loop (which is 10388 // loop invariant). 10389 // 10390 // A similar reasoning applies for a monotonically decreasing predicate, by 10391 // replacing true with false and false with true in the above two bullets. 10392 bool Increasing = *MonotonicType == ScalarEvolution::MonotonicallyIncreasing; 10393 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 10394 10395 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 10396 return None; 10397 10398 return ScalarEvolution::LoopInvariantPredicate(Pred, ArLHS->getStart(), RHS); 10399 } 10400 10401 Optional<ScalarEvolution::LoopInvariantPredicate> 10402 ScalarEvolution::getLoopInvariantExitCondDuringFirstIterations( 10403 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 10404 const Instruction *CtxI, const SCEV *MaxIter) { 10405 // Try to prove the following set of facts: 10406 // - The predicate is monotonic in the iteration space. 10407 // - If the check does not fail on the 1st iteration: 10408 // - No overflow will happen during first MaxIter iterations; 10409 // - It will not fail on the MaxIter'th iteration. 10410 // If the check does fail on the 1st iteration, we leave the loop and no 10411 // other checks matter. 10412 10413 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 10414 if (!isLoopInvariant(RHS, L)) { 10415 if (!isLoopInvariant(LHS, L)) 10416 return None; 10417 10418 std::swap(LHS, RHS); 10419 Pred = ICmpInst::getSwappedPredicate(Pred); 10420 } 10421 10422 auto *AR = dyn_cast<SCEVAddRecExpr>(LHS); 10423 if (!AR || AR->getLoop() != L) 10424 return None; 10425 10426 // The predicate must be relational (i.e. <, <=, >=, >). 10427 if (!ICmpInst::isRelational(Pred)) 10428 return None; 10429 10430 // TODO: Support steps other than +/- 1. 10431 const SCEV *Step = AR->getStepRecurrence(*this); 10432 auto *One = getOne(Step->getType()); 10433 auto *MinusOne = getNegativeSCEV(One); 10434 if (Step != One && Step != MinusOne) 10435 return None; 10436 10437 // Type mismatch here means that MaxIter is potentially larger than max 10438 // unsigned value in start type, which mean we cannot prove no wrap for the 10439 // indvar. 10440 if (AR->getType() != MaxIter->getType()) 10441 return None; 10442 10443 // Value of IV on suggested last iteration. 10444 const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this); 10445 // Does it still meet the requirement? 10446 if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS)) 10447 return None; 10448 // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does 10449 // not exceed max unsigned value of this type), this effectively proves 10450 // that there is no wrap during the iteration. To prove that there is no 10451 // signed/unsigned wrap, we need to check that 10452 // Start <= Last for step = 1 or Start >= Last for step = -1. 10453 ICmpInst::Predicate NoOverflowPred = 10454 CmpInst::isSigned(Pred) ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 10455 if (Step == MinusOne) 10456 NoOverflowPred = CmpInst::getSwappedPredicate(NoOverflowPred); 10457 const SCEV *Start = AR->getStart(); 10458 if (!isKnownPredicateAt(NoOverflowPred, Start, Last, CtxI)) 10459 return None; 10460 10461 // Everything is fine. 10462 return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS); 10463 } 10464 10465 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 10466 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 10467 if (HasSameValue(LHS, RHS)) 10468 return ICmpInst::isTrueWhenEqual(Pred); 10469 10470 // This code is split out from isKnownPredicate because it is called from 10471 // within isLoopEntryGuardedByCond. 10472 10473 auto CheckRanges = [&](const ConstantRange &RangeLHS, 10474 const ConstantRange &RangeRHS) { 10475 return RangeLHS.icmp(Pred, RangeRHS); 10476 }; 10477 10478 // The check at the top of the function catches the case where the values are 10479 // known to be equal. 10480 if (Pred == CmpInst::ICMP_EQ) 10481 return false; 10482 10483 if (Pred == CmpInst::ICMP_NE) { 10484 if (CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 10485 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS))) 10486 return true; 10487 auto *Diff = getMinusSCEV(LHS, RHS); 10488 return !isa<SCEVCouldNotCompute>(Diff) && isKnownNonZero(Diff); 10489 } 10490 10491 if (CmpInst::isSigned(Pred)) 10492 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 10493 10494 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 10495 } 10496 10497 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 10498 const SCEV *LHS, 10499 const SCEV *RHS) { 10500 // Match X to (A + C1)<ExpectedFlags> and Y to (A + C2)<ExpectedFlags>, where 10501 // C1 and C2 are constant integers. If either X or Y are not add expressions, 10502 // consider them as X + 0 and Y + 0 respectively. C1 and C2 are returned via 10503 // OutC1 and OutC2. 10504 auto MatchBinaryAddToConst = [this](const SCEV *X, const SCEV *Y, 10505 APInt &OutC1, APInt &OutC2, 10506 SCEV::NoWrapFlags ExpectedFlags) { 10507 const SCEV *XNonConstOp, *XConstOp; 10508 const SCEV *YNonConstOp, *YConstOp; 10509 SCEV::NoWrapFlags XFlagsPresent; 10510 SCEV::NoWrapFlags YFlagsPresent; 10511 10512 if (!splitBinaryAdd(X, XConstOp, XNonConstOp, XFlagsPresent)) { 10513 XConstOp = getZero(X->getType()); 10514 XNonConstOp = X; 10515 XFlagsPresent = ExpectedFlags; 10516 } 10517 if (!isa<SCEVConstant>(XConstOp) || 10518 (XFlagsPresent & ExpectedFlags) != ExpectedFlags) 10519 return false; 10520 10521 if (!splitBinaryAdd(Y, YConstOp, YNonConstOp, YFlagsPresent)) { 10522 YConstOp = getZero(Y->getType()); 10523 YNonConstOp = Y; 10524 YFlagsPresent = ExpectedFlags; 10525 } 10526 10527 if (!isa<SCEVConstant>(YConstOp) || 10528 (YFlagsPresent & ExpectedFlags) != ExpectedFlags) 10529 return false; 10530 10531 if (YNonConstOp != XNonConstOp) 10532 return false; 10533 10534 OutC1 = cast<SCEVConstant>(XConstOp)->getAPInt(); 10535 OutC2 = cast<SCEVConstant>(YConstOp)->getAPInt(); 10536 10537 return true; 10538 }; 10539 10540 APInt C1; 10541 APInt C2; 10542 10543 switch (Pred) { 10544 default: 10545 break; 10546 10547 case ICmpInst::ICMP_SGE: 10548 std::swap(LHS, RHS); 10549 LLVM_FALLTHROUGH; 10550 case ICmpInst::ICMP_SLE: 10551 // (X + C1)<nsw> s<= (X + C2)<nsw> if C1 s<= C2. 10552 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.sle(C2)) 10553 return true; 10554 10555 break; 10556 10557 case ICmpInst::ICMP_SGT: 10558 std::swap(LHS, RHS); 10559 LLVM_FALLTHROUGH; 10560 case ICmpInst::ICMP_SLT: 10561 // (X + C1)<nsw> s< (X + C2)<nsw> if C1 s< C2. 10562 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.slt(C2)) 10563 return true; 10564 10565 break; 10566 10567 case ICmpInst::ICMP_UGE: 10568 std::swap(LHS, RHS); 10569 LLVM_FALLTHROUGH; 10570 case ICmpInst::ICMP_ULE: 10571 // (X + C1)<nuw> u<= (X + C2)<nuw> for C1 u<= C2. 10572 if (MatchBinaryAddToConst(RHS, LHS, C2, C1, SCEV::FlagNUW) && C1.ule(C2)) 10573 return true; 10574 10575 break; 10576 10577 case ICmpInst::ICMP_UGT: 10578 std::swap(LHS, RHS); 10579 LLVM_FALLTHROUGH; 10580 case ICmpInst::ICMP_ULT: 10581 // (X + C1)<nuw> u< (X + C2)<nuw> if C1 u< C2. 10582 if (MatchBinaryAddToConst(RHS, LHS, C2, C1, SCEV::FlagNUW) && C1.ult(C2)) 10583 return true; 10584 break; 10585 } 10586 10587 return false; 10588 } 10589 10590 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 10591 const SCEV *LHS, 10592 const SCEV *RHS) { 10593 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 10594 return false; 10595 10596 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 10597 // the stack can result in exponential time complexity. 10598 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 10599 10600 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 10601 // 10602 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 10603 // isKnownPredicate. isKnownPredicate is more powerful, but also more 10604 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 10605 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 10606 // use isKnownPredicate later if needed. 10607 return isKnownNonNegative(RHS) && 10608 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 10609 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 10610 } 10611 10612 bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB, 10613 ICmpInst::Predicate Pred, 10614 const SCEV *LHS, const SCEV *RHS) { 10615 // No need to even try if we know the module has no guards. 10616 if (!HasGuards) 10617 return false; 10618 10619 return any_of(*BB, [&](const Instruction &I) { 10620 using namespace llvm::PatternMatch; 10621 10622 Value *Condition; 10623 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 10624 m_Value(Condition))) && 10625 isImpliedCond(Pred, LHS, RHS, Condition, false); 10626 }); 10627 } 10628 10629 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 10630 /// protected by a conditional between LHS and RHS. This is used to 10631 /// to eliminate casts. 10632 bool 10633 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 10634 ICmpInst::Predicate Pred, 10635 const SCEV *LHS, const SCEV *RHS) { 10636 // Interpret a null as meaning no loop, where there is obviously no guard 10637 // (interprocedural conditions notwithstanding). 10638 if (!L) return true; 10639 10640 if (VerifyIR) 10641 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && 10642 "This cannot be done on broken IR!"); 10643 10644 10645 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 10646 return true; 10647 10648 BasicBlock *Latch = L->getLoopLatch(); 10649 if (!Latch) 10650 return false; 10651 10652 BranchInst *LoopContinuePredicate = 10653 dyn_cast<BranchInst>(Latch->getTerminator()); 10654 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 10655 isImpliedCond(Pred, LHS, RHS, 10656 LoopContinuePredicate->getCondition(), 10657 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 10658 return true; 10659 10660 // We don't want more than one activation of the following loops on the stack 10661 // -- that can lead to O(n!) time complexity. 10662 if (WalkingBEDominatingConds) 10663 return false; 10664 10665 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 10666 10667 // See if we can exploit a trip count to prove the predicate. 10668 const auto &BETakenInfo = getBackedgeTakenInfo(L); 10669 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 10670 if (LatchBECount != getCouldNotCompute()) { 10671 // We know that Latch branches back to the loop header exactly 10672 // LatchBECount times. This means the backdege condition at Latch is 10673 // equivalent to "{0,+,1} u< LatchBECount". 10674 Type *Ty = LatchBECount->getType(); 10675 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 10676 const SCEV *LoopCounter = 10677 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 10678 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 10679 LatchBECount)) 10680 return true; 10681 } 10682 10683 // Check conditions due to any @llvm.assume intrinsics. 10684 for (auto &AssumeVH : AC.assumptions()) { 10685 if (!AssumeVH) 10686 continue; 10687 auto *CI = cast<CallInst>(AssumeVH); 10688 if (!DT.dominates(CI, Latch->getTerminator())) 10689 continue; 10690 10691 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 10692 return true; 10693 } 10694 10695 // If the loop is not reachable from the entry block, we risk running into an 10696 // infinite loop as we walk up into the dom tree. These loops do not matter 10697 // anyway, so we just return a conservative answer when we see them. 10698 if (!DT.isReachableFromEntry(L->getHeader())) 10699 return false; 10700 10701 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 10702 return true; 10703 10704 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 10705 DTN != HeaderDTN; DTN = DTN->getIDom()) { 10706 assert(DTN && "should reach the loop header before reaching the root!"); 10707 10708 BasicBlock *BB = DTN->getBlock(); 10709 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 10710 return true; 10711 10712 BasicBlock *PBB = BB->getSinglePredecessor(); 10713 if (!PBB) 10714 continue; 10715 10716 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 10717 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 10718 continue; 10719 10720 Value *Condition = ContinuePredicate->getCondition(); 10721 10722 // If we have an edge `E` within the loop body that dominates the only 10723 // latch, the condition guarding `E` also guards the backedge. This 10724 // reasoning works only for loops with a single latch. 10725 10726 BasicBlockEdge DominatingEdge(PBB, BB); 10727 if (DominatingEdge.isSingleEdge()) { 10728 // We're constructively (and conservatively) enumerating edges within the 10729 // loop body that dominate the latch. The dominator tree better agree 10730 // with us on this: 10731 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 10732 10733 if (isImpliedCond(Pred, LHS, RHS, Condition, 10734 BB != ContinuePredicate->getSuccessor(0))) 10735 return true; 10736 } 10737 } 10738 10739 return false; 10740 } 10741 10742 bool ScalarEvolution::isBasicBlockEntryGuardedByCond(const BasicBlock *BB, 10743 ICmpInst::Predicate Pred, 10744 const SCEV *LHS, 10745 const SCEV *RHS) { 10746 if (VerifyIR) 10747 assert(!verifyFunction(*BB->getParent(), &dbgs()) && 10748 "This cannot be done on broken IR!"); 10749 10750 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove 10751 // the facts (a >= b && a != b) separately. A typical situation is when the 10752 // non-strict comparison is known from ranges and non-equality is known from 10753 // dominating predicates. If we are proving strict comparison, we always try 10754 // to prove non-equality and non-strict comparison separately. 10755 auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred); 10756 const bool ProvingStrictComparison = (Pred != NonStrictPredicate); 10757 bool ProvedNonStrictComparison = false; 10758 bool ProvedNonEquality = false; 10759 10760 auto SplitAndProve = 10761 [&](std::function<bool(ICmpInst::Predicate)> Fn) -> bool { 10762 if (!ProvedNonStrictComparison) 10763 ProvedNonStrictComparison = Fn(NonStrictPredicate); 10764 if (!ProvedNonEquality) 10765 ProvedNonEquality = Fn(ICmpInst::ICMP_NE); 10766 if (ProvedNonStrictComparison && ProvedNonEquality) 10767 return true; 10768 return false; 10769 }; 10770 10771 if (ProvingStrictComparison) { 10772 auto ProofFn = [&](ICmpInst::Predicate P) { 10773 return isKnownViaNonRecursiveReasoning(P, LHS, RHS); 10774 }; 10775 if (SplitAndProve(ProofFn)) 10776 return true; 10777 } 10778 10779 // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard. 10780 auto ProveViaGuard = [&](const BasicBlock *Block) { 10781 if (isImpliedViaGuard(Block, Pred, LHS, RHS)) 10782 return true; 10783 if (ProvingStrictComparison) { 10784 auto ProofFn = [&](ICmpInst::Predicate P) { 10785 return isImpliedViaGuard(Block, P, LHS, RHS); 10786 }; 10787 if (SplitAndProve(ProofFn)) 10788 return true; 10789 } 10790 return false; 10791 }; 10792 10793 // Try to prove (Pred, LHS, RHS) using isImpliedCond. 10794 auto ProveViaCond = [&](const Value *Condition, bool Inverse) { 10795 const Instruction *CtxI = &BB->front(); 10796 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, CtxI)) 10797 return true; 10798 if (ProvingStrictComparison) { 10799 auto ProofFn = [&](ICmpInst::Predicate P) { 10800 return isImpliedCond(P, LHS, RHS, Condition, Inverse, CtxI); 10801 }; 10802 if (SplitAndProve(ProofFn)) 10803 return true; 10804 } 10805 return false; 10806 }; 10807 10808 // Starting at the block's predecessor, climb up the predecessor chain, as long 10809 // as there are predecessors that can be found that have unique successors 10810 // leading to the original block. 10811 const Loop *ContainingLoop = LI.getLoopFor(BB); 10812 const BasicBlock *PredBB; 10813 if (ContainingLoop && ContainingLoop->getHeader() == BB) 10814 PredBB = ContainingLoop->getLoopPredecessor(); 10815 else 10816 PredBB = BB->getSinglePredecessor(); 10817 for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB); 10818 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 10819 if (ProveViaGuard(Pair.first)) 10820 return true; 10821 10822 const BranchInst *LoopEntryPredicate = 10823 dyn_cast<BranchInst>(Pair.first->getTerminator()); 10824 if (!LoopEntryPredicate || 10825 LoopEntryPredicate->isUnconditional()) 10826 continue; 10827 10828 if (ProveViaCond(LoopEntryPredicate->getCondition(), 10829 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 10830 return true; 10831 } 10832 10833 // Check conditions due to any @llvm.assume intrinsics. 10834 for (auto &AssumeVH : AC.assumptions()) { 10835 if (!AssumeVH) 10836 continue; 10837 auto *CI = cast<CallInst>(AssumeVH); 10838 if (!DT.dominates(CI, BB)) 10839 continue; 10840 10841 if (ProveViaCond(CI->getArgOperand(0), false)) 10842 return true; 10843 } 10844 10845 return false; 10846 } 10847 10848 bool ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 10849 ICmpInst::Predicate Pred, 10850 const SCEV *LHS, 10851 const SCEV *RHS) { 10852 // Interpret a null as meaning no loop, where there is obviously no guard 10853 // (interprocedural conditions notwithstanding). 10854 if (!L) 10855 return false; 10856 10857 // Both LHS and RHS must be available at loop entry. 10858 assert(isAvailableAtLoopEntry(LHS, L) && 10859 "LHS is not available at Loop Entry"); 10860 assert(isAvailableAtLoopEntry(RHS, L) && 10861 "RHS is not available at Loop Entry"); 10862 10863 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 10864 return true; 10865 10866 return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS); 10867 } 10868 10869 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 10870 const SCEV *RHS, 10871 const Value *FoundCondValue, bool Inverse, 10872 const Instruction *CtxI) { 10873 // False conditions implies anything. Do not bother analyzing it further. 10874 if (FoundCondValue == 10875 ConstantInt::getBool(FoundCondValue->getContext(), Inverse)) 10876 return true; 10877 10878 if (!PendingLoopPredicates.insert(FoundCondValue).second) 10879 return false; 10880 10881 auto ClearOnExit = 10882 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 10883 10884 // Recursively handle And and Or conditions. 10885 const Value *Op0, *Op1; 10886 if (match(FoundCondValue, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) { 10887 if (!Inverse) 10888 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) || 10889 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI); 10890 } else if (match(FoundCondValue, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) { 10891 if (Inverse) 10892 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) || 10893 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI); 10894 } 10895 10896 const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 10897 if (!ICI) return false; 10898 10899 // Now that we found a conditional branch that dominates the loop or controls 10900 // the loop latch. Check to see if it is the comparison we are looking for. 10901 ICmpInst::Predicate FoundPred; 10902 if (Inverse) 10903 FoundPred = ICI->getInversePredicate(); 10904 else 10905 FoundPred = ICI->getPredicate(); 10906 10907 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 10908 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 10909 10910 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, CtxI); 10911 } 10912 10913 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 10914 const SCEV *RHS, 10915 ICmpInst::Predicate FoundPred, 10916 const SCEV *FoundLHS, const SCEV *FoundRHS, 10917 const Instruction *CtxI) { 10918 // Balance the types. 10919 if (getTypeSizeInBits(LHS->getType()) < 10920 getTypeSizeInBits(FoundLHS->getType())) { 10921 // For unsigned and equality predicates, try to prove that both found 10922 // operands fit into narrow unsigned range. If so, try to prove facts in 10923 // narrow types. 10924 if (!CmpInst::isSigned(FoundPred) && !FoundLHS->getType()->isPointerTy() && 10925 !FoundRHS->getType()->isPointerTy()) { 10926 auto *NarrowType = LHS->getType(); 10927 auto *WideType = FoundLHS->getType(); 10928 auto BitWidth = getTypeSizeInBits(NarrowType); 10929 const SCEV *MaxValue = getZeroExtendExpr( 10930 getConstant(APInt::getMaxValue(BitWidth)), WideType); 10931 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundLHS, 10932 MaxValue) && 10933 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundRHS, 10934 MaxValue)) { 10935 const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType); 10936 const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType); 10937 if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, TruncFoundLHS, 10938 TruncFoundRHS, CtxI)) 10939 return true; 10940 } 10941 } 10942 10943 if (LHS->getType()->isPointerTy() || RHS->getType()->isPointerTy()) 10944 return false; 10945 if (CmpInst::isSigned(Pred)) { 10946 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 10947 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 10948 } else { 10949 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 10950 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 10951 } 10952 } else if (getTypeSizeInBits(LHS->getType()) > 10953 getTypeSizeInBits(FoundLHS->getType())) { 10954 if (FoundLHS->getType()->isPointerTy() || FoundRHS->getType()->isPointerTy()) 10955 return false; 10956 if (CmpInst::isSigned(FoundPred)) { 10957 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 10958 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 10959 } else { 10960 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 10961 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 10962 } 10963 } 10964 return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS, 10965 FoundRHS, CtxI); 10966 } 10967 10968 bool ScalarEvolution::isImpliedCondBalancedTypes( 10969 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 10970 ICmpInst::Predicate FoundPred, const SCEV *FoundLHS, const SCEV *FoundRHS, 10971 const Instruction *CtxI) { 10972 assert(getTypeSizeInBits(LHS->getType()) == 10973 getTypeSizeInBits(FoundLHS->getType()) && 10974 "Types should be balanced!"); 10975 // Canonicalize the query to match the way instcombine will have 10976 // canonicalized the comparison. 10977 if (SimplifyICmpOperands(Pred, LHS, RHS)) 10978 if (LHS == RHS) 10979 return CmpInst::isTrueWhenEqual(Pred); 10980 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 10981 if (FoundLHS == FoundRHS) 10982 return CmpInst::isFalseWhenEqual(FoundPred); 10983 10984 // Check to see if we can make the LHS or RHS match. 10985 if (LHS == FoundRHS || RHS == FoundLHS) { 10986 if (isa<SCEVConstant>(RHS)) { 10987 std::swap(FoundLHS, FoundRHS); 10988 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 10989 } else { 10990 std::swap(LHS, RHS); 10991 Pred = ICmpInst::getSwappedPredicate(Pred); 10992 } 10993 } 10994 10995 // Check whether the found predicate is the same as the desired predicate. 10996 if (FoundPred == Pred) 10997 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI); 10998 10999 // Check whether swapping the found predicate makes it the same as the 11000 // desired predicate. 11001 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 11002 // We can write the implication 11003 // 0. LHS Pred RHS <- FoundLHS SwapPred FoundRHS 11004 // using one of the following ways: 11005 // 1. LHS Pred RHS <- FoundRHS Pred FoundLHS 11006 // 2. RHS SwapPred LHS <- FoundLHS SwapPred FoundRHS 11007 // 3. LHS Pred RHS <- ~FoundLHS Pred ~FoundRHS 11008 // 4. ~LHS SwapPred ~RHS <- FoundLHS SwapPred FoundRHS 11009 // Forms 1. and 2. require swapping the operands of one condition. Don't 11010 // do this if it would break canonical constant/addrec ordering. 11011 if (!isa<SCEVConstant>(RHS) && !isa<SCEVAddRecExpr>(LHS)) 11012 return isImpliedCondOperands(FoundPred, RHS, LHS, FoundLHS, FoundRHS, 11013 CtxI); 11014 if (!isa<SCEVConstant>(FoundRHS) && !isa<SCEVAddRecExpr>(FoundLHS)) 11015 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS, CtxI); 11016 11017 // There's no clear preference between forms 3. and 4., try both. Avoid 11018 // forming getNotSCEV of pointer values as the resulting subtract is 11019 // not legal. 11020 if (!LHS->getType()->isPointerTy() && !RHS->getType()->isPointerTy() && 11021 isImpliedCondOperands(FoundPred, getNotSCEV(LHS), getNotSCEV(RHS), 11022 FoundLHS, FoundRHS, CtxI)) 11023 return true; 11024 11025 if (!FoundLHS->getType()->isPointerTy() && 11026 !FoundRHS->getType()->isPointerTy() && 11027 isImpliedCondOperands(Pred, LHS, RHS, getNotSCEV(FoundLHS), 11028 getNotSCEV(FoundRHS), CtxI)) 11029 return true; 11030 11031 return false; 11032 } 11033 11034 auto IsSignFlippedPredicate = [](CmpInst::Predicate P1, 11035 CmpInst::Predicate P2) { 11036 assert(P1 != P2 && "Handled earlier!"); 11037 return CmpInst::isRelational(P2) && 11038 P1 == CmpInst::getFlippedSignednessPredicate(P2); 11039 }; 11040 if (IsSignFlippedPredicate(Pred, FoundPred)) { 11041 // Unsigned comparison is the same as signed comparison when both the 11042 // operands are non-negative or negative. 11043 if ((isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) || 11044 (isKnownNegative(FoundLHS) && isKnownNegative(FoundRHS))) 11045 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI); 11046 // Create local copies that we can freely swap and canonicalize our 11047 // conditions to "le/lt". 11048 ICmpInst::Predicate CanonicalPred = Pred, CanonicalFoundPred = FoundPred; 11049 const SCEV *CanonicalLHS = LHS, *CanonicalRHS = RHS, 11050 *CanonicalFoundLHS = FoundLHS, *CanonicalFoundRHS = FoundRHS; 11051 if (ICmpInst::isGT(CanonicalPred) || ICmpInst::isGE(CanonicalPred)) { 11052 CanonicalPred = ICmpInst::getSwappedPredicate(CanonicalPred); 11053 CanonicalFoundPred = ICmpInst::getSwappedPredicate(CanonicalFoundPred); 11054 std::swap(CanonicalLHS, CanonicalRHS); 11055 std::swap(CanonicalFoundLHS, CanonicalFoundRHS); 11056 } 11057 assert((ICmpInst::isLT(CanonicalPred) || ICmpInst::isLE(CanonicalPred)) && 11058 "Must be!"); 11059 assert((ICmpInst::isLT(CanonicalFoundPred) || 11060 ICmpInst::isLE(CanonicalFoundPred)) && 11061 "Must be!"); 11062 if (ICmpInst::isSigned(CanonicalPred) && isKnownNonNegative(CanonicalRHS)) 11063 // Use implication: 11064 // x <u y && y >=s 0 --> x <s y. 11065 // If we can prove the left part, the right part is also proven. 11066 return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS, 11067 CanonicalRHS, CanonicalFoundLHS, 11068 CanonicalFoundRHS); 11069 if (ICmpInst::isUnsigned(CanonicalPred) && isKnownNegative(CanonicalRHS)) 11070 // Use implication: 11071 // x <s y && y <s 0 --> x <u y. 11072 // If we can prove the left part, the right part is also proven. 11073 return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS, 11074 CanonicalRHS, CanonicalFoundLHS, 11075 CanonicalFoundRHS); 11076 } 11077 11078 // Check if we can make progress by sharpening ranges. 11079 if (FoundPred == ICmpInst::ICMP_NE && 11080 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 11081 11082 const SCEVConstant *C = nullptr; 11083 const SCEV *V = nullptr; 11084 11085 if (isa<SCEVConstant>(FoundLHS)) { 11086 C = cast<SCEVConstant>(FoundLHS); 11087 V = FoundRHS; 11088 } else { 11089 C = cast<SCEVConstant>(FoundRHS); 11090 V = FoundLHS; 11091 } 11092 11093 // The guarding predicate tells us that C != V. If the known range 11094 // of V is [C, t), we can sharpen the range to [C + 1, t). The 11095 // range we consider has to correspond to same signedness as the 11096 // predicate we're interested in folding. 11097 11098 APInt Min = ICmpInst::isSigned(Pred) ? 11099 getSignedRangeMin(V) : getUnsignedRangeMin(V); 11100 11101 if (Min == C->getAPInt()) { 11102 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 11103 // This is true even if (Min + 1) wraps around -- in case of 11104 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 11105 11106 APInt SharperMin = Min + 1; 11107 11108 switch (Pred) { 11109 case ICmpInst::ICMP_SGE: 11110 case ICmpInst::ICMP_UGE: 11111 // We know V `Pred` SharperMin. If this implies LHS `Pred` 11112 // RHS, we're done. 11113 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin), 11114 CtxI)) 11115 return true; 11116 LLVM_FALLTHROUGH; 11117 11118 case ICmpInst::ICMP_SGT: 11119 case ICmpInst::ICMP_UGT: 11120 // We know from the range information that (V `Pred` Min || 11121 // V == Min). We know from the guarding condition that !(V 11122 // == Min). This gives us 11123 // 11124 // V `Pred` Min || V == Min && !(V == Min) 11125 // => V `Pred` Min 11126 // 11127 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 11128 11129 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min), CtxI)) 11130 return true; 11131 break; 11132 11133 // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively. 11134 case ICmpInst::ICMP_SLE: 11135 case ICmpInst::ICMP_ULE: 11136 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS, 11137 LHS, V, getConstant(SharperMin), CtxI)) 11138 return true; 11139 LLVM_FALLTHROUGH; 11140 11141 case ICmpInst::ICMP_SLT: 11142 case ICmpInst::ICMP_ULT: 11143 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS, 11144 LHS, V, getConstant(Min), CtxI)) 11145 return true; 11146 break; 11147 11148 default: 11149 // No change 11150 break; 11151 } 11152 } 11153 } 11154 11155 // Check whether the actual condition is beyond sufficient. 11156 if (FoundPred == ICmpInst::ICMP_EQ) 11157 if (ICmpInst::isTrueWhenEqual(Pred)) 11158 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI)) 11159 return true; 11160 if (Pred == ICmpInst::ICMP_NE) 11161 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 11162 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS, CtxI)) 11163 return true; 11164 11165 // Otherwise assume the worst. 11166 return false; 11167 } 11168 11169 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 11170 const SCEV *&L, const SCEV *&R, 11171 SCEV::NoWrapFlags &Flags) { 11172 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 11173 if (!AE || AE->getNumOperands() != 2) 11174 return false; 11175 11176 L = AE->getOperand(0); 11177 R = AE->getOperand(1); 11178 Flags = AE->getNoWrapFlags(); 11179 return true; 11180 } 11181 11182 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 11183 const SCEV *Less) { 11184 // We avoid subtracting expressions here because this function is usually 11185 // fairly deep in the call stack (i.e. is called many times). 11186 11187 // X - X = 0. 11188 if (More == Less) 11189 return APInt(getTypeSizeInBits(More->getType()), 0); 11190 11191 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 11192 const auto *LAR = cast<SCEVAddRecExpr>(Less); 11193 const auto *MAR = cast<SCEVAddRecExpr>(More); 11194 11195 if (LAR->getLoop() != MAR->getLoop()) 11196 return None; 11197 11198 // We look at affine expressions only; not for correctness but to keep 11199 // getStepRecurrence cheap. 11200 if (!LAR->isAffine() || !MAR->isAffine()) 11201 return None; 11202 11203 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 11204 return None; 11205 11206 Less = LAR->getStart(); 11207 More = MAR->getStart(); 11208 11209 // fall through 11210 } 11211 11212 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 11213 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 11214 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 11215 return M - L; 11216 } 11217 11218 SCEV::NoWrapFlags Flags; 11219 const SCEV *LLess = nullptr, *RLess = nullptr; 11220 const SCEV *LMore = nullptr, *RMore = nullptr; 11221 const SCEVConstant *C1 = nullptr, *C2 = nullptr; 11222 // Compare (X + C1) vs X. 11223 if (splitBinaryAdd(Less, LLess, RLess, Flags)) 11224 if ((C1 = dyn_cast<SCEVConstant>(LLess))) 11225 if (RLess == More) 11226 return -(C1->getAPInt()); 11227 11228 // Compare X vs (X + C2). 11229 if (splitBinaryAdd(More, LMore, RMore, Flags)) 11230 if ((C2 = dyn_cast<SCEVConstant>(LMore))) 11231 if (RMore == Less) 11232 return C2->getAPInt(); 11233 11234 // Compare (X + C1) vs (X + C2). 11235 if (C1 && C2 && RLess == RMore) 11236 return C2->getAPInt() - C1->getAPInt(); 11237 11238 return None; 11239 } 11240 11241 bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart( 11242 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 11243 const SCEV *FoundLHS, const SCEV *FoundRHS, const Instruction *CtxI) { 11244 // Try to recognize the following pattern: 11245 // 11246 // FoundRHS = ... 11247 // ... 11248 // loop: 11249 // FoundLHS = {Start,+,W} 11250 // context_bb: // Basic block from the same loop 11251 // known(Pred, FoundLHS, FoundRHS) 11252 // 11253 // If some predicate is known in the context of a loop, it is also known on 11254 // each iteration of this loop, including the first iteration. Therefore, in 11255 // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to 11256 // prove the original pred using this fact. 11257 if (!CtxI) 11258 return false; 11259 const BasicBlock *ContextBB = CtxI->getParent(); 11260 // Make sure AR varies in the context block. 11261 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) { 11262 const Loop *L = AR->getLoop(); 11263 // Make sure that context belongs to the loop and executes on 1st iteration 11264 // (if it ever executes at all). 11265 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch())) 11266 return false; 11267 if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop())) 11268 return false; 11269 return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS); 11270 } 11271 11272 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) { 11273 const Loop *L = AR->getLoop(); 11274 // Make sure that context belongs to the loop and executes on 1st iteration 11275 // (if it ever executes at all). 11276 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch())) 11277 return false; 11278 if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop())) 11279 return false; 11280 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart()); 11281 } 11282 11283 return false; 11284 } 11285 11286 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 11287 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 11288 const SCEV *FoundLHS, const SCEV *FoundRHS) { 11289 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 11290 return false; 11291 11292 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 11293 if (!AddRecLHS) 11294 return false; 11295 11296 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 11297 if (!AddRecFoundLHS) 11298 return false; 11299 11300 // We'd like to let SCEV reason about control dependencies, so we constrain 11301 // both the inequalities to be about add recurrences on the same loop. This 11302 // way we can use isLoopEntryGuardedByCond later. 11303 11304 const Loop *L = AddRecFoundLHS->getLoop(); 11305 if (L != AddRecLHS->getLoop()) 11306 return false; 11307 11308 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 11309 // 11310 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 11311 // ... (2) 11312 // 11313 // Informal proof for (2), assuming (1) [*]: 11314 // 11315 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 11316 // 11317 // Then 11318 // 11319 // FoundLHS s< FoundRHS s< INT_MIN - C 11320 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 11321 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 11322 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 11323 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 11324 // <=> FoundLHS + C s< FoundRHS + C 11325 // 11326 // [*]: (1) can be proved by ruling out overflow. 11327 // 11328 // [**]: This can be proved by analyzing all the four possibilities: 11329 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 11330 // (A s>= 0, B s>= 0). 11331 // 11332 // Note: 11333 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 11334 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 11335 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 11336 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 11337 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 11338 // C)". 11339 11340 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 11341 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 11342 if (!LDiff || !RDiff || *LDiff != *RDiff) 11343 return false; 11344 11345 if (LDiff->isMinValue()) 11346 return true; 11347 11348 APInt FoundRHSLimit; 11349 11350 if (Pred == CmpInst::ICMP_ULT) { 11351 FoundRHSLimit = -(*RDiff); 11352 } else { 11353 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 11354 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 11355 } 11356 11357 // Try to prove (1) or (2), as needed. 11358 return isAvailableAtLoopEntry(FoundRHS, L) && 11359 isLoopEntryGuardedByCond(L, Pred, FoundRHS, 11360 getConstant(FoundRHSLimit)); 11361 } 11362 11363 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred, 11364 const SCEV *LHS, const SCEV *RHS, 11365 const SCEV *FoundLHS, 11366 const SCEV *FoundRHS, unsigned Depth) { 11367 const PHINode *LPhi = nullptr, *RPhi = nullptr; 11368 11369 auto ClearOnExit = make_scope_exit([&]() { 11370 if (LPhi) { 11371 bool Erased = PendingMerges.erase(LPhi); 11372 assert(Erased && "Failed to erase LPhi!"); 11373 (void)Erased; 11374 } 11375 if (RPhi) { 11376 bool Erased = PendingMerges.erase(RPhi); 11377 assert(Erased && "Failed to erase RPhi!"); 11378 (void)Erased; 11379 } 11380 }); 11381 11382 // Find respective Phis and check that they are not being pending. 11383 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) 11384 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) { 11385 if (!PendingMerges.insert(Phi).second) 11386 return false; 11387 LPhi = Phi; 11388 } 11389 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS)) 11390 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) { 11391 // If we detect a loop of Phi nodes being processed by this method, for 11392 // example: 11393 // 11394 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ] 11395 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ] 11396 // 11397 // we don't want to deal with a case that complex, so return conservative 11398 // answer false. 11399 if (!PendingMerges.insert(Phi).second) 11400 return false; 11401 RPhi = Phi; 11402 } 11403 11404 // If none of LHS, RHS is a Phi, nothing to do here. 11405 if (!LPhi && !RPhi) 11406 return false; 11407 11408 // If there is a SCEVUnknown Phi we are interested in, make it left. 11409 if (!LPhi) { 11410 std::swap(LHS, RHS); 11411 std::swap(FoundLHS, FoundRHS); 11412 std::swap(LPhi, RPhi); 11413 Pred = ICmpInst::getSwappedPredicate(Pred); 11414 } 11415 11416 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!"); 11417 const BasicBlock *LBB = LPhi->getParent(); 11418 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 11419 11420 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) { 11421 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) || 11422 isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) || 11423 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth); 11424 }; 11425 11426 if (RPhi && RPhi->getParent() == LBB) { 11427 // Case one: RHS is also a SCEVUnknown Phi from the same basic block. 11428 // If we compare two Phis from the same block, and for each entry block 11429 // the predicate is true for incoming values from this block, then the 11430 // predicate is also true for the Phis. 11431 for (const BasicBlock *IncBB : predecessors(LBB)) { 11432 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 11433 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB)); 11434 if (!ProvedEasily(L, R)) 11435 return false; 11436 } 11437 } else if (RAR && RAR->getLoop()->getHeader() == LBB) { 11438 // Case two: RHS is also a Phi from the same basic block, and it is an 11439 // AddRec. It means that there is a loop which has both AddRec and Unknown 11440 // PHIs, for it we can compare incoming values of AddRec from above the loop 11441 // and latch with their respective incoming values of LPhi. 11442 // TODO: Generalize to handle loops with many inputs in a header. 11443 if (LPhi->getNumIncomingValues() != 2) return false; 11444 11445 auto *RLoop = RAR->getLoop(); 11446 auto *Predecessor = RLoop->getLoopPredecessor(); 11447 assert(Predecessor && "Loop with AddRec with no predecessor?"); 11448 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor)); 11449 if (!ProvedEasily(L1, RAR->getStart())) 11450 return false; 11451 auto *Latch = RLoop->getLoopLatch(); 11452 assert(Latch && "Loop with AddRec with no latch?"); 11453 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch)); 11454 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this))) 11455 return false; 11456 } else { 11457 // In all other cases go over inputs of LHS and compare each of them to RHS, 11458 // the predicate is true for (LHS, RHS) if it is true for all such pairs. 11459 // At this point RHS is either a non-Phi, or it is a Phi from some block 11460 // different from LBB. 11461 for (const BasicBlock *IncBB : predecessors(LBB)) { 11462 // Check that RHS is available in this block. 11463 if (!dominates(RHS, IncBB)) 11464 return false; 11465 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 11466 // Make sure L does not refer to a value from a potentially previous 11467 // iteration of a loop. 11468 if (!properlyDominates(L, IncBB)) 11469 return false; 11470 if (!ProvedEasily(L, RHS)) 11471 return false; 11472 } 11473 } 11474 return true; 11475 } 11476 11477 bool ScalarEvolution::isImpliedCondOperandsViaShift(ICmpInst::Predicate Pred, 11478 const SCEV *LHS, 11479 const SCEV *RHS, 11480 const SCEV *FoundLHS, 11481 const SCEV *FoundRHS) { 11482 // We want to imply LHS < RHS from LHS < (RHS >> shiftvalue). First, make 11483 // sure that we are dealing with same LHS. 11484 if (RHS == FoundRHS) { 11485 std::swap(LHS, RHS); 11486 std::swap(FoundLHS, FoundRHS); 11487 Pred = ICmpInst::getSwappedPredicate(Pred); 11488 } 11489 if (LHS != FoundLHS) 11490 return false; 11491 11492 auto *SUFoundRHS = dyn_cast<SCEVUnknown>(FoundRHS); 11493 if (!SUFoundRHS) 11494 return false; 11495 11496 Value *Shiftee, *ShiftValue; 11497 11498 using namespace PatternMatch; 11499 if (match(SUFoundRHS->getValue(), 11500 m_LShr(m_Value(Shiftee), m_Value(ShiftValue)))) { 11501 auto *ShifteeS = getSCEV(Shiftee); 11502 // Prove one of the following: 11503 // LHS <u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <u RHS 11504 // LHS <=u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <=u RHS 11505 // LHS <s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0 11506 // ---> LHS <s RHS 11507 // LHS <=s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0 11508 // ---> LHS <=s RHS 11509 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) 11510 return isKnownPredicate(ICmpInst::ICMP_ULE, ShifteeS, RHS); 11511 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) 11512 if (isKnownNonNegative(ShifteeS)) 11513 return isKnownPredicate(ICmpInst::ICMP_SLE, ShifteeS, RHS); 11514 } 11515 11516 return false; 11517 } 11518 11519 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 11520 const SCEV *LHS, const SCEV *RHS, 11521 const SCEV *FoundLHS, 11522 const SCEV *FoundRHS, 11523 const Instruction *CtxI) { 11524 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 11525 return true; 11526 11527 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 11528 return true; 11529 11530 if (isImpliedCondOperandsViaShift(Pred, LHS, RHS, FoundLHS, FoundRHS)) 11531 return true; 11532 11533 if (isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS, 11534 CtxI)) 11535 return true; 11536 11537 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 11538 FoundLHS, FoundRHS); 11539 } 11540 11541 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values? 11542 template <typename MinMaxExprType> 11543 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr, 11544 const SCEV *Candidate) { 11545 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr); 11546 if (!MinMaxExpr) 11547 return false; 11548 11549 return is_contained(MinMaxExpr->operands(), Candidate); 11550 } 11551 11552 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 11553 ICmpInst::Predicate Pred, 11554 const SCEV *LHS, const SCEV *RHS) { 11555 // If both sides are affine addrecs for the same loop, with equal 11556 // steps, and we know the recurrences don't wrap, then we only 11557 // need to check the predicate on the starting values. 11558 11559 if (!ICmpInst::isRelational(Pred)) 11560 return false; 11561 11562 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 11563 if (!LAR) 11564 return false; 11565 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 11566 if (!RAR) 11567 return false; 11568 if (LAR->getLoop() != RAR->getLoop()) 11569 return false; 11570 if (!LAR->isAffine() || !RAR->isAffine()) 11571 return false; 11572 11573 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 11574 return false; 11575 11576 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 11577 SCEV::FlagNSW : SCEV::FlagNUW; 11578 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 11579 return false; 11580 11581 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 11582 } 11583 11584 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 11585 /// expression? 11586 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 11587 ICmpInst::Predicate Pred, 11588 const SCEV *LHS, const SCEV *RHS) { 11589 switch (Pred) { 11590 default: 11591 return false; 11592 11593 case ICmpInst::ICMP_SGE: 11594 std::swap(LHS, RHS); 11595 LLVM_FALLTHROUGH; 11596 case ICmpInst::ICMP_SLE: 11597 return 11598 // min(A, ...) <= A 11599 IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) || 11600 // A <= max(A, ...) 11601 IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 11602 11603 case ICmpInst::ICMP_UGE: 11604 std::swap(LHS, RHS); 11605 LLVM_FALLTHROUGH; 11606 case ICmpInst::ICMP_ULE: 11607 return 11608 // min(A, ...) <= A 11609 // FIXME: what about umin_seq? 11610 IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) || 11611 // A <= max(A, ...) 11612 IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 11613 } 11614 11615 llvm_unreachable("covered switch fell through?!"); 11616 } 11617 11618 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred, 11619 const SCEV *LHS, const SCEV *RHS, 11620 const SCEV *FoundLHS, 11621 const SCEV *FoundRHS, 11622 unsigned Depth) { 11623 assert(getTypeSizeInBits(LHS->getType()) == 11624 getTypeSizeInBits(RHS->getType()) && 11625 "LHS and RHS have different sizes?"); 11626 assert(getTypeSizeInBits(FoundLHS->getType()) == 11627 getTypeSizeInBits(FoundRHS->getType()) && 11628 "FoundLHS and FoundRHS have different sizes?"); 11629 // We want to avoid hurting the compile time with analysis of too big trees. 11630 if (Depth > MaxSCEVOperationsImplicationDepth) 11631 return false; 11632 11633 // We only want to work with GT comparison so far. 11634 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) { 11635 Pred = CmpInst::getSwappedPredicate(Pred); 11636 std::swap(LHS, RHS); 11637 std::swap(FoundLHS, FoundRHS); 11638 } 11639 11640 // For unsigned, try to reduce it to corresponding signed comparison. 11641 if (Pred == ICmpInst::ICMP_UGT) 11642 // We can replace unsigned predicate with its signed counterpart if all 11643 // involved values are non-negative. 11644 // TODO: We could have better support for unsigned. 11645 if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) { 11646 // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing 11647 // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us 11648 // use this fact to prove that LHS and RHS are non-negative. 11649 const SCEV *MinusOne = getMinusOne(LHS->getType()); 11650 if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS, 11651 FoundRHS) && 11652 isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS, 11653 FoundRHS)) 11654 Pred = ICmpInst::ICMP_SGT; 11655 } 11656 11657 if (Pred != ICmpInst::ICMP_SGT) 11658 return false; 11659 11660 auto GetOpFromSExt = [&](const SCEV *S) { 11661 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S)) 11662 return Ext->getOperand(); 11663 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off 11664 // the constant in some cases. 11665 return S; 11666 }; 11667 11668 // Acquire values from extensions. 11669 auto *OrigLHS = LHS; 11670 auto *OrigFoundLHS = FoundLHS; 11671 LHS = GetOpFromSExt(LHS); 11672 FoundLHS = GetOpFromSExt(FoundLHS); 11673 11674 // Is the SGT predicate can be proved trivially or using the found context. 11675 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) { 11676 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) || 11677 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS, 11678 FoundRHS, Depth + 1); 11679 }; 11680 11681 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) { 11682 // We want to avoid creation of any new non-constant SCEV. Since we are 11683 // going to compare the operands to RHS, we should be certain that we don't 11684 // need any size extensions for this. So let's decline all cases when the 11685 // sizes of types of LHS and RHS do not match. 11686 // TODO: Maybe try to get RHS from sext to catch more cases? 11687 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType())) 11688 return false; 11689 11690 // Should not overflow. 11691 if (!LHSAddExpr->hasNoSignedWrap()) 11692 return false; 11693 11694 auto *LL = LHSAddExpr->getOperand(0); 11695 auto *LR = LHSAddExpr->getOperand(1); 11696 auto *MinusOne = getMinusOne(RHS->getType()); 11697 11698 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context. 11699 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) { 11700 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS); 11701 }; 11702 // Try to prove the following rule: 11703 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS). 11704 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS). 11705 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL)) 11706 return true; 11707 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) { 11708 Value *LL, *LR; 11709 // FIXME: Once we have SDiv implemented, we can get rid of this matching. 11710 11711 using namespace llvm::PatternMatch; 11712 11713 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) { 11714 // Rules for division. 11715 // We are going to perform some comparisons with Denominator and its 11716 // derivative expressions. In general case, creating a SCEV for it may 11717 // lead to a complex analysis of the entire graph, and in particular it 11718 // can request trip count recalculation for the same loop. This would 11719 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid 11720 // this, we only want to create SCEVs that are constants in this section. 11721 // So we bail if Denominator is not a constant. 11722 if (!isa<ConstantInt>(LR)) 11723 return false; 11724 11725 auto *Denominator = cast<SCEVConstant>(getSCEV(LR)); 11726 11727 // We want to make sure that LHS = FoundLHS / Denominator. If it is so, 11728 // then a SCEV for the numerator already exists and matches with FoundLHS. 11729 auto *Numerator = getExistingSCEV(LL); 11730 if (!Numerator || Numerator->getType() != FoundLHS->getType()) 11731 return false; 11732 11733 // Make sure that the numerator matches with FoundLHS and the denominator 11734 // is positive. 11735 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator)) 11736 return false; 11737 11738 auto *DTy = Denominator->getType(); 11739 auto *FRHSTy = FoundRHS->getType(); 11740 if (DTy->isPointerTy() != FRHSTy->isPointerTy()) 11741 // One of types is a pointer and another one is not. We cannot extend 11742 // them properly to a wider type, so let us just reject this case. 11743 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help 11744 // to avoid this check. 11745 return false; 11746 11747 // Given that: 11748 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0. 11749 auto *WTy = getWiderType(DTy, FRHSTy); 11750 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy); 11751 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy); 11752 11753 // Try to prove the following rule: 11754 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS). 11755 // For example, given that FoundLHS > 2. It means that FoundLHS is at 11756 // least 3. If we divide it by Denominator < 4, we will have at least 1. 11757 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2)); 11758 if (isKnownNonPositive(RHS) && 11759 IsSGTViaContext(FoundRHSExt, DenomMinusTwo)) 11760 return true; 11761 11762 // Try to prove the following rule: 11763 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS). 11764 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2. 11765 // If we divide it by Denominator > 2, then: 11766 // 1. If FoundLHS is negative, then the result is 0. 11767 // 2. If FoundLHS is non-negative, then the result is non-negative. 11768 // Anyways, the result is non-negative. 11769 auto *MinusOne = getMinusOne(WTy); 11770 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt); 11771 if (isKnownNegative(RHS) && 11772 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne)) 11773 return true; 11774 } 11775 } 11776 11777 // If our expression contained SCEVUnknown Phis, and we split it down and now 11778 // need to prove something for them, try to prove the predicate for every 11779 // possible incoming values of those Phis. 11780 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1)) 11781 return true; 11782 11783 return false; 11784 } 11785 11786 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred, 11787 const SCEV *LHS, const SCEV *RHS) { 11788 // zext x u<= sext x, sext x s<= zext x 11789 switch (Pred) { 11790 case ICmpInst::ICMP_SGE: 11791 std::swap(LHS, RHS); 11792 LLVM_FALLTHROUGH; 11793 case ICmpInst::ICMP_SLE: { 11794 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt. 11795 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS); 11796 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS); 11797 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 11798 return true; 11799 break; 11800 } 11801 case ICmpInst::ICMP_UGE: 11802 std::swap(LHS, RHS); 11803 LLVM_FALLTHROUGH; 11804 case ICmpInst::ICMP_ULE: { 11805 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then ZExt <u SExt. 11806 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS); 11807 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS); 11808 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 11809 return true; 11810 break; 11811 } 11812 default: 11813 break; 11814 }; 11815 return false; 11816 } 11817 11818 bool 11819 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred, 11820 const SCEV *LHS, const SCEV *RHS) { 11821 return isKnownPredicateExtendIdiom(Pred, LHS, RHS) || 11822 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 11823 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 11824 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 11825 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 11826 } 11827 11828 bool 11829 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 11830 const SCEV *LHS, const SCEV *RHS, 11831 const SCEV *FoundLHS, 11832 const SCEV *FoundRHS) { 11833 switch (Pred) { 11834 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 11835 case ICmpInst::ICMP_EQ: 11836 case ICmpInst::ICMP_NE: 11837 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 11838 return true; 11839 break; 11840 case ICmpInst::ICMP_SLT: 11841 case ICmpInst::ICMP_SLE: 11842 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 11843 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 11844 return true; 11845 break; 11846 case ICmpInst::ICMP_SGT: 11847 case ICmpInst::ICMP_SGE: 11848 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 11849 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 11850 return true; 11851 break; 11852 case ICmpInst::ICMP_ULT: 11853 case ICmpInst::ICMP_ULE: 11854 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 11855 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 11856 return true; 11857 break; 11858 case ICmpInst::ICMP_UGT: 11859 case ICmpInst::ICMP_UGE: 11860 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 11861 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 11862 return true; 11863 break; 11864 } 11865 11866 // Maybe it can be proved via operations? 11867 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS)) 11868 return true; 11869 11870 return false; 11871 } 11872 11873 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 11874 const SCEV *LHS, 11875 const SCEV *RHS, 11876 const SCEV *FoundLHS, 11877 const SCEV *FoundRHS) { 11878 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 11879 // The restriction on `FoundRHS` be lifted easily -- it exists only to 11880 // reduce the compile time impact of this optimization. 11881 return false; 11882 11883 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 11884 if (!Addend) 11885 return false; 11886 11887 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 11888 11889 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 11890 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 11891 ConstantRange FoundLHSRange = 11892 ConstantRange::makeExactICmpRegion(Pred, ConstFoundRHS); 11893 11894 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 11895 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 11896 11897 // We can also compute the range of values for `LHS` that satisfy the 11898 // consequent, "`LHS` `Pred` `RHS`": 11899 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 11900 // The antecedent implies the consequent if every value of `LHS` that 11901 // satisfies the antecedent also satisfies the consequent. 11902 return LHSRange.icmp(Pred, ConstRHS); 11903 } 11904 11905 bool ScalarEvolution::canIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 11906 bool IsSigned) { 11907 assert(isKnownPositive(Stride) && "Positive stride expected!"); 11908 11909 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 11910 const SCEV *One = getOne(Stride->getType()); 11911 11912 if (IsSigned) { 11913 APInt MaxRHS = getSignedRangeMax(RHS); 11914 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 11915 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 11916 11917 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 11918 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS); 11919 } 11920 11921 APInt MaxRHS = getUnsignedRangeMax(RHS); 11922 APInt MaxValue = APInt::getMaxValue(BitWidth); 11923 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 11924 11925 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 11926 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS); 11927 } 11928 11929 bool ScalarEvolution::canIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 11930 bool IsSigned) { 11931 11932 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 11933 const SCEV *One = getOne(Stride->getType()); 11934 11935 if (IsSigned) { 11936 APInt MinRHS = getSignedRangeMin(RHS); 11937 APInt MinValue = APInt::getSignedMinValue(BitWidth); 11938 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 11939 11940 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 11941 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS); 11942 } 11943 11944 APInt MinRHS = getUnsignedRangeMin(RHS); 11945 APInt MinValue = APInt::getMinValue(BitWidth); 11946 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 11947 11948 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 11949 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS); 11950 } 11951 11952 const SCEV *ScalarEvolution::getUDivCeilSCEV(const SCEV *N, const SCEV *D) { 11953 // umin(N, 1) + floor((N - umin(N, 1)) / D) 11954 // This is equivalent to "1 + floor((N - 1) / D)" for N != 0. The umin 11955 // expression fixes the case of N=0. 11956 const SCEV *MinNOne = getUMinExpr(N, getOne(N->getType())); 11957 const SCEV *NMinusOne = getMinusSCEV(N, MinNOne); 11958 return getAddExpr(MinNOne, getUDivExpr(NMinusOne, D)); 11959 } 11960 11961 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, 11962 const SCEV *Stride, 11963 const SCEV *End, 11964 unsigned BitWidth, 11965 bool IsSigned) { 11966 // The logic in this function assumes we can represent a positive stride. 11967 // If we can't, the backedge-taken count must be zero. 11968 if (IsSigned && BitWidth == 1) 11969 return getZero(Stride->getType()); 11970 11971 // This code has only been closely audited for negative strides in the 11972 // unsigned comparison case, it may be correct for signed comparison, but 11973 // that needs to be established. 11974 assert((!IsSigned || !isKnownNonPositive(Stride)) && 11975 "Stride is expected strictly positive for signed case!"); 11976 11977 // Calculate the maximum backedge count based on the range of values 11978 // permitted by Start, End, and Stride. 11979 APInt MinStart = 11980 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start); 11981 11982 APInt MinStride = 11983 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride); 11984 11985 // We assume either the stride is positive, or the backedge-taken count 11986 // is zero. So force StrideForMaxBECount to be at least one. 11987 APInt One(BitWidth, 1); 11988 APInt StrideForMaxBECount = IsSigned ? APIntOps::smax(One, MinStride) 11989 : APIntOps::umax(One, MinStride); 11990 11991 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth) 11992 : APInt::getMaxValue(BitWidth); 11993 APInt Limit = MaxValue - (StrideForMaxBECount - 1); 11994 11995 // Although End can be a MAX expression we estimate MaxEnd considering only 11996 // the case End = RHS of the loop termination condition. This is safe because 11997 // in the other case (End - Start) is zero, leading to a zero maximum backedge 11998 // taken count. 11999 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit) 12000 : APIntOps::umin(getUnsignedRangeMax(End), Limit); 12001 12002 // MaxBECount = ceil((max(MaxEnd, MinStart) - MinStart) / Stride) 12003 MaxEnd = IsSigned ? APIntOps::smax(MaxEnd, MinStart) 12004 : APIntOps::umax(MaxEnd, MinStart); 12005 12006 return getUDivCeilSCEV(getConstant(MaxEnd - MinStart) /* Delta */, 12007 getConstant(StrideForMaxBECount) /* Step */); 12008 } 12009 12010 ScalarEvolution::ExitLimit 12011 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 12012 const Loop *L, bool IsSigned, 12013 bool ControlsExit, bool AllowPredicates) { 12014 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 12015 12016 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 12017 bool PredicatedIV = false; 12018 12019 auto canAssumeNoSelfWrap = [&](const SCEVAddRecExpr *AR) { 12020 // Can we prove this loop *must* be UB if overflow of IV occurs? 12021 // Reasoning goes as follows: 12022 // * Suppose the IV did self wrap. 12023 // * If Stride evenly divides the iteration space, then once wrap 12024 // occurs, the loop must revisit the same values. 12025 // * We know that RHS is invariant, and that none of those values 12026 // caused this exit to be taken previously. Thus, this exit is 12027 // dynamically dead. 12028 // * If this is the sole exit, then a dead exit implies the loop 12029 // must be infinite if there are no abnormal exits. 12030 // * If the loop were infinite, then it must either not be mustprogress 12031 // or have side effects. Otherwise, it must be UB. 12032 // * It can't (by assumption), be UB so we have contradicted our 12033 // premise and can conclude the IV did not in fact self-wrap. 12034 if (!isLoopInvariant(RHS, L)) 12035 return false; 12036 12037 auto *StrideC = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)); 12038 if (!StrideC || !StrideC->getAPInt().isPowerOf2()) 12039 return false; 12040 12041 if (!ControlsExit || !loopHasNoAbnormalExits(L)) 12042 return false; 12043 12044 return loopIsFiniteByAssumption(L); 12045 }; 12046 12047 if (!IV) { 12048 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS)) { 12049 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(ZExt->getOperand()); 12050 if (AR && AR->getLoop() == L && AR->isAffine()) { 12051 auto canProveNUW = [&]() { 12052 if (!isLoopInvariant(RHS, L)) 12053 return false; 12054 12055 if (!isKnownNonZero(AR->getStepRecurrence(*this))) 12056 // We need the sequence defined by AR to strictly increase in the 12057 // unsigned integer domain for the logic below to hold. 12058 return false; 12059 12060 const unsigned InnerBitWidth = getTypeSizeInBits(AR->getType()); 12061 const unsigned OuterBitWidth = getTypeSizeInBits(RHS->getType()); 12062 // If RHS <=u Limit, then there must exist a value V in the sequence 12063 // defined by AR (e.g. {Start,+,Step}) such that V >u RHS, and 12064 // V <=u UINT_MAX. Thus, we must exit the loop before unsigned 12065 // overflow occurs. This limit also implies that a signed comparison 12066 // (in the wide bitwidth) is equivalent to an unsigned comparison as 12067 // the high bits on both sides must be zero. 12068 APInt StrideMax = getUnsignedRangeMax(AR->getStepRecurrence(*this)); 12069 APInt Limit = APInt::getMaxValue(InnerBitWidth) - (StrideMax - 1); 12070 Limit = Limit.zext(OuterBitWidth); 12071 return getUnsignedRangeMax(applyLoopGuards(RHS, L)).ule(Limit); 12072 }; 12073 auto Flags = AR->getNoWrapFlags(); 12074 if (!hasFlags(Flags, SCEV::FlagNUW) && canProveNUW()) 12075 Flags = setFlags(Flags, SCEV::FlagNUW); 12076 12077 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags); 12078 if (AR->hasNoUnsignedWrap()) { 12079 // Emulate what getZeroExtendExpr would have done during construction 12080 // if we'd been able to infer the fact just above at that time. 12081 const SCEV *Step = AR->getStepRecurrence(*this); 12082 Type *Ty = ZExt->getType(); 12083 auto *S = getAddRecExpr( 12084 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 0), 12085 getZeroExtendExpr(Step, Ty, 0), L, AR->getNoWrapFlags()); 12086 IV = dyn_cast<SCEVAddRecExpr>(S); 12087 } 12088 } 12089 } 12090 } 12091 12092 12093 if (!IV && AllowPredicates) { 12094 // Try to make this an AddRec using runtime tests, in the first X 12095 // iterations of this loop, where X is the SCEV expression found by the 12096 // algorithm below. 12097 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 12098 PredicatedIV = true; 12099 } 12100 12101 // Avoid weird loops 12102 if (!IV || IV->getLoop() != L || !IV->isAffine()) 12103 return getCouldNotCompute(); 12104 12105 // A precondition of this method is that the condition being analyzed 12106 // reaches an exiting branch which dominates the latch. Given that, we can 12107 // assume that an increment which violates the nowrap specification and 12108 // produces poison must cause undefined behavior when the resulting poison 12109 // value is branched upon and thus we can conclude that the backedge is 12110 // taken no more often than would be required to produce that poison value. 12111 // Note that a well defined loop can exit on the iteration which violates 12112 // the nowrap specification if there is another exit (either explicit or 12113 // implicit/exceptional) which causes the loop to execute before the 12114 // exiting instruction we're analyzing would trigger UB. 12115 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW; 12116 bool NoWrap = ControlsExit && IV->getNoWrapFlags(WrapType); 12117 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; 12118 12119 const SCEV *Stride = IV->getStepRecurrence(*this); 12120 12121 bool PositiveStride = isKnownPositive(Stride); 12122 12123 // Avoid negative or zero stride values. 12124 if (!PositiveStride) { 12125 // We can compute the correct backedge taken count for loops with unknown 12126 // strides if we can prove that the loop is not an infinite loop with side 12127 // effects. Here's the loop structure we are trying to handle - 12128 // 12129 // i = start 12130 // do { 12131 // A[i] = i; 12132 // i += s; 12133 // } while (i < end); 12134 // 12135 // The backedge taken count for such loops is evaluated as - 12136 // (max(end, start + stride) - start - 1) /u stride 12137 // 12138 // The additional preconditions that we need to check to prove correctness 12139 // of the above formula is as follows - 12140 // 12141 // a) IV is either nuw or nsw depending upon signedness (indicated by the 12142 // NoWrap flag). 12143 // b) the loop is guaranteed to be finite (e.g. is mustprogress and has 12144 // no side effects within the loop) 12145 // c) loop has a single static exit (with no abnormal exits) 12146 // 12147 // Precondition a) implies that if the stride is negative, this is a single 12148 // trip loop. The backedge taken count formula reduces to zero in this case. 12149 // 12150 // Precondition b) and c) combine to imply that if rhs is invariant in L, 12151 // then a zero stride means the backedge can't be taken without executing 12152 // undefined behavior. 12153 // 12154 // The positive stride case is the same as isKnownPositive(Stride) returning 12155 // true (original behavior of the function). 12156 // 12157 if (PredicatedIV || !NoWrap || !loopIsFiniteByAssumption(L) || 12158 !loopHasNoAbnormalExits(L)) 12159 return getCouldNotCompute(); 12160 12161 // This bailout is protecting the logic in computeMaxBECountForLT which 12162 // has not yet been sufficiently auditted or tested with negative strides. 12163 // We used to filter out all known-non-positive cases here, we're in the 12164 // process of being less restrictive bit by bit. 12165 if (IsSigned && isKnownNonPositive(Stride)) 12166 return getCouldNotCompute(); 12167 12168 if (!isKnownNonZero(Stride)) { 12169 // If we have a step of zero, and RHS isn't invariant in L, we don't know 12170 // if it might eventually be greater than start and if so, on which 12171 // iteration. We can't even produce a useful upper bound. 12172 if (!isLoopInvariant(RHS, L)) 12173 return getCouldNotCompute(); 12174 12175 // We allow a potentially zero stride, but we need to divide by stride 12176 // below. Since the loop can't be infinite and this check must control 12177 // the sole exit, we can infer the exit must be taken on the first 12178 // iteration (e.g. backedge count = 0) if the stride is zero. Given that, 12179 // we know the numerator in the divides below must be zero, so we can 12180 // pick an arbitrary non-zero value for the denominator (e.g. stride) 12181 // and produce the right result. 12182 // FIXME: Handle the case where Stride is poison? 12183 auto wouldZeroStrideBeUB = [&]() { 12184 // Proof by contradiction. Suppose the stride were zero. If we can 12185 // prove that the backedge *is* taken on the first iteration, then since 12186 // we know this condition controls the sole exit, we must have an 12187 // infinite loop. We can't have a (well defined) infinite loop per 12188 // check just above. 12189 // Note: The (Start - Stride) term is used to get the start' term from 12190 // (start' + stride,+,stride). Remember that we only care about the 12191 // result of this expression when stride == 0 at runtime. 12192 auto *StartIfZero = getMinusSCEV(IV->getStart(), Stride); 12193 return isLoopEntryGuardedByCond(L, Cond, StartIfZero, RHS); 12194 }; 12195 if (!wouldZeroStrideBeUB()) { 12196 Stride = getUMaxExpr(Stride, getOne(Stride->getType())); 12197 } 12198 } 12199 } else if (!Stride->isOne() && !NoWrap) { 12200 auto isUBOnWrap = [&]() { 12201 // From no-self-wrap, we need to then prove no-(un)signed-wrap. This 12202 // follows trivially from the fact that every (un)signed-wrapped, but 12203 // not self-wrapped value must be LT than the last value before 12204 // (un)signed wrap. Since we know that last value didn't exit, nor 12205 // will any smaller one. 12206 return canAssumeNoSelfWrap(IV); 12207 }; 12208 12209 // Avoid proven overflow cases: this will ensure that the backedge taken 12210 // count will not generate any unsigned overflow. Relaxed no-overflow 12211 // conditions exploit NoWrapFlags, allowing to optimize in presence of 12212 // undefined behaviors like the case of C language. 12213 if (canIVOverflowOnLT(RHS, Stride, IsSigned) && !isUBOnWrap()) 12214 return getCouldNotCompute(); 12215 } 12216 12217 // On all paths just preceeding, we established the following invariant: 12218 // IV can be assumed not to overflow up to and including the exiting 12219 // iteration. We proved this in one of two ways: 12220 // 1) We can show overflow doesn't occur before the exiting iteration 12221 // 1a) canIVOverflowOnLT, and b) step of one 12222 // 2) We can show that if overflow occurs, the loop must execute UB 12223 // before any possible exit. 12224 // Note that we have not yet proved RHS invariant (in general). 12225 12226 const SCEV *Start = IV->getStart(); 12227 12228 // Preserve pointer-typed Start/RHS to pass to isLoopEntryGuardedByCond. 12229 // If we convert to integers, isLoopEntryGuardedByCond will miss some cases. 12230 // Use integer-typed versions for actual computation; we can't subtract 12231 // pointers in general. 12232 const SCEV *OrigStart = Start; 12233 const SCEV *OrigRHS = RHS; 12234 if (Start->getType()->isPointerTy()) { 12235 Start = getLosslessPtrToIntExpr(Start); 12236 if (isa<SCEVCouldNotCompute>(Start)) 12237 return Start; 12238 } 12239 if (RHS->getType()->isPointerTy()) { 12240 RHS = getLosslessPtrToIntExpr(RHS); 12241 if (isa<SCEVCouldNotCompute>(RHS)) 12242 return RHS; 12243 } 12244 12245 // When the RHS is not invariant, we do not know the end bound of the loop and 12246 // cannot calculate the ExactBECount needed by ExitLimit. However, we can 12247 // calculate the MaxBECount, given the start, stride and max value for the end 12248 // bound of the loop (RHS), and the fact that IV does not overflow (which is 12249 // checked above). 12250 if (!isLoopInvariant(RHS, L)) { 12251 const SCEV *MaxBECount = computeMaxBECountForLT( 12252 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 12253 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount, 12254 false /*MaxOrZero*/, Predicates); 12255 } 12256 12257 // We use the expression (max(End,Start)-Start)/Stride to describe the 12258 // backedge count, as if the backedge is taken at least once max(End,Start) 12259 // is End and so the result is as above, and if not max(End,Start) is Start 12260 // so we get a backedge count of zero. 12261 const SCEV *BECount = nullptr; 12262 auto *OrigStartMinusStride = getMinusSCEV(OrigStart, Stride); 12263 assert(isAvailableAtLoopEntry(OrigStartMinusStride, L) && "Must be!"); 12264 assert(isAvailableAtLoopEntry(OrigStart, L) && "Must be!"); 12265 assert(isAvailableAtLoopEntry(OrigRHS, L) && "Must be!"); 12266 // Can we prove (max(RHS,Start) > Start - Stride? 12267 if (isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigStart) && 12268 isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigRHS)) { 12269 // In this case, we can use a refined formula for computing backedge taken 12270 // count. The general formula remains: 12271 // "End-Start /uceiling Stride" where "End = max(RHS,Start)" 12272 // We want to use the alternate formula: 12273 // "((End - 1) - (Start - Stride)) /u Stride" 12274 // Let's do a quick case analysis to show these are equivalent under 12275 // our precondition that max(RHS,Start) > Start - Stride. 12276 // * For RHS <= Start, the backedge-taken count must be zero. 12277 // "((End - 1) - (Start - Stride)) /u Stride" reduces to 12278 // "((Start - 1) - (Start - Stride)) /u Stride" which simplies to 12279 // "Stride - 1 /u Stride" which is indeed zero for all non-zero values 12280 // of Stride. For 0 stride, we've use umin(1,Stride) above, reducing 12281 // this to the stride of 1 case. 12282 // * For RHS >= Start, the backedge count must be "RHS-Start /uceil Stride". 12283 // "((End - 1) - (Start - Stride)) /u Stride" reduces to 12284 // "((RHS - 1) - (Start - Stride)) /u Stride" reassociates to 12285 // "((RHS - (Start - Stride) - 1) /u Stride". 12286 // Our preconditions trivially imply no overflow in that form. 12287 const SCEV *MinusOne = getMinusOne(Stride->getType()); 12288 const SCEV *Numerator = 12289 getMinusSCEV(getAddExpr(RHS, MinusOne), getMinusSCEV(Start, Stride)); 12290 BECount = getUDivExpr(Numerator, Stride); 12291 } 12292 12293 const SCEV *BECountIfBackedgeTaken = nullptr; 12294 if (!BECount) { 12295 auto canProveRHSGreaterThanEqualStart = [&]() { 12296 auto CondGE = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 12297 if (isLoopEntryGuardedByCond(L, CondGE, OrigRHS, OrigStart)) 12298 return true; 12299 12300 // (RHS > Start - 1) implies RHS >= Start. 12301 // * "RHS >= Start" is trivially equivalent to "RHS > Start - 1" if 12302 // "Start - 1" doesn't overflow. 12303 // * For signed comparison, if Start - 1 does overflow, it's equal 12304 // to INT_MAX, and "RHS >s INT_MAX" is trivially false. 12305 // * For unsigned comparison, if Start - 1 does overflow, it's equal 12306 // to UINT_MAX, and "RHS >u UINT_MAX" is trivially false. 12307 // 12308 // FIXME: Should isLoopEntryGuardedByCond do this for us? 12309 auto CondGT = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 12310 auto *StartMinusOne = getAddExpr(OrigStart, 12311 getMinusOne(OrigStart->getType())); 12312 return isLoopEntryGuardedByCond(L, CondGT, OrigRHS, StartMinusOne); 12313 }; 12314 12315 // If we know that RHS >= Start in the context of loop, then we know that 12316 // max(RHS, Start) = RHS at this point. 12317 const SCEV *End; 12318 if (canProveRHSGreaterThanEqualStart()) { 12319 End = RHS; 12320 } else { 12321 // If RHS < Start, the backedge will be taken zero times. So in 12322 // general, we can write the backedge-taken count as: 12323 // 12324 // RHS >= Start ? ceil(RHS - Start) / Stride : 0 12325 // 12326 // We convert it to the following to make it more convenient for SCEV: 12327 // 12328 // ceil(max(RHS, Start) - Start) / Stride 12329 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 12330 12331 // See what would happen if we assume the backedge is taken. This is 12332 // used to compute MaxBECount. 12333 BECountIfBackedgeTaken = getUDivCeilSCEV(getMinusSCEV(RHS, Start), Stride); 12334 } 12335 12336 // At this point, we know: 12337 // 12338 // 1. If IsSigned, Start <=s End; otherwise, Start <=u End 12339 // 2. The index variable doesn't overflow. 12340 // 12341 // Therefore, we know N exists such that 12342 // (Start + Stride * N) >= End, and computing "(Start + Stride * N)" 12343 // doesn't overflow. 12344 // 12345 // Using this information, try to prove whether the addition in 12346 // "(Start - End) + (Stride - 1)" has unsigned overflow. 12347 const SCEV *One = getOne(Stride->getType()); 12348 bool MayAddOverflow = [&] { 12349 if (auto *StrideC = dyn_cast<SCEVConstant>(Stride)) { 12350 if (StrideC->getAPInt().isPowerOf2()) { 12351 // Suppose Stride is a power of two, and Start/End are unsigned 12352 // integers. Let UMAX be the largest representable unsigned 12353 // integer. 12354 // 12355 // By the preconditions of this function, we know 12356 // "(Start + Stride * N) >= End", and this doesn't overflow. 12357 // As a formula: 12358 // 12359 // End <= (Start + Stride * N) <= UMAX 12360 // 12361 // Subtracting Start from all the terms: 12362 // 12363 // End - Start <= Stride * N <= UMAX - Start 12364 // 12365 // Since Start is unsigned, UMAX - Start <= UMAX. Therefore: 12366 // 12367 // End - Start <= Stride * N <= UMAX 12368 // 12369 // Stride * N is a multiple of Stride. Therefore, 12370 // 12371 // End - Start <= Stride * N <= UMAX - (UMAX mod Stride) 12372 // 12373 // Since Stride is a power of two, UMAX + 1 is divisible by Stride. 12374 // Therefore, UMAX mod Stride == Stride - 1. So we can write: 12375 // 12376 // End - Start <= Stride * N <= UMAX - Stride - 1 12377 // 12378 // Dropping the middle term: 12379 // 12380 // End - Start <= UMAX - Stride - 1 12381 // 12382 // Adding Stride - 1 to both sides: 12383 // 12384 // (End - Start) + (Stride - 1) <= UMAX 12385 // 12386 // In other words, the addition doesn't have unsigned overflow. 12387 // 12388 // A similar proof works if we treat Start/End as signed values. 12389 // Just rewrite steps before "End - Start <= Stride * N <= UMAX" to 12390 // use signed max instead of unsigned max. Note that we're trying 12391 // to prove a lack of unsigned overflow in either case. 12392 return false; 12393 } 12394 } 12395 if (Start == Stride || Start == getMinusSCEV(Stride, One)) { 12396 // If Start is equal to Stride, (End - Start) + (Stride - 1) == End - 1. 12397 // If !IsSigned, 0 <u Stride == Start <=u End; so 0 <u End - 1 <u End. 12398 // If IsSigned, 0 <s Stride == Start <=s End; so 0 <s End - 1 <s End. 12399 // 12400 // If Start is equal to Stride - 1, (End - Start) + Stride - 1 == End. 12401 return false; 12402 } 12403 return true; 12404 }(); 12405 12406 const SCEV *Delta = getMinusSCEV(End, Start); 12407 if (!MayAddOverflow) { 12408 // floor((D + (S - 1)) / S) 12409 // We prefer this formulation if it's legal because it's fewer operations. 12410 BECount = 12411 getUDivExpr(getAddExpr(Delta, getMinusSCEV(Stride, One)), Stride); 12412 } else { 12413 BECount = getUDivCeilSCEV(Delta, Stride); 12414 } 12415 } 12416 12417 const SCEV *MaxBECount; 12418 bool MaxOrZero = false; 12419 if (isa<SCEVConstant>(BECount)) { 12420 MaxBECount = BECount; 12421 } else if (BECountIfBackedgeTaken && 12422 isa<SCEVConstant>(BECountIfBackedgeTaken)) { 12423 // If we know exactly how many times the backedge will be taken if it's 12424 // taken at least once, then the backedge count will either be that or 12425 // zero. 12426 MaxBECount = BECountIfBackedgeTaken; 12427 MaxOrZero = true; 12428 } else { 12429 MaxBECount = computeMaxBECountForLT( 12430 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 12431 } 12432 12433 if (isa<SCEVCouldNotCompute>(MaxBECount) && 12434 !isa<SCEVCouldNotCompute>(BECount)) 12435 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 12436 12437 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 12438 } 12439 12440 ScalarEvolution::ExitLimit 12441 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 12442 const Loop *L, bool IsSigned, 12443 bool ControlsExit, bool AllowPredicates) { 12444 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 12445 // We handle only IV > Invariant 12446 if (!isLoopInvariant(RHS, L)) 12447 return getCouldNotCompute(); 12448 12449 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 12450 if (!IV && AllowPredicates) 12451 // Try to make this an AddRec using runtime tests, in the first X 12452 // iterations of this loop, where X is the SCEV expression found by the 12453 // algorithm below. 12454 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 12455 12456 // Avoid weird loops 12457 if (!IV || IV->getLoop() != L || !IV->isAffine()) 12458 return getCouldNotCompute(); 12459 12460 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW; 12461 bool NoWrap = ControlsExit && IV->getNoWrapFlags(WrapType); 12462 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 12463 12464 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 12465 12466 // Avoid negative or zero stride values 12467 if (!isKnownPositive(Stride)) 12468 return getCouldNotCompute(); 12469 12470 // Avoid proven overflow cases: this will ensure that the backedge taken count 12471 // will not generate any unsigned overflow. Relaxed no-overflow conditions 12472 // exploit NoWrapFlags, allowing to optimize in presence of undefined 12473 // behaviors like the case of C language. 12474 if (!Stride->isOne() && !NoWrap) 12475 if (canIVOverflowOnGT(RHS, Stride, IsSigned)) 12476 return getCouldNotCompute(); 12477 12478 const SCEV *Start = IV->getStart(); 12479 const SCEV *End = RHS; 12480 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) { 12481 // If we know that Start >= RHS in the context of loop, then we know that 12482 // min(RHS, Start) = RHS at this point. 12483 if (isLoopEntryGuardedByCond( 12484 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS)) 12485 End = RHS; 12486 else 12487 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 12488 } 12489 12490 if (Start->getType()->isPointerTy()) { 12491 Start = getLosslessPtrToIntExpr(Start); 12492 if (isa<SCEVCouldNotCompute>(Start)) 12493 return Start; 12494 } 12495 if (End->getType()->isPointerTy()) { 12496 End = getLosslessPtrToIntExpr(End); 12497 if (isa<SCEVCouldNotCompute>(End)) 12498 return End; 12499 } 12500 12501 // Compute ((Start - End) + (Stride - 1)) / Stride. 12502 // FIXME: This can overflow. Holding off on fixing this for now; 12503 // howManyGreaterThans will hopefully be gone soon. 12504 const SCEV *One = getOne(Stride->getType()); 12505 const SCEV *BECount = getUDivExpr( 12506 getAddExpr(getMinusSCEV(Start, End), getMinusSCEV(Stride, One)), Stride); 12507 12508 APInt MaxStart = IsSigned ? getSignedRangeMax(Start) 12509 : getUnsignedRangeMax(Start); 12510 12511 APInt MinStride = IsSigned ? getSignedRangeMin(Stride) 12512 : getUnsignedRangeMin(Stride); 12513 12514 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 12515 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 12516 : APInt::getMinValue(BitWidth) + (MinStride - 1); 12517 12518 // Although End can be a MIN expression we estimate MinEnd considering only 12519 // the case End = RHS. This is safe because in the other case (Start - End) 12520 // is zero, leading to a zero maximum backedge taken count. 12521 APInt MinEnd = 12522 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit) 12523 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit); 12524 12525 const SCEV *MaxBECount = isa<SCEVConstant>(BECount) 12526 ? BECount 12527 : getUDivCeilSCEV(getConstant(MaxStart - MinEnd), 12528 getConstant(MinStride)); 12529 12530 if (isa<SCEVCouldNotCompute>(MaxBECount)) 12531 MaxBECount = BECount; 12532 12533 return ExitLimit(BECount, MaxBECount, false, Predicates); 12534 } 12535 12536 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 12537 ScalarEvolution &SE) const { 12538 if (Range.isFullSet()) // Infinite loop. 12539 return SE.getCouldNotCompute(); 12540 12541 // If the start is a non-zero constant, shift the range to simplify things. 12542 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 12543 if (!SC->getValue()->isZero()) { 12544 SmallVector<const SCEV *, 4> Operands(operands()); 12545 Operands[0] = SE.getZero(SC->getType()); 12546 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 12547 getNoWrapFlags(FlagNW)); 12548 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 12549 return ShiftedAddRec->getNumIterationsInRange( 12550 Range.subtract(SC->getAPInt()), SE); 12551 // This is strange and shouldn't happen. 12552 return SE.getCouldNotCompute(); 12553 } 12554 12555 // The only time we can solve this is when we have all constant indices. 12556 // Otherwise, we cannot determine the overflow conditions. 12557 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 12558 return SE.getCouldNotCompute(); 12559 12560 // Okay at this point we know that all elements of the chrec are constants and 12561 // that the start element is zero. 12562 12563 // First check to see if the range contains zero. If not, the first 12564 // iteration exits. 12565 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 12566 if (!Range.contains(APInt(BitWidth, 0))) 12567 return SE.getZero(getType()); 12568 12569 if (isAffine()) { 12570 // If this is an affine expression then we have this situation: 12571 // Solve {0,+,A} in Range === Ax in Range 12572 12573 // We know that zero is in the range. If A is positive then we know that 12574 // the upper value of the range must be the first possible exit value. 12575 // If A is negative then the lower of the range is the last possible loop 12576 // value. Also note that we already checked for a full range. 12577 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 12578 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower(); 12579 12580 // The exit value should be (End+A)/A. 12581 APInt ExitVal = (End + A).udiv(A); 12582 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 12583 12584 // Evaluate at the exit value. If we really did fall out of the valid 12585 // range, then we computed our trip count, otherwise wrap around or other 12586 // things must have happened. 12587 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 12588 if (Range.contains(Val->getValue())) 12589 return SE.getCouldNotCompute(); // Something strange happened 12590 12591 // Ensure that the previous value is in the range. 12592 assert(Range.contains( 12593 EvaluateConstantChrecAtConstant(this, 12594 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && 12595 "Linear scev computation is off in a bad way!"); 12596 return SE.getConstant(ExitValue); 12597 } 12598 12599 if (isQuadratic()) { 12600 if (auto S = SolveQuadraticAddRecRange(this, Range, SE)) 12601 return SE.getConstant(S.getValue()); 12602 } 12603 12604 return SE.getCouldNotCompute(); 12605 } 12606 12607 const SCEVAddRecExpr * 12608 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const { 12609 assert(getNumOperands() > 1 && "AddRec with zero step?"); 12610 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)), 12611 // but in this case we cannot guarantee that the value returned will be an 12612 // AddRec because SCEV does not have a fixed point where it stops 12613 // simplification: it is legal to return ({rec1} + {rec2}). For example, it 12614 // may happen if we reach arithmetic depth limit while simplifying. So we 12615 // construct the returned value explicitly. 12616 SmallVector<const SCEV *, 3> Ops; 12617 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and 12618 // (this + Step) is {A+B,+,B+C,+...,+,N}. 12619 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i) 12620 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1))); 12621 // We know that the last operand is not a constant zero (otherwise it would 12622 // have been popped out earlier). This guarantees us that if the result has 12623 // the same last operand, then it will also not be popped out, meaning that 12624 // the returned value will be an AddRec. 12625 const SCEV *Last = getOperand(getNumOperands() - 1); 12626 assert(!Last->isZero() && "Recurrency with zero step?"); 12627 Ops.push_back(Last); 12628 return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(), 12629 SCEV::FlagAnyWrap)); 12630 } 12631 12632 // Return true when S contains at least an undef value. 12633 bool ScalarEvolution::containsUndefs(const SCEV *S) const { 12634 return SCEVExprContains(S, [](const SCEV *S) { 12635 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 12636 return isa<UndefValue>(SU->getValue()); 12637 return false; 12638 }); 12639 } 12640 12641 /// Return the size of an element read or written by Inst. 12642 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 12643 Type *Ty; 12644 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 12645 Ty = Store->getValueOperand()->getType(); 12646 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 12647 Ty = Load->getType(); 12648 else 12649 return nullptr; 12650 12651 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 12652 return getSizeOfExpr(ETy, Ty); 12653 } 12654 12655 //===----------------------------------------------------------------------===// 12656 // SCEVCallbackVH Class Implementation 12657 //===----------------------------------------------------------------------===// 12658 12659 void ScalarEvolution::SCEVCallbackVH::deleted() { 12660 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 12661 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 12662 SE->ConstantEvolutionLoopExitValue.erase(PN); 12663 SE->eraseValueFromMap(getValPtr()); 12664 // this now dangles! 12665 } 12666 12667 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 12668 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 12669 12670 // Forget all the expressions associated with users of the old value, 12671 // so that future queries will recompute the expressions using the new 12672 // value. 12673 Value *Old = getValPtr(); 12674 SmallVector<User *, 16> Worklist(Old->users()); 12675 SmallPtrSet<User *, 8> Visited; 12676 while (!Worklist.empty()) { 12677 User *U = Worklist.pop_back_val(); 12678 // Deleting the Old value will cause this to dangle. Postpone 12679 // that until everything else is done. 12680 if (U == Old) 12681 continue; 12682 if (!Visited.insert(U).second) 12683 continue; 12684 if (PHINode *PN = dyn_cast<PHINode>(U)) 12685 SE->ConstantEvolutionLoopExitValue.erase(PN); 12686 SE->eraseValueFromMap(U); 12687 llvm::append_range(Worklist, U->users()); 12688 } 12689 // Delete the Old value. 12690 if (PHINode *PN = dyn_cast<PHINode>(Old)) 12691 SE->ConstantEvolutionLoopExitValue.erase(PN); 12692 SE->eraseValueFromMap(Old); 12693 // this now dangles! 12694 } 12695 12696 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 12697 : CallbackVH(V), SE(se) {} 12698 12699 //===----------------------------------------------------------------------===// 12700 // ScalarEvolution Class Implementation 12701 //===----------------------------------------------------------------------===// 12702 12703 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 12704 AssumptionCache &AC, DominatorTree &DT, 12705 LoopInfo &LI) 12706 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 12707 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64), 12708 LoopDispositions(64), BlockDispositions(64) { 12709 // To use guards for proving predicates, we need to scan every instruction in 12710 // relevant basic blocks, and not just terminators. Doing this is a waste of 12711 // time if the IR does not actually contain any calls to 12712 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 12713 // 12714 // This pessimizes the case where a pass that preserves ScalarEvolution wants 12715 // to _add_ guards to the module when there weren't any before, and wants 12716 // ScalarEvolution to optimize based on those guards. For now we prefer to be 12717 // efficient in lieu of being smart in that rather obscure case. 12718 12719 auto *GuardDecl = F.getParent()->getFunction( 12720 Intrinsic::getName(Intrinsic::experimental_guard)); 12721 HasGuards = GuardDecl && !GuardDecl->use_empty(); 12722 } 12723 12724 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 12725 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 12726 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 12727 ValueExprMap(std::move(Arg.ValueExprMap)), 12728 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 12729 PendingPhiRanges(std::move(Arg.PendingPhiRanges)), 12730 PendingMerges(std::move(Arg.PendingMerges)), 12731 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)), 12732 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 12733 PredicatedBackedgeTakenCounts( 12734 std::move(Arg.PredicatedBackedgeTakenCounts)), 12735 BECountUsers(std::move(Arg.BECountUsers)), 12736 ConstantEvolutionLoopExitValue( 12737 std::move(Arg.ConstantEvolutionLoopExitValue)), 12738 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 12739 ValuesAtScopesUsers(std::move(Arg.ValuesAtScopesUsers)), 12740 LoopDispositions(std::move(Arg.LoopDispositions)), 12741 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 12742 BlockDispositions(std::move(Arg.BlockDispositions)), 12743 SCEVUsers(std::move(Arg.SCEVUsers)), 12744 UnsignedRanges(std::move(Arg.UnsignedRanges)), 12745 SignedRanges(std::move(Arg.SignedRanges)), 12746 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 12747 UniquePreds(std::move(Arg.UniquePreds)), 12748 SCEVAllocator(std::move(Arg.SCEVAllocator)), 12749 LoopUsers(std::move(Arg.LoopUsers)), 12750 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)), 12751 FirstUnknown(Arg.FirstUnknown) { 12752 Arg.FirstUnknown = nullptr; 12753 } 12754 12755 ScalarEvolution::~ScalarEvolution() { 12756 // Iterate through all the SCEVUnknown instances and call their 12757 // destructors, so that they release their references to their values. 12758 for (SCEVUnknown *U = FirstUnknown; U;) { 12759 SCEVUnknown *Tmp = U; 12760 U = U->Next; 12761 Tmp->~SCEVUnknown(); 12762 } 12763 FirstUnknown = nullptr; 12764 12765 ExprValueMap.clear(); 12766 ValueExprMap.clear(); 12767 HasRecMap.clear(); 12768 BackedgeTakenCounts.clear(); 12769 PredicatedBackedgeTakenCounts.clear(); 12770 12771 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 12772 assert(PendingPhiRanges.empty() && "getRangeRef garbage"); 12773 assert(PendingMerges.empty() && "isImpliedViaMerge garbage"); 12774 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 12775 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 12776 } 12777 12778 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 12779 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 12780 } 12781 12782 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 12783 const Loop *L) { 12784 // Print all inner loops first 12785 for (Loop *I : *L) 12786 PrintLoopInfo(OS, SE, I); 12787 12788 OS << "Loop "; 12789 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12790 OS << ": "; 12791 12792 SmallVector<BasicBlock *, 8> ExitingBlocks; 12793 L->getExitingBlocks(ExitingBlocks); 12794 if (ExitingBlocks.size() != 1) 12795 OS << "<multiple exits> "; 12796 12797 if (SE->hasLoopInvariantBackedgeTakenCount(L)) 12798 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n"; 12799 else 12800 OS << "Unpredictable backedge-taken count.\n"; 12801 12802 if (ExitingBlocks.size() > 1) 12803 for (BasicBlock *ExitingBlock : ExitingBlocks) { 12804 OS << " exit count for " << ExitingBlock->getName() << ": " 12805 << *SE->getExitCount(L, ExitingBlock) << "\n"; 12806 } 12807 12808 OS << "Loop "; 12809 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12810 OS << ": "; 12811 12812 if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) { 12813 OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L); 12814 if (SE->isBackedgeTakenCountMaxOrZero(L)) 12815 OS << ", actual taken count either this or zero."; 12816 } else { 12817 OS << "Unpredictable max backedge-taken count. "; 12818 } 12819 12820 OS << "\n" 12821 "Loop "; 12822 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12823 OS << ": "; 12824 12825 SmallVector<const SCEVPredicate *, 4> Preds; 12826 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Preds); 12827 if (!isa<SCEVCouldNotCompute>(PBT)) { 12828 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 12829 OS << " Predicates:\n"; 12830 SCEVUnionPredicate Dedup(Preds); 12831 Dedup.print(OS, 4); 12832 } else { 12833 OS << "Unpredictable predicated backedge-taken count. "; 12834 } 12835 OS << "\n"; 12836 12837 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 12838 OS << "Loop "; 12839 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12840 OS << ": "; 12841 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n"; 12842 } 12843 } 12844 12845 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 12846 switch (LD) { 12847 case ScalarEvolution::LoopVariant: 12848 return "Variant"; 12849 case ScalarEvolution::LoopInvariant: 12850 return "Invariant"; 12851 case ScalarEvolution::LoopComputable: 12852 return "Computable"; 12853 } 12854 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 12855 } 12856 12857 void ScalarEvolution::print(raw_ostream &OS) const { 12858 // ScalarEvolution's implementation of the print method is to print 12859 // out SCEV values of all instructions that are interesting. Doing 12860 // this potentially causes it to create new SCEV objects though, 12861 // which technically conflicts with the const qualifier. This isn't 12862 // observable from outside the class though, so casting away the 12863 // const isn't dangerous. 12864 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 12865 12866 if (ClassifyExpressions) { 12867 OS << "Classifying expressions for: "; 12868 F.printAsOperand(OS, /*PrintType=*/false); 12869 OS << "\n"; 12870 for (Instruction &I : instructions(F)) 12871 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 12872 OS << I << '\n'; 12873 OS << " --> "; 12874 const SCEV *SV = SE.getSCEV(&I); 12875 SV->print(OS); 12876 if (!isa<SCEVCouldNotCompute>(SV)) { 12877 OS << " U: "; 12878 SE.getUnsignedRange(SV).print(OS); 12879 OS << " S: "; 12880 SE.getSignedRange(SV).print(OS); 12881 } 12882 12883 const Loop *L = LI.getLoopFor(I.getParent()); 12884 12885 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 12886 if (AtUse != SV) { 12887 OS << " --> "; 12888 AtUse->print(OS); 12889 if (!isa<SCEVCouldNotCompute>(AtUse)) { 12890 OS << " U: "; 12891 SE.getUnsignedRange(AtUse).print(OS); 12892 OS << " S: "; 12893 SE.getSignedRange(AtUse).print(OS); 12894 } 12895 } 12896 12897 if (L) { 12898 OS << "\t\t" "Exits: "; 12899 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 12900 if (!SE.isLoopInvariant(ExitValue, L)) { 12901 OS << "<<Unknown>>"; 12902 } else { 12903 OS << *ExitValue; 12904 } 12905 12906 bool First = true; 12907 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 12908 if (First) { 12909 OS << "\t\t" "LoopDispositions: { "; 12910 First = false; 12911 } else { 12912 OS << ", "; 12913 } 12914 12915 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12916 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 12917 } 12918 12919 for (auto *InnerL : depth_first(L)) { 12920 if (InnerL == L) 12921 continue; 12922 if (First) { 12923 OS << "\t\t" "LoopDispositions: { "; 12924 First = false; 12925 } else { 12926 OS << ", "; 12927 } 12928 12929 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12930 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 12931 } 12932 12933 OS << " }"; 12934 } 12935 12936 OS << "\n"; 12937 } 12938 } 12939 12940 OS << "Determining loop execution counts for: "; 12941 F.printAsOperand(OS, /*PrintType=*/false); 12942 OS << "\n"; 12943 for (Loop *I : LI) 12944 PrintLoopInfo(OS, &SE, I); 12945 } 12946 12947 ScalarEvolution::LoopDisposition 12948 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 12949 auto &Values = LoopDispositions[S]; 12950 for (auto &V : Values) { 12951 if (V.getPointer() == L) 12952 return V.getInt(); 12953 } 12954 Values.emplace_back(L, LoopVariant); 12955 LoopDisposition D = computeLoopDisposition(S, L); 12956 auto &Values2 = LoopDispositions[S]; 12957 for (auto &V : llvm::reverse(Values2)) { 12958 if (V.getPointer() == L) { 12959 V.setInt(D); 12960 break; 12961 } 12962 } 12963 return D; 12964 } 12965 12966 ScalarEvolution::LoopDisposition 12967 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 12968 switch (S->getSCEVType()) { 12969 case scConstant: 12970 return LoopInvariant; 12971 case scPtrToInt: 12972 case scTruncate: 12973 case scZeroExtend: 12974 case scSignExtend: 12975 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 12976 case scAddRecExpr: { 12977 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 12978 12979 // If L is the addrec's loop, it's computable. 12980 if (AR->getLoop() == L) 12981 return LoopComputable; 12982 12983 // Add recurrences are never invariant in the function-body (null loop). 12984 if (!L) 12985 return LoopVariant; 12986 12987 // Everything that is not defined at loop entry is variant. 12988 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) 12989 return LoopVariant; 12990 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not" 12991 " dominate the contained loop's header?"); 12992 12993 // This recurrence is invariant w.r.t. L if AR's loop contains L. 12994 if (AR->getLoop()->contains(L)) 12995 return LoopInvariant; 12996 12997 // This recurrence is variant w.r.t. L if any of its operands 12998 // are variant. 12999 for (auto *Op : AR->operands()) 13000 if (!isLoopInvariant(Op, L)) 13001 return LoopVariant; 13002 13003 // Otherwise it's loop-invariant. 13004 return LoopInvariant; 13005 } 13006 case scAddExpr: 13007 case scMulExpr: 13008 case scUMaxExpr: 13009 case scSMaxExpr: 13010 case scUMinExpr: 13011 case scSMinExpr: 13012 case scSequentialUMinExpr: { 13013 bool HasVarying = false; 13014 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 13015 LoopDisposition D = getLoopDisposition(Op, L); 13016 if (D == LoopVariant) 13017 return LoopVariant; 13018 if (D == LoopComputable) 13019 HasVarying = true; 13020 } 13021 return HasVarying ? LoopComputable : LoopInvariant; 13022 } 13023 case scUDivExpr: { 13024 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 13025 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 13026 if (LD == LoopVariant) 13027 return LoopVariant; 13028 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 13029 if (RD == LoopVariant) 13030 return LoopVariant; 13031 return (LD == LoopInvariant && RD == LoopInvariant) ? 13032 LoopInvariant : LoopComputable; 13033 } 13034 case scUnknown: 13035 // All non-instruction values are loop invariant. All instructions are loop 13036 // invariant if they are not contained in the specified loop. 13037 // Instructions are never considered invariant in the function body 13038 // (null loop) because they are defined within the "loop". 13039 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 13040 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 13041 return LoopInvariant; 13042 case scCouldNotCompute: 13043 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 13044 } 13045 llvm_unreachable("Unknown SCEV kind!"); 13046 } 13047 13048 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 13049 return getLoopDisposition(S, L) == LoopInvariant; 13050 } 13051 13052 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 13053 return getLoopDisposition(S, L) == LoopComputable; 13054 } 13055 13056 ScalarEvolution::BlockDisposition 13057 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 13058 auto &Values = BlockDispositions[S]; 13059 for (auto &V : Values) { 13060 if (V.getPointer() == BB) 13061 return V.getInt(); 13062 } 13063 Values.emplace_back(BB, DoesNotDominateBlock); 13064 BlockDisposition D = computeBlockDisposition(S, BB); 13065 auto &Values2 = BlockDispositions[S]; 13066 for (auto &V : llvm::reverse(Values2)) { 13067 if (V.getPointer() == BB) { 13068 V.setInt(D); 13069 break; 13070 } 13071 } 13072 return D; 13073 } 13074 13075 ScalarEvolution::BlockDisposition 13076 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 13077 switch (S->getSCEVType()) { 13078 case scConstant: 13079 return ProperlyDominatesBlock; 13080 case scPtrToInt: 13081 case scTruncate: 13082 case scZeroExtend: 13083 case scSignExtend: 13084 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 13085 case scAddRecExpr: { 13086 // This uses a "dominates" query instead of "properly dominates" query 13087 // to test for proper dominance too, because the instruction which 13088 // produces the addrec's value is a PHI, and a PHI effectively properly 13089 // dominates its entire containing block. 13090 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 13091 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 13092 return DoesNotDominateBlock; 13093 13094 // Fall through into SCEVNAryExpr handling. 13095 LLVM_FALLTHROUGH; 13096 } 13097 case scAddExpr: 13098 case scMulExpr: 13099 case scUMaxExpr: 13100 case scSMaxExpr: 13101 case scUMinExpr: 13102 case scSMinExpr: 13103 case scSequentialUMinExpr: { 13104 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 13105 bool Proper = true; 13106 for (const SCEV *NAryOp : NAry->operands()) { 13107 BlockDisposition D = getBlockDisposition(NAryOp, BB); 13108 if (D == DoesNotDominateBlock) 13109 return DoesNotDominateBlock; 13110 if (D == DominatesBlock) 13111 Proper = false; 13112 } 13113 return Proper ? ProperlyDominatesBlock : DominatesBlock; 13114 } 13115 case scUDivExpr: { 13116 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 13117 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 13118 BlockDisposition LD = getBlockDisposition(LHS, BB); 13119 if (LD == DoesNotDominateBlock) 13120 return DoesNotDominateBlock; 13121 BlockDisposition RD = getBlockDisposition(RHS, BB); 13122 if (RD == DoesNotDominateBlock) 13123 return DoesNotDominateBlock; 13124 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 13125 ProperlyDominatesBlock : DominatesBlock; 13126 } 13127 case scUnknown: 13128 if (Instruction *I = 13129 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 13130 if (I->getParent() == BB) 13131 return DominatesBlock; 13132 if (DT.properlyDominates(I->getParent(), BB)) 13133 return ProperlyDominatesBlock; 13134 return DoesNotDominateBlock; 13135 } 13136 return ProperlyDominatesBlock; 13137 case scCouldNotCompute: 13138 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 13139 } 13140 llvm_unreachable("Unknown SCEV kind!"); 13141 } 13142 13143 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 13144 return getBlockDisposition(S, BB) >= DominatesBlock; 13145 } 13146 13147 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 13148 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 13149 } 13150 13151 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 13152 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); 13153 } 13154 13155 void ScalarEvolution::forgetBackedgeTakenCounts(const Loop *L, 13156 bool Predicated) { 13157 auto &BECounts = 13158 Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts; 13159 auto It = BECounts.find(L); 13160 if (It != BECounts.end()) { 13161 for (const ExitNotTakenInfo &ENT : It->second.ExitNotTaken) { 13162 if (!isa<SCEVConstant>(ENT.ExactNotTaken)) { 13163 auto UserIt = BECountUsers.find(ENT.ExactNotTaken); 13164 assert(UserIt != BECountUsers.end()); 13165 UserIt->second.erase({L, Predicated}); 13166 } 13167 } 13168 BECounts.erase(It); 13169 } 13170 } 13171 13172 void ScalarEvolution::forgetMemoizedResults(ArrayRef<const SCEV *> SCEVs) { 13173 SmallPtrSet<const SCEV *, 8> ToForget(SCEVs.begin(), SCEVs.end()); 13174 SmallVector<const SCEV *, 8> Worklist(ToForget.begin(), ToForget.end()); 13175 13176 while (!Worklist.empty()) { 13177 const SCEV *Curr = Worklist.pop_back_val(); 13178 auto Users = SCEVUsers.find(Curr); 13179 if (Users != SCEVUsers.end()) 13180 for (auto *User : Users->second) 13181 if (ToForget.insert(User).second) 13182 Worklist.push_back(User); 13183 } 13184 13185 for (auto *S : ToForget) 13186 forgetMemoizedResultsImpl(S); 13187 13188 for (auto I = PredicatedSCEVRewrites.begin(); 13189 I != PredicatedSCEVRewrites.end();) { 13190 std::pair<const SCEV *, const Loop *> Entry = I->first; 13191 if (ToForget.count(Entry.first)) 13192 PredicatedSCEVRewrites.erase(I++); 13193 else 13194 ++I; 13195 } 13196 } 13197 13198 void ScalarEvolution::forgetMemoizedResultsImpl(const SCEV *S) { 13199 LoopDispositions.erase(S); 13200 BlockDispositions.erase(S); 13201 UnsignedRanges.erase(S); 13202 SignedRanges.erase(S); 13203 HasRecMap.erase(S); 13204 MinTrailingZerosCache.erase(S); 13205 13206 auto ExprIt = ExprValueMap.find(S); 13207 if (ExprIt != ExprValueMap.end()) { 13208 for (auto &ValueAndOffset : ExprIt->second) { 13209 if (ValueAndOffset.second == nullptr) { 13210 auto ValueIt = ValueExprMap.find_as(ValueAndOffset.first); 13211 if (ValueIt != ValueExprMap.end()) 13212 ValueExprMap.erase(ValueIt); 13213 } 13214 } 13215 ExprValueMap.erase(ExprIt); 13216 } 13217 13218 auto ScopeIt = ValuesAtScopes.find(S); 13219 if (ScopeIt != ValuesAtScopes.end()) { 13220 for (const auto &Pair : ScopeIt->second) 13221 if (!isa_and_nonnull<SCEVConstant>(Pair.second)) 13222 erase_value(ValuesAtScopesUsers[Pair.second], 13223 std::make_pair(Pair.first, S)); 13224 ValuesAtScopes.erase(ScopeIt); 13225 } 13226 13227 auto ScopeUserIt = ValuesAtScopesUsers.find(S); 13228 if (ScopeUserIt != ValuesAtScopesUsers.end()) { 13229 for (const auto &Pair : ScopeUserIt->second) 13230 erase_value(ValuesAtScopes[Pair.second], std::make_pair(Pair.first, S)); 13231 ValuesAtScopesUsers.erase(ScopeUserIt); 13232 } 13233 13234 auto BEUsersIt = BECountUsers.find(S); 13235 if (BEUsersIt != BECountUsers.end()) { 13236 // Work on a copy, as forgetBackedgeTakenCounts() will modify the original. 13237 auto Copy = BEUsersIt->second; 13238 for (const auto &Pair : Copy) 13239 forgetBackedgeTakenCounts(Pair.getPointer(), Pair.getInt()); 13240 BECountUsers.erase(BEUsersIt); 13241 } 13242 } 13243 13244 void 13245 ScalarEvolution::getUsedLoops(const SCEV *S, 13246 SmallPtrSetImpl<const Loop *> &LoopsUsed) { 13247 struct FindUsedLoops { 13248 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed) 13249 : LoopsUsed(LoopsUsed) {} 13250 SmallPtrSetImpl<const Loop *> &LoopsUsed; 13251 bool follow(const SCEV *S) { 13252 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) 13253 LoopsUsed.insert(AR->getLoop()); 13254 return true; 13255 } 13256 13257 bool isDone() const { return false; } 13258 }; 13259 13260 FindUsedLoops F(LoopsUsed); 13261 SCEVTraversal<FindUsedLoops>(F).visitAll(S); 13262 } 13263 13264 void ScalarEvolution::verify() const { 13265 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 13266 ScalarEvolution SE2(F, TLI, AC, DT, LI); 13267 13268 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end()); 13269 13270 // Map's SCEV expressions from one ScalarEvolution "universe" to another. 13271 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> { 13272 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {} 13273 13274 const SCEV *visitConstant(const SCEVConstant *Constant) { 13275 return SE.getConstant(Constant->getAPInt()); 13276 } 13277 13278 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 13279 return SE.getUnknown(Expr->getValue()); 13280 } 13281 13282 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { 13283 return SE.getCouldNotCompute(); 13284 } 13285 }; 13286 13287 SCEVMapper SCM(SE2); 13288 13289 while (!LoopStack.empty()) { 13290 auto *L = LoopStack.pop_back_val(); 13291 llvm::append_range(LoopStack, *L); 13292 13293 auto *CurBECount = SCM.visit( 13294 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L)); 13295 auto *NewBECount = SE2.getBackedgeTakenCount(L); 13296 13297 if (CurBECount == SE2.getCouldNotCompute() || 13298 NewBECount == SE2.getCouldNotCompute()) { 13299 // NB! This situation is legal, but is very suspicious -- whatever pass 13300 // change the loop to make a trip count go from could not compute to 13301 // computable or vice-versa *should have* invalidated SCEV. However, we 13302 // choose not to assert here (for now) since we don't want false 13303 // positives. 13304 continue; 13305 } 13306 13307 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) { 13308 // SCEV treats "undef" as an unknown but consistent value (i.e. it does 13309 // not propagate undef aggressively). This means we can (and do) fail 13310 // verification in cases where a transform makes the trip count of a loop 13311 // go from "undef" to "undef+1" (say). The transform is fine, since in 13312 // both cases the loop iterates "undef" times, but SCEV thinks we 13313 // increased the trip count of the loop by 1 incorrectly. 13314 continue; 13315 } 13316 13317 if (SE.getTypeSizeInBits(CurBECount->getType()) > 13318 SE.getTypeSizeInBits(NewBECount->getType())) 13319 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType()); 13320 else if (SE.getTypeSizeInBits(CurBECount->getType()) < 13321 SE.getTypeSizeInBits(NewBECount->getType())) 13322 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType()); 13323 13324 const SCEV *Delta = SE2.getMinusSCEV(CurBECount, NewBECount); 13325 13326 // Unless VerifySCEVStrict is set, we only compare constant deltas. 13327 if ((VerifySCEVStrict || isa<SCEVConstant>(Delta)) && !Delta->isZero()) { 13328 dbgs() << "Trip Count for " << *L << " Changed!\n"; 13329 dbgs() << "Old: " << *CurBECount << "\n"; 13330 dbgs() << "New: " << *NewBECount << "\n"; 13331 dbgs() << "Delta: " << *Delta << "\n"; 13332 std::abort(); 13333 } 13334 } 13335 13336 // Collect all valid loops currently in LoopInfo. 13337 SmallPtrSet<Loop *, 32> ValidLoops; 13338 SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end()); 13339 while (!Worklist.empty()) { 13340 Loop *L = Worklist.pop_back_val(); 13341 if (ValidLoops.contains(L)) 13342 continue; 13343 ValidLoops.insert(L); 13344 Worklist.append(L->begin(), L->end()); 13345 } 13346 for (auto &KV : ValueExprMap) { 13347 #ifndef NDEBUG 13348 // Check for SCEV expressions referencing invalid/deleted loops. 13349 if (auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second)) { 13350 assert(ValidLoops.contains(AR->getLoop()) && 13351 "AddRec references invalid loop"); 13352 } 13353 #endif 13354 13355 // Check that the value is also part of the reverse map. 13356 auto It = ExprValueMap.find(KV.second); 13357 if (It == ExprValueMap.end() || !It->second.contains({KV.first, nullptr})) { 13358 dbgs() << "Value " << *KV.first 13359 << " is in ValueExprMap but not in ExprValueMap\n"; 13360 std::abort(); 13361 } 13362 } 13363 13364 for (const auto &KV : ExprValueMap) { 13365 for (const auto &ValueAndOffset : KV.second) { 13366 if (ValueAndOffset.second != nullptr) 13367 continue; 13368 13369 auto It = ValueExprMap.find_as(ValueAndOffset.first); 13370 if (It == ValueExprMap.end()) { 13371 dbgs() << "Value " << *ValueAndOffset.first 13372 << " is in ExprValueMap but not in ValueExprMap\n"; 13373 std::abort(); 13374 } 13375 if (It->second != KV.first) { 13376 dbgs() << "Value " << *ValueAndOffset.first 13377 << " mapped to " << *It->second 13378 << " rather than " << *KV.first << "\n"; 13379 std::abort(); 13380 } 13381 } 13382 } 13383 13384 // Verify integrity of SCEV users. 13385 for (const auto &S : UniqueSCEVs) { 13386 SmallVector<const SCEV *, 4> Ops; 13387 collectUniqueOps(&S, Ops); 13388 for (const auto *Op : Ops) { 13389 // We do not store dependencies of constants. 13390 if (isa<SCEVConstant>(Op)) 13391 continue; 13392 auto It = SCEVUsers.find(Op); 13393 if (It != SCEVUsers.end() && It->second.count(&S)) 13394 continue; 13395 dbgs() << "Use of operand " << *Op << " by user " << S 13396 << " is not being tracked!\n"; 13397 std::abort(); 13398 } 13399 } 13400 13401 // Verify integrity of ValuesAtScopes users. 13402 for (const auto &ValueAndVec : ValuesAtScopes) { 13403 const SCEV *Value = ValueAndVec.first; 13404 for (const auto &LoopAndValueAtScope : ValueAndVec.second) { 13405 const Loop *L = LoopAndValueAtScope.first; 13406 const SCEV *ValueAtScope = LoopAndValueAtScope.second; 13407 if (!isa<SCEVConstant>(ValueAtScope)) { 13408 auto It = ValuesAtScopesUsers.find(ValueAtScope); 13409 if (It != ValuesAtScopesUsers.end() && 13410 is_contained(It->second, std::make_pair(L, Value))) 13411 continue; 13412 dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: " 13413 << *ValueAtScope << " missing in ValuesAtScopesUsers\n"; 13414 std::abort(); 13415 } 13416 } 13417 } 13418 13419 for (const auto &ValueAtScopeAndVec : ValuesAtScopesUsers) { 13420 const SCEV *ValueAtScope = ValueAtScopeAndVec.first; 13421 for (const auto &LoopAndValue : ValueAtScopeAndVec.second) { 13422 const Loop *L = LoopAndValue.first; 13423 const SCEV *Value = LoopAndValue.second; 13424 assert(!isa<SCEVConstant>(Value)); 13425 auto It = ValuesAtScopes.find(Value); 13426 if (It != ValuesAtScopes.end() && 13427 is_contained(It->second, std::make_pair(L, ValueAtScope))) 13428 continue; 13429 dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: " 13430 << *ValueAtScope << " missing in ValuesAtScopes\n"; 13431 std::abort(); 13432 } 13433 } 13434 13435 // Verify integrity of BECountUsers. 13436 auto VerifyBECountUsers = [&](bool Predicated) { 13437 auto &BECounts = 13438 Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts; 13439 for (const auto &LoopAndBEInfo : BECounts) { 13440 for (const ExitNotTakenInfo &ENT : LoopAndBEInfo.second.ExitNotTaken) { 13441 if (!isa<SCEVConstant>(ENT.ExactNotTaken)) { 13442 auto UserIt = BECountUsers.find(ENT.ExactNotTaken); 13443 if (UserIt != BECountUsers.end() && 13444 UserIt->second.contains({ LoopAndBEInfo.first, Predicated })) 13445 continue; 13446 dbgs() << "Value " << *ENT.ExactNotTaken << " for loop " 13447 << *LoopAndBEInfo.first << " missing from BECountUsers\n"; 13448 std::abort(); 13449 } 13450 } 13451 } 13452 }; 13453 VerifyBECountUsers(/* Predicated */ false); 13454 VerifyBECountUsers(/* Predicated */ true); 13455 } 13456 13457 bool ScalarEvolution::invalidate( 13458 Function &F, const PreservedAnalyses &PA, 13459 FunctionAnalysisManager::Invalidator &Inv) { 13460 // Invalidate the ScalarEvolution object whenever it isn't preserved or one 13461 // of its dependencies is invalidated. 13462 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>(); 13463 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || 13464 Inv.invalidate<AssumptionAnalysis>(F, PA) || 13465 Inv.invalidate<DominatorTreeAnalysis>(F, PA) || 13466 Inv.invalidate<LoopAnalysis>(F, PA); 13467 } 13468 13469 AnalysisKey ScalarEvolutionAnalysis::Key; 13470 13471 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 13472 FunctionAnalysisManager &AM) { 13473 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 13474 AM.getResult<AssumptionAnalysis>(F), 13475 AM.getResult<DominatorTreeAnalysis>(F), 13476 AM.getResult<LoopAnalysis>(F)); 13477 } 13478 13479 PreservedAnalyses 13480 ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) { 13481 AM.getResult<ScalarEvolutionAnalysis>(F).verify(); 13482 return PreservedAnalyses::all(); 13483 } 13484 13485 PreservedAnalyses 13486 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 13487 // For compatibility with opt's -analyze feature under legacy pass manager 13488 // which was not ported to NPM. This keeps tests using 13489 // update_analyze_test_checks.py working. 13490 OS << "Printing analysis 'Scalar Evolution Analysis' for function '" 13491 << F.getName() << "':\n"; 13492 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 13493 return PreservedAnalyses::all(); 13494 } 13495 13496 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 13497 "Scalar Evolution Analysis", false, true) 13498 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 13499 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 13500 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 13501 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 13502 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 13503 "Scalar Evolution Analysis", false, true) 13504 13505 char ScalarEvolutionWrapperPass::ID = 0; 13506 13507 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 13508 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 13509 } 13510 13511 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 13512 SE.reset(new ScalarEvolution( 13513 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F), 13514 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 13515 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 13516 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 13517 return false; 13518 } 13519 13520 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 13521 13522 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 13523 SE->print(OS); 13524 } 13525 13526 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 13527 if (!VerifySCEV) 13528 return; 13529 13530 SE->verify(); 13531 } 13532 13533 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 13534 AU.setPreservesAll(); 13535 AU.addRequiredTransitive<AssumptionCacheTracker>(); 13536 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 13537 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 13538 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 13539 } 13540 13541 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS, 13542 const SCEV *RHS) { 13543 return getComparePredicate(ICmpInst::ICMP_EQ, LHS, RHS); 13544 } 13545 13546 const SCEVPredicate * 13547 ScalarEvolution::getComparePredicate(const ICmpInst::Predicate Pred, 13548 const SCEV *LHS, const SCEV *RHS) { 13549 FoldingSetNodeID ID; 13550 assert(LHS->getType() == RHS->getType() && 13551 "Type mismatch between LHS and RHS"); 13552 // Unique this node based on the arguments 13553 ID.AddInteger(SCEVPredicate::P_Compare); 13554 ID.AddInteger(Pred); 13555 ID.AddPointer(LHS); 13556 ID.AddPointer(RHS); 13557 void *IP = nullptr; 13558 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 13559 return S; 13560 SCEVComparePredicate *Eq = new (SCEVAllocator) 13561 SCEVComparePredicate(ID.Intern(SCEVAllocator), Pred, LHS, RHS); 13562 UniquePreds.InsertNode(Eq, IP); 13563 return Eq; 13564 } 13565 13566 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 13567 const SCEVAddRecExpr *AR, 13568 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 13569 FoldingSetNodeID ID; 13570 // Unique this node based on the arguments 13571 ID.AddInteger(SCEVPredicate::P_Wrap); 13572 ID.AddPointer(AR); 13573 ID.AddInteger(AddedFlags); 13574 void *IP = nullptr; 13575 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 13576 return S; 13577 auto *OF = new (SCEVAllocator) 13578 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 13579 UniquePreds.InsertNode(OF, IP); 13580 return OF; 13581 } 13582 13583 namespace { 13584 13585 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 13586 public: 13587 13588 /// Rewrites \p S in the context of a loop L and the SCEV predication 13589 /// infrastructure. 13590 /// 13591 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 13592 /// equivalences present in \p Pred. 13593 /// 13594 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 13595 /// \p NewPreds such that the result will be an AddRecExpr. 13596 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 13597 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 13598 SCEVUnionPredicate *Pred) { 13599 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 13600 return Rewriter.visit(S); 13601 } 13602 13603 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 13604 if (Pred) { 13605 auto ExprPreds = Pred->getPredicatesForExpr(Expr); 13606 for (auto *Pred : ExprPreds) 13607 if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred)) 13608 if (IPred->getLHS() == Expr && 13609 IPred->getPredicate() == ICmpInst::ICMP_EQ) 13610 return IPred->getRHS(); 13611 } 13612 return convertToAddRecWithPreds(Expr); 13613 } 13614 13615 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 13616 const SCEV *Operand = visit(Expr->getOperand()); 13617 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 13618 if (AR && AR->getLoop() == L && AR->isAffine()) { 13619 // This couldn't be folded because the operand didn't have the nuw 13620 // flag. Add the nusw flag as an assumption that we could make. 13621 const SCEV *Step = AR->getStepRecurrence(SE); 13622 Type *Ty = Expr->getType(); 13623 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 13624 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 13625 SE.getSignExtendExpr(Step, Ty), L, 13626 AR->getNoWrapFlags()); 13627 } 13628 return SE.getZeroExtendExpr(Operand, Expr->getType()); 13629 } 13630 13631 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 13632 const SCEV *Operand = visit(Expr->getOperand()); 13633 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 13634 if (AR && AR->getLoop() == L && AR->isAffine()) { 13635 // This couldn't be folded because the operand didn't have the nsw 13636 // flag. Add the nssw flag as an assumption that we could make. 13637 const SCEV *Step = AR->getStepRecurrence(SE); 13638 Type *Ty = Expr->getType(); 13639 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 13640 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 13641 SE.getSignExtendExpr(Step, Ty), L, 13642 AR->getNoWrapFlags()); 13643 } 13644 return SE.getSignExtendExpr(Operand, Expr->getType()); 13645 } 13646 13647 private: 13648 explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 13649 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 13650 SCEVUnionPredicate *Pred) 13651 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 13652 13653 bool addOverflowAssumption(const SCEVPredicate *P) { 13654 if (!NewPreds) { 13655 // Check if we've already made this assumption. 13656 return Pred && Pred->implies(P); 13657 } 13658 NewPreds->insert(P); 13659 return true; 13660 } 13661 13662 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 13663 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 13664 auto *A = SE.getWrapPredicate(AR, AddedFlags); 13665 return addOverflowAssumption(A); 13666 } 13667 13668 // If \p Expr represents a PHINode, we try to see if it can be represented 13669 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible 13670 // to add this predicate as a runtime overflow check, we return the AddRec. 13671 // If \p Expr does not meet these conditions (is not a PHI node, or we 13672 // couldn't create an AddRec for it, or couldn't add the predicate), we just 13673 // return \p Expr. 13674 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) { 13675 if (!isa<PHINode>(Expr->getValue())) 13676 return Expr; 13677 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 13678 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr); 13679 if (!PredicatedRewrite) 13680 return Expr; 13681 for (auto *P : PredicatedRewrite->second){ 13682 // Wrap predicates from outer loops are not supported. 13683 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) { 13684 auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr()); 13685 if (L != AR->getLoop()) 13686 return Expr; 13687 } 13688 if (!addOverflowAssumption(P)) 13689 return Expr; 13690 } 13691 return PredicatedRewrite->first; 13692 } 13693 13694 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 13695 SCEVUnionPredicate *Pred; 13696 const Loop *L; 13697 }; 13698 13699 } // end anonymous namespace 13700 13701 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 13702 SCEVUnionPredicate &Preds) { 13703 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 13704 } 13705 13706 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 13707 const SCEV *S, const Loop *L, 13708 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 13709 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 13710 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 13711 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 13712 13713 if (!AddRec) 13714 return nullptr; 13715 13716 // Since the transformation was successful, we can now transfer the SCEV 13717 // predicates. 13718 for (auto *P : TransformPreds) 13719 Preds.insert(P); 13720 13721 return AddRec; 13722 } 13723 13724 /// SCEV predicates 13725 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 13726 SCEVPredicateKind Kind) 13727 : FastID(ID), Kind(Kind) {} 13728 13729 SCEVComparePredicate::SCEVComparePredicate(const FoldingSetNodeIDRef ID, 13730 const ICmpInst::Predicate Pred, 13731 const SCEV *LHS, const SCEV *RHS) 13732 : SCEVPredicate(ID, P_Compare), Pred(Pred), LHS(LHS), RHS(RHS) { 13733 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match"); 13734 assert(LHS != RHS && "LHS and RHS are the same SCEV"); 13735 } 13736 13737 bool SCEVComparePredicate::implies(const SCEVPredicate *N) const { 13738 const auto *Op = dyn_cast<SCEVComparePredicate>(N); 13739 13740 if (!Op) 13741 return false; 13742 13743 if (Pred != ICmpInst::ICMP_EQ) 13744 return false; 13745 13746 return Op->LHS == LHS && Op->RHS == RHS; 13747 } 13748 13749 bool SCEVComparePredicate::isAlwaysTrue() const { return false; } 13750 13751 const SCEV *SCEVComparePredicate::getExpr() const { return LHS; } 13752 13753 void SCEVComparePredicate::print(raw_ostream &OS, unsigned Depth) const { 13754 if (Pred == ICmpInst::ICMP_EQ) 13755 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 13756 else 13757 OS.indent(Depth) << "Compare predicate: " << *LHS 13758 << " " << CmpInst::getPredicateName(Pred) << ") " 13759 << *RHS << "\n"; 13760 13761 } 13762 13763 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 13764 const SCEVAddRecExpr *AR, 13765 IncrementWrapFlags Flags) 13766 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 13767 13768 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 13769 13770 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 13771 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 13772 13773 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 13774 } 13775 13776 bool SCEVWrapPredicate::isAlwaysTrue() const { 13777 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 13778 IncrementWrapFlags IFlags = Flags; 13779 13780 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 13781 IFlags = clearFlags(IFlags, IncrementNSSW); 13782 13783 return IFlags == IncrementAnyWrap; 13784 } 13785 13786 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 13787 OS.indent(Depth) << *getExpr() << " Added Flags: "; 13788 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 13789 OS << "<nusw>"; 13790 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 13791 OS << "<nssw>"; 13792 OS << "\n"; 13793 } 13794 13795 SCEVWrapPredicate::IncrementWrapFlags 13796 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 13797 ScalarEvolution &SE) { 13798 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 13799 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 13800 13801 // We can safely transfer the NSW flag as NSSW. 13802 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 13803 ImpliedFlags = IncrementNSSW; 13804 13805 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 13806 // If the increment is positive, the SCEV NUW flag will also imply the 13807 // WrapPredicate NUSW flag. 13808 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 13809 if (Step->getValue()->getValue().isNonNegative()) 13810 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 13811 } 13812 13813 return ImpliedFlags; 13814 } 13815 13816 /// Union predicates don't get cached so create a dummy set ID for it. 13817 SCEVUnionPredicate::SCEVUnionPredicate(ArrayRef<const SCEVPredicate *> Preds) 13818 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) { 13819 for (auto *P : Preds) 13820 add(P); 13821 } 13822 13823 bool SCEVUnionPredicate::isAlwaysTrue() const { 13824 return all_of(Preds, 13825 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 13826 } 13827 13828 ArrayRef<const SCEVPredicate *> 13829 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 13830 auto I = SCEVToPreds.find(Expr); 13831 if (I == SCEVToPreds.end()) 13832 return ArrayRef<const SCEVPredicate *>(); 13833 return I->second; 13834 } 13835 13836 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 13837 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 13838 return all_of(Set->Preds, 13839 [this](const SCEVPredicate *I) { return this->implies(I); }); 13840 13841 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 13842 if (ScevPredsIt == SCEVToPreds.end()) 13843 return false; 13844 auto &SCEVPreds = ScevPredsIt->second; 13845 13846 return any_of(SCEVPreds, 13847 [N](const SCEVPredicate *I) { return I->implies(N); }); 13848 } 13849 13850 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 13851 13852 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 13853 for (auto Pred : Preds) 13854 Pred->print(OS, Depth); 13855 } 13856 13857 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 13858 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 13859 for (auto Pred : Set->Preds) 13860 add(Pred); 13861 return; 13862 } 13863 13864 if (implies(N)) 13865 return; 13866 13867 const SCEV *Key = N->getExpr(); 13868 assert(Key && "Only SCEVUnionPredicate doesn't have an " 13869 " associated expression!"); 13870 13871 SCEVToPreds[Key].push_back(N); 13872 Preds.push_back(N); 13873 } 13874 13875 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 13876 Loop &L) 13877 : SE(SE), L(L) { 13878 SmallVector<const SCEVPredicate*, 4> Empty; 13879 Preds = std::make_unique<SCEVUnionPredicate>(Empty); 13880 } 13881 13882 void ScalarEvolution::registerUser(const SCEV *User, 13883 ArrayRef<const SCEV *> Ops) { 13884 for (auto *Op : Ops) 13885 // We do not expect that forgetting cached data for SCEVConstants will ever 13886 // open any prospects for sharpening or introduce any correctness issues, 13887 // so we don't bother storing their dependencies. 13888 if (!isa<SCEVConstant>(Op)) 13889 SCEVUsers[Op].insert(User); 13890 } 13891 13892 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 13893 const SCEV *Expr = SE.getSCEV(V); 13894 RewriteEntry &Entry = RewriteMap[Expr]; 13895 13896 // If we already have an entry and the version matches, return it. 13897 if (Entry.second && Generation == Entry.first) 13898 return Entry.second; 13899 13900 // We found an entry but it's stale. Rewrite the stale entry 13901 // according to the current predicate. 13902 if (Entry.second) 13903 Expr = Entry.second; 13904 13905 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, *Preds); 13906 Entry = {Generation, NewSCEV}; 13907 13908 return NewSCEV; 13909 } 13910 13911 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 13912 if (!BackedgeCount) { 13913 SmallVector<const SCEVPredicate *, 4> Preds; 13914 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, Preds); 13915 for (auto *P : Preds) 13916 addPredicate(*P); 13917 } 13918 return BackedgeCount; 13919 } 13920 13921 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 13922 if (Preds->implies(&Pred)) 13923 return; 13924 13925 auto &OldPreds = Preds->getPredicates(); 13926 SmallVector<const SCEVPredicate*, 4> NewPreds(OldPreds.begin(), OldPreds.end()); 13927 NewPreds.push_back(&Pred); 13928 Preds = std::make_unique<SCEVUnionPredicate>(NewPreds); 13929 updateGeneration(); 13930 } 13931 13932 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 13933 return *Preds; 13934 } 13935 13936 void PredicatedScalarEvolution::updateGeneration() { 13937 // If the generation number wrapped recompute everything. 13938 if (++Generation == 0) { 13939 for (auto &II : RewriteMap) { 13940 const SCEV *Rewritten = II.second.second; 13941 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, *Preds)}; 13942 } 13943 } 13944 } 13945 13946 void PredicatedScalarEvolution::setNoOverflow( 13947 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 13948 const SCEV *Expr = getSCEV(V); 13949 const auto *AR = cast<SCEVAddRecExpr>(Expr); 13950 13951 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 13952 13953 // Clear the statically implied flags. 13954 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 13955 addPredicate(*SE.getWrapPredicate(AR, Flags)); 13956 13957 auto II = FlagsMap.insert({V, Flags}); 13958 if (!II.second) 13959 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 13960 } 13961 13962 bool PredicatedScalarEvolution::hasNoOverflow( 13963 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 13964 const SCEV *Expr = getSCEV(V); 13965 const auto *AR = cast<SCEVAddRecExpr>(Expr); 13966 13967 Flags = SCEVWrapPredicate::clearFlags( 13968 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 13969 13970 auto II = FlagsMap.find(V); 13971 13972 if (II != FlagsMap.end()) 13973 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 13974 13975 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 13976 } 13977 13978 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 13979 const SCEV *Expr = this->getSCEV(V); 13980 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 13981 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 13982 13983 if (!New) 13984 return nullptr; 13985 13986 for (auto *P : NewPreds) 13987 addPredicate(*P); 13988 13989 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 13990 return New; 13991 } 13992 13993 PredicatedScalarEvolution::PredicatedScalarEvolution( 13994 const PredicatedScalarEvolution &Init) 13995 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), 13996 Preds(std::make_unique<SCEVUnionPredicate>(Init.Preds->getPredicates())), 13997 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 13998 for (auto I : Init.FlagsMap) 13999 FlagsMap.insert(I); 14000 } 14001 14002 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 14003 // For each block. 14004 for (auto *BB : L.getBlocks()) 14005 for (auto &I : *BB) { 14006 if (!SE.isSCEVable(I.getType())) 14007 continue; 14008 14009 auto *Expr = SE.getSCEV(&I); 14010 auto II = RewriteMap.find(Expr); 14011 14012 if (II == RewriteMap.end()) 14013 continue; 14014 14015 // Don't print things that are not interesting. 14016 if (II->second.second == Expr) 14017 continue; 14018 14019 OS.indent(Depth) << "[PSE]" << I << ":\n"; 14020 OS.indent(Depth + 2) << *Expr << "\n"; 14021 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 14022 } 14023 } 14024 14025 // Match the mathematical pattern A - (A / B) * B, where A and B can be 14026 // arbitrary expressions. Also match zext (trunc A to iB) to iY, which is used 14027 // for URem with constant power-of-2 second operands. 14028 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is 14029 // 4, A / B becomes X / 8). 14030 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS, 14031 const SCEV *&RHS) { 14032 // Try to match 'zext (trunc A to iB) to iY', which is used 14033 // for URem with constant power-of-2 second operands. Make sure the size of 14034 // the operand A matches the size of the whole expressions. 14035 if (const auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(Expr)) 14036 if (const auto *Trunc = dyn_cast<SCEVTruncateExpr>(ZExt->getOperand(0))) { 14037 LHS = Trunc->getOperand(); 14038 // Bail out if the type of the LHS is larger than the type of the 14039 // expression for now. 14040 if (getTypeSizeInBits(LHS->getType()) > 14041 getTypeSizeInBits(Expr->getType())) 14042 return false; 14043 if (LHS->getType() != Expr->getType()) 14044 LHS = getZeroExtendExpr(LHS, Expr->getType()); 14045 RHS = getConstant(APInt(getTypeSizeInBits(Expr->getType()), 1) 14046 << getTypeSizeInBits(Trunc->getType())); 14047 return true; 14048 } 14049 const auto *Add = dyn_cast<SCEVAddExpr>(Expr); 14050 if (Add == nullptr || Add->getNumOperands() != 2) 14051 return false; 14052 14053 const SCEV *A = Add->getOperand(1); 14054 const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0)); 14055 14056 if (Mul == nullptr) 14057 return false; 14058 14059 const auto MatchURemWithDivisor = [&](const SCEV *B) { 14060 // (SomeExpr + (-(SomeExpr / B) * B)). 14061 if (Expr == getURemExpr(A, B)) { 14062 LHS = A; 14063 RHS = B; 14064 return true; 14065 } 14066 return false; 14067 }; 14068 14069 // (SomeExpr + (-1 * (SomeExpr / B) * B)). 14070 if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0))) 14071 return MatchURemWithDivisor(Mul->getOperand(1)) || 14072 MatchURemWithDivisor(Mul->getOperand(2)); 14073 14074 // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)). 14075 if (Mul->getNumOperands() == 2) 14076 return MatchURemWithDivisor(Mul->getOperand(1)) || 14077 MatchURemWithDivisor(Mul->getOperand(0)) || 14078 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) || 14079 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0))); 14080 return false; 14081 } 14082 14083 const SCEV * 14084 ScalarEvolution::computeSymbolicMaxBackedgeTakenCount(const Loop *L) { 14085 SmallVector<BasicBlock*, 16> ExitingBlocks; 14086 L->getExitingBlocks(ExitingBlocks); 14087 14088 // Form an expression for the maximum exit count possible for this loop. We 14089 // merge the max and exact information to approximate a version of 14090 // getConstantMaxBackedgeTakenCount which isn't restricted to just constants. 14091 SmallVector<const SCEV*, 4> ExitCounts; 14092 for (BasicBlock *ExitingBB : ExitingBlocks) { 14093 const SCEV *ExitCount = getExitCount(L, ExitingBB); 14094 if (isa<SCEVCouldNotCompute>(ExitCount)) 14095 ExitCount = getExitCount(L, ExitingBB, 14096 ScalarEvolution::ConstantMaximum); 14097 if (!isa<SCEVCouldNotCompute>(ExitCount)) { 14098 assert(DT.dominates(ExitingBB, L->getLoopLatch()) && 14099 "We should only have known counts for exiting blocks that " 14100 "dominate latch!"); 14101 ExitCounts.push_back(ExitCount); 14102 } 14103 } 14104 if (ExitCounts.empty()) 14105 return getCouldNotCompute(); 14106 return getUMinFromMismatchedTypes(ExitCounts); 14107 } 14108 14109 /// A rewriter to replace SCEV expressions in Map with the corresponding entry 14110 /// in the map. It skips AddRecExpr because we cannot guarantee that the 14111 /// replacement is loop invariant in the loop of the AddRec. 14112 /// 14113 /// At the moment only rewriting SCEVUnknown and SCEVZeroExtendExpr is 14114 /// supported. 14115 class SCEVLoopGuardRewriter : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> { 14116 const DenseMap<const SCEV *, const SCEV *> ⤅ 14117 14118 public: 14119 SCEVLoopGuardRewriter(ScalarEvolution &SE, 14120 DenseMap<const SCEV *, const SCEV *> &M) 14121 : SCEVRewriteVisitor(SE), Map(M) {} 14122 14123 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; } 14124 14125 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 14126 auto I = Map.find(Expr); 14127 if (I == Map.end()) 14128 return Expr; 14129 return I->second; 14130 } 14131 14132 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 14133 auto I = Map.find(Expr); 14134 if (I == Map.end()) 14135 return SCEVRewriteVisitor<SCEVLoopGuardRewriter>::visitZeroExtendExpr( 14136 Expr); 14137 return I->second; 14138 } 14139 }; 14140 14141 const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) { 14142 SmallVector<const SCEV *> ExprsToRewrite; 14143 auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS, 14144 const SCEV *RHS, 14145 DenseMap<const SCEV *, const SCEV *> 14146 &RewriteMap) { 14147 // WARNING: It is generally unsound to apply any wrap flags to the proposed 14148 // replacement SCEV which isn't directly implied by the structure of that 14149 // SCEV. In particular, using contextual facts to imply flags is *NOT* 14150 // legal. See the scoping rules for flags in the header to understand why. 14151 14152 // If LHS is a constant, apply information to the other expression. 14153 if (isa<SCEVConstant>(LHS)) { 14154 std::swap(LHS, RHS); 14155 Predicate = CmpInst::getSwappedPredicate(Predicate); 14156 } 14157 14158 // Check for a condition of the form (-C1 + X < C2). InstCombine will 14159 // create this form when combining two checks of the form (X u< C2 + C1) and 14160 // (X >=u C1). 14161 auto MatchRangeCheckIdiom = [this, Predicate, LHS, RHS, &RewriteMap, 14162 &ExprsToRewrite]() { 14163 auto *AddExpr = dyn_cast<SCEVAddExpr>(LHS); 14164 if (!AddExpr || AddExpr->getNumOperands() != 2) 14165 return false; 14166 14167 auto *C1 = dyn_cast<SCEVConstant>(AddExpr->getOperand(0)); 14168 auto *LHSUnknown = dyn_cast<SCEVUnknown>(AddExpr->getOperand(1)); 14169 auto *C2 = dyn_cast<SCEVConstant>(RHS); 14170 if (!C1 || !C2 || !LHSUnknown) 14171 return false; 14172 14173 auto ExactRegion = 14174 ConstantRange::makeExactICmpRegion(Predicate, C2->getAPInt()) 14175 .sub(C1->getAPInt()); 14176 14177 // Bail out, unless we have a non-wrapping, monotonic range. 14178 if (ExactRegion.isWrappedSet() || ExactRegion.isFullSet()) 14179 return false; 14180 auto I = RewriteMap.find(LHSUnknown); 14181 const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHSUnknown; 14182 RewriteMap[LHSUnknown] = getUMaxExpr( 14183 getConstant(ExactRegion.getUnsignedMin()), 14184 getUMinExpr(RewrittenLHS, getConstant(ExactRegion.getUnsignedMax()))); 14185 ExprsToRewrite.push_back(LHSUnknown); 14186 return true; 14187 }; 14188 if (MatchRangeCheckIdiom()) 14189 return; 14190 14191 // If we have LHS == 0, check if LHS is computing a property of some unknown 14192 // SCEV %v which we can rewrite %v to express explicitly. 14193 const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS); 14194 if (Predicate == CmpInst::ICMP_EQ && RHSC && 14195 RHSC->getValue()->isNullValue()) { 14196 // If LHS is A % B, i.e. A % B == 0, rewrite A to (A /u B) * B to 14197 // explicitly express that. 14198 const SCEV *URemLHS = nullptr; 14199 const SCEV *URemRHS = nullptr; 14200 if (matchURem(LHS, URemLHS, URemRHS)) { 14201 if (const SCEVUnknown *LHSUnknown = dyn_cast<SCEVUnknown>(URemLHS)) { 14202 auto Multiple = getMulExpr(getUDivExpr(URemLHS, URemRHS), URemRHS); 14203 RewriteMap[LHSUnknown] = Multiple; 14204 ExprsToRewrite.push_back(LHSUnknown); 14205 return; 14206 } 14207 } 14208 } 14209 14210 // Do not apply information for constants or if RHS contains an AddRec. 14211 if (isa<SCEVConstant>(LHS) || containsAddRecurrence(RHS)) 14212 return; 14213 14214 // If RHS is SCEVUnknown, make sure the information is applied to it. 14215 if (!isa<SCEVUnknown>(LHS) && isa<SCEVUnknown>(RHS)) { 14216 std::swap(LHS, RHS); 14217 Predicate = CmpInst::getSwappedPredicate(Predicate); 14218 } 14219 14220 // Limit to expressions that can be rewritten. 14221 if (!isa<SCEVUnknown>(LHS) && !isa<SCEVZeroExtendExpr>(LHS)) 14222 return; 14223 14224 // Check whether LHS has already been rewritten. In that case we want to 14225 // chain further rewrites onto the already rewritten value. 14226 auto I = RewriteMap.find(LHS); 14227 const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHS; 14228 14229 const SCEV *RewrittenRHS = nullptr; 14230 switch (Predicate) { 14231 case CmpInst::ICMP_ULT: 14232 RewrittenRHS = 14233 getUMinExpr(RewrittenLHS, getMinusSCEV(RHS, getOne(RHS->getType()))); 14234 break; 14235 case CmpInst::ICMP_SLT: 14236 RewrittenRHS = 14237 getSMinExpr(RewrittenLHS, getMinusSCEV(RHS, getOne(RHS->getType()))); 14238 break; 14239 case CmpInst::ICMP_ULE: 14240 RewrittenRHS = getUMinExpr(RewrittenLHS, RHS); 14241 break; 14242 case CmpInst::ICMP_SLE: 14243 RewrittenRHS = getSMinExpr(RewrittenLHS, RHS); 14244 break; 14245 case CmpInst::ICMP_UGT: 14246 RewrittenRHS = 14247 getUMaxExpr(RewrittenLHS, getAddExpr(RHS, getOne(RHS->getType()))); 14248 break; 14249 case CmpInst::ICMP_SGT: 14250 RewrittenRHS = 14251 getSMaxExpr(RewrittenLHS, getAddExpr(RHS, getOne(RHS->getType()))); 14252 break; 14253 case CmpInst::ICMP_UGE: 14254 RewrittenRHS = getUMaxExpr(RewrittenLHS, RHS); 14255 break; 14256 case CmpInst::ICMP_SGE: 14257 RewrittenRHS = getSMaxExpr(RewrittenLHS, RHS); 14258 break; 14259 case CmpInst::ICMP_EQ: 14260 if (isa<SCEVConstant>(RHS)) 14261 RewrittenRHS = RHS; 14262 break; 14263 case CmpInst::ICMP_NE: 14264 if (isa<SCEVConstant>(RHS) && 14265 cast<SCEVConstant>(RHS)->getValue()->isNullValue()) 14266 RewrittenRHS = getUMaxExpr(RewrittenLHS, getOne(RHS->getType())); 14267 break; 14268 default: 14269 break; 14270 } 14271 14272 if (RewrittenRHS) { 14273 RewriteMap[LHS] = RewrittenRHS; 14274 if (LHS == RewrittenLHS) 14275 ExprsToRewrite.push_back(LHS); 14276 } 14277 }; 14278 // First, collect conditions from dominating branches. Starting at the loop 14279 // predecessor, climb up the predecessor chain, as long as there are 14280 // predecessors that can be found that have unique successors leading to the 14281 // original header. 14282 // TODO: share this logic with isLoopEntryGuardedByCond. 14283 SmallVector<std::pair<Value *, bool>> Terms; 14284 for (std::pair<const BasicBlock *, const BasicBlock *> Pair( 14285 L->getLoopPredecessor(), L->getHeader()); 14286 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 14287 14288 const BranchInst *LoopEntryPredicate = 14289 dyn_cast<BranchInst>(Pair.first->getTerminator()); 14290 if (!LoopEntryPredicate || LoopEntryPredicate->isUnconditional()) 14291 continue; 14292 14293 Terms.emplace_back(LoopEntryPredicate->getCondition(), 14294 LoopEntryPredicate->getSuccessor(0) == Pair.second); 14295 } 14296 14297 // Now apply the information from the collected conditions to RewriteMap. 14298 // Conditions are processed in reverse order, so the earliest conditions is 14299 // processed first. This ensures the SCEVs with the shortest dependency chains 14300 // are constructed first. 14301 DenseMap<const SCEV *, const SCEV *> RewriteMap; 14302 for (auto &E : reverse(Terms)) { 14303 bool EnterIfTrue = E.second; 14304 SmallVector<Value *, 8> Worklist; 14305 SmallPtrSet<Value *, 8> Visited; 14306 Worklist.push_back(E.first); 14307 while (!Worklist.empty()) { 14308 Value *Cond = Worklist.pop_back_val(); 14309 if (!Visited.insert(Cond).second) 14310 continue; 14311 14312 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) { 14313 auto Predicate = 14314 EnterIfTrue ? Cmp->getPredicate() : Cmp->getInversePredicate(); 14315 CollectCondition(Predicate, getSCEV(Cmp->getOperand(0)), 14316 getSCEV(Cmp->getOperand(1)), RewriteMap); 14317 continue; 14318 } 14319 14320 Value *L, *R; 14321 if (EnterIfTrue ? match(Cond, m_LogicalAnd(m_Value(L), m_Value(R))) 14322 : match(Cond, m_LogicalOr(m_Value(L), m_Value(R)))) { 14323 Worklist.push_back(L); 14324 Worklist.push_back(R); 14325 } 14326 } 14327 } 14328 14329 // Also collect information from assumptions dominating the loop. 14330 for (auto &AssumeVH : AC.assumptions()) { 14331 if (!AssumeVH) 14332 continue; 14333 auto *AssumeI = cast<CallInst>(AssumeVH); 14334 auto *Cmp = dyn_cast<ICmpInst>(AssumeI->getOperand(0)); 14335 if (!Cmp || !DT.dominates(AssumeI, L->getHeader())) 14336 continue; 14337 CollectCondition(Cmp->getPredicate(), getSCEV(Cmp->getOperand(0)), 14338 getSCEV(Cmp->getOperand(1)), RewriteMap); 14339 } 14340 14341 if (RewriteMap.empty()) 14342 return Expr; 14343 14344 // Now that all rewrite information is collect, rewrite the collected 14345 // expressions with the information in the map. This applies information to 14346 // sub-expressions. 14347 if (ExprsToRewrite.size() > 1) { 14348 for (const SCEV *Expr : ExprsToRewrite) { 14349 const SCEV *RewriteTo = RewriteMap[Expr]; 14350 RewriteMap.erase(Expr); 14351 SCEVLoopGuardRewriter Rewriter(*this, RewriteMap); 14352 RewriteMap.insert({Expr, Rewriter.visit(RewriteTo)}); 14353 } 14354 } 14355 14356 SCEVLoopGuardRewriter Rewriter(*this, RewriteMap); 14357 return Rewriter.visit(Expr); 14358 } 14359