1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file contains the implementation of the scalar evolution analysis 11 // engine, which is used primarily to analyze expressions involving induction 12 // variables in loops. 13 // 14 // There are several aspects to this library. First is the representation of 15 // scalar expressions, which are represented as subclasses of the SCEV class. 16 // These classes are used to represent certain types of subexpressions that we 17 // can handle. We only create one SCEV of a particular shape, so 18 // pointer-comparisons for equality are legal. 19 // 20 // One important aspect of the SCEV objects is that they are never cyclic, even 21 // if there is a cycle in the dataflow for an expression (ie, a PHI node). If 22 // the PHI node is one of the idioms that we can represent (e.g., a polynomial 23 // recurrence) then we represent it directly as a recurrence node, otherwise we 24 // represent it as a SCEVUnknown node. 25 // 26 // In addition to being able to represent expressions of various types, we also 27 // have folders that are used to build the *canonical* representation for a 28 // particular expression. These folders are capable of using a variety of 29 // rewrite rules to simplify the expressions. 30 // 31 // Once the folders are defined, we can implement the more interesting 32 // higher-level code, such as the code that recognizes PHI nodes of various 33 // types, computes the execution count of a loop, etc. 34 // 35 // TODO: We should use these routines and value representations to implement 36 // dependence analysis! 37 // 38 //===----------------------------------------------------------------------===// 39 // 40 // There are several good references for the techniques used in this analysis. 41 // 42 // Chains of recurrences -- a method to expedite the evaluation 43 // of closed-form functions 44 // Olaf Bachmann, Paul S. Wang, Eugene V. Zima 45 // 46 // On computational properties of chains of recurrences 47 // Eugene V. Zima 48 // 49 // Symbolic Evaluation of Chains of Recurrences for Loop Optimization 50 // Robert A. van Engelen 51 // 52 // Efficient Symbolic Analysis for Optimizing Compilers 53 // Robert A. van Engelen 54 // 55 // Using the chains of recurrences algebra for data dependence testing and 56 // induction variable substitution 57 // MS Thesis, Johnie Birch 58 // 59 //===----------------------------------------------------------------------===// 60 61 #include "llvm/Analysis/ScalarEvolution.h" 62 #include "llvm/ADT/Optional.h" 63 #include "llvm/ADT/STLExtras.h" 64 #include "llvm/ADT/ScopeExit.h" 65 #include "llvm/ADT/Sequence.h" 66 #include "llvm/ADT/SmallPtrSet.h" 67 #include "llvm/ADT/Statistic.h" 68 #include "llvm/Analysis/AssumptionCache.h" 69 #include "llvm/Analysis/ConstantFolding.h" 70 #include "llvm/Analysis/InstructionSimplify.h" 71 #include "llvm/Analysis/LoopInfo.h" 72 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 73 #include "llvm/Analysis/TargetLibraryInfo.h" 74 #include "llvm/Analysis/ValueTracking.h" 75 #include "llvm/IR/ConstantRange.h" 76 #include "llvm/IR/Constants.h" 77 #include "llvm/IR/DataLayout.h" 78 #include "llvm/IR/DerivedTypes.h" 79 #include "llvm/IR/Dominators.h" 80 #include "llvm/IR/GetElementPtrTypeIterator.h" 81 #include "llvm/IR/GlobalAlias.h" 82 #include "llvm/IR/GlobalVariable.h" 83 #include "llvm/IR/InstIterator.h" 84 #include "llvm/IR/Instructions.h" 85 #include "llvm/IR/LLVMContext.h" 86 #include "llvm/IR/Metadata.h" 87 #include "llvm/IR/Operator.h" 88 #include "llvm/IR/PatternMatch.h" 89 #include "llvm/Support/CommandLine.h" 90 #include "llvm/Support/Debug.h" 91 #include "llvm/Support/ErrorHandling.h" 92 #include "llvm/Support/MathExtras.h" 93 #include "llvm/Support/raw_ostream.h" 94 #include "llvm/Support/SaveAndRestore.h" 95 #include <algorithm> 96 using namespace llvm; 97 98 #define DEBUG_TYPE "scalar-evolution" 99 100 STATISTIC(NumArrayLenItCounts, 101 "Number of trip counts computed with array length"); 102 STATISTIC(NumTripCountsComputed, 103 "Number of loops with predictable loop counts"); 104 STATISTIC(NumTripCountsNotComputed, 105 "Number of loops without predictable loop counts"); 106 STATISTIC(NumBruteForceTripCountsComputed, 107 "Number of loops with trip counts computed by force"); 108 109 static cl::opt<unsigned> 110 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, 111 cl::desc("Maximum number of iterations SCEV will " 112 "symbolically execute a constant " 113 "derived loop"), 114 cl::init(100)); 115 116 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean. 117 static cl::opt<bool> 118 VerifySCEV("verify-scev", 119 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)")); 120 static cl::opt<bool> 121 VerifySCEVMap("verify-scev-maps", 122 cl::desc("Verify no dangling value in ScalarEvolution's " 123 "ExprValueMap (slow)")); 124 125 static cl::opt<unsigned> MulOpsInlineThreshold( 126 "scev-mulops-inline-threshold", cl::Hidden, 127 cl::desc("Threshold for inlining multiplication operands into a SCEV"), 128 cl::init(1000)); 129 130 //===----------------------------------------------------------------------===// 131 // SCEV class definitions 132 //===----------------------------------------------------------------------===// 133 134 //===----------------------------------------------------------------------===// 135 // Implementation of the SCEV class. 136 // 137 138 LLVM_DUMP_METHOD 139 void SCEV::dump() const { 140 print(dbgs()); 141 dbgs() << '\n'; 142 } 143 144 void SCEV::print(raw_ostream &OS) const { 145 switch (static_cast<SCEVTypes>(getSCEVType())) { 146 case scConstant: 147 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false); 148 return; 149 case scTruncate: { 150 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this); 151 const SCEV *Op = Trunc->getOperand(); 152 OS << "(trunc " << *Op->getType() << " " << *Op << " to " 153 << *Trunc->getType() << ")"; 154 return; 155 } 156 case scZeroExtend: { 157 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this); 158 const SCEV *Op = ZExt->getOperand(); 159 OS << "(zext " << *Op->getType() << " " << *Op << " to " 160 << *ZExt->getType() << ")"; 161 return; 162 } 163 case scSignExtend: { 164 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this); 165 const SCEV *Op = SExt->getOperand(); 166 OS << "(sext " << *Op->getType() << " " << *Op << " to " 167 << *SExt->getType() << ")"; 168 return; 169 } 170 case scAddRecExpr: { 171 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this); 172 OS << "{" << *AR->getOperand(0); 173 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i) 174 OS << ",+," << *AR->getOperand(i); 175 OS << "}<"; 176 if (AR->hasNoUnsignedWrap()) 177 OS << "nuw><"; 178 if (AR->hasNoSignedWrap()) 179 OS << "nsw><"; 180 if (AR->hasNoSelfWrap() && 181 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW))) 182 OS << "nw><"; 183 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false); 184 OS << ">"; 185 return; 186 } 187 case scAddExpr: 188 case scMulExpr: 189 case scUMaxExpr: 190 case scSMaxExpr: { 191 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this); 192 const char *OpStr = nullptr; 193 switch (NAry->getSCEVType()) { 194 case scAddExpr: OpStr = " + "; break; 195 case scMulExpr: OpStr = " * "; break; 196 case scUMaxExpr: OpStr = " umax "; break; 197 case scSMaxExpr: OpStr = " smax "; break; 198 } 199 OS << "("; 200 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end(); 201 I != E; ++I) { 202 OS << **I; 203 if (std::next(I) != E) 204 OS << OpStr; 205 } 206 OS << ")"; 207 switch (NAry->getSCEVType()) { 208 case scAddExpr: 209 case scMulExpr: 210 if (NAry->hasNoUnsignedWrap()) 211 OS << "<nuw>"; 212 if (NAry->hasNoSignedWrap()) 213 OS << "<nsw>"; 214 } 215 return; 216 } 217 case scUDivExpr: { 218 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this); 219 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")"; 220 return; 221 } 222 case scUnknown: { 223 const SCEVUnknown *U = cast<SCEVUnknown>(this); 224 Type *AllocTy; 225 if (U->isSizeOf(AllocTy)) { 226 OS << "sizeof(" << *AllocTy << ")"; 227 return; 228 } 229 if (U->isAlignOf(AllocTy)) { 230 OS << "alignof(" << *AllocTy << ")"; 231 return; 232 } 233 234 Type *CTy; 235 Constant *FieldNo; 236 if (U->isOffsetOf(CTy, FieldNo)) { 237 OS << "offsetof(" << *CTy << ", "; 238 FieldNo->printAsOperand(OS, false); 239 OS << ")"; 240 return; 241 } 242 243 // Otherwise just print it normally. 244 U->getValue()->printAsOperand(OS, false); 245 return; 246 } 247 case scCouldNotCompute: 248 OS << "***COULDNOTCOMPUTE***"; 249 return; 250 } 251 llvm_unreachable("Unknown SCEV kind!"); 252 } 253 254 Type *SCEV::getType() const { 255 switch (static_cast<SCEVTypes>(getSCEVType())) { 256 case scConstant: 257 return cast<SCEVConstant>(this)->getType(); 258 case scTruncate: 259 case scZeroExtend: 260 case scSignExtend: 261 return cast<SCEVCastExpr>(this)->getType(); 262 case scAddRecExpr: 263 case scMulExpr: 264 case scUMaxExpr: 265 case scSMaxExpr: 266 return cast<SCEVNAryExpr>(this)->getType(); 267 case scAddExpr: 268 return cast<SCEVAddExpr>(this)->getType(); 269 case scUDivExpr: 270 return cast<SCEVUDivExpr>(this)->getType(); 271 case scUnknown: 272 return cast<SCEVUnknown>(this)->getType(); 273 case scCouldNotCompute: 274 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 275 } 276 llvm_unreachable("Unknown SCEV kind!"); 277 } 278 279 bool SCEV::isZero() const { 280 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 281 return SC->getValue()->isZero(); 282 return false; 283 } 284 285 bool SCEV::isOne() const { 286 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 287 return SC->getValue()->isOne(); 288 return false; 289 } 290 291 bool SCEV::isAllOnesValue() const { 292 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 293 return SC->getValue()->isAllOnesValue(); 294 return false; 295 } 296 297 bool SCEV::isNonConstantNegative() const { 298 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this); 299 if (!Mul) return false; 300 301 // If there is a constant factor, it will be first. 302 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); 303 if (!SC) return false; 304 305 // Return true if the value is negative, this matches things like (-42 * V). 306 return SC->getAPInt().isNegative(); 307 } 308 309 SCEVCouldNotCompute::SCEVCouldNotCompute() : 310 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {} 311 312 bool SCEVCouldNotCompute::classof(const SCEV *S) { 313 return S->getSCEVType() == scCouldNotCompute; 314 } 315 316 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) { 317 FoldingSetNodeID ID; 318 ID.AddInteger(scConstant); 319 ID.AddPointer(V); 320 void *IP = nullptr; 321 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 322 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V); 323 UniqueSCEVs.InsertNode(S, IP); 324 return S; 325 } 326 327 const SCEV *ScalarEvolution::getConstant(const APInt &Val) { 328 return getConstant(ConstantInt::get(getContext(), Val)); 329 } 330 331 const SCEV * 332 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) { 333 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty)); 334 return getConstant(ConstantInt::get(ITy, V, isSigned)); 335 } 336 337 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, 338 unsigned SCEVTy, const SCEV *op, Type *ty) 339 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {} 340 341 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, 342 const SCEV *op, Type *ty) 343 : SCEVCastExpr(ID, scTruncate, op, ty) { 344 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && 345 (Ty->isIntegerTy() || Ty->isPointerTy()) && 346 "Cannot truncate non-integer value!"); 347 } 348 349 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, 350 const SCEV *op, Type *ty) 351 : SCEVCastExpr(ID, scZeroExtend, op, ty) { 352 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && 353 (Ty->isIntegerTy() || Ty->isPointerTy()) && 354 "Cannot zero extend non-integer value!"); 355 } 356 357 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, 358 const SCEV *op, Type *ty) 359 : SCEVCastExpr(ID, scSignExtend, op, ty) { 360 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && 361 (Ty->isIntegerTy() || Ty->isPointerTy()) && 362 "Cannot sign extend non-integer value!"); 363 } 364 365 void SCEVUnknown::deleted() { 366 // Clear this SCEVUnknown from various maps. 367 SE->forgetMemoizedResults(this); 368 369 // Remove this SCEVUnknown from the uniquing map. 370 SE->UniqueSCEVs.RemoveNode(this); 371 372 // Release the value. 373 setValPtr(nullptr); 374 } 375 376 void SCEVUnknown::allUsesReplacedWith(Value *New) { 377 // Clear this SCEVUnknown from various maps. 378 SE->forgetMemoizedResults(this); 379 380 // Remove this SCEVUnknown from the uniquing map. 381 SE->UniqueSCEVs.RemoveNode(this); 382 383 // Update this SCEVUnknown to point to the new value. This is needed 384 // because there may still be outstanding SCEVs which still point to 385 // this SCEVUnknown. 386 setValPtr(New); 387 } 388 389 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const { 390 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 391 if (VCE->getOpcode() == Instruction::PtrToInt) 392 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 393 if (CE->getOpcode() == Instruction::GetElementPtr && 394 CE->getOperand(0)->isNullValue() && 395 CE->getNumOperands() == 2) 396 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1))) 397 if (CI->isOne()) { 398 AllocTy = cast<PointerType>(CE->getOperand(0)->getType()) 399 ->getElementType(); 400 return true; 401 } 402 403 return false; 404 } 405 406 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const { 407 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 408 if (VCE->getOpcode() == Instruction::PtrToInt) 409 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 410 if (CE->getOpcode() == Instruction::GetElementPtr && 411 CE->getOperand(0)->isNullValue()) { 412 Type *Ty = 413 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 414 if (StructType *STy = dyn_cast<StructType>(Ty)) 415 if (!STy->isPacked() && 416 CE->getNumOperands() == 3 && 417 CE->getOperand(1)->isNullValue()) { 418 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2))) 419 if (CI->isOne() && 420 STy->getNumElements() == 2 && 421 STy->getElementType(0)->isIntegerTy(1)) { 422 AllocTy = STy->getElementType(1); 423 return true; 424 } 425 } 426 } 427 428 return false; 429 } 430 431 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const { 432 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 433 if (VCE->getOpcode() == Instruction::PtrToInt) 434 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 435 if (CE->getOpcode() == Instruction::GetElementPtr && 436 CE->getNumOperands() == 3 && 437 CE->getOperand(0)->isNullValue() && 438 CE->getOperand(1)->isNullValue()) { 439 Type *Ty = 440 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 441 // Ignore vector types here so that ScalarEvolutionExpander doesn't 442 // emit getelementptrs that index into vectors. 443 if (Ty->isStructTy() || Ty->isArrayTy()) { 444 CTy = Ty; 445 FieldNo = CE->getOperand(2); 446 return true; 447 } 448 } 449 450 return false; 451 } 452 453 //===----------------------------------------------------------------------===// 454 // SCEV Utilities 455 //===----------------------------------------------------------------------===// 456 457 /// Compare the two values \p LV and \p RV in terms of their "complexity" where 458 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order 459 /// operands in SCEV expressions. \p EqCache is a set of pairs of values that 460 /// have been previously deemed to be "equally complex" by this routine. It is 461 /// intended to avoid exponential time complexity in cases like: 462 /// 463 /// %a = f(%x, %y) 464 /// %b = f(%a, %a) 465 /// %c = f(%b, %b) 466 /// 467 /// %d = f(%x, %y) 468 /// %e = f(%d, %d) 469 /// %f = f(%e, %e) 470 /// 471 /// CompareValueComplexity(%f, %c) 472 /// 473 /// Since we do not continue running this routine on expression trees once we 474 /// have seen unequal values, there is no need to track them in the cache. 475 static int 476 CompareValueComplexity(SmallSet<std::pair<Value *, Value *>, 8> &EqCache, 477 const LoopInfo *const LI, Value *LV, Value *RV, 478 unsigned DepthLeft = 2) { 479 if (DepthLeft == 0 || EqCache.count({LV, RV})) 480 return 0; 481 482 // Order pointer values after integer values. This helps SCEVExpander form 483 // GEPs. 484 bool LIsPointer = LV->getType()->isPointerTy(), 485 RIsPointer = RV->getType()->isPointerTy(); 486 if (LIsPointer != RIsPointer) 487 return (int)LIsPointer - (int)RIsPointer; 488 489 // Compare getValueID values. 490 unsigned LID = LV->getValueID(), RID = RV->getValueID(); 491 if (LID != RID) 492 return (int)LID - (int)RID; 493 494 // Sort arguments by their position. 495 if (const auto *LA = dyn_cast<Argument>(LV)) { 496 const auto *RA = cast<Argument>(RV); 497 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo(); 498 return (int)LArgNo - (int)RArgNo; 499 } 500 501 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) { 502 const auto *RGV = cast<GlobalValue>(RV); 503 504 const auto IsGVNameSemantic = [&](const GlobalValue *GV) { 505 auto LT = GV->getLinkage(); 506 return !(GlobalValue::isPrivateLinkage(LT) || 507 GlobalValue::isInternalLinkage(LT)); 508 }; 509 510 // Use the names to distinguish the two values, but only if the 511 // names are semantically important. 512 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV)) 513 return LGV->getName().compare(RGV->getName()); 514 } 515 516 // For instructions, compare their loop depth, and their operand count. This 517 // is pretty loose. 518 if (const auto *LInst = dyn_cast<Instruction>(LV)) { 519 const auto *RInst = cast<Instruction>(RV); 520 521 // Compare loop depths. 522 const BasicBlock *LParent = LInst->getParent(), 523 *RParent = RInst->getParent(); 524 if (LParent != RParent) { 525 unsigned LDepth = LI->getLoopDepth(LParent), 526 RDepth = LI->getLoopDepth(RParent); 527 if (LDepth != RDepth) 528 return (int)LDepth - (int)RDepth; 529 } 530 531 // Compare the number of operands. 532 unsigned LNumOps = LInst->getNumOperands(), 533 RNumOps = RInst->getNumOperands(); 534 if (LNumOps != RNumOps) 535 return (int)LNumOps - (int)RNumOps; 536 537 for (unsigned Idx : seq(0u, LNumOps)) { 538 int Result = 539 CompareValueComplexity(EqCache, LI, LInst->getOperand(Idx), 540 RInst->getOperand(Idx), DepthLeft - 1); 541 if (Result != 0) 542 return Result; 543 EqCache.insert({LV, RV}); 544 } 545 } 546 547 return 0; 548 } 549 550 // Return negative, zero, or positive, if LHS is less than, equal to, or greater 551 // than RHS, respectively. A three-way result allows recursive comparisons to be 552 // more efficient. 553 static int CompareSCEVComplexity(const LoopInfo *const LI, const SCEV *LHS, 554 const SCEV *RHS) { 555 // Fast-path: SCEVs are uniqued so we can do a quick equality check. 556 if (LHS == RHS) 557 return 0; 558 559 // Primarily, sort the SCEVs by their getSCEVType(). 560 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType(); 561 if (LType != RType) 562 return (int)LType - (int)RType; 563 564 // Aside from the getSCEVType() ordering, the particular ordering 565 // isn't very important except that it's beneficial to be consistent, 566 // so that (a + b) and (b + a) don't end up as different expressions. 567 switch (static_cast<SCEVTypes>(LType)) { 568 case scUnknown: { 569 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS); 570 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); 571 572 SmallSet<std::pair<Value *, Value *>, 8> EqCache; 573 return CompareValueComplexity(EqCache, LI, LU->getValue(), RU->getValue()); 574 } 575 576 case scConstant: { 577 const SCEVConstant *LC = cast<SCEVConstant>(LHS); 578 const SCEVConstant *RC = cast<SCEVConstant>(RHS); 579 580 // Compare constant values. 581 const APInt &LA = LC->getAPInt(); 582 const APInt &RA = RC->getAPInt(); 583 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth(); 584 if (LBitWidth != RBitWidth) 585 return (int)LBitWidth - (int)RBitWidth; 586 return LA.ult(RA) ? -1 : 1; 587 } 588 589 case scAddRecExpr: { 590 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); 591 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); 592 593 // Compare addrec loop depths. 594 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); 595 if (LLoop != RLoop) { 596 unsigned LDepth = LLoop->getLoopDepth(), RDepth = RLoop->getLoopDepth(); 597 if (LDepth != RDepth) 598 return (int)LDepth - (int)RDepth; 599 } 600 601 // Addrec complexity grows with operand count. 602 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands(); 603 if (LNumOps != RNumOps) 604 return (int)LNumOps - (int)RNumOps; 605 606 // Lexicographically compare. 607 for (unsigned i = 0; i != LNumOps; ++i) { 608 long X = CompareSCEVComplexity(LI, LA->getOperand(i), RA->getOperand(i)); 609 if (X != 0) 610 return X; 611 } 612 613 return 0; 614 } 615 616 case scAddExpr: 617 case scMulExpr: 618 case scSMaxExpr: 619 case scUMaxExpr: { 620 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); 621 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); 622 623 // Lexicographically compare n-ary expressions. 624 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); 625 if (LNumOps != RNumOps) 626 return (int)LNumOps - (int)RNumOps; 627 628 for (unsigned i = 0; i != LNumOps; ++i) { 629 if (i >= RNumOps) 630 return 1; 631 long X = CompareSCEVComplexity(LI, LC->getOperand(i), RC->getOperand(i)); 632 if (X != 0) 633 return X; 634 } 635 return (int)LNumOps - (int)RNumOps; 636 } 637 638 case scUDivExpr: { 639 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); 640 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); 641 642 // Lexicographically compare udiv expressions. 643 long X = CompareSCEVComplexity(LI, LC->getLHS(), RC->getLHS()); 644 if (X != 0) 645 return X; 646 return CompareSCEVComplexity(LI, LC->getRHS(), RC->getRHS()); 647 } 648 649 case scTruncate: 650 case scZeroExtend: 651 case scSignExtend: { 652 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS); 653 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS); 654 655 // Compare cast expressions by operand. 656 return CompareSCEVComplexity(LI, LC->getOperand(), RC->getOperand()); 657 } 658 659 case scCouldNotCompute: 660 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 661 } 662 llvm_unreachable("Unknown SCEV kind!"); 663 } 664 665 /// Given a list of SCEV objects, order them by their complexity, and group 666 /// objects of the same complexity together by value. When this routine is 667 /// finished, we know that any duplicates in the vector are consecutive and that 668 /// complexity is monotonically increasing. 669 /// 670 /// Note that we go take special precautions to ensure that we get deterministic 671 /// results from this routine. In other words, we don't want the results of 672 /// this to depend on where the addresses of various SCEV objects happened to 673 /// land in memory. 674 /// 675 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, 676 LoopInfo *LI) { 677 if (Ops.size() < 2) return; // Noop 678 if (Ops.size() == 2) { 679 // This is the common case, which also happens to be trivially simple. 680 // Special case it. 681 const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; 682 if (CompareSCEVComplexity(LI, RHS, LHS) < 0) 683 std::swap(LHS, RHS); 684 return; 685 } 686 687 // Do the rough sort by complexity. 688 std::stable_sort(Ops.begin(), Ops.end(), 689 [LI](const SCEV *LHS, const SCEV *RHS) { 690 return CompareSCEVComplexity(LI, LHS, RHS) < 0; 691 }); 692 693 // Now that we are sorted by complexity, group elements of the same 694 // complexity. Note that this is, at worst, N^2, but the vector is likely to 695 // be extremely short in practice. Note that we take this approach because we 696 // do not want to depend on the addresses of the objects we are grouping. 697 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { 698 const SCEV *S = Ops[i]; 699 unsigned Complexity = S->getSCEVType(); 700 701 // If there are any objects of the same complexity and same value as this 702 // one, group them. 703 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { 704 if (Ops[j] == S) { // Found a duplicate. 705 // Move it to immediately after i'th element. 706 std::swap(Ops[i+1], Ops[j]); 707 ++i; // no need to rescan it. 708 if (i == e-2) return; // Done! 709 } 710 } 711 } 712 } 713 714 // Returns the size of the SCEV S. 715 static inline int sizeOfSCEV(const SCEV *S) { 716 struct FindSCEVSize { 717 int Size; 718 FindSCEVSize() : Size(0) {} 719 720 bool follow(const SCEV *S) { 721 ++Size; 722 // Keep looking at all operands of S. 723 return true; 724 } 725 bool isDone() const { 726 return false; 727 } 728 }; 729 730 FindSCEVSize F; 731 SCEVTraversal<FindSCEVSize> ST(F); 732 ST.visitAll(S); 733 return F.Size; 734 } 735 736 namespace { 737 738 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> { 739 public: 740 // Computes the Quotient and Remainder of the division of Numerator by 741 // Denominator. 742 static void divide(ScalarEvolution &SE, const SCEV *Numerator, 743 const SCEV *Denominator, const SCEV **Quotient, 744 const SCEV **Remainder) { 745 assert(Numerator && Denominator && "Uninitialized SCEV"); 746 747 SCEVDivision D(SE, Numerator, Denominator); 748 749 // Check for the trivial case here to avoid having to check for it in the 750 // rest of the code. 751 if (Numerator == Denominator) { 752 *Quotient = D.One; 753 *Remainder = D.Zero; 754 return; 755 } 756 757 if (Numerator->isZero()) { 758 *Quotient = D.Zero; 759 *Remainder = D.Zero; 760 return; 761 } 762 763 // A simple case when N/1. The quotient is N. 764 if (Denominator->isOne()) { 765 *Quotient = Numerator; 766 *Remainder = D.Zero; 767 return; 768 } 769 770 // Split the Denominator when it is a product. 771 if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) { 772 const SCEV *Q, *R; 773 *Quotient = Numerator; 774 for (const SCEV *Op : T->operands()) { 775 divide(SE, *Quotient, Op, &Q, &R); 776 *Quotient = Q; 777 778 // Bail out when the Numerator is not divisible by one of the terms of 779 // the Denominator. 780 if (!R->isZero()) { 781 *Quotient = D.Zero; 782 *Remainder = Numerator; 783 return; 784 } 785 } 786 *Remainder = D.Zero; 787 return; 788 } 789 790 D.visit(Numerator); 791 *Quotient = D.Quotient; 792 *Remainder = D.Remainder; 793 } 794 795 // Except in the trivial case described above, we do not know how to divide 796 // Expr by Denominator for the following functions with empty implementation. 797 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {} 798 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {} 799 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {} 800 void visitUDivExpr(const SCEVUDivExpr *Numerator) {} 801 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {} 802 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {} 803 void visitUnknown(const SCEVUnknown *Numerator) {} 804 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {} 805 806 void visitConstant(const SCEVConstant *Numerator) { 807 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) { 808 APInt NumeratorVal = Numerator->getAPInt(); 809 APInt DenominatorVal = D->getAPInt(); 810 uint32_t NumeratorBW = NumeratorVal.getBitWidth(); 811 uint32_t DenominatorBW = DenominatorVal.getBitWidth(); 812 813 if (NumeratorBW > DenominatorBW) 814 DenominatorVal = DenominatorVal.sext(NumeratorBW); 815 else if (NumeratorBW < DenominatorBW) 816 NumeratorVal = NumeratorVal.sext(DenominatorBW); 817 818 APInt QuotientVal(NumeratorVal.getBitWidth(), 0); 819 APInt RemainderVal(NumeratorVal.getBitWidth(), 0); 820 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal); 821 Quotient = SE.getConstant(QuotientVal); 822 Remainder = SE.getConstant(RemainderVal); 823 return; 824 } 825 } 826 827 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) { 828 const SCEV *StartQ, *StartR, *StepQ, *StepR; 829 if (!Numerator->isAffine()) 830 return cannotDivide(Numerator); 831 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR); 832 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR); 833 // Bail out if the types do not match. 834 Type *Ty = Denominator->getType(); 835 if (Ty != StartQ->getType() || Ty != StartR->getType() || 836 Ty != StepQ->getType() || Ty != StepR->getType()) 837 return cannotDivide(Numerator); 838 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(), 839 Numerator->getNoWrapFlags()); 840 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(), 841 Numerator->getNoWrapFlags()); 842 } 843 844 void visitAddExpr(const SCEVAddExpr *Numerator) { 845 SmallVector<const SCEV *, 2> Qs, Rs; 846 Type *Ty = Denominator->getType(); 847 848 for (const SCEV *Op : Numerator->operands()) { 849 const SCEV *Q, *R; 850 divide(SE, Op, Denominator, &Q, &R); 851 852 // Bail out if types do not match. 853 if (Ty != Q->getType() || Ty != R->getType()) 854 return cannotDivide(Numerator); 855 856 Qs.push_back(Q); 857 Rs.push_back(R); 858 } 859 860 if (Qs.size() == 1) { 861 Quotient = Qs[0]; 862 Remainder = Rs[0]; 863 return; 864 } 865 866 Quotient = SE.getAddExpr(Qs); 867 Remainder = SE.getAddExpr(Rs); 868 } 869 870 void visitMulExpr(const SCEVMulExpr *Numerator) { 871 SmallVector<const SCEV *, 2> Qs; 872 Type *Ty = Denominator->getType(); 873 874 bool FoundDenominatorTerm = false; 875 for (const SCEV *Op : Numerator->operands()) { 876 // Bail out if types do not match. 877 if (Ty != Op->getType()) 878 return cannotDivide(Numerator); 879 880 if (FoundDenominatorTerm) { 881 Qs.push_back(Op); 882 continue; 883 } 884 885 // Check whether Denominator divides one of the product operands. 886 const SCEV *Q, *R; 887 divide(SE, Op, Denominator, &Q, &R); 888 if (!R->isZero()) { 889 Qs.push_back(Op); 890 continue; 891 } 892 893 // Bail out if types do not match. 894 if (Ty != Q->getType()) 895 return cannotDivide(Numerator); 896 897 FoundDenominatorTerm = true; 898 Qs.push_back(Q); 899 } 900 901 if (FoundDenominatorTerm) { 902 Remainder = Zero; 903 if (Qs.size() == 1) 904 Quotient = Qs[0]; 905 else 906 Quotient = SE.getMulExpr(Qs); 907 return; 908 } 909 910 if (!isa<SCEVUnknown>(Denominator)) 911 return cannotDivide(Numerator); 912 913 // The Remainder is obtained by replacing Denominator by 0 in Numerator. 914 ValueToValueMap RewriteMap; 915 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 916 cast<SCEVConstant>(Zero)->getValue(); 917 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 918 919 if (Remainder->isZero()) { 920 // The Quotient is obtained by replacing Denominator by 1 in Numerator. 921 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 922 cast<SCEVConstant>(One)->getValue(); 923 Quotient = 924 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 925 return; 926 } 927 928 // Quotient is (Numerator - Remainder) divided by Denominator. 929 const SCEV *Q, *R; 930 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder); 931 // This SCEV does not seem to simplify: fail the division here. 932 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator)) 933 return cannotDivide(Numerator); 934 divide(SE, Diff, Denominator, &Q, &R); 935 if (R != Zero) 936 return cannotDivide(Numerator); 937 Quotient = Q; 938 } 939 940 private: 941 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator, 942 const SCEV *Denominator) 943 : SE(S), Denominator(Denominator) { 944 Zero = SE.getZero(Denominator->getType()); 945 One = SE.getOne(Denominator->getType()); 946 947 // We generally do not know how to divide Expr by Denominator. We 948 // initialize the division to a "cannot divide" state to simplify the rest 949 // of the code. 950 cannotDivide(Numerator); 951 } 952 953 // Convenience function for giving up on the division. We set the quotient to 954 // be equal to zero and the remainder to be equal to the numerator. 955 void cannotDivide(const SCEV *Numerator) { 956 Quotient = Zero; 957 Remainder = Numerator; 958 } 959 960 ScalarEvolution &SE; 961 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One; 962 }; 963 964 } 965 966 //===----------------------------------------------------------------------===// 967 // Simple SCEV method implementations 968 //===----------------------------------------------------------------------===// 969 970 /// Compute BC(It, K). The result has width W. Assume, K > 0. 971 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, 972 ScalarEvolution &SE, 973 Type *ResultTy) { 974 // Handle the simplest case efficiently. 975 if (K == 1) 976 return SE.getTruncateOrZeroExtend(It, ResultTy); 977 978 // We are using the following formula for BC(It, K): 979 // 980 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! 981 // 982 // Suppose, W is the bitwidth of the return value. We must be prepared for 983 // overflow. Hence, we must assure that the result of our computation is 984 // equal to the accurate one modulo 2^W. Unfortunately, division isn't 985 // safe in modular arithmetic. 986 // 987 // However, this code doesn't use exactly that formula; the formula it uses 988 // is something like the following, where T is the number of factors of 2 in 989 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is 990 // exponentiation: 991 // 992 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) 993 // 994 // This formula is trivially equivalent to the previous formula. However, 995 // this formula can be implemented much more efficiently. The trick is that 996 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular 997 // arithmetic. To do exact division in modular arithmetic, all we have 998 // to do is multiply by the inverse. Therefore, this step can be done at 999 // width W. 1000 // 1001 // The next issue is how to safely do the division by 2^T. The way this 1002 // is done is by doing the multiplication step at a width of at least W + T 1003 // bits. This way, the bottom W+T bits of the product are accurate. Then, 1004 // when we perform the division by 2^T (which is equivalent to a right shift 1005 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get 1006 // truncated out after the division by 2^T. 1007 // 1008 // In comparison to just directly using the first formula, this technique 1009 // is much more efficient; using the first formula requires W * K bits, 1010 // but this formula less than W + K bits. Also, the first formula requires 1011 // a division step, whereas this formula only requires multiplies and shifts. 1012 // 1013 // It doesn't matter whether the subtraction step is done in the calculation 1014 // width or the input iteration count's width; if the subtraction overflows, 1015 // the result must be zero anyway. We prefer here to do it in the width of 1016 // the induction variable because it helps a lot for certain cases; CodeGen 1017 // isn't smart enough to ignore the overflow, which leads to much less 1018 // efficient code if the width of the subtraction is wider than the native 1019 // register width. 1020 // 1021 // (It's possible to not widen at all by pulling out factors of 2 before 1022 // the multiplication; for example, K=2 can be calculated as 1023 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires 1024 // extra arithmetic, so it's not an obvious win, and it gets 1025 // much more complicated for K > 3.) 1026 1027 // Protection from insane SCEVs; this bound is conservative, 1028 // but it probably doesn't matter. 1029 if (K > 1000) 1030 return SE.getCouldNotCompute(); 1031 1032 unsigned W = SE.getTypeSizeInBits(ResultTy); 1033 1034 // Calculate K! / 2^T and T; we divide out the factors of two before 1035 // multiplying for calculating K! / 2^T to avoid overflow. 1036 // Other overflow doesn't matter because we only care about the bottom 1037 // W bits of the result. 1038 APInt OddFactorial(W, 1); 1039 unsigned T = 1; 1040 for (unsigned i = 3; i <= K; ++i) { 1041 APInt Mult(W, i); 1042 unsigned TwoFactors = Mult.countTrailingZeros(); 1043 T += TwoFactors; 1044 Mult = Mult.lshr(TwoFactors); 1045 OddFactorial *= Mult; 1046 } 1047 1048 // We need at least W + T bits for the multiplication step 1049 unsigned CalculationBits = W + T; 1050 1051 // Calculate 2^T, at width T+W. 1052 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T); 1053 1054 // Calculate the multiplicative inverse of K! / 2^T; 1055 // this multiplication factor will perform the exact division by 1056 // K! / 2^T. 1057 APInt Mod = APInt::getSignedMinValue(W+1); 1058 APInt MultiplyFactor = OddFactorial.zext(W+1); 1059 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); 1060 MultiplyFactor = MultiplyFactor.trunc(W); 1061 1062 // Calculate the product, at width T+W 1063 IntegerType *CalculationTy = IntegerType::get(SE.getContext(), 1064 CalculationBits); 1065 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); 1066 for (unsigned i = 1; i != K; ++i) { 1067 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); 1068 Dividend = SE.getMulExpr(Dividend, 1069 SE.getTruncateOrZeroExtend(S, CalculationTy)); 1070 } 1071 1072 // Divide by 2^T 1073 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); 1074 1075 // Truncate the result, and divide by K! / 2^T. 1076 1077 return SE.getMulExpr(SE.getConstant(MultiplyFactor), 1078 SE.getTruncateOrZeroExtend(DivResult, ResultTy)); 1079 } 1080 1081 /// Return the value of this chain of recurrences at the specified iteration 1082 /// number. We can evaluate this recurrence by multiplying each element in the 1083 /// chain by the binomial coefficient corresponding to it. In other words, we 1084 /// can evaluate {A,+,B,+,C,+,D} as: 1085 /// 1086 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) 1087 /// 1088 /// where BC(It, k) stands for binomial coefficient. 1089 /// 1090 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, 1091 ScalarEvolution &SE) const { 1092 const SCEV *Result = getStart(); 1093 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 1094 // The computation is correct in the face of overflow provided that the 1095 // multiplication is performed _after_ the evaluation of the binomial 1096 // coefficient. 1097 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType()); 1098 if (isa<SCEVCouldNotCompute>(Coeff)) 1099 return Coeff; 1100 1101 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff)); 1102 } 1103 return Result; 1104 } 1105 1106 //===----------------------------------------------------------------------===// 1107 // SCEV Expression folder implementations 1108 //===----------------------------------------------------------------------===// 1109 1110 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, 1111 Type *Ty) { 1112 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && 1113 "This is not a truncating conversion!"); 1114 assert(isSCEVable(Ty) && 1115 "This is not a conversion to a SCEVable type!"); 1116 Ty = getEffectiveSCEVType(Ty); 1117 1118 FoldingSetNodeID ID; 1119 ID.AddInteger(scTruncate); 1120 ID.AddPointer(Op); 1121 ID.AddPointer(Ty); 1122 void *IP = nullptr; 1123 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1124 1125 // Fold if the operand is constant. 1126 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1127 return getConstant( 1128 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); 1129 1130 // trunc(trunc(x)) --> trunc(x) 1131 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) 1132 return getTruncateExpr(ST->getOperand(), Ty); 1133 1134 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing 1135 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1136 return getTruncateOrSignExtend(SS->getOperand(), Ty); 1137 1138 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing 1139 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1140 return getTruncateOrZeroExtend(SZ->getOperand(), Ty); 1141 1142 // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can 1143 // eliminate all the truncates, or we replace other casts with truncates. 1144 if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) { 1145 SmallVector<const SCEV *, 4> Operands; 1146 bool hasTrunc = false; 1147 for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) { 1148 const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty); 1149 if (!isa<SCEVCastExpr>(SA->getOperand(i))) 1150 hasTrunc = isa<SCEVTruncateExpr>(S); 1151 Operands.push_back(S); 1152 } 1153 if (!hasTrunc) 1154 return getAddExpr(Operands); 1155 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL. 1156 } 1157 1158 // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can 1159 // eliminate all the truncates, or we replace other casts with truncates. 1160 if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) { 1161 SmallVector<const SCEV *, 4> Operands; 1162 bool hasTrunc = false; 1163 for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) { 1164 const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty); 1165 if (!isa<SCEVCastExpr>(SM->getOperand(i))) 1166 hasTrunc = isa<SCEVTruncateExpr>(S); 1167 Operands.push_back(S); 1168 } 1169 if (!hasTrunc) 1170 return getMulExpr(Operands); 1171 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL. 1172 } 1173 1174 // If the input value is a chrec scev, truncate the chrec's operands. 1175 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 1176 SmallVector<const SCEV *, 4> Operands; 1177 for (const SCEV *Op : AddRec->operands()) 1178 Operands.push_back(getTruncateExpr(Op, Ty)); 1179 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap); 1180 } 1181 1182 // The cast wasn't folded; create an explicit cast node. We can reuse 1183 // the existing insert position since if we get here, we won't have 1184 // made any changes which would invalidate it. 1185 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), 1186 Op, Ty); 1187 UniqueSCEVs.InsertNode(S, IP); 1188 return S; 1189 } 1190 1191 // Get the limit of a recurrence such that incrementing by Step cannot cause 1192 // signed overflow as long as the value of the recurrence within the 1193 // loop does not exceed this limit before incrementing. 1194 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step, 1195 ICmpInst::Predicate *Pred, 1196 ScalarEvolution *SE) { 1197 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1198 if (SE->isKnownPositive(Step)) { 1199 *Pred = ICmpInst::ICMP_SLT; 1200 return SE->getConstant(APInt::getSignedMinValue(BitWidth) - 1201 SE->getSignedRange(Step).getSignedMax()); 1202 } 1203 if (SE->isKnownNegative(Step)) { 1204 *Pred = ICmpInst::ICMP_SGT; 1205 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - 1206 SE->getSignedRange(Step).getSignedMin()); 1207 } 1208 return nullptr; 1209 } 1210 1211 // Get the limit of a recurrence such that incrementing by Step cannot cause 1212 // unsigned overflow as long as the value of the recurrence within the loop does 1213 // not exceed this limit before incrementing. 1214 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step, 1215 ICmpInst::Predicate *Pred, 1216 ScalarEvolution *SE) { 1217 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1218 *Pred = ICmpInst::ICMP_ULT; 1219 1220 return SE->getConstant(APInt::getMinValue(BitWidth) - 1221 SE->getUnsignedRange(Step).getUnsignedMax()); 1222 } 1223 1224 namespace { 1225 1226 struct ExtendOpTraitsBase { 1227 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *); 1228 }; 1229 1230 // Used to make code generic over signed and unsigned overflow. 1231 template <typename ExtendOp> struct ExtendOpTraits { 1232 // Members present: 1233 // 1234 // static const SCEV::NoWrapFlags WrapType; 1235 // 1236 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr; 1237 // 1238 // static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1239 // ICmpInst::Predicate *Pred, 1240 // ScalarEvolution *SE); 1241 }; 1242 1243 template <> 1244 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase { 1245 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW; 1246 1247 static const GetExtendExprTy GetExtendExpr; 1248 1249 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1250 ICmpInst::Predicate *Pred, 1251 ScalarEvolution *SE) { 1252 return getSignedOverflowLimitForStep(Step, Pred, SE); 1253 } 1254 }; 1255 1256 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1257 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr; 1258 1259 template <> 1260 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase { 1261 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW; 1262 1263 static const GetExtendExprTy GetExtendExpr; 1264 1265 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1266 ICmpInst::Predicate *Pred, 1267 ScalarEvolution *SE) { 1268 return getUnsignedOverflowLimitForStep(Step, Pred, SE); 1269 } 1270 }; 1271 1272 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1273 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr; 1274 } 1275 1276 // The recurrence AR has been shown to have no signed/unsigned wrap or something 1277 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as 1278 // easily prove NSW/NUW for its preincrement or postincrement sibling. This 1279 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step + 1280 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the 1281 // expression "Step + sext/zext(PreIncAR)" is congruent with 1282 // "sext/zext(PostIncAR)" 1283 template <typename ExtendOpTy> 1284 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, 1285 ScalarEvolution *SE) { 1286 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1287 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1288 1289 const Loop *L = AR->getLoop(); 1290 const SCEV *Start = AR->getStart(); 1291 const SCEV *Step = AR->getStepRecurrence(*SE); 1292 1293 // Check for a simple looking step prior to loop entry. 1294 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); 1295 if (!SA) 1296 return nullptr; 1297 1298 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV 1299 // subtraction is expensive. For this purpose, perform a quick and dirty 1300 // difference, by checking for Step in the operand list. 1301 SmallVector<const SCEV *, 4> DiffOps; 1302 for (const SCEV *Op : SA->operands()) 1303 if (Op != Step) 1304 DiffOps.push_back(Op); 1305 1306 if (DiffOps.size() == SA->getNumOperands()) 1307 return nullptr; 1308 1309 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` + 1310 // `Step`: 1311 1312 // 1. NSW/NUW flags on the step increment. 1313 auto PreStartFlags = 1314 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW); 1315 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags); 1316 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( 1317 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); 1318 1319 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies 1320 // "S+X does not sign/unsign-overflow". 1321 // 1322 1323 const SCEV *BECount = SE->getBackedgeTakenCount(L); 1324 if (PreAR && PreAR->getNoWrapFlags(WrapType) && 1325 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) 1326 return PreStart; 1327 1328 // 2. Direct overflow check on the step operation's expression. 1329 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); 1330 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); 1331 const SCEV *OperandExtendedStart = 1332 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy), 1333 (SE->*GetExtendExpr)(Step, WideTy)); 1334 if ((SE->*GetExtendExpr)(Start, WideTy) == OperandExtendedStart) { 1335 if (PreAR && AR->getNoWrapFlags(WrapType)) { 1336 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW 1337 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then 1338 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. 1339 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType); 1340 } 1341 return PreStart; 1342 } 1343 1344 // 3. Loop precondition. 1345 ICmpInst::Predicate Pred; 1346 const SCEV *OverflowLimit = 1347 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); 1348 1349 if (OverflowLimit && 1350 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) 1351 return PreStart; 1352 1353 return nullptr; 1354 } 1355 1356 // Get the normalized zero or sign extended expression for this AddRec's Start. 1357 template <typename ExtendOpTy> 1358 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, 1359 ScalarEvolution *SE) { 1360 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1361 1362 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE); 1363 if (!PreStart) 1364 return (SE->*GetExtendExpr)(AR->getStart(), Ty); 1365 1366 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty), 1367 (SE->*GetExtendExpr)(PreStart, Ty)); 1368 } 1369 1370 // Try to prove away overflow by looking at "nearby" add recurrences. A 1371 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it 1372 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. 1373 // 1374 // Formally: 1375 // 1376 // {S,+,X} == {S-T,+,X} + T 1377 // => Ext({S,+,X}) == Ext({S-T,+,X} + T) 1378 // 1379 // If ({S-T,+,X} + T) does not overflow ... (1) 1380 // 1381 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) 1382 // 1383 // If {S-T,+,X} does not overflow ... (2) 1384 // 1385 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) 1386 // == {Ext(S-T)+Ext(T),+,Ext(X)} 1387 // 1388 // If (S-T)+T does not overflow ... (3) 1389 // 1390 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} 1391 // == {Ext(S),+,Ext(X)} == LHS 1392 // 1393 // Thus, if (1), (2) and (3) are true for some T, then 1394 // Ext({S,+,X}) == {Ext(S),+,Ext(X)} 1395 // 1396 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) 1397 // does not overflow" restricted to the 0th iteration. Therefore we only need 1398 // to check for (1) and (2). 1399 // 1400 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T 1401 // is `Delta` (defined below). 1402 // 1403 template <typename ExtendOpTy> 1404 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, 1405 const SCEV *Step, 1406 const Loop *L) { 1407 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1408 1409 // We restrict `Start` to a constant to prevent SCEV from spending too much 1410 // time here. It is correct (but more expensive) to continue with a 1411 // non-constant `Start` and do a general SCEV subtraction to compute 1412 // `PreStart` below. 1413 // 1414 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); 1415 if (!StartC) 1416 return false; 1417 1418 APInt StartAI = StartC->getAPInt(); 1419 1420 for (unsigned Delta : {-2, -1, 1, 2}) { 1421 const SCEV *PreStart = getConstant(StartAI - Delta); 1422 1423 FoldingSetNodeID ID; 1424 ID.AddInteger(scAddRecExpr); 1425 ID.AddPointer(PreStart); 1426 ID.AddPointer(Step); 1427 ID.AddPointer(L); 1428 void *IP = nullptr; 1429 const auto *PreAR = 1430 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 1431 1432 // Give up if we don't already have the add recurrence we need because 1433 // actually constructing an add recurrence is relatively expensive. 1434 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2) 1435 const SCEV *DeltaS = getConstant(StartC->getType(), Delta); 1436 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; 1437 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep( 1438 DeltaS, &Pred, this); 1439 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1) 1440 return true; 1441 } 1442 } 1443 1444 return false; 1445 } 1446 1447 const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op, 1448 Type *Ty) { 1449 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1450 "This is not an extending conversion!"); 1451 assert(isSCEVable(Ty) && 1452 "This is not a conversion to a SCEVable type!"); 1453 Ty = getEffectiveSCEVType(Ty); 1454 1455 // Fold if the operand is constant. 1456 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1457 return getConstant( 1458 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty))); 1459 1460 // zext(zext(x)) --> zext(x) 1461 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1462 return getZeroExtendExpr(SZ->getOperand(), Ty); 1463 1464 // Before doing any expensive analysis, check to see if we've already 1465 // computed a SCEV for this Op and Ty. 1466 FoldingSetNodeID ID; 1467 ID.AddInteger(scZeroExtend); 1468 ID.AddPointer(Op); 1469 ID.AddPointer(Ty); 1470 void *IP = nullptr; 1471 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1472 1473 // zext(trunc(x)) --> zext(x) or x or trunc(x) 1474 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1475 // It's possible the bits taken off by the truncate were all zero bits. If 1476 // so, we should be able to simplify this further. 1477 const SCEV *X = ST->getOperand(); 1478 ConstantRange CR = getUnsignedRange(X); 1479 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1480 unsigned NewBits = getTypeSizeInBits(Ty); 1481 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( 1482 CR.zextOrTrunc(NewBits))) 1483 return getTruncateOrZeroExtend(X, Ty); 1484 } 1485 1486 // If the input value is a chrec scev, and we can prove that the value 1487 // did not overflow the old, smaller, value, we can zero extend all of the 1488 // operands (often constants). This allows analysis of something like 1489 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } 1490 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1491 if (AR->isAffine()) { 1492 const SCEV *Start = AR->getStart(); 1493 const SCEV *Step = AR->getStepRecurrence(*this); 1494 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1495 const Loop *L = AR->getLoop(); 1496 1497 if (!AR->hasNoUnsignedWrap()) { 1498 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1499 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1500 } 1501 1502 // If we have special knowledge that this addrec won't overflow, 1503 // we don't need to do any further analysis. 1504 if (AR->hasNoUnsignedWrap()) 1505 return getAddRecExpr( 1506 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), 1507 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1508 1509 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1510 // Note that this serves two purposes: It filters out loops that are 1511 // simply not analyzable, and it covers the case where this code is 1512 // being called from within backedge-taken count analysis, such that 1513 // attempting to ask for the backedge-taken count would likely result 1514 // in infinite recursion. In the later case, the analysis code will 1515 // cope with a conservative value, and it will take care to purge 1516 // that value once it has finished. 1517 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); 1518 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1519 // Manually compute the final value for AR, checking for 1520 // overflow. 1521 1522 // Check whether the backedge-taken count can be losslessly casted to 1523 // the addrec's type. The count is always unsigned. 1524 const SCEV *CastedMaxBECount = 1525 getTruncateOrZeroExtend(MaxBECount, Start->getType()); 1526 const SCEV *RecastedMaxBECount = 1527 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); 1528 if (MaxBECount == RecastedMaxBECount) { 1529 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1530 // Check whether Start+Step*MaxBECount has no unsigned overflow. 1531 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step); 1532 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul), WideTy); 1533 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy); 1534 const SCEV *WideMaxBECount = 1535 getZeroExtendExpr(CastedMaxBECount, WideTy); 1536 const SCEV *OperandExtendedAdd = 1537 getAddExpr(WideStart, 1538 getMulExpr(WideMaxBECount, 1539 getZeroExtendExpr(Step, WideTy))); 1540 if (ZAdd == OperandExtendedAdd) { 1541 // Cache knowledge of AR NUW, which is propagated to this AddRec. 1542 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1543 // Return the expression with the addrec on the outside. 1544 return getAddRecExpr( 1545 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), 1546 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1547 } 1548 // Similar to above, only this time treat the step value as signed. 1549 // This covers loops that count down. 1550 OperandExtendedAdd = 1551 getAddExpr(WideStart, 1552 getMulExpr(WideMaxBECount, 1553 getSignExtendExpr(Step, WideTy))); 1554 if (ZAdd == OperandExtendedAdd) { 1555 // Cache knowledge of AR NW, which is propagated to this AddRec. 1556 // Negative step causes unsigned wrap, but it still can't self-wrap. 1557 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1558 // Return the expression with the addrec on the outside. 1559 return getAddRecExpr( 1560 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), 1561 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1562 } 1563 } 1564 } 1565 1566 // Normally, in the cases we can prove no-overflow via a 1567 // backedge guarding condition, we can also compute a backedge 1568 // taken count for the loop. The exceptions are assumptions and 1569 // guards present in the loop -- SCEV is not great at exploiting 1570 // these to compute max backedge taken counts, but can still use 1571 // these to prove lack of overflow. Use this fact to avoid 1572 // doing extra work that may not pay off. 1573 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1574 !AC.assumptions().empty()) { 1575 // If the backedge is guarded by a comparison with the pre-inc 1576 // value the addrec is safe. Also, if the entry is guarded by 1577 // a comparison with the start value and the backedge is 1578 // guarded by a comparison with the post-inc value, the addrec 1579 // is safe. 1580 if (isKnownPositive(Step)) { 1581 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 1582 getUnsignedRange(Step).getUnsignedMax()); 1583 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 1584 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) && 1585 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, 1586 AR->getPostIncExpr(*this), N))) { 1587 // Cache knowledge of AR NUW, which is propagated to this 1588 // AddRec. 1589 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1590 // Return the expression with the addrec on the outside. 1591 return getAddRecExpr( 1592 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), 1593 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1594 } 1595 } else if (isKnownNegative(Step)) { 1596 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - 1597 getSignedRange(Step).getSignedMin()); 1598 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || 1599 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) && 1600 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, 1601 AR->getPostIncExpr(*this), N))) { 1602 // Cache knowledge of AR NW, which is propagated to this 1603 // AddRec. Negative step causes unsigned wrap, but it 1604 // still can't self-wrap. 1605 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1606 // Return the expression with the addrec on the outside. 1607 return getAddRecExpr( 1608 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), 1609 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1610 } 1611 } 1612 } 1613 1614 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { 1615 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1616 return getAddRecExpr( 1617 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), 1618 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1619 } 1620 } 1621 1622 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1623 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> 1624 if (SA->hasNoUnsignedWrap()) { 1625 // If the addition does not unsign overflow then we can, by definition, 1626 // commute the zero extension with the addition operation. 1627 SmallVector<const SCEV *, 4> Ops; 1628 for (const auto *Op : SA->operands()) 1629 Ops.push_back(getZeroExtendExpr(Op, Ty)); 1630 return getAddExpr(Ops, SCEV::FlagNUW); 1631 } 1632 } 1633 1634 // The cast wasn't folded; create an explicit cast node. 1635 // Recompute the insert position, as it may have been invalidated. 1636 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1637 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1638 Op, Ty); 1639 UniqueSCEVs.InsertNode(S, IP); 1640 return S; 1641 } 1642 1643 const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op, 1644 Type *Ty) { 1645 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1646 "This is not an extending conversion!"); 1647 assert(isSCEVable(Ty) && 1648 "This is not a conversion to a SCEVable type!"); 1649 Ty = getEffectiveSCEVType(Ty); 1650 1651 // Fold if the operand is constant. 1652 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1653 return getConstant( 1654 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); 1655 1656 // sext(sext(x)) --> sext(x) 1657 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1658 return getSignExtendExpr(SS->getOperand(), Ty); 1659 1660 // sext(zext(x)) --> zext(x) 1661 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1662 return getZeroExtendExpr(SZ->getOperand(), Ty); 1663 1664 // Before doing any expensive analysis, check to see if we've already 1665 // computed a SCEV for this Op and Ty. 1666 FoldingSetNodeID ID; 1667 ID.AddInteger(scSignExtend); 1668 ID.AddPointer(Op); 1669 ID.AddPointer(Ty); 1670 void *IP = nullptr; 1671 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1672 1673 // sext(trunc(x)) --> sext(x) or x or trunc(x) 1674 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1675 // It's possible the bits taken off by the truncate were all sign bits. If 1676 // so, we should be able to simplify this further. 1677 const SCEV *X = ST->getOperand(); 1678 ConstantRange CR = getSignedRange(X); 1679 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1680 unsigned NewBits = getTypeSizeInBits(Ty); 1681 if (CR.truncate(TruncBits).signExtend(NewBits).contains( 1682 CR.sextOrTrunc(NewBits))) 1683 return getTruncateOrSignExtend(X, Ty); 1684 } 1685 1686 // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2 1687 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1688 if (SA->getNumOperands() == 2) { 1689 auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0)); 1690 auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1)); 1691 if (SMul && SC1) { 1692 if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) { 1693 const APInt &C1 = SC1->getAPInt(); 1694 const APInt &C2 = SC2->getAPInt(); 1695 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && 1696 C2.ugt(C1) && C2.isPowerOf2()) 1697 return getAddExpr(getSignExtendExpr(SC1, Ty), 1698 getSignExtendExpr(SMul, Ty)); 1699 } 1700 } 1701 } 1702 1703 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 1704 if (SA->hasNoSignedWrap()) { 1705 // If the addition does not sign overflow then we can, by definition, 1706 // commute the sign extension with the addition operation. 1707 SmallVector<const SCEV *, 4> Ops; 1708 for (const auto *Op : SA->operands()) 1709 Ops.push_back(getSignExtendExpr(Op, Ty)); 1710 return getAddExpr(Ops, SCEV::FlagNSW); 1711 } 1712 } 1713 // If the input value is a chrec scev, and we can prove that the value 1714 // did not overflow the old, smaller, value, we can sign extend all of the 1715 // operands (often constants). This allows analysis of something like 1716 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 1717 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1718 if (AR->isAffine()) { 1719 const SCEV *Start = AR->getStart(); 1720 const SCEV *Step = AR->getStepRecurrence(*this); 1721 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1722 const Loop *L = AR->getLoop(); 1723 1724 if (!AR->hasNoSignedWrap()) { 1725 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1726 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1727 } 1728 1729 // If we have special knowledge that this addrec won't overflow, 1730 // we don't need to do any further analysis. 1731 if (AR->hasNoSignedWrap()) 1732 return getAddRecExpr( 1733 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), 1734 getSignExtendExpr(Step, Ty), L, SCEV::FlagNSW); 1735 1736 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1737 // Note that this serves two purposes: It filters out loops that are 1738 // simply not analyzable, and it covers the case where this code is 1739 // being called from within backedge-taken count analysis, such that 1740 // attempting to ask for the backedge-taken count would likely result 1741 // in infinite recursion. In the later case, the analysis code will 1742 // cope with a conservative value, and it will take care to purge 1743 // that value once it has finished. 1744 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); 1745 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1746 // Manually compute the final value for AR, checking for 1747 // overflow. 1748 1749 // Check whether the backedge-taken count can be losslessly casted to 1750 // the addrec's type. The count is always unsigned. 1751 const SCEV *CastedMaxBECount = 1752 getTruncateOrZeroExtend(MaxBECount, Start->getType()); 1753 const SCEV *RecastedMaxBECount = 1754 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); 1755 if (MaxBECount == RecastedMaxBECount) { 1756 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1757 // Check whether Start+Step*MaxBECount has no signed overflow. 1758 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step); 1759 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul), WideTy); 1760 const SCEV *WideStart = getSignExtendExpr(Start, WideTy); 1761 const SCEV *WideMaxBECount = 1762 getZeroExtendExpr(CastedMaxBECount, WideTy); 1763 const SCEV *OperandExtendedAdd = 1764 getAddExpr(WideStart, 1765 getMulExpr(WideMaxBECount, 1766 getSignExtendExpr(Step, WideTy))); 1767 if (SAdd == OperandExtendedAdd) { 1768 // Cache knowledge of AR NSW, which is propagated to this AddRec. 1769 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1770 // Return the expression with the addrec on the outside. 1771 return getAddRecExpr( 1772 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), 1773 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1774 } 1775 // Similar to above, only this time treat the step value as unsigned. 1776 // This covers loops that count up with an unsigned step. 1777 OperandExtendedAdd = 1778 getAddExpr(WideStart, 1779 getMulExpr(WideMaxBECount, 1780 getZeroExtendExpr(Step, WideTy))); 1781 if (SAdd == OperandExtendedAdd) { 1782 // If AR wraps around then 1783 // 1784 // abs(Step) * MaxBECount > unsigned-max(AR->getType()) 1785 // => SAdd != OperandExtendedAdd 1786 // 1787 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> 1788 // (SAdd == OperandExtendedAdd => AR is NW) 1789 1790 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1791 1792 // Return the expression with the addrec on the outside. 1793 return getAddRecExpr( 1794 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), 1795 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1796 } 1797 } 1798 } 1799 1800 // Normally, in the cases we can prove no-overflow via a 1801 // backedge guarding condition, we can also compute a backedge 1802 // taken count for the loop. The exceptions are assumptions and 1803 // guards present in the loop -- SCEV is not great at exploiting 1804 // these to compute max backedge taken counts, but can still use 1805 // these to prove lack of overflow. Use this fact to avoid 1806 // doing extra work that may not pay off. 1807 1808 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1809 !AC.assumptions().empty()) { 1810 // If the backedge is guarded by a comparison with the pre-inc 1811 // value the addrec is safe. Also, if the entry is guarded by 1812 // a comparison with the start value and the backedge is 1813 // guarded by a comparison with the post-inc value, the addrec 1814 // is safe. 1815 ICmpInst::Predicate Pred; 1816 const SCEV *OverflowLimit = 1817 getSignedOverflowLimitForStep(Step, &Pred, this); 1818 if (OverflowLimit && 1819 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 1820 (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) && 1821 isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this), 1822 OverflowLimit)))) { 1823 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec. 1824 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1825 return getAddRecExpr( 1826 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), 1827 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1828 } 1829 } 1830 1831 // If Start and Step are constants, check if we can apply this 1832 // transformation: 1833 // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2 1834 auto *SC1 = dyn_cast<SCEVConstant>(Start); 1835 auto *SC2 = dyn_cast<SCEVConstant>(Step); 1836 if (SC1 && SC2) { 1837 const APInt &C1 = SC1->getAPInt(); 1838 const APInt &C2 = SC2->getAPInt(); 1839 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) && 1840 C2.isPowerOf2()) { 1841 Start = getSignExtendExpr(Start, Ty); 1842 const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L, 1843 AR->getNoWrapFlags()); 1844 return getAddExpr(Start, getSignExtendExpr(NewAR, Ty)); 1845 } 1846 } 1847 1848 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { 1849 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1850 return getAddRecExpr( 1851 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), 1852 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1853 } 1854 } 1855 1856 // If the input value is provably positive and we could not simplify 1857 // away the sext build a zext instead. 1858 if (isKnownNonNegative(Op)) 1859 return getZeroExtendExpr(Op, Ty); 1860 1861 // The cast wasn't folded; create an explicit cast node. 1862 // Recompute the insert position, as it may have been invalidated. 1863 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1864 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1865 Op, Ty); 1866 UniqueSCEVs.InsertNode(S, IP); 1867 return S; 1868 } 1869 1870 /// getAnyExtendExpr - Return a SCEV for the given operand extended with 1871 /// unspecified bits out to the given type. 1872 /// 1873 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, 1874 Type *Ty) { 1875 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1876 "This is not an extending conversion!"); 1877 assert(isSCEVable(Ty) && 1878 "This is not a conversion to a SCEVable type!"); 1879 Ty = getEffectiveSCEVType(Ty); 1880 1881 // Sign-extend negative constants. 1882 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1883 if (SC->getAPInt().isNegative()) 1884 return getSignExtendExpr(Op, Ty); 1885 1886 // Peel off a truncate cast. 1887 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { 1888 const SCEV *NewOp = T->getOperand(); 1889 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) 1890 return getAnyExtendExpr(NewOp, Ty); 1891 return getTruncateOrNoop(NewOp, Ty); 1892 } 1893 1894 // Next try a zext cast. If the cast is folded, use it. 1895 const SCEV *ZExt = getZeroExtendExpr(Op, Ty); 1896 if (!isa<SCEVZeroExtendExpr>(ZExt)) 1897 return ZExt; 1898 1899 // Next try a sext cast. If the cast is folded, use it. 1900 const SCEV *SExt = getSignExtendExpr(Op, Ty); 1901 if (!isa<SCEVSignExtendExpr>(SExt)) 1902 return SExt; 1903 1904 // Force the cast to be folded into the operands of an addrec. 1905 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { 1906 SmallVector<const SCEV *, 4> Ops; 1907 for (const SCEV *Op : AR->operands()) 1908 Ops.push_back(getAnyExtendExpr(Op, Ty)); 1909 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); 1910 } 1911 1912 // If the expression is obviously signed, use the sext cast value. 1913 if (isa<SCEVSMaxExpr>(Op)) 1914 return SExt; 1915 1916 // Absent any other information, use the zext cast value. 1917 return ZExt; 1918 } 1919 1920 /// Process the given Ops list, which is a list of operands to be added under 1921 /// the given scale, update the given map. This is a helper function for 1922 /// getAddRecExpr. As an example of what it does, given a sequence of operands 1923 /// that would form an add expression like this: 1924 /// 1925 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r) 1926 /// 1927 /// where A and B are constants, update the map with these values: 1928 /// 1929 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) 1930 /// 1931 /// and add 13 + A*B*29 to AccumulatedConstant. 1932 /// This will allow getAddRecExpr to produce this: 1933 /// 1934 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) 1935 /// 1936 /// This form often exposes folding opportunities that are hidden in 1937 /// the original operand list. 1938 /// 1939 /// Return true iff it appears that any interesting folding opportunities 1940 /// may be exposed. This helps getAddRecExpr short-circuit extra work in 1941 /// the common case where no interesting opportunities are present, and 1942 /// is also used as a check to avoid infinite recursion. 1943 /// 1944 static bool 1945 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, 1946 SmallVectorImpl<const SCEV *> &NewOps, 1947 APInt &AccumulatedConstant, 1948 const SCEV *const *Ops, size_t NumOperands, 1949 const APInt &Scale, 1950 ScalarEvolution &SE) { 1951 bool Interesting = false; 1952 1953 // Iterate over the add operands. They are sorted, with constants first. 1954 unsigned i = 0; 1955 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 1956 ++i; 1957 // Pull a buried constant out to the outside. 1958 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) 1959 Interesting = true; 1960 AccumulatedConstant += Scale * C->getAPInt(); 1961 } 1962 1963 // Next comes everything else. We're especially interested in multiplies 1964 // here, but they're in the middle, so just visit the rest with one loop. 1965 for (; i != NumOperands; ++i) { 1966 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); 1967 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { 1968 APInt NewScale = 1969 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); 1970 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { 1971 // A multiplication of a constant with another add; recurse. 1972 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); 1973 Interesting |= 1974 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 1975 Add->op_begin(), Add->getNumOperands(), 1976 NewScale, SE); 1977 } else { 1978 // A multiplication of a constant with some other value. Update 1979 // the map. 1980 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end()); 1981 const SCEV *Key = SE.getMulExpr(MulOps); 1982 auto Pair = M.insert({Key, NewScale}); 1983 if (Pair.second) { 1984 NewOps.push_back(Pair.first->first); 1985 } else { 1986 Pair.first->second += NewScale; 1987 // The map already had an entry for this value, which may indicate 1988 // a folding opportunity. 1989 Interesting = true; 1990 } 1991 } 1992 } else { 1993 // An ordinary operand. Update the map. 1994 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = 1995 M.insert({Ops[i], Scale}); 1996 if (Pair.second) { 1997 NewOps.push_back(Pair.first->first); 1998 } else { 1999 Pair.first->second += Scale; 2000 // The map already had an entry for this value, which may indicate 2001 // a folding opportunity. 2002 Interesting = true; 2003 } 2004 } 2005 } 2006 2007 return Interesting; 2008 } 2009 2010 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and 2011 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of 2012 // can't-overflow flags for the operation if possible. 2013 static SCEV::NoWrapFlags 2014 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, 2015 const SmallVectorImpl<const SCEV *> &Ops, 2016 SCEV::NoWrapFlags Flags) { 2017 using namespace std::placeholders; 2018 typedef OverflowingBinaryOperator OBO; 2019 2020 bool CanAnalyze = 2021 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; 2022 (void)CanAnalyze; 2023 assert(CanAnalyze && "don't call from other places!"); 2024 2025 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 2026 SCEV::NoWrapFlags SignOrUnsignWrap = 2027 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2028 2029 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 2030 auto IsKnownNonNegative = [&](const SCEV *S) { 2031 return SE->isKnownNonNegative(S); 2032 }; 2033 2034 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) 2035 Flags = 2036 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); 2037 2038 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2039 2040 if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr && 2041 Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) { 2042 2043 // (A + C) --> (A + C)<nsw> if the addition does not sign overflow 2044 // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow 2045 2046 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); 2047 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { 2048 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2049 Instruction::Add, C, OBO::NoSignedWrap); 2050 if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) 2051 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2052 } 2053 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { 2054 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2055 Instruction::Add, C, OBO::NoUnsignedWrap); 2056 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) 2057 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2058 } 2059 } 2060 2061 return Flags; 2062 } 2063 2064 /// Get a canonical add expression, or something simpler if possible. 2065 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2066 SCEV::NoWrapFlags Flags) { 2067 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && 2068 "only nuw or nsw allowed"); 2069 assert(!Ops.empty() && "Cannot get empty add!"); 2070 if (Ops.size() == 1) return Ops[0]; 2071 #ifndef NDEBUG 2072 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2073 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2074 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2075 "SCEVAddExpr operand types don't match!"); 2076 #endif 2077 2078 // Sort by complexity, this groups all similar expression types together. 2079 GroupByComplexity(Ops, &LI); 2080 2081 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags); 2082 2083 // If there are any constants, fold them together. 2084 unsigned Idx = 0; 2085 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2086 ++Idx; 2087 assert(Idx < Ops.size()); 2088 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2089 // We found two constants, fold them together! 2090 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); 2091 if (Ops.size() == 2) return Ops[0]; 2092 Ops.erase(Ops.begin()+1); // Erase the folded element 2093 LHSC = cast<SCEVConstant>(Ops[0]); 2094 } 2095 2096 // If we are left with a constant zero being added, strip it off. 2097 if (LHSC->getValue()->isZero()) { 2098 Ops.erase(Ops.begin()); 2099 --Idx; 2100 } 2101 2102 if (Ops.size() == 1) return Ops[0]; 2103 } 2104 2105 // Okay, check to see if the same value occurs in the operand list more than 2106 // once. If so, merge them together into an multiply expression. Since we 2107 // sorted the list, these values are required to be adjacent. 2108 Type *Ty = Ops[0]->getType(); 2109 bool FoundMatch = false; 2110 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 2111 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 2112 // Scan ahead to count how many equal operands there are. 2113 unsigned Count = 2; 2114 while (i+Count != e && Ops[i+Count] == Ops[i]) 2115 ++Count; 2116 // Merge the values into a multiply. 2117 const SCEV *Scale = getConstant(Ty, Count); 2118 const SCEV *Mul = getMulExpr(Scale, Ops[i]); 2119 if (Ops.size() == Count) 2120 return Mul; 2121 Ops[i] = Mul; 2122 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 2123 --i; e -= Count - 1; 2124 FoundMatch = true; 2125 } 2126 if (FoundMatch) 2127 return getAddExpr(Ops, Flags); 2128 2129 // Check for truncates. If all the operands are truncated from the same 2130 // type, see if factoring out the truncate would permit the result to be 2131 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n) 2132 // if the contents of the resulting outer trunc fold to something simple. 2133 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) { 2134 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]); 2135 Type *DstType = Trunc->getType(); 2136 Type *SrcType = Trunc->getOperand()->getType(); 2137 SmallVector<const SCEV *, 8> LargeOps; 2138 bool Ok = true; 2139 // Check all the operands to see if they can be represented in the 2140 // source type of the truncate. 2141 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 2142 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 2143 if (T->getOperand()->getType() != SrcType) { 2144 Ok = false; 2145 break; 2146 } 2147 LargeOps.push_back(T->getOperand()); 2148 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2149 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 2150 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 2151 SmallVector<const SCEV *, 8> LargeMulOps; 2152 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 2153 if (const SCEVTruncateExpr *T = 2154 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 2155 if (T->getOperand()->getType() != SrcType) { 2156 Ok = false; 2157 break; 2158 } 2159 LargeMulOps.push_back(T->getOperand()); 2160 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { 2161 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 2162 } else { 2163 Ok = false; 2164 break; 2165 } 2166 } 2167 if (Ok) 2168 LargeOps.push_back(getMulExpr(LargeMulOps)); 2169 } else { 2170 Ok = false; 2171 break; 2172 } 2173 } 2174 if (Ok) { 2175 // Evaluate the expression in the larger type. 2176 const SCEV *Fold = getAddExpr(LargeOps, Flags); 2177 // If it folds to something simple, use it. Otherwise, don't. 2178 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 2179 return getTruncateExpr(Fold, DstType); 2180 } 2181 } 2182 2183 // Skip past any other cast SCEVs. 2184 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 2185 ++Idx; 2186 2187 // If there are add operands they would be next. 2188 if (Idx < Ops.size()) { 2189 bool DeletedAdd = false; 2190 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2191 // If we have an add, expand the add operands onto the end of the operands 2192 // list. 2193 Ops.erase(Ops.begin()+Idx); 2194 Ops.append(Add->op_begin(), Add->op_end()); 2195 DeletedAdd = true; 2196 } 2197 2198 // If we deleted at least one add, we added operands to the end of the list, 2199 // and they are not necessarily sorted. Recurse to resort and resimplify 2200 // any operands we just acquired. 2201 if (DeletedAdd) 2202 return getAddExpr(Ops); 2203 } 2204 2205 // Skip over the add expression until we get to a multiply. 2206 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2207 ++Idx; 2208 2209 // Check to see if there are any folding opportunities present with 2210 // operands multiplied by constant values. 2211 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2212 uint64_t BitWidth = getTypeSizeInBits(Ty); 2213 DenseMap<const SCEV *, APInt> M; 2214 SmallVector<const SCEV *, 8> NewOps; 2215 APInt AccumulatedConstant(BitWidth, 0); 2216 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2217 Ops.data(), Ops.size(), 2218 APInt(BitWidth, 1), *this)) { 2219 struct APIntCompare { 2220 bool operator()(const APInt &LHS, const APInt &RHS) const { 2221 return LHS.ult(RHS); 2222 } 2223 }; 2224 2225 // Some interesting folding opportunity is present, so its worthwhile to 2226 // re-generate the operands list. Group the operands by constant scale, 2227 // to avoid multiplying by the same constant scale multiple times. 2228 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2229 for (const SCEV *NewOp : NewOps) 2230 MulOpLists[M.find(NewOp)->second].push_back(NewOp); 2231 // Re-generate the operands list. 2232 Ops.clear(); 2233 if (AccumulatedConstant != 0) 2234 Ops.push_back(getConstant(AccumulatedConstant)); 2235 for (auto &MulOp : MulOpLists) 2236 if (MulOp.first != 0) 2237 Ops.push_back(getMulExpr(getConstant(MulOp.first), 2238 getAddExpr(MulOp.second))); 2239 if (Ops.empty()) 2240 return getZero(Ty); 2241 if (Ops.size() == 1) 2242 return Ops[0]; 2243 return getAddExpr(Ops); 2244 } 2245 } 2246 2247 // If we are adding something to a multiply expression, make sure the 2248 // something is not already an operand of the multiply. If so, merge it into 2249 // the multiply. 2250 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2251 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2252 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2253 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2254 if (isa<SCEVConstant>(MulOpSCEV)) 2255 continue; 2256 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2257 if (MulOpSCEV == Ops[AddOp]) { 2258 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2259 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2260 if (Mul->getNumOperands() != 2) { 2261 // If the multiply has more than two operands, we must get the 2262 // Y*Z term. 2263 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2264 Mul->op_begin()+MulOp); 2265 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2266 InnerMul = getMulExpr(MulOps); 2267 } 2268 const SCEV *One = getOne(Ty); 2269 const SCEV *AddOne = getAddExpr(One, InnerMul); 2270 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV); 2271 if (Ops.size() == 2) return OuterMul; 2272 if (AddOp < Idx) { 2273 Ops.erase(Ops.begin()+AddOp); 2274 Ops.erase(Ops.begin()+Idx-1); 2275 } else { 2276 Ops.erase(Ops.begin()+Idx); 2277 Ops.erase(Ops.begin()+AddOp-1); 2278 } 2279 Ops.push_back(OuterMul); 2280 return getAddExpr(Ops); 2281 } 2282 2283 // Check this multiply against other multiplies being added together. 2284 for (unsigned OtherMulIdx = Idx+1; 2285 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2286 ++OtherMulIdx) { 2287 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2288 // If MulOp occurs in OtherMul, we can fold the two multiplies 2289 // together. 2290 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2291 OMulOp != e; ++OMulOp) 2292 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2293 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2294 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2295 if (Mul->getNumOperands() != 2) { 2296 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2297 Mul->op_begin()+MulOp); 2298 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2299 InnerMul1 = getMulExpr(MulOps); 2300 } 2301 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2302 if (OtherMul->getNumOperands() != 2) { 2303 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2304 OtherMul->op_begin()+OMulOp); 2305 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2306 InnerMul2 = getMulExpr(MulOps); 2307 } 2308 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2); 2309 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum); 2310 if (Ops.size() == 2) return OuterMul; 2311 Ops.erase(Ops.begin()+Idx); 2312 Ops.erase(Ops.begin()+OtherMulIdx-1); 2313 Ops.push_back(OuterMul); 2314 return getAddExpr(Ops); 2315 } 2316 } 2317 } 2318 } 2319 2320 // If there are any add recurrences in the operands list, see if any other 2321 // added values are loop invariant. If so, we can fold them into the 2322 // recurrence. 2323 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2324 ++Idx; 2325 2326 // Scan over all recurrences, trying to fold loop invariants into them. 2327 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2328 // Scan all of the other operands to this add and add them to the vector if 2329 // they are loop invariant w.r.t. the recurrence. 2330 SmallVector<const SCEV *, 8> LIOps; 2331 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2332 const Loop *AddRecLoop = AddRec->getLoop(); 2333 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2334 if (isLoopInvariant(Ops[i], AddRecLoop)) { 2335 LIOps.push_back(Ops[i]); 2336 Ops.erase(Ops.begin()+i); 2337 --i; --e; 2338 } 2339 2340 // If we found some loop invariants, fold them into the recurrence. 2341 if (!LIOps.empty()) { 2342 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2343 LIOps.push_back(AddRec->getStart()); 2344 2345 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2346 AddRec->op_end()); 2347 // This follows from the fact that the no-wrap flags on the outer add 2348 // expression are applicable on the 0th iteration, when the add recurrence 2349 // will be equal to its start value. 2350 AddRecOps[0] = getAddExpr(LIOps, Flags); 2351 2352 // Build the new addrec. Propagate the NUW and NSW flags if both the 2353 // outer add and the inner addrec are guaranteed to have no overflow. 2354 // Always propagate NW. 2355 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2356 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2357 2358 // If all of the other operands were loop invariant, we are done. 2359 if (Ops.size() == 1) return NewRec; 2360 2361 // Otherwise, add the folded AddRec by the non-invariant parts. 2362 for (unsigned i = 0;; ++i) 2363 if (Ops[i] == AddRec) { 2364 Ops[i] = NewRec; 2365 break; 2366 } 2367 return getAddExpr(Ops); 2368 } 2369 2370 // Okay, if there weren't any loop invariants to be folded, check to see if 2371 // there are multiple AddRec's with the same loop induction variable being 2372 // added together. If so, we can fold them. 2373 for (unsigned OtherIdx = Idx+1; 2374 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2375 ++OtherIdx) 2376 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2377 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2378 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2379 AddRec->op_end()); 2380 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2381 ++OtherIdx) 2382 if (const auto *OtherAddRec = dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx])) 2383 if (OtherAddRec->getLoop() == AddRecLoop) { 2384 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2385 i != e; ++i) { 2386 if (i >= AddRecOps.size()) { 2387 AddRecOps.append(OtherAddRec->op_begin()+i, 2388 OtherAddRec->op_end()); 2389 break; 2390 } 2391 AddRecOps[i] = getAddExpr(AddRecOps[i], 2392 OtherAddRec->getOperand(i)); 2393 } 2394 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2395 } 2396 // Step size has changed, so we cannot guarantee no self-wraparound. 2397 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2398 return getAddExpr(Ops); 2399 } 2400 2401 // Otherwise couldn't fold anything into this recurrence. Move onto the 2402 // next one. 2403 } 2404 2405 // Okay, it looks like we really DO need an add expr. Check to see if we 2406 // already have one, otherwise create a new one. 2407 FoldingSetNodeID ID; 2408 ID.AddInteger(scAddExpr); 2409 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2410 ID.AddPointer(Ops[i]); 2411 void *IP = nullptr; 2412 SCEVAddExpr *S = 2413 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2414 if (!S) { 2415 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2416 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2417 S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator), 2418 O, Ops.size()); 2419 UniqueSCEVs.InsertNode(S, IP); 2420 } 2421 S->setNoWrapFlags(Flags); 2422 return S; 2423 } 2424 2425 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2426 uint64_t k = i*j; 2427 if (j > 1 && k / j != i) Overflow = true; 2428 return k; 2429 } 2430 2431 /// Compute the result of "n choose k", the binomial coefficient. If an 2432 /// intermediate computation overflows, Overflow will be set and the return will 2433 /// be garbage. Overflow is not cleared on absence of overflow. 2434 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 2435 // We use the multiplicative formula: 2436 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 2437 // At each iteration, we take the n-th term of the numeral and divide by the 2438 // (k-n)th term of the denominator. This division will always produce an 2439 // integral result, and helps reduce the chance of overflow in the 2440 // intermediate computations. However, we can still overflow even when the 2441 // final result would fit. 2442 2443 if (n == 0 || n == k) return 1; 2444 if (k > n) return 0; 2445 2446 if (k > n/2) 2447 k = n-k; 2448 2449 uint64_t r = 1; 2450 for (uint64_t i = 1; i <= k; ++i) { 2451 r = umul_ov(r, n-(i-1), Overflow); 2452 r /= i; 2453 } 2454 return r; 2455 } 2456 2457 /// Determine if any of the operands in this SCEV are a constant or if 2458 /// any of the add or multiply expressions in this SCEV contain a constant. 2459 static bool containsConstantSomewhere(const SCEV *StartExpr) { 2460 SmallVector<const SCEV *, 4> Ops; 2461 Ops.push_back(StartExpr); 2462 while (!Ops.empty()) { 2463 const SCEV *CurrentExpr = Ops.pop_back_val(); 2464 if (isa<SCEVConstant>(*CurrentExpr)) 2465 return true; 2466 2467 if (isa<SCEVAddExpr>(*CurrentExpr) || isa<SCEVMulExpr>(*CurrentExpr)) { 2468 const auto *CurrentNAry = cast<SCEVNAryExpr>(CurrentExpr); 2469 Ops.append(CurrentNAry->op_begin(), CurrentNAry->op_end()); 2470 } 2471 } 2472 return false; 2473 } 2474 2475 /// Get a canonical multiply expression, or something simpler if possible. 2476 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2477 SCEV::NoWrapFlags Flags) { 2478 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && 2479 "only nuw or nsw allowed"); 2480 assert(!Ops.empty() && "Cannot get empty mul!"); 2481 if (Ops.size() == 1) return Ops[0]; 2482 #ifndef NDEBUG 2483 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2484 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2485 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2486 "SCEVMulExpr operand types don't match!"); 2487 #endif 2488 2489 // Sort by complexity, this groups all similar expression types together. 2490 GroupByComplexity(Ops, &LI); 2491 2492 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags); 2493 2494 // If there are any constants, fold them together. 2495 unsigned Idx = 0; 2496 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2497 2498 // C1*(C2+V) -> C1*C2 + C1*V 2499 if (Ops.size() == 2) 2500 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 2501 // If any of Add's ops are Adds or Muls with a constant, 2502 // apply this transformation as well. 2503 if (Add->getNumOperands() == 2) 2504 if (containsConstantSomewhere(Add)) 2505 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)), 2506 getMulExpr(LHSC, Add->getOperand(1))); 2507 2508 ++Idx; 2509 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2510 // We found two constants, fold them together! 2511 ConstantInt *Fold = 2512 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt()); 2513 Ops[0] = getConstant(Fold); 2514 Ops.erase(Ops.begin()+1); // Erase the folded element 2515 if (Ops.size() == 1) return Ops[0]; 2516 LHSC = cast<SCEVConstant>(Ops[0]); 2517 } 2518 2519 // If we are left with a constant one being multiplied, strip it off. 2520 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) { 2521 Ops.erase(Ops.begin()); 2522 --Idx; 2523 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) { 2524 // If we have a multiply of zero, it will always be zero. 2525 return Ops[0]; 2526 } else if (Ops[0]->isAllOnesValue()) { 2527 // If we have a mul by -1 of an add, try distributing the -1 among the 2528 // add operands. 2529 if (Ops.size() == 2) { 2530 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 2531 SmallVector<const SCEV *, 4> NewOps; 2532 bool AnyFolded = false; 2533 for (const SCEV *AddOp : Add->operands()) { 2534 const SCEV *Mul = getMulExpr(Ops[0], AddOp); 2535 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 2536 NewOps.push_back(Mul); 2537 } 2538 if (AnyFolded) 2539 return getAddExpr(NewOps); 2540 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 2541 // Negation preserves a recurrence's no self-wrap property. 2542 SmallVector<const SCEV *, 4> Operands; 2543 for (const SCEV *AddRecOp : AddRec->operands()) 2544 Operands.push_back(getMulExpr(Ops[0], AddRecOp)); 2545 2546 return getAddRecExpr(Operands, AddRec->getLoop(), 2547 AddRec->getNoWrapFlags(SCEV::FlagNW)); 2548 } 2549 } 2550 } 2551 2552 if (Ops.size() == 1) 2553 return Ops[0]; 2554 } 2555 2556 // Skip over the add expression until we get to a multiply. 2557 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2558 ++Idx; 2559 2560 // If there are mul operands inline them all into this expression. 2561 if (Idx < Ops.size()) { 2562 bool DeletedMul = false; 2563 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2564 if (Ops.size() > MulOpsInlineThreshold) 2565 break; 2566 // If we have an mul, expand the mul operands onto the end of the operands 2567 // list. 2568 Ops.erase(Ops.begin()+Idx); 2569 Ops.append(Mul->op_begin(), Mul->op_end()); 2570 DeletedMul = true; 2571 } 2572 2573 // If we deleted at least one mul, we added operands to the end of the list, 2574 // and they are not necessarily sorted. Recurse to resort and resimplify 2575 // any operands we just acquired. 2576 if (DeletedMul) 2577 return getMulExpr(Ops); 2578 } 2579 2580 // If there are any add recurrences in the operands list, see if any other 2581 // added values are loop invariant. If so, we can fold them into the 2582 // recurrence. 2583 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2584 ++Idx; 2585 2586 // Scan over all recurrences, trying to fold loop invariants into them. 2587 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2588 // Scan all of the other operands to this mul and add them to the vector if 2589 // they are loop invariant w.r.t. the recurrence. 2590 SmallVector<const SCEV *, 8> LIOps; 2591 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2592 const Loop *AddRecLoop = AddRec->getLoop(); 2593 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2594 if (isLoopInvariant(Ops[i], AddRecLoop)) { 2595 LIOps.push_back(Ops[i]); 2596 Ops.erase(Ops.begin()+i); 2597 --i; --e; 2598 } 2599 2600 // If we found some loop invariants, fold them into the recurrence. 2601 if (!LIOps.empty()) { 2602 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 2603 SmallVector<const SCEV *, 4> NewOps; 2604 NewOps.reserve(AddRec->getNumOperands()); 2605 const SCEV *Scale = getMulExpr(LIOps); 2606 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 2607 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i))); 2608 2609 // Build the new addrec. Propagate the NUW and NSW flags if both the 2610 // outer mul and the inner addrec are guaranteed to have no overflow. 2611 // 2612 // No self-wrap cannot be guaranteed after changing the step size, but 2613 // will be inferred if either NUW or NSW is true. 2614 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW)); 2615 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags); 2616 2617 // If all of the other operands were loop invariant, we are done. 2618 if (Ops.size() == 1) return NewRec; 2619 2620 // Otherwise, multiply the folded AddRec by the non-invariant parts. 2621 for (unsigned i = 0;; ++i) 2622 if (Ops[i] == AddRec) { 2623 Ops[i] = NewRec; 2624 break; 2625 } 2626 return getMulExpr(Ops); 2627 } 2628 2629 // Okay, if there weren't any loop invariants to be folded, check to see if 2630 // there are multiple AddRec's with the same loop induction variable being 2631 // multiplied together. If so, we can fold them. 2632 2633 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 2634 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 2635 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 2636 // ]]],+,...up to x=2n}. 2637 // Note that the arguments to choose() are always integers with values 2638 // known at compile time, never SCEV objects. 2639 // 2640 // The implementation avoids pointless extra computations when the two 2641 // addrec's are of different length (mathematically, it's equivalent to 2642 // an infinite stream of zeros on the right). 2643 bool OpsModified = false; 2644 for (unsigned OtherIdx = Idx+1; 2645 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2646 ++OtherIdx) { 2647 const SCEVAddRecExpr *OtherAddRec = 2648 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2649 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 2650 continue; 2651 2652 bool Overflow = false; 2653 Type *Ty = AddRec->getType(); 2654 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 2655 SmallVector<const SCEV*, 7> AddRecOps; 2656 for (int x = 0, xe = AddRec->getNumOperands() + 2657 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 2658 const SCEV *Term = getZero(Ty); 2659 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 2660 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 2661 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 2662 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 2663 z < ze && !Overflow; ++z) { 2664 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 2665 uint64_t Coeff; 2666 if (LargerThan64Bits) 2667 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 2668 else 2669 Coeff = Coeff1*Coeff2; 2670 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 2671 const SCEV *Term1 = AddRec->getOperand(y-z); 2672 const SCEV *Term2 = OtherAddRec->getOperand(z); 2673 Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1,Term2)); 2674 } 2675 } 2676 AddRecOps.push_back(Term); 2677 } 2678 if (!Overflow) { 2679 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(), 2680 SCEV::FlagAnyWrap); 2681 if (Ops.size() == 2) return NewAddRec; 2682 Ops[Idx] = NewAddRec; 2683 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2684 OpsModified = true; 2685 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 2686 if (!AddRec) 2687 break; 2688 } 2689 } 2690 if (OpsModified) 2691 return getMulExpr(Ops); 2692 2693 // Otherwise couldn't fold anything into this recurrence. Move onto the 2694 // next one. 2695 } 2696 2697 // Okay, it looks like we really DO need an mul expr. Check to see if we 2698 // already have one, otherwise create a new one. 2699 FoldingSetNodeID ID; 2700 ID.AddInteger(scMulExpr); 2701 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2702 ID.AddPointer(Ops[i]); 2703 void *IP = nullptr; 2704 SCEVMulExpr *S = 2705 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2706 if (!S) { 2707 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2708 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2709 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2710 O, Ops.size()); 2711 UniqueSCEVs.InsertNode(S, IP); 2712 } 2713 S->setNoWrapFlags(Flags); 2714 return S; 2715 } 2716 2717 /// Get a canonical unsigned division expression, or something simpler if 2718 /// possible. 2719 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 2720 const SCEV *RHS) { 2721 assert(getEffectiveSCEVType(LHS->getType()) == 2722 getEffectiveSCEVType(RHS->getType()) && 2723 "SCEVUDivExpr operand types don't match!"); 2724 2725 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 2726 if (RHSC->getValue()->equalsInt(1)) 2727 return LHS; // X udiv 1 --> x 2728 // If the denominator is zero, the result of the udiv is undefined. Don't 2729 // try to analyze it, because the resolution chosen here may differ from 2730 // the resolution chosen in other parts of the compiler. 2731 if (!RHSC->getValue()->isZero()) { 2732 // Determine if the division can be folded into the operands of 2733 // its operands. 2734 // TODO: Generalize this to non-constants by using known-bits information. 2735 Type *Ty = LHS->getType(); 2736 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 2737 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 2738 // For non-power-of-two values, effectively round the value up to the 2739 // nearest power of two. 2740 if (!RHSC->getAPInt().isPowerOf2()) 2741 ++MaxShiftAmt; 2742 IntegerType *ExtTy = 2743 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 2744 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 2745 if (const SCEVConstant *Step = 2746 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 2747 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 2748 const APInt &StepInt = Step->getAPInt(); 2749 const APInt &DivInt = RHSC->getAPInt(); 2750 if (!StepInt.urem(DivInt) && 2751 getZeroExtendExpr(AR, ExtTy) == 2752 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 2753 getZeroExtendExpr(Step, ExtTy), 2754 AR->getLoop(), SCEV::FlagAnyWrap)) { 2755 SmallVector<const SCEV *, 4> Operands; 2756 for (const SCEV *Op : AR->operands()) 2757 Operands.push_back(getUDivExpr(Op, RHS)); 2758 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 2759 } 2760 /// Get a canonical UDivExpr for a recurrence. 2761 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 2762 // We can currently only fold X%N if X is constant. 2763 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 2764 if (StartC && !DivInt.urem(StepInt) && 2765 getZeroExtendExpr(AR, ExtTy) == 2766 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 2767 getZeroExtendExpr(Step, ExtTy), 2768 AR->getLoop(), SCEV::FlagAnyWrap)) { 2769 const APInt &StartInt = StartC->getAPInt(); 2770 const APInt &StartRem = StartInt.urem(StepInt); 2771 if (StartRem != 0) 2772 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step, 2773 AR->getLoop(), SCEV::FlagNW); 2774 } 2775 } 2776 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 2777 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 2778 SmallVector<const SCEV *, 4> Operands; 2779 for (const SCEV *Op : M->operands()) 2780 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 2781 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 2782 // Find an operand that's safely divisible. 2783 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 2784 const SCEV *Op = M->getOperand(i); 2785 const SCEV *Div = getUDivExpr(Op, RHSC); 2786 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 2787 Operands = SmallVector<const SCEV *, 4>(M->op_begin(), 2788 M->op_end()); 2789 Operands[i] = Div; 2790 return getMulExpr(Operands); 2791 } 2792 } 2793 } 2794 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 2795 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 2796 SmallVector<const SCEV *, 4> Operands; 2797 for (const SCEV *Op : A->operands()) 2798 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 2799 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 2800 Operands.clear(); 2801 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 2802 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 2803 if (isa<SCEVUDivExpr>(Op) || 2804 getMulExpr(Op, RHS) != A->getOperand(i)) 2805 break; 2806 Operands.push_back(Op); 2807 } 2808 if (Operands.size() == A->getNumOperands()) 2809 return getAddExpr(Operands); 2810 } 2811 } 2812 2813 // Fold if both operands are constant. 2814 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 2815 Constant *LHSCV = LHSC->getValue(); 2816 Constant *RHSCV = RHSC->getValue(); 2817 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 2818 RHSCV))); 2819 } 2820 } 2821 } 2822 2823 FoldingSetNodeID ID; 2824 ID.AddInteger(scUDivExpr); 2825 ID.AddPointer(LHS); 2826 ID.AddPointer(RHS); 2827 void *IP = nullptr; 2828 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 2829 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 2830 LHS, RHS); 2831 UniqueSCEVs.InsertNode(S, IP); 2832 return S; 2833 } 2834 2835 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 2836 APInt A = C1->getAPInt().abs(); 2837 APInt B = C2->getAPInt().abs(); 2838 uint32_t ABW = A.getBitWidth(); 2839 uint32_t BBW = B.getBitWidth(); 2840 2841 if (ABW > BBW) 2842 B = B.zext(ABW); 2843 else if (ABW < BBW) 2844 A = A.zext(BBW); 2845 2846 return APIntOps::GreatestCommonDivisor(A, B); 2847 } 2848 2849 /// Get a canonical unsigned division expression, or something simpler if 2850 /// possible. There is no representation for an exact udiv in SCEV IR, but we 2851 /// can attempt to remove factors from the LHS and RHS. We can't do this when 2852 /// it's not exact because the udiv may be clearing bits. 2853 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 2854 const SCEV *RHS) { 2855 // TODO: we could try to find factors in all sorts of things, but for now we 2856 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 2857 // end of this file for inspiration. 2858 2859 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 2860 if (!Mul) 2861 return getUDivExpr(LHS, RHS); 2862 2863 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 2864 // If the mulexpr multiplies by a constant, then that constant must be the 2865 // first element of the mulexpr. 2866 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 2867 if (LHSCst == RHSCst) { 2868 SmallVector<const SCEV *, 2> Operands; 2869 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 2870 return getMulExpr(Operands); 2871 } 2872 2873 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 2874 // that there's a factor provided by one of the other terms. We need to 2875 // check. 2876 APInt Factor = gcd(LHSCst, RHSCst); 2877 if (!Factor.isIntN(1)) { 2878 LHSCst = 2879 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 2880 RHSCst = 2881 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 2882 SmallVector<const SCEV *, 2> Operands; 2883 Operands.push_back(LHSCst); 2884 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 2885 LHS = getMulExpr(Operands); 2886 RHS = RHSCst; 2887 Mul = dyn_cast<SCEVMulExpr>(LHS); 2888 if (!Mul) 2889 return getUDivExactExpr(LHS, RHS); 2890 } 2891 } 2892 } 2893 2894 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 2895 if (Mul->getOperand(i) == RHS) { 2896 SmallVector<const SCEV *, 2> Operands; 2897 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 2898 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 2899 return getMulExpr(Operands); 2900 } 2901 } 2902 2903 return getUDivExpr(LHS, RHS); 2904 } 2905 2906 /// Get an add recurrence expression for the specified loop. Simplify the 2907 /// expression as much as possible. 2908 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 2909 const Loop *L, 2910 SCEV::NoWrapFlags Flags) { 2911 SmallVector<const SCEV *, 4> Operands; 2912 Operands.push_back(Start); 2913 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 2914 if (StepChrec->getLoop() == L) { 2915 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 2916 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 2917 } 2918 2919 Operands.push_back(Step); 2920 return getAddRecExpr(Operands, L, Flags); 2921 } 2922 2923 /// Get an add recurrence expression for the specified loop. Simplify the 2924 /// expression as much as possible. 2925 const SCEV * 2926 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 2927 const Loop *L, SCEV::NoWrapFlags Flags) { 2928 if (Operands.size() == 1) return Operands[0]; 2929 #ifndef NDEBUG 2930 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 2931 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 2932 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 2933 "SCEVAddRecExpr operand types don't match!"); 2934 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 2935 assert(isLoopInvariant(Operands[i], L) && 2936 "SCEVAddRecExpr operand is not loop-invariant!"); 2937 #endif 2938 2939 if (Operands.back()->isZero()) { 2940 Operands.pop_back(); 2941 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 2942 } 2943 2944 // It's tempting to want to call getMaxBackedgeTakenCount count here and 2945 // use that information to infer NUW and NSW flags. However, computing a 2946 // BE count requires calling getAddRecExpr, so we may not yet have a 2947 // meaningful BE count at this point (and if we don't, we'd be stuck 2948 // with a SCEVCouldNotCompute as the cached BE count). 2949 2950 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 2951 2952 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 2953 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 2954 const Loop *NestedLoop = NestedAR->getLoop(); 2955 if (L->contains(NestedLoop) 2956 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 2957 : (!NestedLoop->contains(L) && 2958 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 2959 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(), 2960 NestedAR->op_end()); 2961 Operands[0] = NestedAR->getStart(); 2962 // AddRecs require their operands be loop-invariant with respect to their 2963 // loops. Don't perform this transformation if it would break this 2964 // requirement. 2965 bool AllInvariant = all_of( 2966 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 2967 2968 if (AllInvariant) { 2969 // Create a recurrence for the outer loop with the same step size. 2970 // 2971 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 2972 // inner recurrence has the same property. 2973 SCEV::NoWrapFlags OuterFlags = 2974 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 2975 2976 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 2977 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 2978 return isLoopInvariant(Op, NestedLoop); 2979 }); 2980 2981 if (AllInvariant) { 2982 // Ok, both add recurrences are valid after the transformation. 2983 // 2984 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 2985 // the outer recurrence has the same property. 2986 SCEV::NoWrapFlags InnerFlags = 2987 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 2988 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 2989 } 2990 } 2991 // Reset Operands to its original state. 2992 Operands[0] = NestedAR; 2993 } 2994 } 2995 2996 // Okay, it looks like we really DO need an addrec expr. Check to see if we 2997 // already have one, otherwise create a new one. 2998 FoldingSetNodeID ID; 2999 ID.AddInteger(scAddRecExpr); 3000 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3001 ID.AddPointer(Operands[i]); 3002 ID.AddPointer(L); 3003 void *IP = nullptr; 3004 SCEVAddRecExpr *S = 3005 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 3006 if (!S) { 3007 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size()); 3008 std::uninitialized_copy(Operands.begin(), Operands.end(), O); 3009 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator), 3010 O, Operands.size(), L); 3011 UniqueSCEVs.InsertNode(S, IP); 3012 } 3013 S->setNoWrapFlags(Flags); 3014 return S; 3015 } 3016 3017 const SCEV * 3018 ScalarEvolution::getGEPExpr(Type *PointeeType, const SCEV *BaseExpr, 3019 const SmallVectorImpl<const SCEV *> &IndexExprs, 3020 bool InBounds) { 3021 // getSCEV(Base)->getType() has the same address space as Base->getType() 3022 // because SCEV::getType() preserves the address space. 3023 Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType()); 3024 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP 3025 // instruction to its SCEV, because the Instruction may be guarded by control 3026 // flow and the no-overflow bits may not be valid for the expression in any 3027 // context. This can be fixed similarly to how these flags are handled for 3028 // adds. 3029 SCEV::NoWrapFlags Wrap = InBounds ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3030 3031 const SCEV *TotalOffset = getZero(IntPtrTy); 3032 // The address space is unimportant. The first thing we do on CurTy is getting 3033 // its element type. 3034 Type *CurTy = PointerType::getUnqual(PointeeType); 3035 for (const SCEV *IndexExpr : IndexExprs) { 3036 // Compute the (potentially symbolic) offset in bytes for this index. 3037 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 3038 // For a struct, add the member offset. 3039 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 3040 unsigned FieldNo = Index->getZExtValue(); 3041 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo); 3042 3043 // Add the field offset to the running total offset. 3044 TotalOffset = getAddExpr(TotalOffset, FieldOffset); 3045 3046 // Update CurTy to the type of the field at Index. 3047 CurTy = STy->getTypeAtIndex(Index); 3048 } else { 3049 // Update CurTy to its element type. 3050 CurTy = cast<SequentialType>(CurTy)->getElementType(); 3051 // For an array, add the element offset, explicitly scaled. 3052 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy); 3053 // Getelementptr indices are signed. 3054 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy); 3055 3056 // Multiply the index by the element size to compute the element offset. 3057 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap); 3058 3059 // Add the element offset to the running total offset. 3060 TotalOffset = getAddExpr(TotalOffset, LocalOffset); 3061 } 3062 } 3063 3064 // Add the total offset from all the GEP indices to the base. 3065 return getAddExpr(BaseExpr, TotalOffset, Wrap); 3066 } 3067 3068 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, 3069 const SCEV *RHS) { 3070 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3071 return getSMaxExpr(Ops); 3072 } 3073 3074 const SCEV * 3075 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3076 assert(!Ops.empty() && "Cannot get empty smax!"); 3077 if (Ops.size() == 1) return Ops[0]; 3078 #ifndef NDEBUG 3079 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3080 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3081 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3082 "SCEVSMaxExpr operand types don't match!"); 3083 #endif 3084 3085 // Sort by complexity, this groups all similar expression types together. 3086 GroupByComplexity(Ops, &LI); 3087 3088 // If there are any constants, fold them together. 3089 unsigned Idx = 0; 3090 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3091 ++Idx; 3092 assert(Idx < Ops.size()); 3093 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3094 // We found two constants, fold them together! 3095 ConstantInt *Fold = ConstantInt::get( 3096 getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt())); 3097 Ops[0] = getConstant(Fold); 3098 Ops.erase(Ops.begin()+1); // Erase the folded element 3099 if (Ops.size() == 1) return Ops[0]; 3100 LHSC = cast<SCEVConstant>(Ops[0]); 3101 } 3102 3103 // If we are left with a constant minimum-int, strip it off. 3104 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) { 3105 Ops.erase(Ops.begin()); 3106 --Idx; 3107 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) { 3108 // If we have an smax with a constant maximum-int, it will always be 3109 // maximum-int. 3110 return Ops[0]; 3111 } 3112 3113 if (Ops.size() == 1) return Ops[0]; 3114 } 3115 3116 // Find the first SMax 3117 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr) 3118 ++Idx; 3119 3120 // Check to see if one of the operands is an SMax. If so, expand its operands 3121 // onto our operand list, and recurse to simplify. 3122 if (Idx < Ops.size()) { 3123 bool DeletedSMax = false; 3124 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) { 3125 Ops.erase(Ops.begin()+Idx); 3126 Ops.append(SMax->op_begin(), SMax->op_end()); 3127 DeletedSMax = true; 3128 } 3129 3130 if (DeletedSMax) 3131 return getSMaxExpr(Ops); 3132 } 3133 3134 // Okay, check to see if the same value occurs in the operand list twice. If 3135 // so, delete one. Since we sorted the list, these values are required to 3136 // be adjacent. 3137 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 3138 // X smax Y smax Y --> X smax Y 3139 // X smax Y --> X, if X is always greater than Y 3140 if (Ops[i] == Ops[i+1] || 3141 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) { 3142 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); 3143 --i; --e; 3144 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) { 3145 Ops.erase(Ops.begin()+i, Ops.begin()+i+1); 3146 --i; --e; 3147 } 3148 3149 if (Ops.size() == 1) return Ops[0]; 3150 3151 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3152 3153 // Okay, it looks like we really DO need an smax expr. Check to see if we 3154 // already have one, otherwise create a new one. 3155 FoldingSetNodeID ID; 3156 ID.AddInteger(scSMaxExpr); 3157 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3158 ID.AddPointer(Ops[i]); 3159 void *IP = nullptr; 3160 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3161 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3162 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3163 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator), 3164 O, Ops.size()); 3165 UniqueSCEVs.InsertNode(S, IP); 3166 return S; 3167 } 3168 3169 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, 3170 const SCEV *RHS) { 3171 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3172 return getUMaxExpr(Ops); 3173 } 3174 3175 const SCEV * 3176 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3177 assert(!Ops.empty() && "Cannot get empty umax!"); 3178 if (Ops.size() == 1) return Ops[0]; 3179 #ifndef NDEBUG 3180 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3181 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3182 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3183 "SCEVUMaxExpr operand types don't match!"); 3184 #endif 3185 3186 // Sort by complexity, this groups all similar expression types together. 3187 GroupByComplexity(Ops, &LI); 3188 3189 // If there are any constants, fold them together. 3190 unsigned Idx = 0; 3191 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3192 ++Idx; 3193 assert(Idx < Ops.size()); 3194 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3195 // We found two constants, fold them together! 3196 ConstantInt *Fold = ConstantInt::get( 3197 getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt())); 3198 Ops[0] = getConstant(Fold); 3199 Ops.erase(Ops.begin()+1); // Erase the folded element 3200 if (Ops.size() == 1) return Ops[0]; 3201 LHSC = cast<SCEVConstant>(Ops[0]); 3202 } 3203 3204 // If we are left with a constant minimum-int, strip it off. 3205 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) { 3206 Ops.erase(Ops.begin()); 3207 --Idx; 3208 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) { 3209 // If we have an umax with a constant maximum-int, it will always be 3210 // maximum-int. 3211 return Ops[0]; 3212 } 3213 3214 if (Ops.size() == 1) return Ops[0]; 3215 } 3216 3217 // Find the first UMax 3218 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr) 3219 ++Idx; 3220 3221 // Check to see if one of the operands is a UMax. If so, expand its operands 3222 // onto our operand list, and recurse to simplify. 3223 if (Idx < Ops.size()) { 3224 bool DeletedUMax = false; 3225 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) { 3226 Ops.erase(Ops.begin()+Idx); 3227 Ops.append(UMax->op_begin(), UMax->op_end()); 3228 DeletedUMax = true; 3229 } 3230 3231 if (DeletedUMax) 3232 return getUMaxExpr(Ops); 3233 } 3234 3235 // Okay, check to see if the same value occurs in the operand list twice. If 3236 // so, delete one. Since we sorted the list, these values are required to 3237 // be adjacent. 3238 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 3239 // X umax Y umax Y --> X umax Y 3240 // X umax Y --> X, if X is always greater than Y 3241 if (Ops[i] == Ops[i+1] || 3242 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) { 3243 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); 3244 --i; --e; 3245 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) { 3246 Ops.erase(Ops.begin()+i, Ops.begin()+i+1); 3247 --i; --e; 3248 } 3249 3250 if (Ops.size() == 1) return Ops[0]; 3251 3252 assert(!Ops.empty() && "Reduced umax down to nothing!"); 3253 3254 // Okay, it looks like we really DO need a umax expr. Check to see if we 3255 // already have one, otherwise create a new one. 3256 FoldingSetNodeID ID; 3257 ID.AddInteger(scUMaxExpr); 3258 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3259 ID.AddPointer(Ops[i]); 3260 void *IP = nullptr; 3261 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3262 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3263 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3264 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator), 3265 O, Ops.size()); 3266 UniqueSCEVs.InsertNode(S, IP); 3267 return S; 3268 } 3269 3270 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 3271 const SCEV *RHS) { 3272 // ~smax(~x, ~y) == smin(x, y). 3273 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS))); 3274 } 3275 3276 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, 3277 const SCEV *RHS) { 3278 // ~umax(~x, ~y) == umin(x, y) 3279 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS))); 3280 } 3281 3282 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 3283 // We can bypass creating a target-independent 3284 // constant expression and then folding it back into a ConstantInt. 3285 // This is just a compile-time optimization. 3286 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 3287 } 3288 3289 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 3290 StructType *STy, 3291 unsigned FieldNo) { 3292 // We can bypass creating a target-independent 3293 // constant expression and then folding it back into a ConstantInt. 3294 // This is just a compile-time optimization. 3295 return getConstant( 3296 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 3297 } 3298 3299 const SCEV *ScalarEvolution::getUnknown(Value *V) { 3300 // Don't attempt to do anything other than create a SCEVUnknown object 3301 // here. createSCEV only calls getUnknown after checking for all other 3302 // interesting possibilities, and any other code that calls getUnknown 3303 // is doing so in order to hide a value from SCEV canonicalization. 3304 3305 FoldingSetNodeID ID; 3306 ID.AddInteger(scUnknown); 3307 ID.AddPointer(V); 3308 void *IP = nullptr; 3309 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 3310 assert(cast<SCEVUnknown>(S)->getValue() == V && 3311 "Stale SCEVUnknown in uniquing map!"); 3312 return S; 3313 } 3314 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 3315 FirstUnknown); 3316 FirstUnknown = cast<SCEVUnknown>(S); 3317 UniqueSCEVs.InsertNode(S, IP); 3318 return S; 3319 } 3320 3321 //===----------------------------------------------------------------------===// 3322 // Basic SCEV Analysis and PHI Idiom Recognition Code 3323 // 3324 3325 /// Test if values of the given type are analyzable within the SCEV 3326 /// framework. This primarily includes integer types, and it can optionally 3327 /// include pointer types if the ScalarEvolution class has access to 3328 /// target-specific information. 3329 bool ScalarEvolution::isSCEVable(Type *Ty) const { 3330 // Integers and pointers are always SCEVable. 3331 return Ty->isIntegerTy() || Ty->isPointerTy(); 3332 } 3333 3334 /// Return the size in bits of the specified type, for which isSCEVable must 3335 /// return true. 3336 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 3337 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3338 return getDataLayout().getTypeSizeInBits(Ty); 3339 } 3340 3341 /// Return a type with the same bitwidth as the given type and which represents 3342 /// how SCEV will treat the given type, for which isSCEVable must return 3343 /// true. For pointer types, this is the pointer-sized integer type. 3344 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 3345 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3346 3347 if (Ty->isIntegerTy()) 3348 return Ty; 3349 3350 // The only other support type is pointer. 3351 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 3352 return getDataLayout().getIntPtrType(Ty); 3353 } 3354 3355 const SCEV *ScalarEvolution::getCouldNotCompute() { 3356 return CouldNotCompute.get(); 3357 } 3358 3359 bool ScalarEvolution::checkValidity(const SCEV *S) const { 3360 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) { 3361 auto *SU = dyn_cast<SCEVUnknown>(S); 3362 return SU && SU->getValue() == nullptr; 3363 }); 3364 3365 return !ContainsNulls; 3366 } 3367 3368 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 3369 HasRecMapType::iterator I = HasRecMap.find(S); 3370 if (I != HasRecMap.end()) 3371 return I->second; 3372 3373 bool FoundAddRec = 3374 SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); }); 3375 HasRecMap.insert({S, FoundAddRec}); 3376 return FoundAddRec; 3377 } 3378 3379 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. 3380 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an 3381 /// offset I, then return {S', I}, else return {\p S, nullptr}. 3382 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { 3383 const auto *Add = dyn_cast<SCEVAddExpr>(S); 3384 if (!Add) 3385 return {S, nullptr}; 3386 3387 if (Add->getNumOperands() != 2) 3388 return {S, nullptr}; 3389 3390 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); 3391 if (!ConstOp) 3392 return {S, nullptr}; 3393 3394 return {Add->getOperand(1), ConstOp->getValue()}; 3395 } 3396 3397 /// Return the ValueOffsetPair set for \p S. \p S can be represented 3398 /// by the value and offset from any ValueOffsetPair in the set. 3399 SetVector<ScalarEvolution::ValueOffsetPair> * 3400 ScalarEvolution::getSCEVValues(const SCEV *S) { 3401 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 3402 if (SI == ExprValueMap.end()) 3403 return nullptr; 3404 #ifndef NDEBUG 3405 if (VerifySCEVMap) { 3406 // Check there is no dangling Value in the set returned. 3407 for (const auto &VE : SI->second) 3408 assert(ValueExprMap.count(VE.first)); 3409 } 3410 #endif 3411 return &SI->second; 3412 } 3413 3414 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) 3415 /// cannot be used separately. eraseValueFromMap should be used to remove 3416 /// V from ValueExprMap and ExprValueMap at the same time. 3417 void ScalarEvolution::eraseValueFromMap(Value *V) { 3418 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3419 if (I != ValueExprMap.end()) { 3420 const SCEV *S = I->second; 3421 // Remove {V, 0} from the set of ExprValueMap[S] 3422 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S)) 3423 SV->remove({V, nullptr}); 3424 3425 // Remove {V, Offset} from the set of ExprValueMap[Stripped] 3426 const SCEV *Stripped; 3427 ConstantInt *Offset; 3428 std::tie(Stripped, Offset) = splitAddExpr(S); 3429 if (Offset != nullptr) { 3430 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped)) 3431 SV->remove({V, Offset}); 3432 } 3433 ValueExprMap.erase(V); 3434 } 3435 } 3436 3437 /// Return an existing SCEV if it exists, otherwise analyze the expression and 3438 /// create a new one. 3439 const SCEV *ScalarEvolution::getSCEV(Value *V) { 3440 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3441 3442 const SCEV *S = getExistingSCEV(V); 3443 if (S == nullptr) { 3444 S = createSCEV(V); 3445 // During PHI resolution, it is possible to create two SCEVs for the same 3446 // V, so it is needed to double check whether V->S is inserted into 3447 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 3448 std::pair<ValueExprMapType::iterator, bool> Pair = 3449 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 3450 if (Pair.second) { 3451 ExprValueMap[S].insert({V, nullptr}); 3452 3453 // If S == Stripped + Offset, add Stripped -> {V, Offset} into 3454 // ExprValueMap. 3455 const SCEV *Stripped = S; 3456 ConstantInt *Offset = nullptr; 3457 std::tie(Stripped, Offset) = splitAddExpr(S); 3458 // If stripped is SCEVUnknown, don't bother to save 3459 // Stripped -> {V, offset}. It doesn't simplify and sometimes even 3460 // increase the complexity of the expansion code. 3461 // If V is GetElementPtrInst, don't save Stripped -> {V, offset} 3462 // because it may generate add/sub instead of GEP in SCEV expansion. 3463 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && 3464 !isa<GetElementPtrInst>(V)) 3465 ExprValueMap[Stripped].insert({V, Offset}); 3466 } 3467 } 3468 return S; 3469 } 3470 3471 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 3472 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3473 3474 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3475 if (I != ValueExprMap.end()) { 3476 const SCEV *S = I->second; 3477 if (checkValidity(S)) 3478 return S; 3479 eraseValueFromMap(V); 3480 forgetMemoizedResults(S); 3481 } 3482 return nullptr; 3483 } 3484 3485 /// Return a SCEV corresponding to -V = -1*V 3486 /// 3487 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 3488 SCEV::NoWrapFlags Flags) { 3489 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3490 return getConstant( 3491 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 3492 3493 Type *Ty = V->getType(); 3494 Ty = getEffectiveSCEVType(Ty); 3495 return getMulExpr( 3496 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags); 3497 } 3498 3499 /// Return a SCEV corresponding to ~V = -1-V 3500 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 3501 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3502 return getConstant( 3503 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 3504 3505 Type *Ty = V->getType(); 3506 Ty = getEffectiveSCEVType(Ty); 3507 const SCEV *AllOnes = 3508 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))); 3509 return getMinusSCEV(AllOnes, V); 3510 } 3511 3512 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 3513 SCEV::NoWrapFlags Flags) { 3514 // Fast path: X - X --> 0. 3515 if (LHS == RHS) 3516 return getZero(LHS->getType()); 3517 3518 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 3519 // makes it so that we cannot make much use of NUW. 3520 auto AddFlags = SCEV::FlagAnyWrap; 3521 const bool RHSIsNotMinSigned = 3522 !getSignedRange(RHS).getSignedMin().isMinSignedValue(); 3523 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) { 3524 // Let M be the minimum representable signed value. Then (-1)*RHS 3525 // signed-wraps if and only if RHS is M. That can happen even for 3526 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 3527 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 3528 // (-1)*RHS, we need to prove that RHS != M. 3529 // 3530 // If LHS is non-negative and we know that LHS - RHS does not 3531 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 3532 // either by proving that RHS > M or that LHS >= 0. 3533 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 3534 AddFlags = SCEV::FlagNSW; 3535 } 3536 } 3537 3538 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 3539 // RHS is NSW and LHS >= 0. 3540 // 3541 // The difficulty here is that the NSW flag may have been proven 3542 // relative to a loop that is to be found in a recurrence in LHS and 3543 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 3544 // larger scope than intended. 3545 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3546 3547 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags); 3548 } 3549 3550 const SCEV * 3551 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) { 3552 Type *SrcTy = V->getType(); 3553 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3554 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3555 "Cannot truncate or zero extend with non-integer arguments!"); 3556 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3557 return V; // No conversion 3558 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 3559 return getTruncateExpr(V, Ty); 3560 return getZeroExtendExpr(V, Ty); 3561 } 3562 3563 const SCEV * 3564 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, 3565 Type *Ty) { 3566 Type *SrcTy = V->getType(); 3567 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3568 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3569 "Cannot truncate or zero extend with non-integer arguments!"); 3570 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3571 return V; // No conversion 3572 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 3573 return getTruncateExpr(V, Ty); 3574 return getSignExtendExpr(V, Ty); 3575 } 3576 3577 const SCEV * 3578 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 3579 Type *SrcTy = V->getType(); 3580 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3581 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3582 "Cannot noop or zero extend with non-integer arguments!"); 3583 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3584 "getNoopOrZeroExtend cannot truncate!"); 3585 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3586 return V; // No conversion 3587 return getZeroExtendExpr(V, Ty); 3588 } 3589 3590 const SCEV * 3591 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 3592 Type *SrcTy = V->getType(); 3593 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3594 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3595 "Cannot noop or sign extend with non-integer arguments!"); 3596 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3597 "getNoopOrSignExtend cannot truncate!"); 3598 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3599 return V; // No conversion 3600 return getSignExtendExpr(V, Ty); 3601 } 3602 3603 const SCEV * 3604 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 3605 Type *SrcTy = V->getType(); 3606 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3607 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3608 "Cannot noop or any extend with non-integer arguments!"); 3609 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3610 "getNoopOrAnyExtend cannot truncate!"); 3611 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3612 return V; // No conversion 3613 return getAnyExtendExpr(V, Ty); 3614 } 3615 3616 const SCEV * 3617 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 3618 Type *SrcTy = V->getType(); 3619 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3620 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3621 "Cannot truncate or noop with non-integer arguments!"); 3622 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 3623 "getTruncateOrNoop cannot extend!"); 3624 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3625 return V; // No conversion 3626 return getTruncateExpr(V, Ty); 3627 } 3628 3629 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 3630 const SCEV *RHS) { 3631 const SCEV *PromotedLHS = LHS; 3632 const SCEV *PromotedRHS = RHS; 3633 3634 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 3635 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 3636 else 3637 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 3638 3639 return getUMaxExpr(PromotedLHS, PromotedRHS); 3640 } 3641 3642 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 3643 const SCEV *RHS) { 3644 const SCEV *PromotedLHS = LHS; 3645 const SCEV *PromotedRHS = RHS; 3646 3647 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 3648 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 3649 else 3650 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 3651 3652 return getUMinExpr(PromotedLHS, PromotedRHS); 3653 } 3654 3655 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 3656 // A pointer operand may evaluate to a nonpointer expression, such as null. 3657 if (!V->getType()->isPointerTy()) 3658 return V; 3659 3660 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) { 3661 return getPointerBase(Cast->getOperand()); 3662 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) { 3663 const SCEV *PtrOp = nullptr; 3664 for (const SCEV *NAryOp : NAry->operands()) { 3665 if (NAryOp->getType()->isPointerTy()) { 3666 // Cannot find the base of an expression with multiple pointer operands. 3667 if (PtrOp) 3668 return V; 3669 PtrOp = NAryOp; 3670 } 3671 } 3672 if (!PtrOp) 3673 return V; 3674 return getPointerBase(PtrOp); 3675 } 3676 return V; 3677 } 3678 3679 /// Push users of the given Instruction onto the given Worklist. 3680 static void 3681 PushDefUseChildren(Instruction *I, 3682 SmallVectorImpl<Instruction *> &Worklist) { 3683 // Push the def-use children onto the Worklist stack. 3684 for (User *U : I->users()) 3685 Worklist.push_back(cast<Instruction>(U)); 3686 } 3687 3688 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { 3689 SmallVector<Instruction *, 16> Worklist; 3690 PushDefUseChildren(PN, Worklist); 3691 3692 SmallPtrSet<Instruction *, 8> Visited; 3693 Visited.insert(PN); 3694 while (!Worklist.empty()) { 3695 Instruction *I = Worklist.pop_back_val(); 3696 if (!Visited.insert(I).second) 3697 continue; 3698 3699 auto It = ValueExprMap.find_as(static_cast<Value *>(I)); 3700 if (It != ValueExprMap.end()) { 3701 const SCEV *Old = It->second; 3702 3703 // Short-circuit the def-use traversal if the symbolic name 3704 // ceases to appear in expressions. 3705 if (Old != SymName && !hasOperand(Old, SymName)) 3706 continue; 3707 3708 // SCEVUnknown for a PHI either means that it has an unrecognized 3709 // structure, it's a PHI that's in the progress of being computed 3710 // by createNodeForPHI, or it's a single-value PHI. In the first case, 3711 // additional loop trip count information isn't going to change anything. 3712 // In the second case, createNodeForPHI will perform the necessary 3713 // updates on its own when it gets to that point. In the third, we do 3714 // want to forget the SCEVUnknown. 3715 if (!isa<PHINode>(I) || 3716 !isa<SCEVUnknown>(Old) || 3717 (I != PN && Old == SymName)) { 3718 eraseValueFromMap(It->first); 3719 forgetMemoizedResults(Old); 3720 } 3721 } 3722 3723 PushDefUseChildren(I, Worklist); 3724 } 3725 } 3726 3727 namespace { 3728 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 3729 public: 3730 static const SCEV *rewrite(const SCEV *S, const Loop *L, 3731 ScalarEvolution &SE) { 3732 SCEVInitRewriter Rewriter(L, SE); 3733 const SCEV *Result = Rewriter.visit(S); 3734 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 3735 } 3736 3737 SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 3738 : SCEVRewriteVisitor(SE), L(L), Valid(true) {} 3739 3740 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 3741 if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant)) 3742 Valid = false; 3743 return Expr; 3744 } 3745 3746 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 3747 // Only allow AddRecExprs for this loop. 3748 if (Expr->getLoop() == L) 3749 return Expr->getStart(); 3750 Valid = false; 3751 return Expr; 3752 } 3753 3754 bool isValid() { return Valid; } 3755 3756 private: 3757 const Loop *L; 3758 bool Valid; 3759 }; 3760 3761 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 3762 public: 3763 static const SCEV *rewrite(const SCEV *S, const Loop *L, 3764 ScalarEvolution &SE) { 3765 SCEVShiftRewriter Rewriter(L, SE); 3766 const SCEV *Result = Rewriter.visit(S); 3767 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 3768 } 3769 3770 SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 3771 : SCEVRewriteVisitor(SE), L(L), Valid(true) {} 3772 3773 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 3774 // Only allow AddRecExprs for this loop. 3775 if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant)) 3776 Valid = false; 3777 return Expr; 3778 } 3779 3780 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 3781 if (Expr->getLoop() == L && Expr->isAffine()) 3782 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 3783 Valid = false; 3784 return Expr; 3785 } 3786 bool isValid() { return Valid; } 3787 3788 private: 3789 const Loop *L; 3790 bool Valid; 3791 }; 3792 } // end anonymous namespace 3793 3794 SCEV::NoWrapFlags 3795 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 3796 if (!AR->isAffine()) 3797 return SCEV::FlagAnyWrap; 3798 3799 typedef OverflowingBinaryOperator OBO; 3800 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 3801 3802 if (!AR->hasNoSignedWrap()) { 3803 ConstantRange AddRecRange = getSignedRange(AR); 3804 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 3805 3806 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 3807 Instruction::Add, IncRange, OBO::NoSignedWrap); 3808 if (NSWRegion.contains(AddRecRange)) 3809 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 3810 } 3811 3812 if (!AR->hasNoUnsignedWrap()) { 3813 ConstantRange AddRecRange = getUnsignedRange(AR); 3814 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 3815 3816 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 3817 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 3818 if (NUWRegion.contains(AddRecRange)) 3819 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 3820 } 3821 3822 return Result; 3823 } 3824 3825 namespace { 3826 /// Represents an abstract binary operation. This may exist as a 3827 /// normal instruction or constant expression, or may have been 3828 /// derived from an expression tree. 3829 struct BinaryOp { 3830 unsigned Opcode; 3831 Value *LHS; 3832 Value *RHS; 3833 bool IsNSW; 3834 bool IsNUW; 3835 3836 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 3837 /// constant expression. 3838 Operator *Op; 3839 3840 explicit BinaryOp(Operator *Op) 3841 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 3842 IsNSW(false), IsNUW(false), Op(Op) { 3843 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 3844 IsNSW = OBO->hasNoSignedWrap(); 3845 IsNUW = OBO->hasNoUnsignedWrap(); 3846 } 3847 } 3848 3849 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 3850 bool IsNUW = false) 3851 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW), 3852 Op(nullptr) {} 3853 }; 3854 } 3855 3856 3857 /// Try to map \p V into a BinaryOp, and return \c None on failure. 3858 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 3859 auto *Op = dyn_cast<Operator>(V); 3860 if (!Op) 3861 return None; 3862 3863 // Implementation detail: all the cleverness here should happen without 3864 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 3865 // SCEV expressions when possible, and we should not break that. 3866 3867 switch (Op->getOpcode()) { 3868 case Instruction::Add: 3869 case Instruction::Sub: 3870 case Instruction::Mul: 3871 case Instruction::UDiv: 3872 case Instruction::And: 3873 case Instruction::Or: 3874 case Instruction::AShr: 3875 case Instruction::Shl: 3876 return BinaryOp(Op); 3877 3878 case Instruction::Xor: 3879 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 3880 // If the RHS of the xor is a signbit, then this is just an add. 3881 // Instcombine turns add of signbit into xor as a strength reduction step. 3882 if (RHSC->getValue().isSignBit()) 3883 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 3884 return BinaryOp(Op); 3885 3886 case Instruction::LShr: 3887 // Turn logical shift right of a constant into a unsigned divide. 3888 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 3889 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 3890 3891 // If the shift count is not less than the bitwidth, the result of 3892 // the shift is undefined. Don't try to analyze it, because the 3893 // resolution chosen here may differ from the resolution chosen in 3894 // other parts of the compiler. 3895 if (SA->getValue().ult(BitWidth)) { 3896 Constant *X = 3897 ConstantInt::get(SA->getContext(), 3898 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 3899 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 3900 } 3901 } 3902 return BinaryOp(Op); 3903 3904 case Instruction::ExtractValue: { 3905 auto *EVI = cast<ExtractValueInst>(Op); 3906 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 3907 break; 3908 3909 auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand()); 3910 if (!CI) 3911 break; 3912 3913 if (auto *F = CI->getCalledFunction()) 3914 switch (F->getIntrinsicID()) { 3915 case Intrinsic::sadd_with_overflow: 3916 case Intrinsic::uadd_with_overflow: { 3917 if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT)) 3918 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 3919 CI->getArgOperand(1)); 3920 3921 // Now that we know that all uses of the arithmetic-result component of 3922 // CI are guarded by the overflow check, we can go ahead and pretend 3923 // that the arithmetic is non-overflowing. 3924 if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow) 3925 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 3926 CI->getArgOperand(1), /* IsNSW = */ true, 3927 /* IsNUW = */ false); 3928 else 3929 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 3930 CI->getArgOperand(1), /* IsNSW = */ false, 3931 /* IsNUW*/ true); 3932 } 3933 3934 case Intrinsic::ssub_with_overflow: 3935 case Intrinsic::usub_with_overflow: 3936 return BinaryOp(Instruction::Sub, CI->getArgOperand(0), 3937 CI->getArgOperand(1)); 3938 3939 case Intrinsic::smul_with_overflow: 3940 case Intrinsic::umul_with_overflow: 3941 return BinaryOp(Instruction::Mul, CI->getArgOperand(0), 3942 CI->getArgOperand(1)); 3943 default: 3944 break; 3945 } 3946 } 3947 3948 default: 3949 break; 3950 } 3951 3952 return None; 3953 } 3954 3955 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 3956 const Loop *L = LI.getLoopFor(PN->getParent()); 3957 if (!L || L->getHeader() != PN->getParent()) 3958 return nullptr; 3959 3960 // The loop may have multiple entrances or multiple exits; we can analyze 3961 // this phi as an addrec if it has a unique entry value and a unique 3962 // backedge value. 3963 Value *BEValueV = nullptr, *StartValueV = nullptr; 3964 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 3965 Value *V = PN->getIncomingValue(i); 3966 if (L->contains(PN->getIncomingBlock(i))) { 3967 if (!BEValueV) { 3968 BEValueV = V; 3969 } else if (BEValueV != V) { 3970 BEValueV = nullptr; 3971 break; 3972 } 3973 } else if (!StartValueV) { 3974 StartValueV = V; 3975 } else if (StartValueV != V) { 3976 StartValueV = nullptr; 3977 break; 3978 } 3979 } 3980 if (BEValueV && StartValueV) { 3981 // While we are analyzing this PHI node, handle its value symbolically. 3982 const SCEV *SymbolicName = getUnknown(PN); 3983 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 3984 "PHI node already processed?"); 3985 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); 3986 3987 // Using this symbolic name for the PHI, analyze the value coming around 3988 // the back-edge. 3989 const SCEV *BEValue = getSCEV(BEValueV); 3990 3991 // NOTE: If BEValue is loop invariant, we know that the PHI node just 3992 // has a special value for the first iteration of the loop. 3993 3994 // If the value coming around the backedge is an add with the symbolic 3995 // value we just inserted, then we found a simple induction variable! 3996 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 3997 // If there is a single occurrence of the symbolic value, replace it 3998 // with a recurrence. 3999 unsigned FoundIndex = Add->getNumOperands(); 4000 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4001 if (Add->getOperand(i) == SymbolicName) 4002 if (FoundIndex == e) { 4003 FoundIndex = i; 4004 break; 4005 } 4006 4007 if (FoundIndex != Add->getNumOperands()) { 4008 // Create an add with everything but the specified operand. 4009 SmallVector<const SCEV *, 8> Ops; 4010 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4011 if (i != FoundIndex) 4012 Ops.push_back(Add->getOperand(i)); 4013 const SCEV *Accum = getAddExpr(Ops); 4014 4015 // This is not a valid addrec if the step amount is varying each 4016 // loop iteration, but is not itself an addrec in this loop. 4017 if (isLoopInvariant(Accum, L) || 4018 (isa<SCEVAddRecExpr>(Accum) && 4019 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 4020 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 4021 4022 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 4023 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 4024 if (BO->IsNUW) 4025 Flags = setFlags(Flags, SCEV::FlagNUW); 4026 if (BO->IsNSW) 4027 Flags = setFlags(Flags, SCEV::FlagNSW); 4028 } 4029 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 4030 // If the increment is an inbounds GEP, then we know the address 4031 // space cannot be wrapped around. We cannot make any guarantee 4032 // about signed or unsigned overflow because pointers are 4033 // unsigned but we may have a negative index from the base 4034 // pointer. We can guarantee that no unsigned wrap occurs if the 4035 // indices form a positive value. 4036 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 4037 Flags = setFlags(Flags, SCEV::FlagNW); 4038 4039 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 4040 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 4041 Flags = setFlags(Flags, SCEV::FlagNUW); 4042 } 4043 4044 // We cannot transfer nuw and nsw flags from subtraction 4045 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 4046 // for instance. 4047 } 4048 4049 const SCEV *StartVal = getSCEV(StartValueV); 4050 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 4051 4052 // Okay, for the entire analysis of this edge we assumed the PHI 4053 // to be symbolic. We now need to go back and purge all of the 4054 // entries for the scalars that use the symbolic expression. 4055 forgetSymbolicName(PN, SymbolicName); 4056 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 4057 4058 // We can add Flags to the post-inc expression only if we 4059 // know that it us *undefined behavior* for BEValueV to 4060 // overflow. 4061 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 4062 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 4063 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 4064 4065 return PHISCEV; 4066 } 4067 } 4068 } else { 4069 // Otherwise, this could be a loop like this: 4070 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 4071 // In this case, j = {1,+,1} and BEValue is j. 4072 // Because the other in-value of i (0) fits the evolution of BEValue 4073 // i really is an addrec evolution. 4074 // 4075 // We can generalize this saying that i is the shifted value of BEValue 4076 // by one iteration: 4077 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 4078 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 4079 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this); 4080 if (Shifted != getCouldNotCompute() && 4081 Start != getCouldNotCompute()) { 4082 const SCEV *StartVal = getSCEV(StartValueV); 4083 if (Start == StartVal) { 4084 // Okay, for the entire analysis of this edge we assumed the PHI 4085 // to be symbolic. We now need to go back and purge all of the 4086 // entries for the scalars that use the symbolic expression. 4087 forgetSymbolicName(PN, SymbolicName); 4088 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; 4089 return Shifted; 4090 } 4091 } 4092 } 4093 4094 // Remove the temporary PHI node SCEV that has been inserted while intending 4095 // to create an AddRecExpr for this PHI node. We can not keep this temporary 4096 // as it will prevent later (possibly simpler) SCEV expressions to be added 4097 // to the ValueExprMap. 4098 eraseValueFromMap(PN); 4099 } 4100 4101 return nullptr; 4102 } 4103 4104 // Checks if the SCEV S is available at BB. S is considered available at BB 4105 // if S can be materialized at BB without introducing a fault. 4106 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 4107 BasicBlock *BB) { 4108 struct CheckAvailable { 4109 bool TraversalDone = false; 4110 bool Available = true; 4111 4112 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 4113 BasicBlock *BB = nullptr; 4114 DominatorTree &DT; 4115 4116 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 4117 : L(L), BB(BB), DT(DT) {} 4118 4119 bool setUnavailable() { 4120 TraversalDone = true; 4121 Available = false; 4122 return false; 4123 } 4124 4125 bool follow(const SCEV *S) { 4126 switch (S->getSCEVType()) { 4127 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend: 4128 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr: 4129 // These expressions are available if their operand(s) is/are. 4130 return true; 4131 4132 case scAddRecExpr: { 4133 // We allow add recurrences that are on the loop BB is in, or some 4134 // outer loop. This guarantees availability because the value of the 4135 // add recurrence at BB is simply the "current" value of the induction 4136 // variable. We can relax this in the future; for instance an add 4137 // recurrence on a sibling dominating loop is also available at BB. 4138 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 4139 if (L && (ARLoop == L || ARLoop->contains(L))) 4140 return true; 4141 4142 return setUnavailable(); 4143 } 4144 4145 case scUnknown: { 4146 // For SCEVUnknown, we check for simple dominance. 4147 const auto *SU = cast<SCEVUnknown>(S); 4148 Value *V = SU->getValue(); 4149 4150 if (isa<Argument>(V)) 4151 return false; 4152 4153 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 4154 return false; 4155 4156 return setUnavailable(); 4157 } 4158 4159 case scUDivExpr: 4160 case scCouldNotCompute: 4161 // We do not try to smart about these at all. 4162 return setUnavailable(); 4163 } 4164 llvm_unreachable("switch should be fully covered!"); 4165 } 4166 4167 bool isDone() { return TraversalDone; } 4168 }; 4169 4170 CheckAvailable CA(L, BB, DT); 4171 SCEVTraversal<CheckAvailable> ST(CA); 4172 4173 ST.visitAll(S); 4174 return CA.Available; 4175 } 4176 4177 // Try to match a control flow sequence that branches out at BI and merges back 4178 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 4179 // match. 4180 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 4181 Value *&C, Value *&LHS, Value *&RHS) { 4182 C = BI->getCondition(); 4183 4184 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 4185 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 4186 4187 if (!LeftEdge.isSingleEdge()) 4188 return false; 4189 4190 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 4191 4192 Use &LeftUse = Merge->getOperandUse(0); 4193 Use &RightUse = Merge->getOperandUse(1); 4194 4195 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 4196 LHS = LeftUse; 4197 RHS = RightUse; 4198 return true; 4199 } 4200 4201 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 4202 LHS = RightUse; 4203 RHS = LeftUse; 4204 return true; 4205 } 4206 4207 return false; 4208 } 4209 4210 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 4211 auto IsReachable = 4212 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 4213 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 4214 const Loop *L = LI.getLoopFor(PN->getParent()); 4215 4216 // We don't want to break LCSSA, even in a SCEV expression tree. 4217 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 4218 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 4219 return nullptr; 4220 4221 // Try to match 4222 // 4223 // br %cond, label %left, label %right 4224 // left: 4225 // br label %merge 4226 // right: 4227 // br label %merge 4228 // merge: 4229 // V = phi [ %x, %left ], [ %y, %right ] 4230 // 4231 // as "select %cond, %x, %y" 4232 4233 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 4234 assert(IDom && "At least the entry block should dominate PN"); 4235 4236 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 4237 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 4238 4239 if (BI && BI->isConditional() && 4240 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 4241 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 4242 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 4243 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 4244 } 4245 4246 return nullptr; 4247 } 4248 4249 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 4250 if (const SCEV *S = createAddRecFromPHI(PN)) 4251 return S; 4252 4253 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 4254 return S; 4255 4256 // If the PHI has a single incoming value, follow that value, unless the 4257 // PHI's incoming blocks are in a different loop, in which case doing so 4258 // risks breaking LCSSA form. Instcombine would normally zap these, but 4259 // it doesn't have DominatorTree information, so it may miss cases. 4260 if (Value *V = SimplifyInstruction(PN, getDataLayout(), &TLI, &DT, &AC)) 4261 if (LI.replacementPreservesLCSSAForm(PN, V)) 4262 return getSCEV(V); 4263 4264 // If it's not a loop phi, we can't handle it yet. 4265 return getUnknown(PN); 4266 } 4267 4268 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, 4269 Value *Cond, 4270 Value *TrueVal, 4271 Value *FalseVal) { 4272 // Handle "constant" branch or select. This can occur for instance when a 4273 // loop pass transforms an inner loop and moves on to process the outer loop. 4274 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 4275 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 4276 4277 // Try to match some simple smax or umax patterns. 4278 auto *ICI = dyn_cast<ICmpInst>(Cond); 4279 if (!ICI) 4280 return getUnknown(I); 4281 4282 Value *LHS = ICI->getOperand(0); 4283 Value *RHS = ICI->getOperand(1); 4284 4285 switch (ICI->getPredicate()) { 4286 case ICmpInst::ICMP_SLT: 4287 case ICmpInst::ICMP_SLE: 4288 std::swap(LHS, RHS); 4289 LLVM_FALLTHROUGH; 4290 case ICmpInst::ICMP_SGT: 4291 case ICmpInst::ICMP_SGE: 4292 // a >s b ? a+x : b+x -> smax(a, b)+x 4293 // a >s b ? b+x : a+x -> smin(a, b)+x 4294 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 4295 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType()); 4296 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType()); 4297 const SCEV *LA = getSCEV(TrueVal); 4298 const SCEV *RA = getSCEV(FalseVal); 4299 const SCEV *LDiff = getMinusSCEV(LA, LS); 4300 const SCEV *RDiff = getMinusSCEV(RA, RS); 4301 if (LDiff == RDiff) 4302 return getAddExpr(getSMaxExpr(LS, RS), LDiff); 4303 LDiff = getMinusSCEV(LA, RS); 4304 RDiff = getMinusSCEV(RA, LS); 4305 if (LDiff == RDiff) 4306 return getAddExpr(getSMinExpr(LS, RS), LDiff); 4307 } 4308 break; 4309 case ICmpInst::ICMP_ULT: 4310 case ICmpInst::ICMP_ULE: 4311 std::swap(LHS, RHS); 4312 LLVM_FALLTHROUGH; 4313 case ICmpInst::ICMP_UGT: 4314 case ICmpInst::ICMP_UGE: 4315 // a >u b ? a+x : b+x -> umax(a, b)+x 4316 // a >u b ? b+x : a+x -> umin(a, b)+x 4317 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 4318 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 4319 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType()); 4320 const SCEV *LA = getSCEV(TrueVal); 4321 const SCEV *RA = getSCEV(FalseVal); 4322 const SCEV *LDiff = getMinusSCEV(LA, LS); 4323 const SCEV *RDiff = getMinusSCEV(RA, RS); 4324 if (LDiff == RDiff) 4325 return getAddExpr(getUMaxExpr(LS, RS), LDiff); 4326 LDiff = getMinusSCEV(LA, RS); 4327 RDiff = getMinusSCEV(RA, LS); 4328 if (LDiff == RDiff) 4329 return getAddExpr(getUMinExpr(LS, RS), LDiff); 4330 } 4331 break; 4332 case ICmpInst::ICMP_NE: 4333 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 4334 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 4335 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 4336 const SCEV *One = getOne(I->getType()); 4337 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 4338 const SCEV *LA = getSCEV(TrueVal); 4339 const SCEV *RA = getSCEV(FalseVal); 4340 const SCEV *LDiff = getMinusSCEV(LA, LS); 4341 const SCEV *RDiff = getMinusSCEV(RA, One); 4342 if (LDiff == RDiff) 4343 return getAddExpr(getUMaxExpr(One, LS), LDiff); 4344 } 4345 break; 4346 case ICmpInst::ICMP_EQ: 4347 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 4348 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 4349 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 4350 const SCEV *One = getOne(I->getType()); 4351 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 4352 const SCEV *LA = getSCEV(TrueVal); 4353 const SCEV *RA = getSCEV(FalseVal); 4354 const SCEV *LDiff = getMinusSCEV(LA, One); 4355 const SCEV *RDiff = getMinusSCEV(RA, LS); 4356 if (LDiff == RDiff) 4357 return getAddExpr(getUMaxExpr(One, LS), LDiff); 4358 } 4359 break; 4360 default: 4361 break; 4362 } 4363 4364 return getUnknown(I); 4365 } 4366 4367 /// Expand GEP instructions into add and multiply operations. This allows them 4368 /// to be analyzed by regular SCEV code. 4369 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 4370 // Don't attempt to analyze GEPs over unsized objects. 4371 if (!GEP->getSourceElementType()->isSized()) 4372 return getUnknown(GEP); 4373 4374 SmallVector<const SCEV *, 4> IndexExprs; 4375 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) 4376 IndexExprs.push_back(getSCEV(*Index)); 4377 return getGEPExpr(GEP->getSourceElementType(), 4378 getSCEV(GEP->getPointerOperand()), 4379 IndexExprs, GEP->isInBounds()); 4380 } 4381 4382 uint32_t 4383 ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 4384 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 4385 return C->getAPInt().countTrailingZeros(); 4386 4387 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 4388 return std::min(GetMinTrailingZeros(T->getOperand()), 4389 (uint32_t)getTypeSizeInBits(T->getType())); 4390 4391 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 4392 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 4393 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ? 4394 getTypeSizeInBits(E->getType()) : OpRes; 4395 } 4396 4397 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 4398 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 4399 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ? 4400 getTypeSizeInBits(E->getType()) : OpRes; 4401 } 4402 4403 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 4404 // The result is the min of all operands results. 4405 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 4406 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 4407 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 4408 return MinOpRes; 4409 } 4410 4411 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 4412 // The result is the sum of all operands results. 4413 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 4414 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 4415 for (unsigned i = 1, e = M->getNumOperands(); 4416 SumOpRes != BitWidth && i != e; ++i) 4417 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), 4418 BitWidth); 4419 return SumOpRes; 4420 } 4421 4422 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 4423 // The result is the min of all operands results. 4424 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 4425 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 4426 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 4427 return MinOpRes; 4428 } 4429 4430 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 4431 // The result is the min of all operands results. 4432 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 4433 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 4434 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 4435 return MinOpRes; 4436 } 4437 4438 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 4439 // The result is the min of all operands results. 4440 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 4441 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 4442 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 4443 return MinOpRes; 4444 } 4445 4446 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 4447 // For a SCEVUnknown, ask ValueTracking. 4448 unsigned BitWidth = getTypeSizeInBits(U->getType()); 4449 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0); 4450 computeKnownBits(U->getValue(), Zeros, Ones, getDataLayout(), 0, &AC, 4451 nullptr, &DT); 4452 return Zeros.countTrailingOnes(); 4453 } 4454 4455 // SCEVUDivExpr 4456 return 0; 4457 } 4458 4459 /// Helper method to assign a range to V from metadata present in the IR. 4460 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 4461 if (Instruction *I = dyn_cast<Instruction>(V)) 4462 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 4463 return getConstantRangeFromMetadata(*MD); 4464 4465 return None; 4466 } 4467 4468 /// Determine the range for a particular SCEV. If SignHint is 4469 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 4470 /// with a "cleaner" unsigned (resp. signed) representation. 4471 ConstantRange 4472 ScalarEvolution::getRange(const SCEV *S, 4473 ScalarEvolution::RangeSignHint SignHint) { 4474 DenseMap<const SCEV *, ConstantRange> &Cache = 4475 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 4476 : SignedRanges; 4477 4478 // See if we've computed this range already. 4479 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 4480 if (I != Cache.end()) 4481 return I->second; 4482 4483 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 4484 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 4485 4486 unsigned BitWidth = getTypeSizeInBits(S->getType()); 4487 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 4488 4489 // If the value has known zeros, the maximum value will have those known zeros 4490 // as well. 4491 uint32_t TZ = GetMinTrailingZeros(S); 4492 if (TZ != 0) { 4493 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 4494 ConservativeResult = 4495 ConstantRange(APInt::getMinValue(BitWidth), 4496 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 4497 else 4498 ConservativeResult = ConstantRange( 4499 APInt::getSignedMinValue(BitWidth), 4500 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 4501 } 4502 4503 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 4504 ConstantRange X = getRange(Add->getOperand(0), SignHint); 4505 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 4506 X = X.add(getRange(Add->getOperand(i), SignHint)); 4507 return setRange(Add, SignHint, ConservativeResult.intersectWith(X)); 4508 } 4509 4510 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 4511 ConstantRange X = getRange(Mul->getOperand(0), SignHint); 4512 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 4513 X = X.multiply(getRange(Mul->getOperand(i), SignHint)); 4514 return setRange(Mul, SignHint, ConservativeResult.intersectWith(X)); 4515 } 4516 4517 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 4518 ConstantRange X = getRange(SMax->getOperand(0), SignHint); 4519 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 4520 X = X.smax(getRange(SMax->getOperand(i), SignHint)); 4521 return setRange(SMax, SignHint, ConservativeResult.intersectWith(X)); 4522 } 4523 4524 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 4525 ConstantRange X = getRange(UMax->getOperand(0), SignHint); 4526 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 4527 X = X.umax(getRange(UMax->getOperand(i), SignHint)); 4528 return setRange(UMax, SignHint, ConservativeResult.intersectWith(X)); 4529 } 4530 4531 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 4532 ConstantRange X = getRange(UDiv->getLHS(), SignHint); 4533 ConstantRange Y = getRange(UDiv->getRHS(), SignHint); 4534 return setRange(UDiv, SignHint, 4535 ConservativeResult.intersectWith(X.udiv(Y))); 4536 } 4537 4538 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 4539 ConstantRange X = getRange(ZExt->getOperand(), SignHint); 4540 return setRange(ZExt, SignHint, 4541 ConservativeResult.intersectWith(X.zeroExtend(BitWidth))); 4542 } 4543 4544 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 4545 ConstantRange X = getRange(SExt->getOperand(), SignHint); 4546 return setRange(SExt, SignHint, 4547 ConservativeResult.intersectWith(X.signExtend(BitWidth))); 4548 } 4549 4550 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 4551 ConstantRange X = getRange(Trunc->getOperand(), SignHint); 4552 return setRange(Trunc, SignHint, 4553 ConservativeResult.intersectWith(X.truncate(BitWidth))); 4554 } 4555 4556 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 4557 // If there's no unsigned wrap, the value will never be less than its 4558 // initial value. 4559 if (AddRec->hasNoUnsignedWrap()) 4560 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart())) 4561 if (!C->getValue()->isZero()) 4562 ConservativeResult = ConservativeResult.intersectWith( 4563 ConstantRange(C->getAPInt(), APInt(BitWidth, 0))); 4564 4565 // If there's no signed wrap, and all the operands have the same sign or 4566 // zero, the value won't ever change sign. 4567 if (AddRec->hasNoSignedWrap()) { 4568 bool AllNonNeg = true; 4569 bool AllNonPos = true; 4570 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 4571 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false; 4572 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false; 4573 } 4574 if (AllNonNeg) 4575 ConservativeResult = ConservativeResult.intersectWith( 4576 ConstantRange(APInt(BitWidth, 0), 4577 APInt::getSignedMinValue(BitWidth))); 4578 else if (AllNonPos) 4579 ConservativeResult = ConservativeResult.intersectWith( 4580 ConstantRange(APInt::getSignedMinValue(BitWidth), 4581 APInt(BitWidth, 1))); 4582 } 4583 4584 // TODO: non-affine addrec 4585 if (AddRec->isAffine()) { 4586 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop()); 4587 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 4588 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 4589 auto RangeFromAffine = getRangeForAffineAR( 4590 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 4591 BitWidth); 4592 if (!RangeFromAffine.isFullSet()) 4593 ConservativeResult = 4594 ConservativeResult.intersectWith(RangeFromAffine); 4595 4596 auto RangeFromFactoring = getRangeViaFactoring( 4597 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 4598 BitWidth); 4599 if (!RangeFromFactoring.isFullSet()) 4600 ConservativeResult = 4601 ConservativeResult.intersectWith(RangeFromFactoring); 4602 } 4603 } 4604 4605 return setRange(AddRec, SignHint, ConservativeResult); 4606 } 4607 4608 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 4609 // Check if the IR explicitly contains !range metadata. 4610 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 4611 if (MDRange.hasValue()) 4612 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue()); 4613 4614 // Split here to avoid paying the compile-time cost of calling both 4615 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted 4616 // if needed. 4617 const DataLayout &DL = getDataLayout(); 4618 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) { 4619 // For a SCEVUnknown, ask ValueTracking. 4620 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0); 4621 computeKnownBits(U->getValue(), Zeros, Ones, DL, 0, &AC, nullptr, &DT); 4622 if (Ones != ~Zeros + 1) 4623 ConservativeResult = 4624 ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1)); 4625 } else { 4626 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED && 4627 "generalize as needed!"); 4628 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 4629 if (NS > 1) 4630 ConservativeResult = ConservativeResult.intersectWith( 4631 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 4632 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1)); 4633 } 4634 4635 return setRange(U, SignHint, ConservativeResult); 4636 } 4637 4638 return setRange(S, SignHint, ConservativeResult); 4639 } 4640 4641 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 4642 const SCEV *Step, 4643 const SCEV *MaxBECount, 4644 unsigned BitWidth) { 4645 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 4646 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 4647 "Precondition!"); 4648 4649 ConstantRange Result(BitWidth, /* isFullSet = */ true); 4650 4651 // Check for overflow. This must be done with ConstantRange arithmetic 4652 // because we could be called from within the ScalarEvolution overflow 4653 // checking code. 4654 4655 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 4656 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount); 4657 ConstantRange ZExtMaxBECountRange = 4658 MaxBECountRange.zextOrTrunc(BitWidth * 2 + 1); 4659 4660 ConstantRange StepSRange = getSignedRange(Step); 4661 ConstantRange SExtStepSRange = StepSRange.sextOrTrunc(BitWidth * 2 + 1); 4662 4663 ConstantRange StartURange = getUnsignedRange(Start); 4664 ConstantRange EndURange = 4665 StartURange.add(MaxBECountRange.multiply(StepSRange)); 4666 4667 // Check for unsigned overflow. 4668 ConstantRange ZExtStartURange = StartURange.zextOrTrunc(BitWidth * 2 + 1); 4669 ConstantRange ZExtEndURange = EndURange.zextOrTrunc(BitWidth * 2 + 1); 4670 if (ZExtStartURange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) == 4671 ZExtEndURange) { 4672 APInt Min = APIntOps::umin(StartURange.getUnsignedMin(), 4673 EndURange.getUnsignedMin()); 4674 APInt Max = APIntOps::umax(StartURange.getUnsignedMax(), 4675 EndURange.getUnsignedMax()); 4676 bool IsFullRange = Min.isMinValue() && Max.isMaxValue(); 4677 if (!IsFullRange) 4678 Result = 4679 Result.intersectWith(ConstantRange(Min, Max + 1)); 4680 } 4681 4682 ConstantRange StartSRange = getSignedRange(Start); 4683 ConstantRange EndSRange = 4684 StartSRange.add(MaxBECountRange.multiply(StepSRange)); 4685 4686 // Check for signed overflow. This must be done with ConstantRange 4687 // arithmetic because we could be called from within the ScalarEvolution 4688 // overflow checking code. 4689 ConstantRange SExtStartSRange = StartSRange.sextOrTrunc(BitWidth * 2 + 1); 4690 ConstantRange SExtEndSRange = EndSRange.sextOrTrunc(BitWidth * 2 + 1); 4691 if (SExtStartSRange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) == 4692 SExtEndSRange) { 4693 APInt Min = 4694 APIntOps::smin(StartSRange.getSignedMin(), EndSRange.getSignedMin()); 4695 APInt Max = 4696 APIntOps::smax(StartSRange.getSignedMax(), EndSRange.getSignedMax()); 4697 bool IsFullRange = Min.isMinSignedValue() && Max.isMaxSignedValue(); 4698 if (!IsFullRange) 4699 Result = 4700 Result.intersectWith(ConstantRange(Min, Max + 1)); 4701 } 4702 4703 return Result; 4704 } 4705 4706 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 4707 const SCEV *Step, 4708 const SCEV *MaxBECount, 4709 unsigned BitWidth) { 4710 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 4711 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 4712 4713 struct SelectPattern { 4714 Value *Condition = nullptr; 4715 APInt TrueValue; 4716 APInt FalseValue; 4717 4718 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 4719 const SCEV *S) { 4720 Optional<unsigned> CastOp; 4721 APInt Offset(BitWidth, 0); 4722 4723 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 4724 "Should be!"); 4725 4726 // Peel off a constant offset: 4727 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 4728 // In the future we could consider being smarter here and handle 4729 // {Start+Step,+,Step} too. 4730 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 4731 return; 4732 4733 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 4734 S = SA->getOperand(1); 4735 } 4736 4737 // Peel off a cast operation 4738 if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) { 4739 CastOp = SCast->getSCEVType(); 4740 S = SCast->getOperand(); 4741 } 4742 4743 using namespace llvm::PatternMatch; 4744 4745 auto *SU = dyn_cast<SCEVUnknown>(S); 4746 const APInt *TrueVal, *FalseVal; 4747 if (!SU || 4748 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 4749 m_APInt(FalseVal)))) { 4750 Condition = nullptr; 4751 return; 4752 } 4753 4754 TrueValue = *TrueVal; 4755 FalseValue = *FalseVal; 4756 4757 // Re-apply the cast we peeled off earlier 4758 if (CastOp.hasValue()) 4759 switch (*CastOp) { 4760 default: 4761 llvm_unreachable("Unknown SCEV cast type!"); 4762 4763 case scTruncate: 4764 TrueValue = TrueValue.trunc(BitWidth); 4765 FalseValue = FalseValue.trunc(BitWidth); 4766 break; 4767 case scZeroExtend: 4768 TrueValue = TrueValue.zext(BitWidth); 4769 FalseValue = FalseValue.zext(BitWidth); 4770 break; 4771 case scSignExtend: 4772 TrueValue = TrueValue.sext(BitWidth); 4773 FalseValue = FalseValue.sext(BitWidth); 4774 break; 4775 } 4776 4777 // Re-apply the constant offset we peeled off earlier 4778 TrueValue += Offset; 4779 FalseValue += Offset; 4780 } 4781 4782 bool isRecognized() { return Condition != nullptr; } 4783 }; 4784 4785 SelectPattern StartPattern(*this, BitWidth, Start); 4786 if (!StartPattern.isRecognized()) 4787 return ConstantRange(BitWidth, /* isFullSet = */ true); 4788 4789 SelectPattern StepPattern(*this, BitWidth, Step); 4790 if (!StepPattern.isRecognized()) 4791 return ConstantRange(BitWidth, /* isFullSet = */ true); 4792 4793 if (StartPattern.Condition != StepPattern.Condition) { 4794 // We don't handle this case today; but we could, by considering four 4795 // possibilities below instead of two. I'm not sure if there are cases where 4796 // that will help over what getRange already does, though. 4797 return ConstantRange(BitWidth, /* isFullSet = */ true); 4798 } 4799 4800 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 4801 // construct arbitrary general SCEV expressions here. This function is called 4802 // from deep in the call stack, and calling getSCEV (on a sext instruction, 4803 // say) can end up caching a suboptimal value. 4804 4805 // FIXME: without the explicit `this` receiver below, MSVC errors out with 4806 // C2352 and C2512 (otherwise it isn't needed). 4807 4808 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 4809 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 4810 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 4811 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 4812 4813 ConstantRange TrueRange = 4814 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 4815 ConstantRange FalseRange = 4816 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 4817 4818 return TrueRange.unionWith(FalseRange); 4819 } 4820 4821 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 4822 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 4823 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 4824 4825 // Return early if there are no flags to propagate to the SCEV. 4826 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 4827 if (BinOp->hasNoUnsignedWrap()) 4828 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 4829 if (BinOp->hasNoSignedWrap()) 4830 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 4831 if (Flags == SCEV::FlagAnyWrap) 4832 return SCEV::FlagAnyWrap; 4833 4834 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 4835 } 4836 4837 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 4838 // Here we check that I is in the header of the innermost loop containing I, 4839 // since we only deal with instructions in the loop header. The actual loop we 4840 // need to check later will come from an add recurrence, but getting that 4841 // requires computing the SCEV of the operands, which can be expensive. This 4842 // check we can do cheaply to rule out some cases early. 4843 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent()); 4844 if (InnermostContainingLoop == nullptr || 4845 InnermostContainingLoop->getHeader() != I->getParent()) 4846 return false; 4847 4848 // Only proceed if we can prove that I does not yield poison. 4849 if (!isKnownNotFullPoison(I)) return false; 4850 4851 // At this point we know that if I is executed, then it does not wrap 4852 // according to at least one of NSW or NUW. If I is not executed, then we do 4853 // not know if the calculation that I represents would wrap. Multiple 4854 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 4855 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 4856 // derived from other instructions that map to the same SCEV. We cannot make 4857 // that guarantee for cases where I is not executed. So we need to find the 4858 // loop that I is considered in relation to and prove that I is executed for 4859 // every iteration of that loop. That implies that the value that I 4860 // calculates does not wrap anywhere in the loop, so then we can apply the 4861 // flags to the SCEV. 4862 // 4863 // We check isLoopInvariant to disambiguate in case we are adding recurrences 4864 // from different loops, so that we know which loop to prove that I is 4865 // executed in. 4866 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) { 4867 // I could be an extractvalue from a call to an overflow intrinsic. 4868 // TODO: We can do better here in some cases. 4869 if (!isSCEVable(I->getOperand(OpIndex)->getType())) 4870 return false; 4871 const SCEV *Op = getSCEV(I->getOperand(OpIndex)); 4872 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 4873 bool AllOtherOpsLoopInvariant = true; 4874 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands(); 4875 ++OtherOpIndex) { 4876 if (OtherOpIndex != OpIndex) { 4877 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex)); 4878 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) { 4879 AllOtherOpsLoopInvariant = false; 4880 break; 4881 } 4882 } 4883 } 4884 if (AllOtherOpsLoopInvariant && 4885 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop())) 4886 return true; 4887 } 4888 } 4889 return false; 4890 } 4891 4892 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 4893 // If we know that \c I can never be poison period, then that's enough. 4894 if (isSCEVExprNeverPoison(I)) 4895 return true; 4896 4897 // For an add recurrence specifically, we assume that infinite loops without 4898 // side effects are undefined behavior, and then reason as follows: 4899 // 4900 // If the add recurrence is poison in any iteration, it is poison on all 4901 // future iterations (since incrementing poison yields poison). If the result 4902 // of the add recurrence is fed into the loop latch condition and the loop 4903 // does not contain any throws or exiting blocks other than the latch, we now 4904 // have the ability to "choose" whether the backedge is taken or not (by 4905 // choosing a sufficiently evil value for the poison feeding into the branch) 4906 // for every iteration including and after the one in which \p I first became 4907 // poison. There are two possibilities (let's call the iteration in which \p 4908 // I first became poison as K): 4909 // 4910 // 1. In the set of iterations including and after K, the loop body executes 4911 // no side effects. In this case executing the backege an infinte number 4912 // of times will yield undefined behavior. 4913 // 4914 // 2. In the set of iterations including and after K, the loop body executes 4915 // at least one side effect. In this case, that specific instance of side 4916 // effect is control dependent on poison, which also yields undefined 4917 // behavior. 4918 4919 auto *ExitingBB = L->getExitingBlock(); 4920 auto *LatchBB = L->getLoopLatch(); 4921 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 4922 return false; 4923 4924 SmallPtrSet<const Instruction *, 16> Pushed; 4925 SmallVector<const Instruction *, 8> PoisonStack; 4926 4927 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 4928 // things that are known to be fully poison under that assumption go on the 4929 // PoisonStack. 4930 Pushed.insert(I); 4931 PoisonStack.push_back(I); 4932 4933 bool LatchControlDependentOnPoison = false; 4934 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 4935 const Instruction *Poison = PoisonStack.pop_back_val(); 4936 4937 for (auto *PoisonUser : Poison->users()) { 4938 if (propagatesFullPoison(cast<Instruction>(PoisonUser))) { 4939 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 4940 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 4941 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 4942 assert(BI->isConditional() && "Only possibility!"); 4943 if (BI->getParent() == LatchBB) { 4944 LatchControlDependentOnPoison = true; 4945 break; 4946 } 4947 } 4948 } 4949 } 4950 4951 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 4952 } 4953 4954 ScalarEvolution::LoopProperties 4955 ScalarEvolution::getLoopProperties(const Loop *L) { 4956 typedef ScalarEvolution::LoopProperties LoopProperties; 4957 4958 auto Itr = LoopPropertiesCache.find(L); 4959 if (Itr == LoopPropertiesCache.end()) { 4960 auto HasSideEffects = [](Instruction *I) { 4961 if (auto *SI = dyn_cast<StoreInst>(I)) 4962 return !SI->isSimple(); 4963 4964 return I->mayHaveSideEffects(); 4965 }; 4966 4967 LoopProperties LP = {/* HasNoAbnormalExits */ true, 4968 /*HasNoSideEffects*/ true}; 4969 4970 for (auto *BB : L->getBlocks()) 4971 for (auto &I : *BB) { 4972 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 4973 LP.HasNoAbnormalExits = false; 4974 if (HasSideEffects(&I)) 4975 LP.HasNoSideEffects = false; 4976 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 4977 break; // We're already as pessimistic as we can get. 4978 } 4979 4980 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 4981 assert(InsertPair.second && "We just checked!"); 4982 Itr = InsertPair.first; 4983 } 4984 4985 return Itr->second; 4986 } 4987 4988 const SCEV *ScalarEvolution::createSCEV(Value *V) { 4989 if (!isSCEVable(V->getType())) 4990 return getUnknown(V); 4991 4992 if (Instruction *I = dyn_cast<Instruction>(V)) { 4993 // Don't attempt to analyze instructions in blocks that aren't 4994 // reachable. Such instructions don't matter, and they aren't required 4995 // to obey basic rules for definitions dominating uses which this 4996 // analysis depends on. 4997 if (!DT.isReachableFromEntry(I->getParent())) 4998 return getUnknown(V); 4999 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 5000 return getConstant(CI); 5001 else if (isa<ConstantPointerNull>(V)) 5002 return getZero(V->getType()); 5003 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 5004 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 5005 else if (!isa<ConstantExpr>(V)) 5006 return getUnknown(V); 5007 5008 Operator *U = cast<Operator>(V); 5009 if (auto BO = MatchBinaryOp(U, DT)) { 5010 switch (BO->Opcode) { 5011 case Instruction::Add: { 5012 // The simple thing to do would be to just call getSCEV on both operands 5013 // and call getAddExpr with the result. However if we're looking at a 5014 // bunch of things all added together, this can be quite inefficient, 5015 // because it leads to N-1 getAddExpr calls for N ultimate operands. 5016 // Instead, gather up all the operands and make a single getAddExpr call. 5017 // LLVM IR canonical form means we need only traverse the left operands. 5018 SmallVector<const SCEV *, 4> AddOps; 5019 do { 5020 if (BO->Op) { 5021 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 5022 AddOps.push_back(OpSCEV); 5023 break; 5024 } 5025 5026 // If a NUW or NSW flag can be applied to the SCEV for this 5027 // addition, then compute the SCEV for this addition by itself 5028 // with a separate call to getAddExpr. We need to do that 5029 // instead of pushing the operands of the addition onto AddOps, 5030 // since the flags are only known to apply to this particular 5031 // addition - they may not apply to other additions that can be 5032 // formed with operands from AddOps. 5033 const SCEV *RHS = getSCEV(BO->RHS); 5034 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 5035 if (Flags != SCEV::FlagAnyWrap) { 5036 const SCEV *LHS = getSCEV(BO->LHS); 5037 if (BO->Opcode == Instruction::Sub) 5038 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 5039 else 5040 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 5041 break; 5042 } 5043 } 5044 5045 if (BO->Opcode == Instruction::Sub) 5046 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 5047 else 5048 AddOps.push_back(getSCEV(BO->RHS)); 5049 5050 auto NewBO = MatchBinaryOp(BO->LHS, DT); 5051 if (!NewBO || (NewBO->Opcode != Instruction::Add && 5052 NewBO->Opcode != Instruction::Sub)) { 5053 AddOps.push_back(getSCEV(BO->LHS)); 5054 break; 5055 } 5056 BO = NewBO; 5057 } while (true); 5058 5059 return getAddExpr(AddOps); 5060 } 5061 5062 case Instruction::Mul: { 5063 SmallVector<const SCEV *, 4> MulOps; 5064 do { 5065 if (BO->Op) { 5066 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 5067 MulOps.push_back(OpSCEV); 5068 break; 5069 } 5070 5071 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 5072 if (Flags != SCEV::FlagAnyWrap) { 5073 MulOps.push_back( 5074 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 5075 break; 5076 } 5077 } 5078 5079 MulOps.push_back(getSCEV(BO->RHS)); 5080 auto NewBO = MatchBinaryOp(BO->LHS, DT); 5081 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 5082 MulOps.push_back(getSCEV(BO->LHS)); 5083 break; 5084 } 5085 BO = NewBO; 5086 } while (true); 5087 5088 return getMulExpr(MulOps); 5089 } 5090 case Instruction::UDiv: 5091 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 5092 case Instruction::Sub: { 5093 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5094 if (BO->Op) 5095 Flags = getNoWrapFlagsFromUB(BO->Op); 5096 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 5097 } 5098 case Instruction::And: 5099 // For an expression like x&255 that merely masks off the high bits, 5100 // use zext(trunc(x)) as the SCEV expression. 5101 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 5102 if (CI->isNullValue()) 5103 return getSCEV(BO->RHS); 5104 if (CI->isAllOnesValue()) 5105 return getSCEV(BO->LHS); 5106 const APInt &A = CI->getValue(); 5107 5108 // Instcombine's ShrinkDemandedConstant may strip bits out of 5109 // constants, obscuring what would otherwise be a low-bits mask. 5110 // Use computeKnownBits to compute what ShrinkDemandedConstant 5111 // knew about to reconstruct a low-bits mask value. 5112 unsigned LZ = A.countLeadingZeros(); 5113 unsigned TZ = A.countTrailingZeros(); 5114 unsigned BitWidth = A.getBitWidth(); 5115 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0); 5116 computeKnownBits(BO->LHS, KnownZero, KnownOne, getDataLayout(), 5117 0, &AC, nullptr, &DT); 5118 5119 APInt EffectiveMask = 5120 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 5121 if ((LZ != 0 || TZ != 0) && !((~A & ~KnownZero) & EffectiveMask)) { 5122 const SCEV *MulCount = getConstant(ConstantInt::get( 5123 getContext(), APInt::getOneBitSet(BitWidth, TZ))); 5124 return getMulExpr( 5125 getZeroExtendExpr( 5126 getTruncateExpr( 5127 getUDivExactExpr(getSCEV(BO->LHS), MulCount), 5128 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 5129 BO->LHS->getType()), 5130 MulCount); 5131 } 5132 } 5133 break; 5134 5135 case Instruction::Or: 5136 // If the RHS of the Or is a constant, we may have something like: 5137 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 5138 // optimizations will transparently handle this case. 5139 // 5140 // In order for this transformation to be safe, the LHS must be of the 5141 // form X*(2^n) and the Or constant must be less than 2^n. 5142 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 5143 const SCEV *LHS = getSCEV(BO->LHS); 5144 const APInt &CIVal = CI->getValue(); 5145 if (GetMinTrailingZeros(LHS) >= 5146 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 5147 // Build a plain add SCEV. 5148 const SCEV *S = getAddExpr(LHS, getSCEV(CI)); 5149 // If the LHS of the add was an addrec and it has no-wrap flags, 5150 // transfer the no-wrap flags, since an or won't introduce a wrap. 5151 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) { 5152 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS); 5153 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags( 5154 OldAR->getNoWrapFlags()); 5155 } 5156 return S; 5157 } 5158 } 5159 break; 5160 5161 case Instruction::Xor: 5162 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 5163 // If the RHS of xor is -1, then this is a not operation. 5164 if (CI->isAllOnesValue()) 5165 return getNotSCEV(getSCEV(BO->LHS)); 5166 5167 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 5168 // This is a variant of the check for xor with -1, and it handles 5169 // the case where instcombine has trimmed non-demanded bits out 5170 // of an xor with -1. 5171 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 5172 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 5173 if (LBO->getOpcode() == Instruction::And && 5174 LCI->getValue() == CI->getValue()) 5175 if (const SCEVZeroExtendExpr *Z = 5176 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 5177 Type *UTy = BO->LHS->getType(); 5178 const SCEV *Z0 = Z->getOperand(); 5179 Type *Z0Ty = Z0->getType(); 5180 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 5181 5182 // If C is a low-bits mask, the zero extend is serving to 5183 // mask off the high bits. Complement the operand and 5184 // re-apply the zext. 5185 if (APIntOps::isMask(Z0TySize, CI->getValue())) 5186 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 5187 5188 // If C is a single bit, it may be in the sign-bit position 5189 // before the zero-extend. In this case, represent the xor 5190 // using an add, which is equivalent, and re-apply the zext. 5191 APInt Trunc = CI->getValue().trunc(Z0TySize); 5192 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 5193 Trunc.isSignBit()) 5194 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 5195 UTy); 5196 } 5197 } 5198 break; 5199 5200 case Instruction::Shl: 5201 // Turn shift left of a constant amount into a multiply. 5202 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 5203 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 5204 5205 // If the shift count is not less than the bitwidth, the result of 5206 // the shift is undefined. Don't try to analyze it, because the 5207 // resolution chosen here may differ from the resolution chosen in 5208 // other parts of the compiler. 5209 if (SA->getValue().uge(BitWidth)) 5210 break; 5211 5212 // It is currently not resolved how to interpret NSW for left 5213 // shift by BitWidth - 1, so we avoid applying flags in that 5214 // case. Remove this check (or this comment) once the situation 5215 // is resolved. See 5216 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html 5217 // and http://reviews.llvm.org/D8890 . 5218 auto Flags = SCEV::FlagAnyWrap; 5219 if (BO->Op && SA->getValue().ult(BitWidth - 1)) 5220 Flags = getNoWrapFlagsFromUB(BO->Op); 5221 5222 Constant *X = ConstantInt::get(getContext(), 5223 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 5224 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 5225 } 5226 break; 5227 5228 case Instruction::AShr: 5229 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression. 5230 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) 5231 if (Operator *L = dyn_cast<Operator>(BO->LHS)) 5232 if (L->getOpcode() == Instruction::Shl && 5233 L->getOperand(1) == BO->RHS) { 5234 uint64_t BitWidth = getTypeSizeInBits(BO->LHS->getType()); 5235 5236 // If the shift count is not less than the bitwidth, the result of 5237 // the shift is undefined. Don't try to analyze it, because the 5238 // resolution chosen here may differ from the resolution chosen in 5239 // other parts of the compiler. 5240 if (CI->getValue().uge(BitWidth)) 5241 break; 5242 5243 uint64_t Amt = BitWidth - CI->getZExtValue(); 5244 if (Amt == BitWidth) 5245 return getSCEV(L->getOperand(0)); // shift by zero --> noop 5246 return getSignExtendExpr( 5247 getTruncateExpr(getSCEV(L->getOperand(0)), 5248 IntegerType::get(getContext(), Amt)), 5249 BO->LHS->getType()); 5250 } 5251 break; 5252 } 5253 } 5254 5255 switch (U->getOpcode()) { 5256 case Instruction::Trunc: 5257 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 5258 5259 case Instruction::ZExt: 5260 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 5261 5262 case Instruction::SExt: 5263 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 5264 5265 case Instruction::BitCast: 5266 // BitCasts are no-op casts so we just eliminate the cast. 5267 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 5268 return getSCEV(U->getOperand(0)); 5269 break; 5270 5271 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can 5272 // lead to pointer expressions which cannot safely be expanded to GEPs, 5273 // because ScalarEvolution doesn't respect the GEP aliasing rules when 5274 // simplifying integer expressions. 5275 5276 case Instruction::GetElementPtr: 5277 return createNodeForGEP(cast<GEPOperator>(U)); 5278 5279 case Instruction::PHI: 5280 return createNodeForPHI(cast<PHINode>(U)); 5281 5282 case Instruction::Select: 5283 // U can also be a select constant expr, which let fall through. Since 5284 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 5285 // constant expressions cannot have instructions as operands, we'd have 5286 // returned getUnknown for a select constant expressions anyway. 5287 if (isa<Instruction>(U)) 5288 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 5289 U->getOperand(1), U->getOperand(2)); 5290 break; 5291 5292 case Instruction::Call: 5293 case Instruction::Invoke: 5294 if (Value *RV = CallSite(U).getReturnedArgOperand()) 5295 return getSCEV(RV); 5296 break; 5297 } 5298 5299 return getUnknown(V); 5300 } 5301 5302 5303 5304 //===----------------------------------------------------------------------===// 5305 // Iteration Count Computation Code 5306 // 5307 5308 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 5309 if (!ExitCount) 5310 return 0; 5311 5312 ConstantInt *ExitConst = ExitCount->getValue(); 5313 5314 // Guard against huge trip counts. 5315 if (ExitConst->getValue().getActiveBits() > 32) 5316 return 0; 5317 5318 // In case of integer overflow, this returns 0, which is correct. 5319 return ((unsigned)ExitConst->getZExtValue()) + 1; 5320 } 5321 5322 unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L) { 5323 if (BasicBlock *ExitingBB = L->getExitingBlock()) 5324 return getSmallConstantTripCount(L, ExitingBB); 5325 5326 // No trip count information for multiple exits. 5327 return 0; 5328 } 5329 5330 unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L, 5331 BasicBlock *ExitingBlock) { 5332 assert(ExitingBlock && "Must pass a non-null exiting block!"); 5333 assert(L->isLoopExiting(ExitingBlock) && 5334 "Exiting block must actually branch out of the loop!"); 5335 const SCEVConstant *ExitCount = 5336 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 5337 return getConstantTripCount(ExitCount); 5338 } 5339 5340 unsigned ScalarEvolution::getSmallConstantMaxTripCount(Loop *L) { 5341 const auto *MaxExitCount = 5342 dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L)); 5343 return getConstantTripCount(MaxExitCount); 5344 } 5345 5346 unsigned ScalarEvolution::getSmallConstantTripMultiple(Loop *L) { 5347 if (BasicBlock *ExitingBB = L->getExitingBlock()) 5348 return getSmallConstantTripMultiple(L, ExitingBB); 5349 5350 // No trip multiple information for multiple exits. 5351 return 0; 5352 } 5353 5354 /// Returns the largest constant divisor of the trip count of this loop as a 5355 /// normal unsigned value, if possible. This means that the actual trip count is 5356 /// always a multiple of the returned value (don't forget the trip count could 5357 /// very well be zero as well!). 5358 /// 5359 /// Returns 1 if the trip count is unknown or not guaranteed to be the 5360 /// multiple of a constant (which is also the case if the trip count is simply 5361 /// constant, use getSmallConstantTripCount for that case), Will also return 1 5362 /// if the trip count is very large (>= 2^32). 5363 /// 5364 /// As explained in the comments for getSmallConstantTripCount, this assumes 5365 /// that control exits the loop via ExitingBlock. 5366 unsigned 5367 ScalarEvolution::getSmallConstantTripMultiple(Loop *L, 5368 BasicBlock *ExitingBlock) { 5369 assert(ExitingBlock && "Must pass a non-null exiting block!"); 5370 assert(L->isLoopExiting(ExitingBlock) && 5371 "Exiting block must actually branch out of the loop!"); 5372 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 5373 if (ExitCount == getCouldNotCompute()) 5374 return 1; 5375 5376 // Get the trip count from the BE count by adding 1. 5377 const SCEV *TCMul = getAddExpr(ExitCount, getOne(ExitCount->getType())); 5378 // FIXME: SCEV distributes multiplication as V1*C1 + V2*C1. We could attempt 5379 // to factor simple cases. 5380 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(TCMul)) 5381 TCMul = Mul->getOperand(0); 5382 5383 const SCEVConstant *MulC = dyn_cast<SCEVConstant>(TCMul); 5384 if (!MulC) 5385 return 1; 5386 5387 ConstantInt *Result = MulC->getValue(); 5388 5389 // Guard against huge trip counts (this requires checking 5390 // for zero to handle the case where the trip count == -1 and the 5391 // addition wraps). 5392 if (!Result || Result->getValue().getActiveBits() > 32 || 5393 Result->getValue().getActiveBits() == 0) 5394 return 1; 5395 5396 return (unsigned)Result->getZExtValue(); 5397 } 5398 5399 /// Get the expression for the number of loop iterations for which this loop is 5400 /// guaranteed not to exit via ExitingBlock. Otherwise return 5401 /// SCEVCouldNotCompute. 5402 const SCEV *ScalarEvolution::getExitCount(Loop *L, BasicBlock *ExitingBlock) { 5403 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 5404 } 5405 5406 const SCEV * 5407 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 5408 SCEVUnionPredicate &Preds) { 5409 return getPredicatedBackedgeTakenInfo(L).getExact(this, &Preds); 5410 } 5411 5412 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) { 5413 return getBackedgeTakenInfo(L).getExact(this); 5414 } 5415 5416 /// Similar to getBackedgeTakenCount, except return the least SCEV value that is 5417 /// known never to be less than the actual backedge taken count. 5418 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) { 5419 return getBackedgeTakenInfo(L).getMax(this); 5420 } 5421 5422 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 5423 return getBackedgeTakenInfo(L).isMaxOrZero(this); 5424 } 5425 5426 /// Push PHI nodes in the header of the given loop onto the given Worklist. 5427 static void 5428 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { 5429 BasicBlock *Header = L->getHeader(); 5430 5431 // Push all Loop-header PHIs onto the Worklist stack. 5432 for (BasicBlock::iterator I = Header->begin(); 5433 PHINode *PN = dyn_cast<PHINode>(I); ++I) 5434 Worklist.push_back(PN); 5435 } 5436 5437 const ScalarEvolution::BackedgeTakenInfo & 5438 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 5439 auto &BTI = getBackedgeTakenInfo(L); 5440 if (BTI.hasFullInfo()) 5441 return BTI; 5442 5443 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 5444 5445 if (!Pair.second) 5446 return Pair.first->second; 5447 5448 BackedgeTakenInfo Result = 5449 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 5450 5451 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 5452 } 5453 5454 const ScalarEvolution::BackedgeTakenInfo & 5455 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 5456 // Initially insert an invalid entry for this loop. If the insertion 5457 // succeeds, proceed to actually compute a backedge-taken count and 5458 // update the value. The temporary CouldNotCompute value tells SCEV 5459 // code elsewhere that it shouldn't attempt to request a new 5460 // backedge-taken count, which could result in infinite recursion. 5461 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 5462 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 5463 if (!Pair.second) 5464 return Pair.first->second; 5465 5466 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 5467 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 5468 // must be cleared in this scope. 5469 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 5470 5471 if (Result.getExact(this) != getCouldNotCompute()) { 5472 assert(isLoopInvariant(Result.getExact(this), L) && 5473 isLoopInvariant(Result.getMax(this), L) && 5474 "Computed backedge-taken count isn't loop invariant for loop!"); 5475 ++NumTripCountsComputed; 5476 } 5477 else if (Result.getMax(this) == getCouldNotCompute() && 5478 isa<PHINode>(L->getHeader()->begin())) { 5479 // Only count loops that have phi nodes as not being computable. 5480 ++NumTripCountsNotComputed; 5481 } 5482 5483 // Now that we know more about the trip count for this loop, forget any 5484 // existing SCEV values for PHI nodes in this loop since they are only 5485 // conservative estimates made without the benefit of trip count 5486 // information. This is similar to the code in forgetLoop, except that 5487 // it handles SCEVUnknown PHI nodes specially. 5488 if (Result.hasAnyInfo()) { 5489 SmallVector<Instruction *, 16> Worklist; 5490 PushLoopPHIs(L, Worklist); 5491 5492 SmallPtrSet<Instruction *, 8> Visited; 5493 while (!Worklist.empty()) { 5494 Instruction *I = Worklist.pop_back_val(); 5495 if (!Visited.insert(I).second) 5496 continue; 5497 5498 ValueExprMapType::iterator It = 5499 ValueExprMap.find_as(static_cast<Value *>(I)); 5500 if (It != ValueExprMap.end()) { 5501 const SCEV *Old = It->second; 5502 5503 // SCEVUnknown for a PHI either means that it has an unrecognized 5504 // structure, or it's a PHI that's in the progress of being computed 5505 // by createNodeForPHI. In the former case, additional loop trip 5506 // count information isn't going to change anything. In the later 5507 // case, createNodeForPHI will perform the necessary updates on its 5508 // own when it gets to that point. 5509 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 5510 eraseValueFromMap(It->first); 5511 forgetMemoizedResults(Old); 5512 } 5513 if (PHINode *PN = dyn_cast<PHINode>(I)) 5514 ConstantEvolutionLoopExitValue.erase(PN); 5515 } 5516 5517 PushDefUseChildren(I, Worklist); 5518 } 5519 } 5520 5521 // Re-lookup the insert position, since the call to 5522 // computeBackedgeTakenCount above could result in a 5523 // recusive call to getBackedgeTakenInfo (on a different 5524 // loop), which would invalidate the iterator computed 5525 // earlier. 5526 return BackedgeTakenCounts.find(L)->second = std::move(Result); 5527 } 5528 5529 void ScalarEvolution::forgetLoop(const Loop *L) { 5530 // Drop any stored trip count value. 5531 auto RemoveLoopFromBackedgeMap = 5532 [L](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 5533 auto BTCPos = Map.find(L); 5534 if (BTCPos != Map.end()) { 5535 BTCPos->second.clear(); 5536 Map.erase(BTCPos); 5537 } 5538 }; 5539 5540 RemoveLoopFromBackedgeMap(BackedgeTakenCounts); 5541 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts); 5542 5543 // Drop information about expressions based on loop-header PHIs. 5544 SmallVector<Instruction *, 16> Worklist; 5545 PushLoopPHIs(L, Worklist); 5546 5547 SmallPtrSet<Instruction *, 8> Visited; 5548 while (!Worklist.empty()) { 5549 Instruction *I = Worklist.pop_back_val(); 5550 if (!Visited.insert(I).second) 5551 continue; 5552 5553 ValueExprMapType::iterator It = 5554 ValueExprMap.find_as(static_cast<Value *>(I)); 5555 if (It != ValueExprMap.end()) { 5556 eraseValueFromMap(It->first); 5557 forgetMemoizedResults(It->second); 5558 if (PHINode *PN = dyn_cast<PHINode>(I)) 5559 ConstantEvolutionLoopExitValue.erase(PN); 5560 } 5561 5562 PushDefUseChildren(I, Worklist); 5563 } 5564 5565 // Forget all contained loops too, to avoid dangling entries in the 5566 // ValuesAtScopes map. 5567 for (Loop *I : *L) 5568 forgetLoop(I); 5569 5570 LoopPropertiesCache.erase(L); 5571 } 5572 5573 void ScalarEvolution::forgetValue(Value *V) { 5574 Instruction *I = dyn_cast<Instruction>(V); 5575 if (!I) return; 5576 5577 // Drop information about expressions based on loop-header PHIs. 5578 SmallVector<Instruction *, 16> Worklist; 5579 Worklist.push_back(I); 5580 5581 SmallPtrSet<Instruction *, 8> Visited; 5582 while (!Worklist.empty()) { 5583 I = Worklist.pop_back_val(); 5584 if (!Visited.insert(I).second) 5585 continue; 5586 5587 ValueExprMapType::iterator It = 5588 ValueExprMap.find_as(static_cast<Value *>(I)); 5589 if (It != ValueExprMap.end()) { 5590 eraseValueFromMap(It->first); 5591 forgetMemoizedResults(It->second); 5592 if (PHINode *PN = dyn_cast<PHINode>(I)) 5593 ConstantEvolutionLoopExitValue.erase(PN); 5594 } 5595 5596 PushDefUseChildren(I, Worklist); 5597 } 5598 } 5599 5600 /// Get the exact loop backedge taken count considering all loop exits. A 5601 /// computable result can only be returned for loops with a single exit. 5602 /// Returning the minimum taken count among all exits is incorrect because one 5603 /// of the loop's exit limit's may have been skipped. howFarToZero assumes that 5604 /// the limit of each loop test is never skipped. This is a valid assumption as 5605 /// long as the loop exits via that test. For precise results, it is the 5606 /// caller's responsibility to specify the relevant loop exit using 5607 /// getExact(ExitingBlock, SE). 5608 const SCEV * 5609 ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE, 5610 SCEVUnionPredicate *Preds) const { 5611 // If any exits were not computable, the loop is not computable. 5612 if (!isComplete() || ExitNotTaken.empty()) 5613 return SE->getCouldNotCompute(); 5614 5615 const SCEV *BECount = nullptr; 5616 for (auto &ENT : ExitNotTaken) { 5617 assert(ENT.ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV"); 5618 5619 if (!BECount) 5620 BECount = ENT.ExactNotTaken; 5621 else if (BECount != ENT.ExactNotTaken) 5622 return SE->getCouldNotCompute(); 5623 if (Preds && !ENT.hasAlwaysTruePredicate()) 5624 Preds->add(ENT.Predicate.get()); 5625 5626 assert((Preds || ENT.hasAlwaysTruePredicate()) && 5627 "Predicate should be always true!"); 5628 } 5629 5630 assert(BECount && "Invalid not taken count for loop exit"); 5631 return BECount; 5632 } 5633 5634 /// Get the exact not taken count for this loop exit. 5635 const SCEV * 5636 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock, 5637 ScalarEvolution *SE) const { 5638 for (auto &ENT : ExitNotTaken) 5639 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 5640 return ENT.ExactNotTaken; 5641 5642 return SE->getCouldNotCompute(); 5643 } 5644 5645 /// getMax - Get the max backedge taken count for the loop. 5646 const SCEV * 5647 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const { 5648 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 5649 return !ENT.hasAlwaysTruePredicate(); 5650 }; 5651 5652 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax()) 5653 return SE->getCouldNotCompute(); 5654 5655 return getMax(); 5656 } 5657 5658 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const { 5659 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 5660 return !ENT.hasAlwaysTruePredicate(); 5661 }; 5662 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 5663 } 5664 5665 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S, 5666 ScalarEvolution *SE) const { 5667 if (getMax() && getMax() != SE->getCouldNotCompute() && 5668 SE->hasOperand(getMax(), S)) 5669 return true; 5670 5671 for (auto &ENT : ExitNotTaken) 5672 if (ENT.ExactNotTaken != SE->getCouldNotCompute() && 5673 SE->hasOperand(ENT.ExactNotTaken, S)) 5674 return true; 5675 5676 return false; 5677 } 5678 5679 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 5680 /// computable exit into a persistent ExitNotTakenInfo array. 5681 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 5682 SmallVectorImpl<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> 5683 &&ExitCounts, 5684 bool Complete, const SCEV *MaxCount, bool MaxOrZero) 5685 : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) { 5686 typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo; 5687 ExitNotTaken.reserve(ExitCounts.size()); 5688 std::transform( 5689 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 5690 [&](const EdgeExitInfo &EEI) { 5691 BasicBlock *ExitBB = EEI.first; 5692 const ExitLimit &EL = EEI.second; 5693 if (EL.Predicates.empty()) 5694 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr); 5695 5696 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); 5697 for (auto *Pred : EL.Predicates) 5698 Predicate->add(Pred); 5699 5700 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate)); 5701 }); 5702 } 5703 5704 /// Invalidate this result and free the ExitNotTakenInfo array. 5705 void ScalarEvolution::BackedgeTakenInfo::clear() { 5706 ExitNotTaken.clear(); 5707 } 5708 5709 /// Compute the number of times the backedge of the specified loop will execute. 5710 ScalarEvolution::BackedgeTakenInfo 5711 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 5712 bool AllowPredicates) { 5713 SmallVector<BasicBlock *, 8> ExitingBlocks; 5714 L->getExitingBlocks(ExitingBlocks); 5715 5716 typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo; 5717 5718 SmallVector<EdgeExitInfo, 4> ExitCounts; 5719 bool CouldComputeBECount = true; 5720 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 5721 const SCEV *MustExitMaxBECount = nullptr; 5722 const SCEV *MayExitMaxBECount = nullptr; 5723 bool MustExitMaxOrZero = false; 5724 5725 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 5726 // and compute maxBECount. 5727 // Do a union of all the predicates here. 5728 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 5729 BasicBlock *ExitBB = ExitingBlocks[i]; 5730 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 5731 5732 assert((AllowPredicates || EL.Predicates.empty()) && 5733 "Predicated exit limit when predicates are not allowed!"); 5734 5735 // 1. For each exit that can be computed, add an entry to ExitCounts. 5736 // CouldComputeBECount is true only if all exits can be computed. 5737 if (EL.ExactNotTaken == getCouldNotCompute()) 5738 // We couldn't compute an exact value for this exit, so 5739 // we won't be able to compute an exact value for the loop. 5740 CouldComputeBECount = false; 5741 else 5742 ExitCounts.emplace_back(ExitBB, EL); 5743 5744 // 2. Derive the loop's MaxBECount from each exit's max number of 5745 // non-exiting iterations. Partition the loop exits into two kinds: 5746 // LoopMustExits and LoopMayExits. 5747 // 5748 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 5749 // is a LoopMayExit. If any computable LoopMustExit is found, then 5750 // MaxBECount is the minimum EL.MaxNotTaken of computable 5751 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 5752 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 5753 // computable EL.MaxNotTaken. 5754 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 5755 DT.dominates(ExitBB, Latch)) { 5756 if (!MustExitMaxBECount) { 5757 MustExitMaxBECount = EL.MaxNotTaken; 5758 MustExitMaxOrZero = EL.MaxOrZero; 5759 } else { 5760 MustExitMaxBECount = 5761 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 5762 } 5763 } else if (MayExitMaxBECount != getCouldNotCompute()) { 5764 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 5765 MayExitMaxBECount = EL.MaxNotTaken; 5766 else { 5767 MayExitMaxBECount = 5768 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 5769 } 5770 } 5771 } 5772 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 5773 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 5774 // The loop backedge will be taken the maximum or zero times if there's 5775 // a single exit that must be taken the maximum or zero times. 5776 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 5777 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 5778 MaxBECount, MaxOrZero); 5779 } 5780 5781 ScalarEvolution::ExitLimit 5782 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 5783 bool AllowPredicates) { 5784 5785 // Okay, we've chosen an exiting block. See what condition causes us to exit 5786 // at this block and remember the exit block and whether all other targets 5787 // lead to the loop header. 5788 bool MustExecuteLoopHeader = true; 5789 BasicBlock *Exit = nullptr; 5790 for (auto *SBB : successors(ExitingBlock)) 5791 if (!L->contains(SBB)) { 5792 if (Exit) // Multiple exit successors. 5793 return getCouldNotCompute(); 5794 Exit = SBB; 5795 } else if (SBB != L->getHeader()) { 5796 MustExecuteLoopHeader = false; 5797 } 5798 5799 // At this point, we know we have a conditional branch that determines whether 5800 // the loop is exited. However, we don't know if the branch is executed each 5801 // time through the loop. If not, then the execution count of the branch will 5802 // not be equal to the trip count of the loop. 5803 // 5804 // Currently we check for this by checking to see if the Exit branch goes to 5805 // the loop header. If so, we know it will always execute the same number of 5806 // times as the loop. We also handle the case where the exit block *is* the 5807 // loop header. This is common for un-rotated loops. 5808 // 5809 // If both of those tests fail, walk up the unique predecessor chain to the 5810 // header, stopping if there is an edge that doesn't exit the loop. If the 5811 // header is reached, the execution count of the branch will be equal to the 5812 // trip count of the loop. 5813 // 5814 // More extensive analysis could be done to handle more cases here. 5815 // 5816 if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) { 5817 // The simple checks failed, try climbing the unique predecessor chain 5818 // up to the header. 5819 bool Ok = false; 5820 for (BasicBlock *BB = ExitingBlock; BB; ) { 5821 BasicBlock *Pred = BB->getUniquePredecessor(); 5822 if (!Pred) 5823 return getCouldNotCompute(); 5824 TerminatorInst *PredTerm = Pred->getTerminator(); 5825 for (const BasicBlock *PredSucc : PredTerm->successors()) { 5826 if (PredSucc == BB) 5827 continue; 5828 // If the predecessor has a successor that isn't BB and isn't 5829 // outside the loop, assume the worst. 5830 if (L->contains(PredSucc)) 5831 return getCouldNotCompute(); 5832 } 5833 if (Pred == L->getHeader()) { 5834 Ok = true; 5835 break; 5836 } 5837 BB = Pred; 5838 } 5839 if (!Ok) 5840 return getCouldNotCompute(); 5841 } 5842 5843 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 5844 TerminatorInst *Term = ExitingBlock->getTerminator(); 5845 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 5846 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 5847 // Proceed to the next level to examine the exit condition expression. 5848 return computeExitLimitFromCond( 5849 L, BI->getCondition(), BI->getSuccessor(0), BI->getSuccessor(1), 5850 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 5851 } 5852 5853 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) 5854 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 5855 /*ControlsExit=*/IsOnlyExit); 5856 5857 return getCouldNotCompute(); 5858 } 5859 5860 ScalarEvolution::ExitLimit 5861 ScalarEvolution::computeExitLimitFromCond(const Loop *L, 5862 Value *ExitCond, 5863 BasicBlock *TBB, 5864 BasicBlock *FBB, 5865 bool ControlsExit, 5866 bool AllowPredicates) { 5867 // Check if the controlling expression for this loop is an And or Or. 5868 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) { 5869 if (BO->getOpcode() == Instruction::And) { 5870 // Recurse on the operands of the and. 5871 bool EitherMayExit = L->contains(TBB); 5872 ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB, 5873 ControlsExit && !EitherMayExit, 5874 AllowPredicates); 5875 ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB, 5876 ControlsExit && !EitherMayExit, 5877 AllowPredicates); 5878 const SCEV *BECount = getCouldNotCompute(); 5879 const SCEV *MaxBECount = getCouldNotCompute(); 5880 if (EitherMayExit) { 5881 // Both conditions must be true for the loop to continue executing. 5882 // Choose the less conservative count. 5883 if (EL0.ExactNotTaken == getCouldNotCompute() || 5884 EL1.ExactNotTaken == getCouldNotCompute()) 5885 BECount = getCouldNotCompute(); 5886 else 5887 BECount = 5888 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 5889 if (EL0.MaxNotTaken == getCouldNotCompute()) 5890 MaxBECount = EL1.MaxNotTaken; 5891 else if (EL1.MaxNotTaken == getCouldNotCompute()) 5892 MaxBECount = EL0.MaxNotTaken; 5893 else 5894 MaxBECount = 5895 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 5896 } else { 5897 // Both conditions must be true at the same time for the loop to exit. 5898 // For now, be conservative. 5899 assert(L->contains(FBB) && "Loop block has no successor in loop!"); 5900 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 5901 MaxBECount = EL0.MaxNotTaken; 5902 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 5903 BECount = EL0.ExactNotTaken; 5904 } 5905 5906 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 5907 // to be more aggressive when computing BECount than when computing 5908 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 5909 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 5910 // to not. 5911 if (isa<SCEVCouldNotCompute>(MaxBECount) && 5912 !isa<SCEVCouldNotCompute>(BECount)) 5913 MaxBECount = BECount; 5914 5915 return ExitLimit(BECount, MaxBECount, false, 5916 {&EL0.Predicates, &EL1.Predicates}); 5917 } 5918 if (BO->getOpcode() == Instruction::Or) { 5919 // Recurse on the operands of the or. 5920 bool EitherMayExit = L->contains(FBB); 5921 ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB, 5922 ControlsExit && !EitherMayExit, 5923 AllowPredicates); 5924 ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB, 5925 ControlsExit && !EitherMayExit, 5926 AllowPredicates); 5927 const SCEV *BECount = getCouldNotCompute(); 5928 const SCEV *MaxBECount = getCouldNotCompute(); 5929 if (EitherMayExit) { 5930 // Both conditions must be false for the loop to continue executing. 5931 // Choose the less conservative count. 5932 if (EL0.ExactNotTaken == getCouldNotCompute() || 5933 EL1.ExactNotTaken == getCouldNotCompute()) 5934 BECount = getCouldNotCompute(); 5935 else 5936 BECount = 5937 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 5938 if (EL0.MaxNotTaken == getCouldNotCompute()) 5939 MaxBECount = EL1.MaxNotTaken; 5940 else if (EL1.MaxNotTaken == getCouldNotCompute()) 5941 MaxBECount = EL0.MaxNotTaken; 5942 else 5943 MaxBECount = 5944 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 5945 } else { 5946 // Both conditions must be false at the same time for the loop to exit. 5947 // For now, be conservative. 5948 assert(L->contains(TBB) && "Loop block has no successor in loop!"); 5949 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 5950 MaxBECount = EL0.MaxNotTaken; 5951 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 5952 BECount = EL0.ExactNotTaken; 5953 } 5954 5955 return ExitLimit(BECount, MaxBECount, false, 5956 {&EL0.Predicates, &EL1.Predicates}); 5957 } 5958 } 5959 5960 // With an icmp, it may be feasible to compute an exact backedge-taken count. 5961 // Proceed to the next level to examine the icmp. 5962 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 5963 ExitLimit EL = 5964 computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit); 5965 if (EL.hasFullInfo() || !AllowPredicates) 5966 return EL; 5967 5968 // Try again, but use SCEV predicates this time. 5969 return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit, 5970 /*AllowPredicates=*/true); 5971 } 5972 5973 // Check for a constant condition. These are normally stripped out by 5974 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 5975 // preserve the CFG and is temporarily leaving constant conditions 5976 // in place. 5977 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 5978 if (L->contains(FBB) == !CI->getZExtValue()) 5979 // The backedge is always taken. 5980 return getCouldNotCompute(); 5981 else 5982 // The backedge is never taken. 5983 return getZero(CI->getType()); 5984 } 5985 5986 // If it's not an integer or pointer comparison then compute it the hard way. 5987 return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB)); 5988 } 5989 5990 ScalarEvolution::ExitLimit 5991 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 5992 ICmpInst *ExitCond, 5993 BasicBlock *TBB, 5994 BasicBlock *FBB, 5995 bool ControlsExit, 5996 bool AllowPredicates) { 5997 5998 // If the condition was exit on true, convert the condition to exit on false 5999 ICmpInst::Predicate Cond; 6000 if (!L->contains(FBB)) 6001 Cond = ExitCond->getPredicate(); 6002 else 6003 Cond = ExitCond->getInversePredicate(); 6004 6005 // Handle common loops like: for (X = "string"; *X; ++X) 6006 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 6007 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 6008 ExitLimit ItCnt = 6009 computeLoadConstantCompareExitLimit(LI, RHS, L, Cond); 6010 if (ItCnt.hasAnyInfo()) 6011 return ItCnt; 6012 } 6013 6014 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 6015 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 6016 6017 // Try to evaluate any dependencies out of the loop. 6018 LHS = getSCEVAtScope(LHS, L); 6019 RHS = getSCEVAtScope(RHS, L); 6020 6021 // At this point, we would like to compute how many iterations of the 6022 // loop the predicate will return true for these inputs. 6023 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 6024 // If there is a loop-invariant, force it into the RHS. 6025 std::swap(LHS, RHS); 6026 Cond = ICmpInst::getSwappedPredicate(Cond); 6027 } 6028 6029 // Simplify the operands before analyzing them. 6030 (void)SimplifyICmpOperands(Cond, LHS, RHS); 6031 6032 // If we have a comparison of a chrec against a constant, try to use value 6033 // ranges to answer this query. 6034 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 6035 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 6036 if (AddRec->getLoop() == L) { 6037 // Form the constant range. 6038 ConstantRange CompRange = 6039 ConstantRange::makeExactICmpRegion(Cond, RHSC->getAPInt()); 6040 6041 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 6042 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 6043 } 6044 6045 switch (Cond) { 6046 case ICmpInst::ICMP_NE: { // while (X != Y) 6047 // Convert to: while (X-Y != 0) 6048 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 6049 AllowPredicates); 6050 if (EL.hasAnyInfo()) return EL; 6051 break; 6052 } 6053 case ICmpInst::ICMP_EQ: { // while (X == Y) 6054 // Convert to: while (X-Y == 0) 6055 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 6056 if (EL.hasAnyInfo()) return EL; 6057 break; 6058 } 6059 case ICmpInst::ICMP_SLT: 6060 case ICmpInst::ICMP_ULT: { // while (X < Y) 6061 bool IsSigned = Cond == ICmpInst::ICMP_SLT; 6062 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 6063 AllowPredicates); 6064 if (EL.hasAnyInfo()) return EL; 6065 break; 6066 } 6067 case ICmpInst::ICMP_SGT: 6068 case ICmpInst::ICMP_UGT: { // while (X > Y) 6069 bool IsSigned = Cond == ICmpInst::ICMP_SGT; 6070 ExitLimit EL = 6071 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 6072 AllowPredicates); 6073 if (EL.hasAnyInfo()) return EL; 6074 break; 6075 } 6076 default: 6077 break; 6078 } 6079 6080 auto *ExhaustiveCount = 6081 computeExitCountExhaustively(L, ExitCond, !L->contains(TBB)); 6082 6083 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 6084 return ExhaustiveCount; 6085 6086 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 6087 ExitCond->getOperand(1), L, Cond); 6088 } 6089 6090 ScalarEvolution::ExitLimit 6091 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 6092 SwitchInst *Switch, 6093 BasicBlock *ExitingBlock, 6094 bool ControlsExit) { 6095 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 6096 6097 // Give up if the exit is the default dest of a switch. 6098 if (Switch->getDefaultDest() == ExitingBlock) 6099 return getCouldNotCompute(); 6100 6101 assert(L->contains(Switch->getDefaultDest()) && 6102 "Default case must not exit the loop!"); 6103 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 6104 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 6105 6106 // while (X != Y) --> while (X-Y != 0) 6107 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 6108 if (EL.hasAnyInfo()) 6109 return EL; 6110 6111 return getCouldNotCompute(); 6112 } 6113 6114 static ConstantInt * 6115 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 6116 ScalarEvolution &SE) { 6117 const SCEV *InVal = SE.getConstant(C); 6118 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 6119 assert(isa<SCEVConstant>(Val) && 6120 "Evaluation of SCEV at constant didn't fold correctly?"); 6121 return cast<SCEVConstant>(Val)->getValue(); 6122 } 6123 6124 /// Given an exit condition of 'icmp op load X, cst', try to see if we can 6125 /// compute the backedge execution count. 6126 ScalarEvolution::ExitLimit 6127 ScalarEvolution::computeLoadConstantCompareExitLimit( 6128 LoadInst *LI, 6129 Constant *RHS, 6130 const Loop *L, 6131 ICmpInst::Predicate predicate) { 6132 6133 if (LI->isVolatile()) return getCouldNotCompute(); 6134 6135 // Check to see if the loaded pointer is a getelementptr of a global. 6136 // TODO: Use SCEV instead of manually grubbing with GEPs. 6137 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 6138 if (!GEP) return getCouldNotCompute(); 6139 6140 // Make sure that it is really a constant global we are gepping, with an 6141 // initializer, and make sure the first IDX is really 0. 6142 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 6143 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || 6144 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 6145 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 6146 return getCouldNotCompute(); 6147 6148 // Okay, we allow one non-constant index into the GEP instruction. 6149 Value *VarIdx = nullptr; 6150 std::vector<Constant*> Indexes; 6151 unsigned VarIdxNum = 0; 6152 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 6153 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 6154 Indexes.push_back(CI); 6155 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 6156 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. 6157 VarIdx = GEP->getOperand(i); 6158 VarIdxNum = i-2; 6159 Indexes.push_back(nullptr); 6160 } 6161 6162 // Loop-invariant loads may be a byproduct of loop optimization. Skip them. 6163 if (!VarIdx) 6164 return getCouldNotCompute(); 6165 6166 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 6167 // Check to see if X is a loop variant variable value now. 6168 const SCEV *Idx = getSCEV(VarIdx); 6169 Idx = getSCEVAtScope(Idx, L); 6170 6171 // We can only recognize very limited forms of loop index expressions, in 6172 // particular, only affine AddRec's like {C1,+,C2}. 6173 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 6174 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) || 6175 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 6176 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 6177 return getCouldNotCompute(); 6178 6179 unsigned MaxSteps = MaxBruteForceIterations; 6180 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 6181 ConstantInt *ItCst = ConstantInt::get( 6182 cast<IntegerType>(IdxExpr->getType()), IterationNum); 6183 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 6184 6185 // Form the GEP offset. 6186 Indexes[VarIdxNum] = Val; 6187 6188 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), 6189 Indexes); 6190 if (!Result) break; // Cannot compute! 6191 6192 // Evaluate the condition for this iteration. 6193 Result = ConstantExpr::getICmp(predicate, Result, RHS); 6194 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 6195 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 6196 ++NumArrayLenItCounts; 6197 return getConstant(ItCst); // Found terminating iteration! 6198 } 6199 } 6200 return getCouldNotCompute(); 6201 } 6202 6203 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 6204 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 6205 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 6206 if (!RHS) 6207 return getCouldNotCompute(); 6208 6209 const BasicBlock *Latch = L->getLoopLatch(); 6210 if (!Latch) 6211 return getCouldNotCompute(); 6212 6213 const BasicBlock *Predecessor = L->getLoopPredecessor(); 6214 if (!Predecessor) 6215 return getCouldNotCompute(); 6216 6217 // Return true if V is of the form "LHS `shift_op` <positive constant>". 6218 // Return LHS in OutLHS and shift_opt in OutOpCode. 6219 auto MatchPositiveShift = 6220 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 6221 6222 using namespace PatternMatch; 6223 6224 ConstantInt *ShiftAmt; 6225 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 6226 OutOpCode = Instruction::LShr; 6227 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 6228 OutOpCode = Instruction::AShr; 6229 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 6230 OutOpCode = Instruction::Shl; 6231 else 6232 return false; 6233 6234 return ShiftAmt->getValue().isStrictlyPositive(); 6235 }; 6236 6237 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 6238 // 6239 // loop: 6240 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 6241 // %iv.shifted = lshr i32 %iv, <positive constant> 6242 // 6243 // Return true on a succesful match. Return the corresponding PHI node (%iv 6244 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 6245 auto MatchShiftRecurrence = 6246 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 6247 Optional<Instruction::BinaryOps> PostShiftOpCode; 6248 6249 { 6250 Instruction::BinaryOps OpC; 6251 Value *V; 6252 6253 // If we encounter a shift instruction, "peel off" the shift operation, 6254 // and remember that we did so. Later when we inspect %iv's backedge 6255 // value, we will make sure that the backedge value uses the same 6256 // operation. 6257 // 6258 // Note: the peeled shift operation does not have to be the same 6259 // instruction as the one feeding into the PHI's backedge value. We only 6260 // really care about it being the same *kind* of shift instruction -- 6261 // that's all that is required for our later inferences to hold. 6262 if (MatchPositiveShift(LHS, V, OpC)) { 6263 PostShiftOpCode = OpC; 6264 LHS = V; 6265 } 6266 } 6267 6268 PNOut = dyn_cast<PHINode>(LHS); 6269 if (!PNOut || PNOut->getParent() != L->getHeader()) 6270 return false; 6271 6272 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 6273 Value *OpLHS; 6274 6275 return 6276 // The backedge value for the PHI node must be a shift by a positive 6277 // amount 6278 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 6279 6280 // of the PHI node itself 6281 OpLHS == PNOut && 6282 6283 // and the kind of shift should be match the kind of shift we peeled 6284 // off, if any. 6285 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 6286 }; 6287 6288 PHINode *PN; 6289 Instruction::BinaryOps OpCode; 6290 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 6291 return getCouldNotCompute(); 6292 6293 const DataLayout &DL = getDataLayout(); 6294 6295 // The key rationale for this optimization is that for some kinds of shift 6296 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 6297 // within a finite number of iterations. If the condition guarding the 6298 // backedge (in the sense that the backedge is taken if the condition is true) 6299 // is false for the value the shift recurrence stabilizes to, then we know 6300 // that the backedge is taken only a finite number of times. 6301 6302 ConstantInt *StableValue = nullptr; 6303 switch (OpCode) { 6304 default: 6305 llvm_unreachable("Impossible case!"); 6306 6307 case Instruction::AShr: { 6308 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 6309 // bitwidth(K) iterations. 6310 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 6311 bool KnownZero, KnownOne; 6312 ComputeSignBit(FirstValue, KnownZero, KnownOne, DL, 0, nullptr, 6313 Predecessor->getTerminator(), &DT); 6314 auto *Ty = cast<IntegerType>(RHS->getType()); 6315 if (KnownZero) 6316 StableValue = ConstantInt::get(Ty, 0); 6317 else if (KnownOne) 6318 StableValue = ConstantInt::get(Ty, -1, true); 6319 else 6320 return getCouldNotCompute(); 6321 6322 break; 6323 } 6324 case Instruction::LShr: 6325 case Instruction::Shl: 6326 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 6327 // stabilize to 0 in at most bitwidth(K) iterations. 6328 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 6329 break; 6330 } 6331 6332 auto *Result = 6333 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 6334 assert(Result->getType()->isIntegerTy(1) && 6335 "Otherwise cannot be an operand to a branch instruction"); 6336 6337 if (Result->isZeroValue()) { 6338 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 6339 const SCEV *UpperBound = 6340 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 6341 return ExitLimit(getCouldNotCompute(), UpperBound, false); 6342 } 6343 6344 return getCouldNotCompute(); 6345 } 6346 6347 /// Return true if we can constant fold an instruction of the specified type, 6348 /// assuming that all operands were constants. 6349 static bool CanConstantFold(const Instruction *I) { 6350 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 6351 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 6352 isa<LoadInst>(I)) 6353 return true; 6354 6355 if (const CallInst *CI = dyn_cast<CallInst>(I)) 6356 if (const Function *F = CI->getCalledFunction()) 6357 return canConstantFoldCallTo(F); 6358 return false; 6359 } 6360 6361 /// Determine whether this instruction can constant evolve within this loop 6362 /// assuming its operands can all constant evolve. 6363 static bool canConstantEvolve(Instruction *I, const Loop *L) { 6364 // An instruction outside of the loop can't be derived from a loop PHI. 6365 if (!L->contains(I)) return false; 6366 6367 if (isa<PHINode>(I)) { 6368 // We don't currently keep track of the control flow needed to evaluate 6369 // PHIs, so we cannot handle PHIs inside of loops. 6370 return L->getHeader() == I->getParent(); 6371 } 6372 6373 // If we won't be able to constant fold this expression even if the operands 6374 // are constants, bail early. 6375 return CanConstantFold(I); 6376 } 6377 6378 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 6379 /// recursing through each instruction operand until reaching a loop header phi. 6380 static PHINode * 6381 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 6382 DenseMap<Instruction *, PHINode *> &PHIMap) { 6383 6384 // Otherwise, we can evaluate this instruction if all of its operands are 6385 // constant or derived from a PHI node themselves. 6386 PHINode *PHI = nullptr; 6387 for (Value *Op : UseInst->operands()) { 6388 if (isa<Constant>(Op)) continue; 6389 6390 Instruction *OpInst = dyn_cast<Instruction>(Op); 6391 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 6392 6393 PHINode *P = dyn_cast<PHINode>(OpInst); 6394 if (!P) 6395 // If this operand is already visited, reuse the prior result. 6396 // We may have P != PHI if this is the deepest point at which the 6397 // inconsistent paths meet. 6398 P = PHIMap.lookup(OpInst); 6399 if (!P) { 6400 // Recurse and memoize the results, whether a phi is found or not. 6401 // This recursive call invalidates pointers into PHIMap. 6402 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap); 6403 PHIMap[OpInst] = P; 6404 } 6405 if (!P) 6406 return nullptr; // Not evolving from PHI 6407 if (PHI && PHI != P) 6408 return nullptr; // Evolving from multiple different PHIs. 6409 PHI = P; 6410 } 6411 // This is a expression evolving from a constant PHI! 6412 return PHI; 6413 } 6414 6415 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 6416 /// in the loop that V is derived from. We allow arbitrary operations along the 6417 /// way, but the operands of an operation must either be constants or a value 6418 /// derived from a constant PHI. If this expression does not fit with these 6419 /// constraints, return null. 6420 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 6421 Instruction *I = dyn_cast<Instruction>(V); 6422 if (!I || !canConstantEvolve(I, L)) return nullptr; 6423 6424 if (PHINode *PN = dyn_cast<PHINode>(I)) 6425 return PN; 6426 6427 // Record non-constant instructions contained by the loop. 6428 DenseMap<Instruction *, PHINode *> PHIMap; 6429 return getConstantEvolvingPHIOperands(I, L, PHIMap); 6430 } 6431 6432 /// EvaluateExpression - Given an expression that passes the 6433 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 6434 /// in the loop has the value PHIVal. If we can't fold this expression for some 6435 /// reason, return null. 6436 static Constant *EvaluateExpression(Value *V, const Loop *L, 6437 DenseMap<Instruction *, Constant *> &Vals, 6438 const DataLayout &DL, 6439 const TargetLibraryInfo *TLI) { 6440 // Convenient constant check, but redundant for recursive calls. 6441 if (Constant *C = dyn_cast<Constant>(V)) return C; 6442 Instruction *I = dyn_cast<Instruction>(V); 6443 if (!I) return nullptr; 6444 6445 if (Constant *C = Vals.lookup(I)) return C; 6446 6447 // An instruction inside the loop depends on a value outside the loop that we 6448 // weren't given a mapping for, or a value such as a call inside the loop. 6449 if (!canConstantEvolve(I, L)) return nullptr; 6450 6451 // An unmapped PHI can be due to a branch or another loop inside this loop, 6452 // or due to this not being the initial iteration through a loop where we 6453 // couldn't compute the evolution of this particular PHI last time. 6454 if (isa<PHINode>(I)) return nullptr; 6455 6456 std::vector<Constant*> Operands(I->getNumOperands()); 6457 6458 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 6459 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 6460 if (!Operand) { 6461 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 6462 if (!Operands[i]) return nullptr; 6463 continue; 6464 } 6465 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 6466 Vals[Operand] = C; 6467 if (!C) return nullptr; 6468 Operands[i] = C; 6469 } 6470 6471 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 6472 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 6473 Operands[1], DL, TLI); 6474 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 6475 if (!LI->isVolatile()) 6476 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 6477 } 6478 return ConstantFoldInstOperands(I, Operands, DL, TLI); 6479 } 6480 6481 6482 // If every incoming value to PN except the one for BB is a specific Constant, 6483 // return that, else return nullptr. 6484 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 6485 Constant *IncomingVal = nullptr; 6486 6487 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 6488 if (PN->getIncomingBlock(i) == BB) 6489 continue; 6490 6491 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 6492 if (!CurrentVal) 6493 return nullptr; 6494 6495 if (IncomingVal != CurrentVal) { 6496 if (IncomingVal) 6497 return nullptr; 6498 IncomingVal = CurrentVal; 6499 } 6500 } 6501 6502 return IncomingVal; 6503 } 6504 6505 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 6506 /// in the header of its containing loop, we know the loop executes a 6507 /// constant number of times, and the PHI node is just a recurrence 6508 /// involving constants, fold it. 6509 Constant * 6510 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 6511 const APInt &BEs, 6512 const Loop *L) { 6513 auto I = ConstantEvolutionLoopExitValue.find(PN); 6514 if (I != ConstantEvolutionLoopExitValue.end()) 6515 return I->second; 6516 6517 if (BEs.ugt(MaxBruteForceIterations)) 6518 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 6519 6520 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 6521 6522 DenseMap<Instruction *, Constant *> CurrentIterVals; 6523 BasicBlock *Header = L->getHeader(); 6524 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 6525 6526 BasicBlock *Latch = L->getLoopLatch(); 6527 if (!Latch) 6528 return nullptr; 6529 6530 for (auto &I : *Header) { 6531 PHINode *PHI = dyn_cast<PHINode>(&I); 6532 if (!PHI) break; 6533 auto *StartCST = getOtherIncomingValue(PHI, Latch); 6534 if (!StartCST) continue; 6535 CurrentIterVals[PHI] = StartCST; 6536 } 6537 if (!CurrentIterVals.count(PN)) 6538 return RetVal = nullptr; 6539 6540 Value *BEValue = PN->getIncomingValueForBlock(Latch); 6541 6542 // Execute the loop symbolically to determine the exit value. 6543 if (BEs.getActiveBits() >= 32) 6544 return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it! 6545 6546 unsigned NumIterations = BEs.getZExtValue(); // must be in range 6547 unsigned IterationNum = 0; 6548 const DataLayout &DL = getDataLayout(); 6549 for (; ; ++IterationNum) { 6550 if (IterationNum == NumIterations) 6551 return RetVal = CurrentIterVals[PN]; // Got exit value! 6552 6553 // Compute the value of the PHIs for the next iteration. 6554 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 6555 DenseMap<Instruction *, Constant *> NextIterVals; 6556 Constant *NextPHI = 6557 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 6558 if (!NextPHI) 6559 return nullptr; // Couldn't evaluate! 6560 NextIterVals[PN] = NextPHI; 6561 6562 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 6563 6564 // Also evaluate the other PHI nodes. However, we don't get to stop if we 6565 // cease to be able to evaluate one of them or if they stop evolving, 6566 // because that doesn't necessarily prevent us from computing PN. 6567 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 6568 for (const auto &I : CurrentIterVals) { 6569 PHINode *PHI = dyn_cast<PHINode>(I.first); 6570 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 6571 PHIsToCompute.emplace_back(PHI, I.second); 6572 } 6573 // We use two distinct loops because EvaluateExpression may invalidate any 6574 // iterators into CurrentIterVals. 6575 for (const auto &I : PHIsToCompute) { 6576 PHINode *PHI = I.first; 6577 Constant *&NextPHI = NextIterVals[PHI]; 6578 if (!NextPHI) { // Not already computed. 6579 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 6580 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 6581 } 6582 if (NextPHI != I.second) 6583 StoppedEvolving = false; 6584 } 6585 6586 // If all entries in CurrentIterVals == NextIterVals then we can stop 6587 // iterating, the loop can't continue to change. 6588 if (StoppedEvolving) 6589 return RetVal = CurrentIterVals[PN]; 6590 6591 CurrentIterVals.swap(NextIterVals); 6592 } 6593 } 6594 6595 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 6596 Value *Cond, 6597 bool ExitWhen) { 6598 PHINode *PN = getConstantEvolvingPHI(Cond, L); 6599 if (!PN) return getCouldNotCompute(); 6600 6601 // If the loop is canonicalized, the PHI will have exactly two entries. 6602 // That's the only form we support here. 6603 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 6604 6605 DenseMap<Instruction *, Constant *> CurrentIterVals; 6606 BasicBlock *Header = L->getHeader(); 6607 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 6608 6609 BasicBlock *Latch = L->getLoopLatch(); 6610 assert(Latch && "Should follow from NumIncomingValues == 2!"); 6611 6612 for (auto &I : *Header) { 6613 PHINode *PHI = dyn_cast<PHINode>(&I); 6614 if (!PHI) 6615 break; 6616 auto *StartCST = getOtherIncomingValue(PHI, Latch); 6617 if (!StartCST) continue; 6618 CurrentIterVals[PHI] = StartCST; 6619 } 6620 if (!CurrentIterVals.count(PN)) 6621 return getCouldNotCompute(); 6622 6623 // Okay, we find a PHI node that defines the trip count of this loop. Execute 6624 // the loop symbolically to determine when the condition gets a value of 6625 // "ExitWhen". 6626 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 6627 const DataLayout &DL = getDataLayout(); 6628 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 6629 auto *CondVal = dyn_cast_or_null<ConstantInt>( 6630 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 6631 6632 // Couldn't symbolically evaluate. 6633 if (!CondVal) return getCouldNotCompute(); 6634 6635 if (CondVal->getValue() == uint64_t(ExitWhen)) { 6636 ++NumBruteForceTripCountsComputed; 6637 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 6638 } 6639 6640 // Update all the PHI nodes for the next iteration. 6641 DenseMap<Instruction *, Constant *> NextIterVals; 6642 6643 // Create a list of which PHIs we need to compute. We want to do this before 6644 // calling EvaluateExpression on them because that may invalidate iterators 6645 // into CurrentIterVals. 6646 SmallVector<PHINode *, 8> PHIsToCompute; 6647 for (const auto &I : CurrentIterVals) { 6648 PHINode *PHI = dyn_cast<PHINode>(I.first); 6649 if (!PHI || PHI->getParent() != Header) continue; 6650 PHIsToCompute.push_back(PHI); 6651 } 6652 for (PHINode *PHI : PHIsToCompute) { 6653 Constant *&NextPHI = NextIterVals[PHI]; 6654 if (NextPHI) continue; // Already computed! 6655 6656 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 6657 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 6658 } 6659 CurrentIterVals.swap(NextIterVals); 6660 } 6661 6662 // Too many iterations were needed to evaluate. 6663 return getCouldNotCompute(); 6664 } 6665 6666 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 6667 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 6668 ValuesAtScopes[V]; 6669 // Check to see if we've folded this expression at this loop before. 6670 for (auto &LS : Values) 6671 if (LS.first == L) 6672 return LS.second ? LS.second : V; 6673 6674 Values.emplace_back(L, nullptr); 6675 6676 // Otherwise compute it. 6677 const SCEV *C = computeSCEVAtScope(V, L); 6678 for (auto &LS : reverse(ValuesAtScopes[V])) 6679 if (LS.first == L) { 6680 LS.second = C; 6681 break; 6682 } 6683 return C; 6684 } 6685 6686 /// This builds up a Constant using the ConstantExpr interface. That way, we 6687 /// will return Constants for objects which aren't represented by a 6688 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 6689 /// Returns NULL if the SCEV isn't representable as a Constant. 6690 static Constant *BuildConstantFromSCEV(const SCEV *V) { 6691 switch (static_cast<SCEVTypes>(V->getSCEVType())) { 6692 case scCouldNotCompute: 6693 case scAddRecExpr: 6694 break; 6695 case scConstant: 6696 return cast<SCEVConstant>(V)->getValue(); 6697 case scUnknown: 6698 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 6699 case scSignExtend: { 6700 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 6701 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 6702 return ConstantExpr::getSExt(CastOp, SS->getType()); 6703 break; 6704 } 6705 case scZeroExtend: { 6706 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 6707 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 6708 return ConstantExpr::getZExt(CastOp, SZ->getType()); 6709 break; 6710 } 6711 case scTruncate: { 6712 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 6713 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 6714 return ConstantExpr::getTrunc(CastOp, ST->getType()); 6715 break; 6716 } 6717 case scAddExpr: { 6718 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 6719 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 6720 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 6721 unsigned AS = PTy->getAddressSpace(); 6722 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 6723 C = ConstantExpr::getBitCast(C, DestPtrTy); 6724 } 6725 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 6726 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 6727 if (!C2) return nullptr; 6728 6729 // First pointer! 6730 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 6731 unsigned AS = C2->getType()->getPointerAddressSpace(); 6732 std::swap(C, C2); 6733 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 6734 // The offsets have been converted to bytes. We can add bytes to an 6735 // i8* by GEP with the byte count in the first index. 6736 C = ConstantExpr::getBitCast(C, DestPtrTy); 6737 } 6738 6739 // Don't bother trying to sum two pointers. We probably can't 6740 // statically compute a load that results from it anyway. 6741 if (C2->getType()->isPointerTy()) 6742 return nullptr; 6743 6744 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 6745 if (PTy->getElementType()->isStructTy()) 6746 C2 = ConstantExpr::getIntegerCast( 6747 C2, Type::getInt32Ty(C->getContext()), true); 6748 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); 6749 } else 6750 C = ConstantExpr::getAdd(C, C2); 6751 } 6752 return C; 6753 } 6754 break; 6755 } 6756 case scMulExpr: { 6757 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 6758 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 6759 // Don't bother with pointers at all. 6760 if (C->getType()->isPointerTy()) return nullptr; 6761 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 6762 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 6763 if (!C2 || C2->getType()->isPointerTy()) return nullptr; 6764 C = ConstantExpr::getMul(C, C2); 6765 } 6766 return C; 6767 } 6768 break; 6769 } 6770 case scUDivExpr: { 6771 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 6772 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 6773 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 6774 if (LHS->getType() == RHS->getType()) 6775 return ConstantExpr::getUDiv(LHS, RHS); 6776 break; 6777 } 6778 case scSMaxExpr: 6779 case scUMaxExpr: 6780 break; // TODO: smax, umax. 6781 } 6782 return nullptr; 6783 } 6784 6785 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 6786 if (isa<SCEVConstant>(V)) return V; 6787 6788 // If this instruction is evolved from a constant-evolving PHI, compute the 6789 // exit value from the loop without using SCEVs. 6790 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 6791 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 6792 const Loop *LI = this->LI[I->getParent()]; 6793 if (LI && LI->getParentLoop() == L) // Looking for loop exit value. 6794 if (PHINode *PN = dyn_cast<PHINode>(I)) 6795 if (PN->getParent() == LI->getHeader()) { 6796 // Okay, there is no closed form solution for the PHI node. Check 6797 // to see if the loop that contains it has a known backedge-taken 6798 // count. If so, we may be able to force computation of the exit 6799 // value. 6800 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI); 6801 if (const SCEVConstant *BTCC = 6802 dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 6803 // Okay, we know how many times the containing loop executes. If 6804 // this is a constant evolving PHI node, get the final value at 6805 // the specified iteration number. 6806 Constant *RV = 6807 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI); 6808 if (RV) return getSCEV(RV); 6809 } 6810 } 6811 6812 // Okay, this is an expression that we cannot symbolically evaluate 6813 // into a SCEV. Check to see if it's possible to symbolically evaluate 6814 // the arguments into constants, and if so, try to constant propagate the 6815 // result. This is particularly useful for computing loop exit values. 6816 if (CanConstantFold(I)) { 6817 SmallVector<Constant *, 4> Operands; 6818 bool MadeImprovement = false; 6819 for (Value *Op : I->operands()) { 6820 if (Constant *C = dyn_cast<Constant>(Op)) { 6821 Operands.push_back(C); 6822 continue; 6823 } 6824 6825 // If any of the operands is non-constant and if they are 6826 // non-integer and non-pointer, don't even try to analyze them 6827 // with scev techniques. 6828 if (!isSCEVable(Op->getType())) 6829 return V; 6830 6831 const SCEV *OrigV = getSCEV(Op); 6832 const SCEV *OpV = getSCEVAtScope(OrigV, L); 6833 MadeImprovement |= OrigV != OpV; 6834 6835 Constant *C = BuildConstantFromSCEV(OpV); 6836 if (!C) return V; 6837 if (C->getType() != Op->getType()) 6838 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 6839 Op->getType(), 6840 false), 6841 C, Op->getType()); 6842 Operands.push_back(C); 6843 } 6844 6845 // Check to see if getSCEVAtScope actually made an improvement. 6846 if (MadeImprovement) { 6847 Constant *C = nullptr; 6848 const DataLayout &DL = getDataLayout(); 6849 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 6850 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 6851 Operands[1], DL, &TLI); 6852 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) { 6853 if (!LI->isVolatile()) 6854 C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 6855 } else 6856 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 6857 if (!C) return V; 6858 return getSCEV(C); 6859 } 6860 } 6861 } 6862 6863 // This is some other type of SCEVUnknown, just return it. 6864 return V; 6865 } 6866 6867 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 6868 // Avoid performing the look-up in the common case where the specified 6869 // expression has no loop-variant portions. 6870 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 6871 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 6872 if (OpAtScope != Comm->getOperand(i)) { 6873 // Okay, at least one of these operands is loop variant but might be 6874 // foldable. Build a new instance of the folded commutative expression. 6875 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 6876 Comm->op_begin()+i); 6877 NewOps.push_back(OpAtScope); 6878 6879 for (++i; i != e; ++i) { 6880 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 6881 NewOps.push_back(OpAtScope); 6882 } 6883 if (isa<SCEVAddExpr>(Comm)) 6884 return getAddExpr(NewOps); 6885 if (isa<SCEVMulExpr>(Comm)) 6886 return getMulExpr(NewOps); 6887 if (isa<SCEVSMaxExpr>(Comm)) 6888 return getSMaxExpr(NewOps); 6889 if (isa<SCEVUMaxExpr>(Comm)) 6890 return getUMaxExpr(NewOps); 6891 llvm_unreachable("Unknown commutative SCEV type!"); 6892 } 6893 } 6894 // If we got here, all operands are loop invariant. 6895 return Comm; 6896 } 6897 6898 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 6899 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 6900 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 6901 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 6902 return Div; // must be loop invariant 6903 return getUDivExpr(LHS, RHS); 6904 } 6905 6906 // If this is a loop recurrence for a loop that does not contain L, then we 6907 // are dealing with the final value computed by the loop. 6908 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 6909 // First, attempt to evaluate each operand. 6910 // Avoid performing the look-up in the common case where the specified 6911 // expression has no loop-variant portions. 6912 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 6913 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 6914 if (OpAtScope == AddRec->getOperand(i)) 6915 continue; 6916 6917 // Okay, at least one of these operands is loop variant but might be 6918 // foldable. Build a new instance of the folded commutative expression. 6919 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 6920 AddRec->op_begin()+i); 6921 NewOps.push_back(OpAtScope); 6922 for (++i; i != e; ++i) 6923 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 6924 6925 const SCEV *FoldedRec = 6926 getAddRecExpr(NewOps, AddRec->getLoop(), 6927 AddRec->getNoWrapFlags(SCEV::FlagNW)); 6928 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 6929 // The addrec may be folded to a nonrecurrence, for example, if the 6930 // induction variable is multiplied by zero after constant folding. Go 6931 // ahead and return the folded value. 6932 if (!AddRec) 6933 return FoldedRec; 6934 break; 6935 } 6936 6937 // If the scope is outside the addrec's loop, evaluate it by using the 6938 // loop exit value of the addrec. 6939 if (!AddRec->getLoop()->contains(L)) { 6940 // To evaluate this recurrence, we need to know how many times the AddRec 6941 // loop iterates. Compute this now. 6942 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 6943 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 6944 6945 // Then, evaluate the AddRec. 6946 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 6947 } 6948 6949 return AddRec; 6950 } 6951 6952 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 6953 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 6954 if (Op == Cast->getOperand()) 6955 return Cast; // must be loop invariant 6956 return getZeroExtendExpr(Op, Cast->getType()); 6957 } 6958 6959 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 6960 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 6961 if (Op == Cast->getOperand()) 6962 return Cast; // must be loop invariant 6963 return getSignExtendExpr(Op, Cast->getType()); 6964 } 6965 6966 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 6967 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 6968 if (Op == Cast->getOperand()) 6969 return Cast; // must be loop invariant 6970 return getTruncateExpr(Op, Cast->getType()); 6971 } 6972 6973 llvm_unreachable("Unknown SCEV type!"); 6974 } 6975 6976 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 6977 return getSCEVAtScope(getSCEV(V), L); 6978 } 6979 6980 /// Finds the minimum unsigned root of the following equation: 6981 /// 6982 /// A * X = B (mod N) 6983 /// 6984 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 6985 /// A and B isn't important. 6986 /// 6987 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 6988 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B, 6989 ScalarEvolution &SE) { 6990 uint32_t BW = A.getBitWidth(); 6991 assert(BW == B.getBitWidth() && "Bit widths must be the same."); 6992 assert(A != 0 && "A must be non-zero."); 6993 6994 // 1. D = gcd(A, N) 6995 // 6996 // The gcd of A and N may have only one prime factor: 2. The number of 6997 // trailing zeros in A is its multiplicity 6998 uint32_t Mult2 = A.countTrailingZeros(); 6999 // D = 2^Mult2 7000 7001 // 2. Check if B is divisible by D. 7002 // 7003 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 7004 // is not less than multiplicity of this prime factor for D. 7005 if (B.countTrailingZeros() < Mult2) 7006 return SE.getCouldNotCompute(); 7007 7008 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 7009 // modulo (N / D). 7010 // 7011 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this 7012 // bit width during computations. 7013 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 7014 APInt Mod(BW + 1, 0); 7015 Mod.setBit(BW - Mult2); // Mod = N / D 7016 APInt I = AD.multiplicativeInverse(Mod); 7017 7018 // 4. Compute the minimum unsigned root of the equation: 7019 // I * (B / D) mod (N / D) 7020 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod); 7021 7022 // The result is guaranteed to be less than 2^BW so we may truncate it to BW 7023 // bits. 7024 return SE.getConstant(Result.trunc(BW)); 7025 } 7026 7027 /// Find the roots of the quadratic equation for the given quadratic chrec 7028 /// {L,+,M,+,N}. This returns either the two roots (which might be the same) or 7029 /// two SCEVCouldNotCompute objects. 7030 /// 7031 static Optional<std::pair<const SCEVConstant *,const SCEVConstant *>> 7032 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 7033 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 7034 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 7035 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 7036 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 7037 7038 // We currently can only solve this if the coefficients are constants. 7039 if (!LC || !MC || !NC) 7040 return None; 7041 7042 uint32_t BitWidth = LC->getAPInt().getBitWidth(); 7043 const APInt &L = LC->getAPInt(); 7044 const APInt &M = MC->getAPInt(); 7045 const APInt &N = NC->getAPInt(); 7046 APInt Two(BitWidth, 2); 7047 APInt Four(BitWidth, 4); 7048 7049 { 7050 using namespace APIntOps; 7051 const APInt& C = L; 7052 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C 7053 // The B coefficient is M-N/2 7054 APInt B(M); 7055 B -= sdiv(N,Two); 7056 7057 // The A coefficient is N/2 7058 APInt A(N.sdiv(Two)); 7059 7060 // Compute the B^2-4ac term. 7061 APInt SqrtTerm(B); 7062 SqrtTerm *= B; 7063 SqrtTerm -= Four * (A * C); 7064 7065 if (SqrtTerm.isNegative()) { 7066 // The loop is provably infinite. 7067 return None; 7068 } 7069 7070 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest 7071 // integer value or else APInt::sqrt() will assert. 7072 APInt SqrtVal(SqrtTerm.sqrt()); 7073 7074 // Compute the two solutions for the quadratic formula. 7075 // The divisions must be performed as signed divisions. 7076 APInt NegB(-B); 7077 APInt TwoA(A << 1); 7078 if (TwoA.isMinValue()) 7079 return None; 7080 7081 LLVMContext &Context = SE.getContext(); 7082 7083 ConstantInt *Solution1 = 7084 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA)); 7085 ConstantInt *Solution2 = 7086 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA)); 7087 7088 return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)), 7089 cast<SCEVConstant>(SE.getConstant(Solution2))); 7090 } // end APIntOps namespace 7091 } 7092 7093 ScalarEvolution::ExitLimit 7094 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 7095 bool AllowPredicates) { 7096 7097 // This is only used for loops with a "x != y" exit test. The exit condition 7098 // is now expressed as a single expression, V = x-y. So the exit test is 7099 // effectively V != 0. We know and take advantage of the fact that this 7100 // expression only being used in a comparison by zero context. 7101 7102 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 7103 // If the value is a constant 7104 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 7105 // If the value is already zero, the branch will execute zero times. 7106 if (C->getValue()->isZero()) return C; 7107 return getCouldNotCompute(); // Otherwise it will loop infinitely. 7108 } 7109 7110 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V); 7111 if (!AddRec && AllowPredicates) 7112 // Try to make this an AddRec using runtime tests, in the first X 7113 // iterations of this loop, where X is the SCEV expression found by the 7114 // algorithm below. 7115 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 7116 7117 if (!AddRec || AddRec->getLoop() != L) 7118 return getCouldNotCompute(); 7119 7120 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 7121 // the quadratic equation to solve it. 7122 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 7123 if (auto Roots = SolveQuadraticEquation(AddRec, *this)) { 7124 const SCEVConstant *R1 = Roots->first; 7125 const SCEVConstant *R2 = Roots->second; 7126 // Pick the smallest positive root value. 7127 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp( 7128 CmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) { 7129 if (!CB->getZExtValue()) 7130 std::swap(R1, R2); // R1 is the minimum root now. 7131 7132 // We can only use this value if the chrec ends up with an exact zero 7133 // value at this index. When solving for "X*X != 5", for example, we 7134 // should not accept a root of 2. 7135 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this); 7136 if (Val->isZero()) 7137 // We found a quadratic root! 7138 return ExitLimit(R1, R1, false, Predicates); 7139 } 7140 } 7141 return getCouldNotCompute(); 7142 } 7143 7144 // Otherwise we can only handle this if it is affine. 7145 if (!AddRec->isAffine()) 7146 return getCouldNotCompute(); 7147 7148 // If this is an affine expression, the execution count of this branch is 7149 // the minimum unsigned root of the following equation: 7150 // 7151 // Start + Step*N = 0 (mod 2^BW) 7152 // 7153 // equivalent to: 7154 // 7155 // Step*N = -Start (mod 2^BW) 7156 // 7157 // where BW is the common bit width of Start and Step. 7158 7159 // Get the initial value for the loop. 7160 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 7161 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 7162 7163 // For now we handle only constant steps. 7164 // 7165 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 7166 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 7167 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 7168 // We have not yet seen any such cases. 7169 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 7170 if (!StepC || StepC->getValue()->equalsInt(0)) 7171 return getCouldNotCompute(); 7172 7173 // For positive steps (counting up until unsigned overflow): 7174 // N = -Start/Step (as unsigned) 7175 // For negative steps (counting down to zero): 7176 // N = Start/-Step 7177 // First compute the unsigned distance from zero in the direction of Step. 7178 bool CountDown = StepC->getAPInt().isNegative(); 7179 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 7180 7181 // Handle unitary steps, which cannot wraparound. 7182 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 7183 // N = Distance (as unsigned) 7184 if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) { 7185 ConstantRange CR = getUnsignedRange(Start); 7186 const SCEV *MaxBECount; 7187 if (!CountDown && CR.getUnsignedMin().isMinValue()) 7188 // When counting up, the worst starting value is 1, not 0. 7189 MaxBECount = CR.getUnsignedMax().isMinValue() 7190 ? getConstant(APInt::getMinValue(CR.getBitWidth())) 7191 : getConstant(APInt::getMaxValue(CR.getBitWidth())); 7192 else 7193 MaxBECount = getConstant(CountDown ? CR.getUnsignedMax() 7194 : -CR.getUnsignedMin()); 7195 return ExitLimit(Distance, MaxBECount, false, Predicates); 7196 } 7197 7198 // As a special case, handle the instance where Step is a positive power of 7199 // two. In this case, determining whether Step divides Distance evenly can be 7200 // done by counting and comparing the number of trailing zeros of Step and 7201 // Distance. 7202 if (!CountDown) { 7203 const APInt &StepV = StepC->getAPInt(); 7204 // StepV.isPowerOf2() returns true if StepV is an positive power of two. It 7205 // also returns true if StepV is maximally negative (eg, INT_MIN), but that 7206 // case is not handled as this code is guarded by !CountDown. 7207 if (StepV.isPowerOf2() && 7208 GetMinTrailingZeros(Distance) >= StepV.countTrailingZeros()) { 7209 // Here we've constrained the equation to be of the form 7210 // 7211 // 2^(N + k) * Distance' = (StepV == 2^N) * X (mod 2^W) ... (0) 7212 // 7213 // where we're operating on a W bit wide integer domain and k is 7214 // non-negative. The smallest unsigned solution for X is the trip count. 7215 // 7216 // (0) is equivalent to: 7217 // 7218 // 2^(N + k) * Distance' - 2^N * X = L * 2^W 7219 // <=> 2^N(2^k * Distance' - X) = L * 2^(W - N) * 2^N 7220 // <=> 2^k * Distance' - X = L * 2^(W - N) 7221 // <=> 2^k * Distance' = L * 2^(W - N) + X ... (1) 7222 // 7223 // The smallest X satisfying (1) is unsigned remainder of dividing the LHS 7224 // by 2^(W - N). 7225 // 7226 // <=> X = 2^k * Distance' URem 2^(W - N) ... (2) 7227 // 7228 // E.g. say we're solving 7229 // 7230 // 2 * Val = 2 * X (in i8) ... (3) 7231 // 7232 // then from (2), we get X = Val URem i8 128 (k = 0 in this case). 7233 // 7234 // Note: It is tempting to solve (3) by setting X = Val, but Val is not 7235 // necessarily the smallest unsigned value of X that satisfies (3). 7236 // E.g. if Val is i8 -127 then the smallest value of X that satisfies (3) 7237 // is i8 1, not i8 -127 7238 7239 const auto *ModuloResult = getUDivExactExpr(Distance, Step); 7240 7241 // Since SCEV does not have a URem node, we construct one using a truncate 7242 // and a zero extend. 7243 7244 unsigned NarrowWidth = StepV.getBitWidth() - StepV.countTrailingZeros(); 7245 auto *NarrowTy = IntegerType::get(getContext(), NarrowWidth); 7246 auto *WideTy = Distance->getType(); 7247 7248 const SCEV *Limit = 7249 getZeroExtendExpr(getTruncateExpr(ModuloResult, NarrowTy), WideTy); 7250 return ExitLimit(Limit, Limit, false, Predicates); 7251 } 7252 } 7253 7254 // If the condition controls loop exit (the loop exits only if the expression 7255 // is true) and the addition is no-wrap we can use unsigned divide to 7256 // compute the backedge count. In this case, the step may not divide the 7257 // distance, but we don't care because if the condition is "missed" the loop 7258 // will have undefined behavior due to wrapping. 7259 if (ControlsExit && AddRec->hasNoSelfWrap() && 7260 loopHasNoAbnormalExits(AddRec->getLoop())) { 7261 const SCEV *Exact = 7262 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 7263 return ExitLimit(Exact, Exact, false, Predicates); 7264 } 7265 7266 // Then, try to solve the above equation provided that Start is constant. 7267 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) { 7268 const SCEV *E = SolveLinEquationWithOverflow( 7269 StepC->getValue()->getValue(), -StartC->getValue()->getValue(), *this); 7270 return ExitLimit(E, E, false, Predicates); 7271 } 7272 return getCouldNotCompute(); 7273 } 7274 7275 ScalarEvolution::ExitLimit 7276 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 7277 // Loops that look like: while (X == 0) are very strange indeed. We don't 7278 // handle them yet except for the trivial case. This could be expanded in the 7279 // future as needed. 7280 7281 // If the value is a constant, check to see if it is known to be non-zero 7282 // already. If so, the backedge will execute zero times. 7283 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 7284 if (!C->getValue()->isNullValue()) 7285 return getZero(C->getType()); 7286 return getCouldNotCompute(); // Otherwise it will loop infinitely. 7287 } 7288 7289 // We could implement others, but I really doubt anyone writes loops like 7290 // this, and if they did, they would already be constant folded. 7291 return getCouldNotCompute(); 7292 } 7293 7294 std::pair<BasicBlock *, BasicBlock *> 7295 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) { 7296 // If the block has a unique predecessor, then there is no path from the 7297 // predecessor to the block that does not go through the direct edge 7298 // from the predecessor to the block. 7299 if (BasicBlock *Pred = BB->getSinglePredecessor()) 7300 return {Pred, BB}; 7301 7302 // A loop's header is defined to be a block that dominates the loop. 7303 // If the header has a unique predecessor outside the loop, it must be 7304 // a block that has exactly one successor that can reach the loop. 7305 if (Loop *L = LI.getLoopFor(BB)) 7306 return {L->getLoopPredecessor(), L->getHeader()}; 7307 7308 return {nullptr, nullptr}; 7309 } 7310 7311 /// SCEV structural equivalence is usually sufficient for testing whether two 7312 /// expressions are equal, however for the purposes of looking for a condition 7313 /// guarding a loop, it can be useful to be a little more general, since a 7314 /// front-end may have replicated the controlling expression. 7315 /// 7316 static bool HasSameValue(const SCEV *A, const SCEV *B) { 7317 // Quick check to see if they are the same SCEV. 7318 if (A == B) return true; 7319 7320 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 7321 // Not all instructions that are "identical" compute the same value. For 7322 // instance, two distinct alloca instructions allocating the same type are 7323 // identical and do not read memory; but compute distinct values. 7324 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 7325 }; 7326 7327 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 7328 // two different instructions with the same value. Check for this case. 7329 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 7330 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 7331 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 7332 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 7333 if (ComputesEqualValues(AI, BI)) 7334 return true; 7335 7336 // Otherwise assume they may have a different value. 7337 return false; 7338 } 7339 7340 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 7341 const SCEV *&LHS, const SCEV *&RHS, 7342 unsigned Depth) { 7343 bool Changed = false; 7344 7345 // If we hit the max recursion limit bail out. 7346 if (Depth >= 3) 7347 return false; 7348 7349 // Canonicalize a constant to the right side. 7350 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 7351 // Check for both operands constant. 7352 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 7353 if (ConstantExpr::getICmp(Pred, 7354 LHSC->getValue(), 7355 RHSC->getValue())->isNullValue()) 7356 goto trivially_false; 7357 else 7358 goto trivially_true; 7359 } 7360 // Otherwise swap the operands to put the constant on the right. 7361 std::swap(LHS, RHS); 7362 Pred = ICmpInst::getSwappedPredicate(Pred); 7363 Changed = true; 7364 } 7365 7366 // If we're comparing an addrec with a value which is loop-invariant in the 7367 // addrec's loop, put the addrec on the left. Also make a dominance check, 7368 // as both operands could be addrecs loop-invariant in each other's loop. 7369 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 7370 const Loop *L = AR->getLoop(); 7371 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 7372 std::swap(LHS, RHS); 7373 Pred = ICmpInst::getSwappedPredicate(Pred); 7374 Changed = true; 7375 } 7376 } 7377 7378 // If there's a constant operand, canonicalize comparisons with boundary 7379 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 7380 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 7381 const APInt &RA = RC->getAPInt(); 7382 7383 bool SimplifiedByConstantRange = false; 7384 7385 if (!ICmpInst::isEquality(Pred)) { 7386 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 7387 if (ExactCR.isFullSet()) 7388 goto trivially_true; 7389 else if (ExactCR.isEmptySet()) 7390 goto trivially_false; 7391 7392 APInt NewRHS; 7393 CmpInst::Predicate NewPred; 7394 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 7395 ICmpInst::isEquality(NewPred)) { 7396 // We were able to convert an inequality to an equality. 7397 Pred = NewPred; 7398 RHS = getConstant(NewRHS); 7399 Changed = SimplifiedByConstantRange = true; 7400 } 7401 } 7402 7403 if (!SimplifiedByConstantRange) { 7404 switch (Pred) { 7405 default: 7406 break; 7407 case ICmpInst::ICMP_EQ: 7408 case ICmpInst::ICMP_NE: 7409 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 7410 if (!RA) 7411 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 7412 if (const SCEVMulExpr *ME = 7413 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 7414 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 7415 ME->getOperand(0)->isAllOnesValue()) { 7416 RHS = AE->getOperand(1); 7417 LHS = ME->getOperand(1); 7418 Changed = true; 7419 } 7420 break; 7421 7422 7423 // The "Should have been caught earlier!" messages refer to the fact 7424 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 7425 // should have fired on the corresponding cases, and canonicalized the 7426 // check to trivially_true or trivially_false. 7427 7428 case ICmpInst::ICMP_UGE: 7429 assert(!RA.isMinValue() && "Should have been caught earlier!"); 7430 Pred = ICmpInst::ICMP_UGT; 7431 RHS = getConstant(RA - 1); 7432 Changed = true; 7433 break; 7434 case ICmpInst::ICMP_ULE: 7435 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 7436 Pred = ICmpInst::ICMP_ULT; 7437 RHS = getConstant(RA + 1); 7438 Changed = true; 7439 break; 7440 case ICmpInst::ICMP_SGE: 7441 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 7442 Pred = ICmpInst::ICMP_SGT; 7443 RHS = getConstant(RA - 1); 7444 Changed = true; 7445 break; 7446 case ICmpInst::ICMP_SLE: 7447 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 7448 Pred = ICmpInst::ICMP_SLT; 7449 RHS = getConstant(RA + 1); 7450 Changed = true; 7451 break; 7452 } 7453 } 7454 } 7455 7456 // Check for obvious equality. 7457 if (HasSameValue(LHS, RHS)) { 7458 if (ICmpInst::isTrueWhenEqual(Pred)) 7459 goto trivially_true; 7460 if (ICmpInst::isFalseWhenEqual(Pred)) 7461 goto trivially_false; 7462 } 7463 7464 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 7465 // adding or subtracting 1 from one of the operands. 7466 switch (Pred) { 7467 case ICmpInst::ICMP_SLE: 7468 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) { 7469 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 7470 SCEV::FlagNSW); 7471 Pred = ICmpInst::ICMP_SLT; 7472 Changed = true; 7473 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) { 7474 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 7475 SCEV::FlagNSW); 7476 Pred = ICmpInst::ICMP_SLT; 7477 Changed = true; 7478 } 7479 break; 7480 case ICmpInst::ICMP_SGE: 7481 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) { 7482 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 7483 SCEV::FlagNSW); 7484 Pred = ICmpInst::ICMP_SGT; 7485 Changed = true; 7486 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) { 7487 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 7488 SCEV::FlagNSW); 7489 Pred = ICmpInst::ICMP_SGT; 7490 Changed = true; 7491 } 7492 break; 7493 case ICmpInst::ICMP_ULE: 7494 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) { 7495 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 7496 SCEV::FlagNUW); 7497 Pred = ICmpInst::ICMP_ULT; 7498 Changed = true; 7499 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) { 7500 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 7501 Pred = ICmpInst::ICMP_ULT; 7502 Changed = true; 7503 } 7504 break; 7505 case ICmpInst::ICMP_UGE: 7506 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) { 7507 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 7508 Pred = ICmpInst::ICMP_UGT; 7509 Changed = true; 7510 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) { 7511 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 7512 SCEV::FlagNUW); 7513 Pred = ICmpInst::ICMP_UGT; 7514 Changed = true; 7515 } 7516 break; 7517 default: 7518 break; 7519 } 7520 7521 // TODO: More simplifications are possible here. 7522 7523 // Recursively simplify until we either hit a recursion limit or nothing 7524 // changes. 7525 if (Changed) 7526 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 7527 7528 return Changed; 7529 7530 trivially_true: 7531 // Return 0 == 0. 7532 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 7533 Pred = ICmpInst::ICMP_EQ; 7534 return true; 7535 7536 trivially_false: 7537 // Return 0 != 0. 7538 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 7539 Pred = ICmpInst::ICMP_NE; 7540 return true; 7541 } 7542 7543 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 7544 return getSignedRange(S).getSignedMax().isNegative(); 7545 } 7546 7547 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 7548 return getSignedRange(S).getSignedMin().isStrictlyPositive(); 7549 } 7550 7551 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 7552 return !getSignedRange(S).getSignedMin().isNegative(); 7553 } 7554 7555 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 7556 return !getSignedRange(S).getSignedMax().isStrictlyPositive(); 7557 } 7558 7559 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 7560 return isKnownNegative(S) || isKnownPositive(S); 7561 } 7562 7563 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 7564 const SCEV *LHS, const SCEV *RHS) { 7565 // Canonicalize the inputs first. 7566 (void)SimplifyICmpOperands(Pred, LHS, RHS); 7567 7568 // If LHS or RHS is an addrec, check to see if the condition is true in 7569 // every iteration of the loop. 7570 // If LHS and RHS are both addrec, both conditions must be true in 7571 // every iteration of the loop. 7572 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 7573 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 7574 bool LeftGuarded = false; 7575 bool RightGuarded = false; 7576 if (LAR) { 7577 const Loop *L = LAR->getLoop(); 7578 if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) && 7579 isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) { 7580 if (!RAR) return true; 7581 LeftGuarded = true; 7582 } 7583 } 7584 if (RAR) { 7585 const Loop *L = RAR->getLoop(); 7586 if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) && 7587 isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) { 7588 if (!LAR) return true; 7589 RightGuarded = true; 7590 } 7591 } 7592 if (LeftGuarded && RightGuarded) 7593 return true; 7594 7595 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 7596 return true; 7597 7598 // Otherwise see what can be done with known constant ranges. 7599 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS); 7600 } 7601 7602 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS, 7603 ICmpInst::Predicate Pred, 7604 bool &Increasing) { 7605 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing); 7606 7607 #ifndef NDEBUG 7608 // Verify an invariant: inverting the predicate should turn a monotonically 7609 // increasing change to a monotonically decreasing one, and vice versa. 7610 bool IncreasingSwapped; 7611 bool ResultSwapped = isMonotonicPredicateImpl( 7612 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped); 7613 7614 assert(Result == ResultSwapped && "should be able to analyze both!"); 7615 if (ResultSwapped) 7616 assert(Increasing == !IncreasingSwapped && 7617 "monotonicity should flip as we flip the predicate"); 7618 #endif 7619 7620 return Result; 7621 } 7622 7623 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS, 7624 ICmpInst::Predicate Pred, 7625 bool &Increasing) { 7626 7627 // A zero step value for LHS means the induction variable is essentially a 7628 // loop invariant value. We don't really depend on the predicate actually 7629 // flipping from false to true (for increasing predicates, and the other way 7630 // around for decreasing predicates), all we care about is that *if* the 7631 // predicate changes then it only changes from false to true. 7632 // 7633 // A zero step value in itself is not very useful, but there may be places 7634 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 7635 // as general as possible. 7636 7637 switch (Pred) { 7638 default: 7639 return false; // Conservative answer 7640 7641 case ICmpInst::ICMP_UGT: 7642 case ICmpInst::ICMP_UGE: 7643 case ICmpInst::ICMP_ULT: 7644 case ICmpInst::ICMP_ULE: 7645 if (!LHS->hasNoUnsignedWrap()) 7646 return false; 7647 7648 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE; 7649 return true; 7650 7651 case ICmpInst::ICMP_SGT: 7652 case ICmpInst::ICMP_SGE: 7653 case ICmpInst::ICMP_SLT: 7654 case ICmpInst::ICMP_SLE: { 7655 if (!LHS->hasNoSignedWrap()) 7656 return false; 7657 7658 const SCEV *Step = LHS->getStepRecurrence(*this); 7659 7660 if (isKnownNonNegative(Step)) { 7661 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE; 7662 return true; 7663 } 7664 7665 if (isKnownNonPositive(Step)) { 7666 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE; 7667 return true; 7668 } 7669 7670 return false; 7671 } 7672 7673 } 7674 7675 llvm_unreachable("switch has default clause!"); 7676 } 7677 7678 bool ScalarEvolution::isLoopInvariantPredicate( 7679 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 7680 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS, 7681 const SCEV *&InvariantRHS) { 7682 7683 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 7684 if (!isLoopInvariant(RHS, L)) { 7685 if (!isLoopInvariant(LHS, L)) 7686 return false; 7687 7688 std::swap(LHS, RHS); 7689 Pred = ICmpInst::getSwappedPredicate(Pred); 7690 } 7691 7692 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 7693 if (!ArLHS || ArLHS->getLoop() != L) 7694 return false; 7695 7696 bool Increasing; 7697 if (!isMonotonicPredicate(ArLHS, Pred, Increasing)) 7698 return false; 7699 7700 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 7701 // true as the loop iterates, and the backedge is control dependent on 7702 // "ArLHS `Pred` RHS" == true then we can reason as follows: 7703 // 7704 // * if the predicate was false in the first iteration then the predicate 7705 // is never evaluated again, since the loop exits without taking the 7706 // backedge. 7707 // * if the predicate was true in the first iteration then it will 7708 // continue to be true for all future iterations since it is 7709 // monotonically increasing. 7710 // 7711 // For both the above possibilities, we can replace the loop varying 7712 // predicate with its value on the first iteration of the loop (which is 7713 // loop invariant). 7714 // 7715 // A similar reasoning applies for a monotonically decreasing predicate, by 7716 // replacing true with false and false with true in the above two bullets. 7717 7718 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 7719 7720 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 7721 return false; 7722 7723 InvariantPred = Pred; 7724 InvariantLHS = ArLHS->getStart(); 7725 InvariantRHS = RHS; 7726 return true; 7727 } 7728 7729 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 7730 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 7731 if (HasSameValue(LHS, RHS)) 7732 return ICmpInst::isTrueWhenEqual(Pred); 7733 7734 // This code is split out from isKnownPredicate because it is called from 7735 // within isLoopEntryGuardedByCond. 7736 7737 auto CheckRanges = 7738 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) { 7739 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS) 7740 .contains(RangeLHS); 7741 }; 7742 7743 // The check at the top of the function catches the case where the values are 7744 // known to be equal. 7745 if (Pred == CmpInst::ICMP_EQ) 7746 return false; 7747 7748 if (Pred == CmpInst::ICMP_NE) 7749 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 7750 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) || 7751 isKnownNonZero(getMinusSCEV(LHS, RHS)); 7752 7753 if (CmpInst::isSigned(Pred)) 7754 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 7755 7756 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 7757 } 7758 7759 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 7760 const SCEV *LHS, 7761 const SCEV *RHS) { 7762 7763 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer. 7764 // Return Y via OutY. 7765 auto MatchBinaryAddToConst = 7766 [this](const SCEV *Result, const SCEV *X, APInt &OutY, 7767 SCEV::NoWrapFlags ExpectedFlags) { 7768 const SCEV *NonConstOp, *ConstOp; 7769 SCEV::NoWrapFlags FlagsPresent; 7770 7771 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) || 7772 !isa<SCEVConstant>(ConstOp) || NonConstOp != X) 7773 return false; 7774 7775 OutY = cast<SCEVConstant>(ConstOp)->getAPInt(); 7776 return (FlagsPresent & ExpectedFlags) == ExpectedFlags; 7777 }; 7778 7779 APInt C; 7780 7781 switch (Pred) { 7782 default: 7783 break; 7784 7785 case ICmpInst::ICMP_SGE: 7786 std::swap(LHS, RHS); 7787 case ICmpInst::ICMP_SLE: 7788 // X s<= (X + C)<nsw> if C >= 0 7789 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative()) 7790 return true; 7791 7792 // (X + C)<nsw> s<= X if C <= 0 7793 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && 7794 !C.isStrictlyPositive()) 7795 return true; 7796 break; 7797 7798 case ICmpInst::ICMP_SGT: 7799 std::swap(LHS, RHS); 7800 case ICmpInst::ICMP_SLT: 7801 // X s< (X + C)<nsw> if C > 0 7802 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && 7803 C.isStrictlyPositive()) 7804 return true; 7805 7806 // (X + C)<nsw> s< X if C < 0 7807 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative()) 7808 return true; 7809 break; 7810 } 7811 7812 return false; 7813 } 7814 7815 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 7816 const SCEV *LHS, 7817 const SCEV *RHS) { 7818 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 7819 return false; 7820 7821 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 7822 // the stack can result in exponential time complexity. 7823 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 7824 7825 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 7826 // 7827 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 7828 // isKnownPredicate. isKnownPredicate is more powerful, but also more 7829 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 7830 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 7831 // use isKnownPredicate later if needed. 7832 return isKnownNonNegative(RHS) && 7833 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 7834 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 7835 } 7836 7837 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB, 7838 ICmpInst::Predicate Pred, 7839 const SCEV *LHS, const SCEV *RHS) { 7840 // No need to even try if we know the module has no guards. 7841 if (!HasGuards) 7842 return false; 7843 7844 return any_of(*BB, [&](Instruction &I) { 7845 using namespace llvm::PatternMatch; 7846 7847 Value *Condition; 7848 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 7849 m_Value(Condition))) && 7850 isImpliedCond(Pred, LHS, RHS, Condition, false); 7851 }); 7852 } 7853 7854 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 7855 /// protected by a conditional between LHS and RHS. This is used to 7856 /// to eliminate casts. 7857 bool 7858 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 7859 ICmpInst::Predicate Pred, 7860 const SCEV *LHS, const SCEV *RHS) { 7861 // Interpret a null as meaning no loop, where there is obviously no guard 7862 // (interprocedural conditions notwithstanding). 7863 if (!L) return true; 7864 7865 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS)) 7866 return true; 7867 7868 BasicBlock *Latch = L->getLoopLatch(); 7869 if (!Latch) 7870 return false; 7871 7872 BranchInst *LoopContinuePredicate = 7873 dyn_cast<BranchInst>(Latch->getTerminator()); 7874 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 7875 isImpliedCond(Pred, LHS, RHS, 7876 LoopContinuePredicate->getCondition(), 7877 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 7878 return true; 7879 7880 // We don't want more than one activation of the following loops on the stack 7881 // -- that can lead to O(n!) time complexity. 7882 if (WalkingBEDominatingConds) 7883 return false; 7884 7885 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 7886 7887 // See if we can exploit a trip count to prove the predicate. 7888 const auto &BETakenInfo = getBackedgeTakenInfo(L); 7889 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 7890 if (LatchBECount != getCouldNotCompute()) { 7891 // We know that Latch branches back to the loop header exactly 7892 // LatchBECount times. This means the backdege condition at Latch is 7893 // equivalent to "{0,+,1} u< LatchBECount". 7894 Type *Ty = LatchBECount->getType(); 7895 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 7896 const SCEV *LoopCounter = 7897 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 7898 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 7899 LatchBECount)) 7900 return true; 7901 } 7902 7903 // Check conditions due to any @llvm.assume intrinsics. 7904 for (auto &AssumeVH : AC.assumptions()) { 7905 if (!AssumeVH) 7906 continue; 7907 auto *CI = cast<CallInst>(AssumeVH); 7908 if (!DT.dominates(CI, Latch->getTerminator())) 7909 continue; 7910 7911 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 7912 return true; 7913 } 7914 7915 // If the loop is not reachable from the entry block, we risk running into an 7916 // infinite loop as we walk up into the dom tree. These loops do not matter 7917 // anyway, so we just return a conservative answer when we see them. 7918 if (!DT.isReachableFromEntry(L->getHeader())) 7919 return false; 7920 7921 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 7922 return true; 7923 7924 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 7925 DTN != HeaderDTN; DTN = DTN->getIDom()) { 7926 7927 assert(DTN && "should reach the loop header before reaching the root!"); 7928 7929 BasicBlock *BB = DTN->getBlock(); 7930 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 7931 return true; 7932 7933 BasicBlock *PBB = BB->getSinglePredecessor(); 7934 if (!PBB) 7935 continue; 7936 7937 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 7938 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 7939 continue; 7940 7941 Value *Condition = ContinuePredicate->getCondition(); 7942 7943 // If we have an edge `E` within the loop body that dominates the only 7944 // latch, the condition guarding `E` also guards the backedge. This 7945 // reasoning works only for loops with a single latch. 7946 7947 BasicBlockEdge DominatingEdge(PBB, BB); 7948 if (DominatingEdge.isSingleEdge()) { 7949 // We're constructively (and conservatively) enumerating edges within the 7950 // loop body that dominate the latch. The dominator tree better agree 7951 // with us on this: 7952 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 7953 7954 if (isImpliedCond(Pred, LHS, RHS, Condition, 7955 BB != ContinuePredicate->getSuccessor(0))) 7956 return true; 7957 } 7958 } 7959 7960 return false; 7961 } 7962 7963 bool 7964 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 7965 ICmpInst::Predicate Pred, 7966 const SCEV *LHS, const SCEV *RHS) { 7967 // Interpret a null as meaning no loop, where there is obviously no guard 7968 // (interprocedural conditions notwithstanding). 7969 if (!L) return false; 7970 7971 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS)) 7972 return true; 7973 7974 // Starting at the loop predecessor, climb up the predecessor chain, as long 7975 // as there are predecessors that can be found that have unique successors 7976 // leading to the original header. 7977 for (std::pair<BasicBlock *, BasicBlock *> 7978 Pair(L->getLoopPredecessor(), L->getHeader()); 7979 Pair.first; 7980 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 7981 7982 if (isImpliedViaGuard(Pair.first, Pred, LHS, RHS)) 7983 return true; 7984 7985 BranchInst *LoopEntryPredicate = 7986 dyn_cast<BranchInst>(Pair.first->getTerminator()); 7987 if (!LoopEntryPredicate || 7988 LoopEntryPredicate->isUnconditional()) 7989 continue; 7990 7991 if (isImpliedCond(Pred, LHS, RHS, 7992 LoopEntryPredicate->getCondition(), 7993 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 7994 return true; 7995 } 7996 7997 // Check conditions due to any @llvm.assume intrinsics. 7998 for (auto &AssumeVH : AC.assumptions()) { 7999 if (!AssumeVH) 8000 continue; 8001 auto *CI = cast<CallInst>(AssumeVH); 8002 if (!DT.dominates(CI, L->getHeader())) 8003 continue; 8004 8005 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 8006 return true; 8007 } 8008 8009 return false; 8010 } 8011 8012 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, 8013 const SCEV *LHS, const SCEV *RHS, 8014 Value *FoundCondValue, 8015 bool Inverse) { 8016 if (!PendingLoopPredicates.insert(FoundCondValue).second) 8017 return false; 8018 8019 auto ClearOnExit = 8020 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 8021 8022 // Recursively handle And and Or conditions. 8023 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) { 8024 if (BO->getOpcode() == Instruction::And) { 8025 if (!Inverse) 8026 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 8027 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 8028 } else if (BO->getOpcode() == Instruction::Or) { 8029 if (Inverse) 8030 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 8031 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 8032 } 8033 } 8034 8035 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 8036 if (!ICI) return false; 8037 8038 // Now that we found a conditional branch that dominates the loop or controls 8039 // the loop latch. Check to see if it is the comparison we are looking for. 8040 ICmpInst::Predicate FoundPred; 8041 if (Inverse) 8042 FoundPred = ICI->getInversePredicate(); 8043 else 8044 FoundPred = ICI->getPredicate(); 8045 8046 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 8047 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 8048 8049 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS); 8050 } 8051 8052 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 8053 const SCEV *RHS, 8054 ICmpInst::Predicate FoundPred, 8055 const SCEV *FoundLHS, 8056 const SCEV *FoundRHS) { 8057 // Balance the types. 8058 if (getTypeSizeInBits(LHS->getType()) < 8059 getTypeSizeInBits(FoundLHS->getType())) { 8060 if (CmpInst::isSigned(Pred)) { 8061 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 8062 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 8063 } else { 8064 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 8065 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 8066 } 8067 } else if (getTypeSizeInBits(LHS->getType()) > 8068 getTypeSizeInBits(FoundLHS->getType())) { 8069 if (CmpInst::isSigned(FoundPred)) { 8070 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 8071 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 8072 } else { 8073 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 8074 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 8075 } 8076 } 8077 8078 // Canonicalize the query to match the way instcombine will have 8079 // canonicalized the comparison. 8080 if (SimplifyICmpOperands(Pred, LHS, RHS)) 8081 if (LHS == RHS) 8082 return CmpInst::isTrueWhenEqual(Pred); 8083 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 8084 if (FoundLHS == FoundRHS) 8085 return CmpInst::isFalseWhenEqual(FoundPred); 8086 8087 // Check to see if we can make the LHS or RHS match. 8088 if (LHS == FoundRHS || RHS == FoundLHS) { 8089 if (isa<SCEVConstant>(RHS)) { 8090 std::swap(FoundLHS, FoundRHS); 8091 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 8092 } else { 8093 std::swap(LHS, RHS); 8094 Pred = ICmpInst::getSwappedPredicate(Pred); 8095 } 8096 } 8097 8098 // Check whether the found predicate is the same as the desired predicate. 8099 if (FoundPred == Pred) 8100 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 8101 8102 // Check whether swapping the found predicate makes it the same as the 8103 // desired predicate. 8104 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 8105 if (isa<SCEVConstant>(RHS)) 8106 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS); 8107 else 8108 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), 8109 RHS, LHS, FoundLHS, FoundRHS); 8110 } 8111 8112 // Unsigned comparison is the same as signed comparison when both the operands 8113 // are non-negative. 8114 if (CmpInst::isUnsigned(FoundPred) && 8115 CmpInst::getSignedPredicate(FoundPred) == Pred && 8116 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) 8117 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 8118 8119 // Check if we can make progress by sharpening ranges. 8120 if (FoundPred == ICmpInst::ICMP_NE && 8121 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 8122 8123 const SCEVConstant *C = nullptr; 8124 const SCEV *V = nullptr; 8125 8126 if (isa<SCEVConstant>(FoundLHS)) { 8127 C = cast<SCEVConstant>(FoundLHS); 8128 V = FoundRHS; 8129 } else { 8130 C = cast<SCEVConstant>(FoundRHS); 8131 V = FoundLHS; 8132 } 8133 8134 // The guarding predicate tells us that C != V. If the known range 8135 // of V is [C, t), we can sharpen the range to [C + 1, t). The 8136 // range we consider has to correspond to same signedness as the 8137 // predicate we're interested in folding. 8138 8139 APInt Min = ICmpInst::isSigned(Pred) ? 8140 getSignedRange(V).getSignedMin() : getUnsignedRange(V).getUnsignedMin(); 8141 8142 if (Min == C->getAPInt()) { 8143 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 8144 // This is true even if (Min + 1) wraps around -- in case of 8145 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 8146 8147 APInt SharperMin = Min + 1; 8148 8149 switch (Pred) { 8150 case ICmpInst::ICMP_SGE: 8151 case ICmpInst::ICMP_UGE: 8152 // We know V `Pred` SharperMin. If this implies LHS `Pred` 8153 // RHS, we're done. 8154 if (isImpliedCondOperands(Pred, LHS, RHS, V, 8155 getConstant(SharperMin))) 8156 return true; 8157 8158 case ICmpInst::ICMP_SGT: 8159 case ICmpInst::ICMP_UGT: 8160 // We know from the range information that (V `Pred` Min || 8161 // V == Min). We know from the guarding condition that !(V 8162 // == Min). This gives us 8163 // 8164 // V `Pred` Min || V == Min && !(V == Min) 8165 // => V `Pred` Min 8166 // 8167 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 8168 8169 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min))) 8170 return true; 8171 8172 default: 8173 // No change 8174 break; 8175 } 8176 } 8177 } 8178 8179 // Check whether the actual condition is beyond sufficient. 8180 if (FoundPred == ICmpInst::ICMP_EQ) 8181 if (ICmpInst::isTrueWhenEqual(Pred)) 8182 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS)) 8183 return true; 8184 if (Pred == ICmpInst::ICMP_NE) 8185 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 8186 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS)) 8187 return true; 8188 8189 // Otherwise assume the worst. 8190 return false; 8191 } 8192 8193 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 8194 const SCEV *&L, const SCEV *&R, 8195 SCEV::NoWrapFlags &Flags) { 8196 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 8197 if (!AE || AE->getNumOperands() != 2) 8198 return false; 8199 8200 L = AE->getOperand(0); 8201 R = AE->getOperand(1); 8202 Flags = AE->getNoWrapFlags(); 8203 return true; 8204 } 8205 8206 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 8207 const SCEV *Less) { 8208 // We avoid subtracting expressions here because this function is usually 8209 // fairly deep in the call stack (i.e. is called many times). 8210 8211 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 8212 const auto *LAR = cast<SCEVAddRecExpr>(Less); 8213 const auto *MAR = cast<SCEVAddRecExpr>(More); 8214 8215 if (LAR->getLoop() != MAR->getLoop()) 8216 return None; 8217 8218 // We look at affine expressions only; not for correctness but to keep 8219 // getStepRecurrence cheap. 8220 if (!LAR->isAffine() || !MAR->isAffine()) 8221 return None; 8222 8223 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 8224 return None; 8225 8226 Less = LAR->getStart(); 8227 More = MAR->getStart(); 8228 8229 // fall through 8230 } 8231 8232 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 8233 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 8234 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 8235 return M - L; 8236 } 8237 8238 const SCEV *L, *R; 8239 SCEV::NoWrapFlags Flags; 8240 if (splitBinaryAdd(Less, L, R, Flags)) 8241 if (const auto *LC = dyn_cast<SCEVConstant>(L)) 8242 if (R == More) 8243 return -(LC->getAPInt()); 8244 8245 if (splitBinaryAdd(More, L, R, Flags)) 8246 if (const auto *LC = dyn_cast<SCEVConstant>(L)) 8247 if (R == Less) 8248 return LC->getAPInt(); 8249 8250 return None; 8251 } 8252 8253 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 8254 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 8255 const SCEV *FoundLHS, const SCEV *FoundRHS) { 8256 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 8257 return false; 8258 8259 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 8260 if (!AddRecLHS) 8261 return false; 8262 8263 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 8264 if (!AddRecFoundLHS) 8265 return false; 8266 8267 // We'd like to let SCEV reason about control dependencies, so we constrain 8268 // both the inequalities to be about add recurrences on the same loop. This 8269 // way we can use isLoopEntryGuardedByCond later. 8270 8271 const Loop *L = AddRecFoundLHS->getLoop(); 8272 if (L != AddRecLHS->getLoop()) 8273 return false; 8274 8275 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 8276 // 8277 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 8278 // ... (2) 8279 // 8280 // Informal proof for (2), assuming (1) [*]: 8281 // 8282 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 8283 // 8284 // Then 8285 // 8286 // FoundLHS s< FoundRHS s< INT_MIN - C 8287 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 8288 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 8289 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 8290 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 8291 // <=> FoundLHS + C s< FoundRHS + C 8292 // 8293 // [*]: (1) can be proved by ruling out overflow. 8294 // 8295 // [**]: This can be proved by analyzing all the four possibilities: 8296 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 8297 // (A s>= 0, B s>= 0). 8298 // 8299 // Note: 8300 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 8301 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 8302 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 8303 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 8304 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 8305 // C)". 8306 8307 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 8308 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 8309 if (!LDiff || !RDiff || *LDiff != *RDiff) 8310 return false; 8311 8312 if (LDiff->isMinValue()) 8313 return true; 8314 8315 APInt FoundRHSLimit; 8316 8317 if (Pred == CmpInst::ICMP_ULT) { 8318 FoundRHSLimit = -(*RDiff); 8319 } else { 8320 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 8321 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 8322 } 8323 8324 // Try to prove (1) or (2), as needed. 8325 return isLoopEntryGuardedByCond(L, Pred, FoundRHS, 8326 getConstant(FoundRHSLimit)); 8327 } 8328 8329 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 8330 const SCEV *LHS, const SCEV *RHS, 8331 const SCEV *FoundLHS, 8332 const SCEV *FoundRHS) { 8333 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 8334 return true; 8335 8336 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 8337 return true; 8338 8339 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 8340 FoundLHS, FoundRHS) || 8341 // ~x < ~y --> x > y 8342 isImpliedCondOperandsHelper(Pred, LHS, RHS, 8343 getNotSCEV(FoundRHS), 8344 getNotSCEV(FoundLHS)); 8345 } 8346 8347 8348 /// If Expr computes ~A, return A else return nullptr 8349 static const SCEV *MatchNotExpr(const SCEV *Expr) { 8350 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 8351 if (!Add || Add->getNumOperands() != 2 || 8352 !Add->getOperand(0)->isAllOnesValue()) 8353 return nullptr; 8354 8355 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 8356 if (!AddRHS || AddRHS->getNumOperands() != 2 || 8357 !AddRHS->getOperand(0)->isAllOnesValue()) 8358 return nullptr; 8359 8360 return AddRHS->getOperand(1); 8361 } 8362 8363 8364 /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values? 8365 template<typename MaxExprType> 8366 static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr, 8367 const SCEV *Candidate) { 8368 const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr); 8369 if (!MaxExpr) return false; 8370 8371 return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end(); 8372 } 8373 8374 8375 /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values? 8376 template<typename MaxExprType> 8377 static bool IsMinConsistingOf(ScalarEvolution &SE, 8378 const SCEV *MaybeMinExpr, 8379 const SCEV *Candidate) { 8380 const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr); 8381 if (!MaybeMaxExpr) 8382 return false; 8383 8384 return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate)); 8385 } 8386 8387 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 8388 ICmpInst::Predicate Pred, 8389 const SCEV *LHS, const SCEV *RHS) { 8390 8391 // If both sides are affine addrecs for the same loop, with equal 8392 // steps, and we know the recurrences don't wrap, then we only 8393 // need to check the predicate on the starting values. 8394 8395 if (!ICmpInst::isRelational(Pred)) 8396 return false; 8397 8398 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 8399 if (!LAR) 8400 return false; 8401 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 8402 if (!RAR) 8403 return false; 8404 if (LAR->getLoop() != RAR->getLoop()) 8405 return false; 8406 if (!LAR->isAffine() || !RAR->isAffine()) 8407 return false; 8408 8409 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 8410 return false; 8411 8412 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 8413 SCEV::FlagNSW : SCEV::FlagNUW; 8414 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 8415 return false; 8416 8417 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 8418 } 8419 8420 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 8421 /// expression? 8422 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 8423 ICmpInst::Predicate Pred, 8424 const SCEV *LHS, const SCEV *RHS) { 8425 switch (Pred) { 8426 default: 8427 return false; 8428 8429 case ICmpInst::ICMP_SGE: 8430 std::swap(LHS, RHS); 8431 LLVM_FALLTHROUGH; 8432 case ICmpInst::ICMP_SLE: 8433 return 8434 // min(A, ...) <= A 8435 IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) || 8436 // A <= max(A, ...) 8437 IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 8438 8439 case ICmpInst::ICMP_UGE: 8440 std::swap(LHS, RHS); 8441 LLVM_FALLTHROUGH; 8442 case ICmpInst::ICMP_ULE: 8443 return 8444 // min(A, ...) <= A 8445 IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) || 8446 // A <= max(A, ...) 8447 IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 8448 } 8449 8450 llvm_unreachable("covered switch fell through?!"); 8451 } 8452 8453 bool 8454 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 8455 const SCEV *LHS, const SCEV *RHS, 8456 const SCEV *FoundLHS, 8457 const SCEV *FoundRHS) { 8458 auto IsKnownPredicateFull = 8459 [this](ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 8460 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 8461 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 8462 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 8463 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 8464 }; 8465 8466 switch (Pred) { 8467 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 8468 case ICmpInst::ICMP_EQ: 8469 case ICmpInst::ICMP_NE: 8470 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 8471 return true; 8472 break; 8473 case ICmpInst::ICMP_SLT: 8474 case ICmpInst::ICMP_SLE: 8475 if (IsKnownPredicateFull(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 8476 IsKnownPredicateFull(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 8477 return true; 8478 break; 8479 case ICmpInst::ICMP_SGT: 8480 case ICmpInst::ICMP_SGE: 8481 if (IsKnownPredicateFull(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 8482 IsKnownPredicateFull(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 8483 return true; 8484 break; 8485 case ICmpInst::ICMP_ULT: 8486 case ICmpInst::ICMP_ULE: 8487 if (IsKnownPredicateFull(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 8488 IsKnownPredicateFull(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 8489 return true; 8490 break; 8491 case ICmpInst::ICMP_UGT: 8492 case ICmpInst::ICMP_UGE: 8493 if (IsKnownPredicateFull(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 8494 IsKnownPredicateFull(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 8495 return true; 8496 break; 8497 } 8498 8499 return false; 8500 } 8501 8502 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 8503 const SCEV *LHS, 8504 const SCEV *RHS, 8505 const SCEV *FoundLHS, 8506 const SCEV *FoundRHS) { 8507 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 8508 // The restriction on `FoundRHS` be lifted easily -- it exists only to 8509 // reduce the compile time impact of this optimization. 8510 return false; 8511 8512 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 8513 if (!Addend) 8514 return false; 8515 8516 APInt ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 8517 8518 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 8519 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 8520 ConstantRange FoundLHSRange = 8521 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); 8522 8523 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 8524 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 8525 8526 // We can also compute the range of values for `LHS` that satisfy the 8527 // consequent, "`LHS` `Pred` `RHS`": 8528 APInt ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 8529 ConstantRange SatisfyingLHSRange = 8530 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS); 8531 8532 // The antecedent implies the consequent if every value of `LHS` that 8533 // satisfies the antecedent also satisfies the consequent. 8534 return SatisfyingLHSRange.contains(LHSRange); 8535 } 8536 8537 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 8538 bool IsSigned, bool NoWrap) { 8539 assert(isKnownPositive(Stride) && "Positive stride expected!"); 8540 8541 if (NoWrap) return false; 8542 8543 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 8544 const SCEV *One = getOne(Stride->getType()); 8545 8546 if (IsSigned) { 8547 APInt MaxRHS = getSignedRange(RHS).getSignedMax(); 8548 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 8549 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One)) 8550 .getSignedMax(); 8551 8552 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 8553 return (MaxValue - MaxStrideMinusOne).slt(MaxRHS); 8554 } 8555 8556 APInt MaxRHS = getUnsignedRange(RHS).getUnsignedMax(); 8557 APInt MaxValue = APInt::getMaxValue(BitWidth); 8558 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One)) 8559 .getUnsignedMax(); 8560 8561 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 8562 return (MaxValue - MaxStrideMinusOne).ult(MaxRHS); 8563 } 8564 8565 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 8566 bool IsSigned, bool NoWrap) { 8567 if (NoWrap) return false; 8568 8569 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 8570 const SCEV *One = getOne(Stride->getType()); 8571 8572 if (IsSigned) { 8573 APInt MinRHS = getSignedRange(RHS).getSignedMin(); 8574 APInt MinValue = APInt::getSignedMinValue(BitWidth); 8575 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One)) 8576 .getSignedMax(); 8577 8578 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 8579 return (MinValue + MaxStrideMinusOne).sgt(MinRHS); 8580 } 8581 8582 APInt MinRHS = getUnsignedRange(RHS).getUnsignedMin(); 8583 APInt MinValue = APInt::getMinValue(BitWidth); 8584 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One)) 8585 .getUnsignedMax(); 8586 8587 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 8588 return (MinValue + MaxStrideMinusOne).ugt(MinRHS); 8589 } 8590 8591 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step, 8592 bool Equality) { 8593 const SCEV *One = getOne(Step->getType()); 8594 Delta = Equality ? getAddExpr(Delta, Step) 8595 : getAddExpr(Delta, getMinusSCEV(Step, One)); 8596 return getUDivExpr(Delta, Step); 8597 } 8598 8599 ScalarEvolution::ExitLimit 8600 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 8601 const Loop *L, bool IsSigned, 8602 bool ControlsExit, bool AllowPredicates) { 8603 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 8604 // We handle only IV < Invariant 8605 if (!isLoopInvariant(RHS, L)) 8606 return getCouldNotCompute(); 8607 8608 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 8609 bool PredicatedIV = false; 8610 8611 if (!IV && AllowPredicates) { 8612 // Try to make this an AddRec using runtime tests, in the first X 8613 // iterations of this loop, where X is the SCEV expression found by the 8614 // algorithm below. 8615 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 8616 PredicatedIV = true; 8617 } 8618 8619 // Avoid weird loops 8620 if (!IV || IV->getLoop() != L || !IV->isAffine()) 8621 return getCouldNotCompute(); 8622 8623 bool NoWrap = ControlsExit && 8624 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 8625 8626 const SCEV *Stride = IV->getStepRecurrence(*this); 8627 8628 bool PositiveStride = isKnownPositive(Stride); 8629 8630 // Avoid negative or zero stride values. 8631 if (!PositiveStride) { 8632 // We can compute the correct backedge taken count for loops with unknown 8633 // strides if we can prove that the loop is not an infinite loop with side 8634 // effects. Here's the loop structure we are trying to handle - 8635 // 8636 // i = start 8637 // do { 8638 // A[i] = i; 8639 // i += s; 8640 // } while (i < end); 8641 // 8642 // The backedge taken count for such loops is evaluated as - 8643 // (max(end, start + stride) - start - 1) /u stride 8644 // 8645 // The additional preconditions that we need to check to prove correctness 8646 // of the above formula is as follows - 8647 // 8648 // a) IV is either nuw or nsw depending upon signedness (indicated by the 8649 // NoWrap flag). 8650 // b) loop is single exit with no side effects. 8651 // 8652 // 8653 // Precondition a) implies that if the stride is negative, this is a single 8654 // trip loop. The backedge taken count formula reduces to zero in this case. 8655 // 8656 // Precondition b) implies that the unknown stride cannot be zero otherwise 8657 // we have UB. 8658 // 8659 // The positive stride case is the same as isKnownPositive(Stride) returning 8660 // true (original behavior of the function). 8661 // 8662 // We want to make sure that the stride is truly unknown as there are edge 8663 // cases where ScalarEvolution propagates no wrap flags to the 8664 // post-increment/decrement IV even though the increment/decrement operation 8665 // itself is wrapping. The computed backedge taken count may be wrong in 8666 // such cases. This is prevented by checking that the stride is not known to 8667 // be either positive or non-positive. For example, no wrap flags are 8668 // propagated to the post-increment IV of this loop with a trip count of 2 - 8669 // 8670 // unsigned char i; 8671 // for(i=127; i<128; i+=129) 8672 // A[i] = i; 8673 // 8674 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) || 8675 !loopHasNoSideEffects(L)) 8676 return getCouldNotCompute(); 8677 8678 } else if (!Stride->isOne() && 8679 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap)) 8680 // Avoid proven overflow cases: this will ensure that the backedge taken 8681 // count will not generate any unsigned overflow. Relaxed no-overflow 8682 // conditions exploit NoWrapFlags, allowing to optimize in presence of 8683 // undefined behaviors like the case of C language. 8684 return getCouldNotCompute(); 8685 8686 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT 8687 : ICmpInst::ICMP_ULT; 8688 const SCEV *Start = IV->getStart(); 8689 const SCEV *End = RHS; 8690 // If the backedge is taken at least once, then it will be taken 8691 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start 8692 // is the LHS value of the less-than comparison the first time it is evaluated 8693 // and End is the RHS. 8694 const SCEV *BECountIfBackedgeTaken = 8695 computeBECount(getMinusSCEV(End, Start), Stride, false); 8696 // If the loop entry is guarded by the result of the backedge test of the 8697 // first loop iteration, then we know the backedge will be taken at least 8698 // once and so the backedge taken count is as above. If not then we use the 8699 // expression (max(End,Start)-Start)/Stride to describe the backedge count, 8700 // as if the backedge is taken at least once max(End,Start) is End and so the 8701 // result is as above, and if not max(End,Start) is Start so we get a backedge 8702 // count of zero. 8703 const SCEV *BECount; 8704 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) 8705 BECount = BECountIfBackedgeTaken; 8706 else { 8707 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 8708 BECount = computeBECount(getMinusSCEV(End, Start), Stride, false); 8709 } 8710 8711 const SCEV *MaxBECount; 8712 bool MaxOrZero = false; 8713 if (isa<SCEVConstant>(BECount)) 8714 MaxBECount = BECount; 8715 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) { 8716 // If we know exactly how many times the backedge will be taken if it's 8717 // taken at least once, then the backedge count will either be that or 8718 // zero. 8719 MaxBECount = BECountIfBackedgeTaken; 8720 MaxOrZero = true; 8721 } else { 8722 // Calculate the maximum backedge count based on the range of values 8723 // permitted by Start, End, and Stride. 8724 APInt MinStart = IsSigned ? getSignedRange(Start).getSignedMin() 8725 : getUnsignedRange(Start).getUnsignedMin(); 8726 8727 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 8728 8729 APInt StrideForMaxBECount; 8730 8731 if (PositiveStride) 8732 StrideForMaxBECount = 8733 IsSigned ? getSignedRange(Stride).getSignedMin() 8734 : getUnsignedRange(Stride).getUnsignedMin(); 8735 else 8736 // Using a stride of 1 is safe when computing max backedge taken count for 8737 // a loop with unknown stride. 8738 StrideForMaxBECount = APInt(BitWidth, 1, IsSigned); 8739 8740 APInt Limit = 8741 IsSigned ? APInt::getSignedMaxValue(BitWidth) - (StrideForMaxBECount - 1) 8742 : APInt::getMaxValue(BitWidth) - (StrideForMaxBECount - 1); 8743 8744 // Although End can be a MAX expression we estimate MaxEnd considering only 8745 // the case End = RHS. This is safe because in the other case (End - Start) 8746 // is zero, leading to a zero maximum backedge taken count. 8747 APInt MaxEnd = 8748 IsSigned ? APIntOps::smin(getSignedRange(RHS).getSignedMax(), Limit) 8749 : APIntOps::umin(getUnsignedRange(RHS).getUnsignedMax(), Limit); 8750 8751 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart), 8752 getConstant(StrideForMaxBECount), false); 8753 } 8754 8755 if (isa<SCEVCouldNotCompute>(MaxBECount)) 8756 MaxBECount = BECount; 8757 8758 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 8759 } 8760 8761 ScalarEvolution::ExitLimit 8762 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 8763 const Loop *L, bool IsSigned, 8764 bool ControlsExit, bool AllowPredicates) { 8765 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 8766 // We handle only IV > Invariant 8767 if (!isLoopInvariant(RHS, L)) 8768 return getCouldNotCompute(); 8769 8770 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 8771 if (!IV && AllowPredicates) 8772 // Try to make this an AddRec using runtime tests, in the first X 8773 // iterations of this loop, where X is the SCEV expression found by the 8774 // algorithm below. 8775 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 8776 8777 // Avoid weird loops 8778 if (!IV || IV->getLoop() != L || !IV->isAffine()) 8779 return getCouldNotCompute(); 8780 8781 bool NoWrap = ControlsExit && 8782 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 8783 8784 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 8785 8786 // Avoid negative or zero stride values 8787 if (!isKnownPositive(Stride)) 8788 return getCouldNotCompute(); 8789 8790 // Avoid proven overflow cases: this will ensure that the backedge taken count 8791 // will not generate any unsigned overflow. Relaxed no-overflow conditions 8792 // exploit NoWrapFlags, allowing to optimize in presence of undefined 8793 // behaviors like the case of C language. 8794 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap)) 8795 return getCouldNotCompute(); 8796 8797 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT 8798 : ICmpInst::ICMP_UGT; 8799 8800 const SCEV *Start = IV->getStart(); 8801 const SCEV *End = RHS; 8802 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) 8803 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 8804 8805 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false); 8806 8807 APInt MaxStart = IsSigned ? getSignedRange(Start).getSignedMax() 8808 : getUnsignedRange(Start).getUnsignedMax(); 8809 8810 APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin() 8811 : getUnsignedRange(Stride).getUnsignedMin(); 8812 8813 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 8814 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 8815 : APInt::getMinValue(BitWidth) + (MinStride - 1); 8816 8817 // Although End can be a MIN expression we estimate MinEnd considering only 8818 // the case End = RHS. This is safe because in the other case (Start - End) 8819 // is zero, leading to a zero maximum backedge taken count. 8820 APInt MinEnd = 8821 IsSigned ? APIntOps::smax(getSignedRange(RHS).getSignedMin(), Limit) 8822 : APIntOps::umax(getUnsignedRange(RHS).getUnsignedMin(), Limit); 8823 8824 8825 const SCEV *MaxBECount = getCouldNotCompute(); 8826 if (isa<SCEVConstant>(BECount)) 8827 MaxBECount = BECount; 8828 else 8829 MaxBECount = computeBECount(getConstant(MaxStart - MinEnd), 8830 getConstant(MinStride), false); 8831 8832 if (isa<SCEVCouldNotCompute>(MaxBECount)) 8833 MaxBECount = BECount; 8834 8835 return ExitLimit(BECount, MaxBECount, false, Predicates); 8836 } 8837 8838 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 8839 ScalarEvolution &SE) const { 8840 if (Range.isFullSet()) // Infinite loop. 8841 return SE.getCouldNotCompute(); 8842 8843 // If the start is a non-zero constant, shift the range to simplify things. 8844 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 8845 if (!SC->getValue()->isZero()) { 8846 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end()); 8847 Operands[0] = SE.getZero(SC->getType()); 8848 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 8849 getNoWrapFlags(FlagNW)); 8850 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 8851 return ShiftedAddRec->getNumIterationsInRange( 8852 Range.subtract(SC->getAPInt()), SE); 8853 // This is strange and shouldn't happen. 8854 return SE.getCouldNotCompute(); 8855 } 8856 8857 // The only time we can solve this is when we have all constant indices. 8858 // Otherwise, we cannot determine the overflow conditions. 8859 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 8860 return SE.getCouldNotCompute(); 8861 8862 // Okay at this point we know that all elements of the chrec are constants and 8863 // that the start element is zero. 8864 8865 // First check to see if the range contains zero. If not, the first 8866 // iteration exits. 8867 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 8868 if (!Range.contains(APInt(BitWidth, 0))) 8869 return SE.getZero(getType()); 8870 8871 if (isAffine()) { 8872 // If this is an affine expression then we have this situation: 8873 // Solve {0,+,A} in Range === Ax in Range 8874 8875 // We know that zero is in the range. If A is positive then we know that 8876 // the upper value of the range must be the first possible exit value. 8877 // If A is negative then the lower of the range is the last possible loop 8878 // value. Also note that we already checked for a full range. 8879 APInt One(BitWidth,1); 8880 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 8881 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower(); 8882 8883 // The exit value should be (End+A)/A. 8884 APInt ExitVal = (End + A).udiv(A); 8885 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 8886 8887 // Evaluate at the exit value. If we really did fall out of the valid 8888 // range, then we computed our trip count, otherwise wrap around or other 8889 // things must have happened. 8890 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 8891 if (Range.contains(Val->getValue())) 8892 return SE.getCouldNotCompute(); // Something strange happened 8893 8894 // Ensure that the previous value is in the range. This is a sanity check. 8895 assert(Range.contains( 8896 EvaluateConstantChrecAtConstant(this, 8897 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) && 8898 "Linear scev computation is off in a bad way!"); 8899 return SE.getConstant(ExitValue); 8900 } else if (isQuadratic()) { 8901 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the 8902 // quadratic equation to solve it. To do this, we must frame our problem in 8903 // terms of figuring out when zero is crossed, instead of when 8904 // Range.getUpper() is crossed. 8905 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end()); 8906 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper())); 8907 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), FlagAnyWrap); 8908 8909 // Next, solve the constructed addrec 8910 if (auto Roots = 8911 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE)) { 8912 const SCEVConstant *R1 = Roots->first; 8913 const SCEVConstant *R2 = Roots->second; 8914 // Pick the smallest positive root value. 8915 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp( 8916 ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) { 8917 if (!CB->getZExtValue()) 8918 std::swap(R1, R2); // R1 is the minimum root now. 8919 8920 // Make sure the root is not off by one. The returned iteration should 8921 // not be in the range, but the previous one should be. When solving 8922 // for "X*X < 5", for example, we should not return a root of 2. 8923 ConstantInt *R1Val = 8924 EvaluateConstantChrecAtConstant(this, R1->getValue(), SE); 8925 if (Range.contains(R1Val->getValue())) { 8926 // The next iteration must be out of the range... 8927 ConstantInt *NextVal = 8928 ConstantInt::get(SE.getContext(), R1->getAPInt() + 1); 8929 8930 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); 8931 if (!Range.contains(R1Val->getValue())) 8932 return SE.getConstant(NextVal); 8933 return SE.getCouldNotCompute(); // Something strange happened 8934 } 8935 8936 // If R1 was not in the range, then it is a good return value. Make 8937 // sure that R1-1 WAS in the range though, just in case. 8938 ConstantInt *NextVal = 8939 ConstantInt::get(SE.getContext(), R1->getAPInt() - 1); 8940 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); 8941 if (Range.contains(R1Val->getValue())) 8942 return R1; 8943 return SE.getCouldNotCompute(); // Something strange happened 8944 } 8945 } 8946 } 8947 8948 return SE.getCouldNotCompute(); 8949 } 8950 8951 // Return true when S contains at least an undef value. 8952 static inline bool containsUndefs(const SCEV *S) { 8953 return SCEVExprContains(S, [](const SCEV *S) { 8954 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 8955 return isa<UndefValue>(SU->getValue()); 8956 else if (const auto *SC = dyn_cast<SCEVConstant>(S)) 8957 return isa<UndefValue>(SC->getValue()); 8958 return false; 8959 }); 8960 } 8961 8962 namespace { 8963 // Collect all steps of SCEV expressions. 8964 struct SCEVCollectStrides { 8965 ScalarEvolution &SE; 8966 SmallVectorImpl<const SCEV *> &Strides; 8967 8968 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) 8969 : SE(SE), Strides(S) {} 8970 8971 bool follow(const SCEV *S) { 8972 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 8973 Strides.push_back(AR->getStepRecurrence(SE)); 8974 return true; 8975 } 8976 bool isDone() const { return false; } 8977 }; 8978 8979 // Collect all SCEVUnknown and SCEVMulExpr expressions. 8980 struct SCEVCollectTerms { 8981 SmallVectorImpl<const SCEV *> &Terms; 8982 8983 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) 8984 : Terms(T) {} 8985 8986 bool follow(const SCEV *S) { 8987 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) || 8988 isa<SCEVSignExtendExpr>(S)) { 8989 if (!containsUndefs(S)) 8990 Terms.push_back(S); 8991 8992 // Stop recursion: once we collected a term, do not walk its operands. 8993 return false; 8994 } 8995 8996 // Keep looking. 8997 return true; 8998 } 8999 bool isDone() const { return false; } 9000 }; 9001 9002 // Check if a SCEV contains an AddRecExpr. 9003 struct SCEVHasAddRec { 9004 bool &ContainsAddRec; 9005 9006 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) { 9007 ContainsAddRec = false; 9008 } 9009 9010 bool follow(const SCEV *S) { 9011 if (isa<SCEVAddRecExpr>(S)) { 9012 ContainsAddRec = true; 9013 9014 // Stop recursion: once we collected a term, do not walk its operands. 9015 return false; 9016 } 9017 9018 // Keep looking. 9019 return true; 9020 } 9021 bool isDone() const { return false; } 9022 }; 9023 9024 // Find factors that are multiplied with an expression that (possibly as a 9025 // subexpression) contains an AddRecExpr. In the expression: 9026 // 9027 // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop)) 9028 // 9029 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)" 9030 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size 9031 // parameters as they form a product with an induction variable. 9032 // 9033 // This collector expects all array size parameters to be in the same MulExpr. 9034 // It might be necessary to later add support for collecting parameters that are 9035 // spread over different nested MulExpr. 9036 struct SCEVCollectAddRecMultiplies { 9037 SmallVectorImpl<const SCEV *> &Terms; 9038 ScalarEvolution &SE; 9039 9040 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE) 9041 : Terms(T), SE(SE) {} 9042 9043 bool follow(const SCEV *S) { 9044 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) { 9045 bool HasAddRec = false; 9046 SmallVector<const SCEV *, 0> Operands; 9047 for (auto Op : Mul->operands()) { 9048 if (isa<SCEVUnknown>(Op)) { 9049 Operands.push_back(Op); 9050 } else { 9051 bool ContainsAddRec; 9052 SCEVHasAddRec ContiansAddRec(ContainsAddRec); 9053 visitAll(Op, ContiansAddRec); 9054 HasAddRec |= ContainsAddRec; 9055 } 9056 } 9057 if (Operands.size() == 0) 9058 return true; 9059 9060 if (!HasAddRec) 9061 return false; 9062 9063 Terms.push_back(SE.getMulExpr(Operands)); 9064 // Stop recursion: once we collected a term, do not walk its operands. 9065 return false; 9066 } 9067 9068 // Keep looking. 9069 return true; 9070 } 9071 bool isDone() const { return false; } 9072 }; 9073 } 9074 9075 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in 9076 /// two places: 9077 /// 1) The strides of AddRec expressions. 9078 /// 2) Unknowns that are multiplied with AddRec expressions. 9079 void ScalarEvolution::collectParametricTerms(const SCEV *Expr, 9080 SmallVectorImpl<const SCEV *> &Terms) { 9081 SmallVector<const SCEV *, 4> Strides; 9082 SCEVCollectStrides StrideCollector(*this, Strides); 9083 visitAll(Expr, StrideCollector); 9084 9085 DEBUG({ 9086 dbgs() << "Strides:\n"; 9087 for (const SCEV *S : Strides) 9088 dbgs() << *S << "\n"; 9089 }); 9090 9091 for (const SCEV *S : Strides) { 9092 SCEVCollectTerms TermCollector(Terms); 9093 visitAll(S, TermCollector); 9094 } 9095 9096 DEBUG({ 9097 dbgs() << "Terms:\n"; 9098 for (const SCEV *T : Terms) 9099 dbgs() << *T << "\n"; 9100 }); 9101 9102 SCEVCollectAddRecMultiplies MulCollector(Terms, *this); 9103 visitAll(Expr, MulCollector); 9104 } 9105 9106 static bool findArrayDimensionsRec(ScalarEvolution &SE, 9107 SmallVectorImpl<const SCEV *> &Terms, 9108 SmallVectorImpl<const SCEV *> &Sizes) { 9109 int Last = Terms.size() - 1; 9110 const SCEV *Step = Terms[Last]; 9111 9112 // End of recursion. 9113 if (Last == 0) { 9114 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { 9115 SmallVector<const SCEV *, 2> Qs; 9116 for (const SCEV *Op : M->operands()) 9117 if (!isa<SCEVConstant>(Op)) 9118 Qs.push_back(Op); 9119 9120 Step = SE.getMulExpr(Qs); 9121 } 9122 9123 Sizes.push_back(Step); 9124 return true; 9125 } 9126 9127 for (const SCEV *&Term : Terms) { 9128 // Normalize the terms before the next call to findArrayDimensionsRec. 9129 const SCEV *Q, *R; 9130 SCEVDivision::divide(SE, Term, Step, &Q, &R); 9131 9132 // Bail out when GCD does not evenly divide one of the terms. 9133 if (!R->isZero()) 9134 return false; 9135 9136 Term = Q; 9137 } 9138 9139 // Remove all SCEVConstants. 9140 Terms.erase( 9141 remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }), 9142 Terms.end()); 9143 9144 if (Terms.size() > 0) 9145 if (!findArrayDimensionsRec(SE, Terms, Sizes)) 9146 return false; 9147 9148 Sizes.push_back(Step); 9149 return true; 9150 } 9151 9152 9153 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. 9154 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) { 9155 for (const SCEV *T : Terms) 9156 if (SCEVExprContains(T, [](const SCEV *S) { return isa<SCEVUnknown>(S); })) 9157 return true; 9158 return false; 9159 } 9160 9161 // Return the number of product terms in S. 9162 static inline int numberOfTerms(const SCEV *S) { 9163 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) 9164 return Expr->getNumOperands(); 9165 return 1; 9166 } 9167 9168 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { 9169 if (isa<SCEVConstant>(T)) 9170 return nullptr; 9171 9172 if (isa<SCEVUnknown>(T)) 9173 return T; 9174 9175 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { 9176 SmallVector<const SCEV *, 2> Factors; 9177 for (const SCEV *Op : M->operands()) 9178 if (!isa<SCEVConstant>(Op)) 9179 Factors.push_back(Op); 9180 9181 return SE.getMulExpr(Factors); 9182 } 9183 9184 return T; 9185 } 9186 9187 /// Return the size of an element read or written by Inst. 9188 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 9189 Type *Ty; 9190 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 9191 Ty = Store->getValueOperand()->getType(); 9192 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 9193 Ty = Load->getType(); 9194 else 9195 return nullptr; 9196 9197 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 9198 return getSizeOfExpr(ETy, Ty); 9199 } 9200 9201 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, 9202 SmallVectorImpl<const SCEV *> &Sizes, 9203 const SCEV *ElementSize) const { 9204 if (Terms.size() < 1 || !ElementSize) 9205 return; 9206 9207 // Early return when Terms do not contain parameters: we do not delinearize 9208 // non parametric SCEVs. 9209 if (!containsParameters(Terms)) 9210 return; 9211 9212 DEBUG({ 9213 dbgs() << "Terms:\n"; 9214 for (const SCEV *T : Terms) 9215 dbgs() << *T << "\n"; 9216 }); 9217 9218 // Remove duplicates. 9219 std::sort(Terms.begin(), Terms.end()); 9220 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); 9221 9222 // Put larger terms first. 9223 std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) { 9224 return numberOfTerms(LHS) > numberOfTerms(RHS); 9225 }); 9226 9227 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 9228 9229 // Try to divide all terms by the element size. If term is not divisible by 9230 // element size, proceed with the original term. 9231 for (const SCEV *&Term : Terms) { 9232 const SCEV *Q, *R; 9233 SCEVDivision::divide(SE, Term, ElementSize, &Q, &R); 9234 if (!Q->isZero()) 9235 Term = Q; 9236 } 9237 9238 SmallVector<const SCEV *, 4> NewTerms; 9239 9240 // Remove constant factors. 9241 for (const SCEV *T : Terms) 9242 if (const SCEV *NewT = removeConstantFactors(SE, T)) 9243 NewTerms.push_back(NewT); 9244 9245 DEBUG({ 9246 dbgs() << "Terms after sorting:\n"; 9247 for (const SCEV *T : NewTerms) 9248 dbgs() << *T << "\n"; 9249 }); 9250 9251 if (NewTerms.empty() || 9252 !findArrayDimensionsRec(SE, NewTerms, Sizes)) { 9253 Sizes.clear(); 9254 return; 9255 } 9256 9257 // The last element to be pushed into Sizes is the size of an element. 9258 Sizes.push_back(ElementSize); 9259 9260 DEBUG({ 9261 dbgs() << "Sizes:\n"; 9262 for (const SCEV *S : Sizes) 9263 dbgs() << *S << "\n"; 9264 }); 9265 } 9266 9267 void ScalarEvolution::computeAccessFunctions( 9268 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, 9269 SmallVectorImpl<const SCEV *> &Sizes) { 9270 9271 // Early exit in case this SCEV is not an affine multivariate function. 9272 if (Sizes.empty()) 9273 return; 9274 9275 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr)) 9276 if (!AR->isAffine()) 9277 return; 9278 9279 const SCEV *Res = Expr; 9280 int Last = Sizes.size() - 1; 9281 for (int i = Last; i >= 0; i--) { 9282 const SCEV *Q, *R; 9283 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); 9284 9285 DEBUG({ 9286 dbgs() << "Res: " << *Res << "\n"; 9287 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; 9288 dbgs() << "Res divided by Sizes[i]:\n"; 9289 dbgs() << "Quotient: " << *Q << "\n"; 9290 dbgs() << "Remainder: " << *R << "\n"; 9291 }); 9292 9293 Res = Q; 9294 9295 // Do not record the last subscript corresponding to the size of elements in 9296 // the array. 9297 if (i == Last) { 9298 9299 // Bail out if the remainder is too complex. 9300 if (isa<SCEVAddRecExpr>(R)) { 9301 Subscripts.clear(); 9302 Sizes.clear(); 9303 return; 9304 } 9305 9306 continue; 9307 } 9308 9309 // Record the access function for the current subscript. 9310 Subscripts.push_back(R); 9311 } 9312 9313 // Also push in last position the remainder of the last division: it will be 9314 // the access function of the innermost dimension. 9315 Subscripts.push_back(Res); 9316 9317 std::reverse(Subscripts.begin(), Subscripts.end()); 9318 9319 DEBUG({ 9320 dbgs() << "Subscripts:\n"; 9321 for (const SCEV *S : Subscripts) 9322 dbgs() << *S << "\n"; 9323 }); 9324 } 9325 9326 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and 9327 /// sizes of an array access. Returns the remainder of the delinearization that 9328 /// is the offset start of the array. The SCEV->delinearize algorithm computes 9329 /// the multiples of SCEV coefficients: that is a pattern matching of sub 9330 /// expressions in the stride and base of a SCEV corresponding to the 9331 /// computation of a GCD (greatest common divisor) of base and stride. When 9332 /// SCEV->delinearize fails, it returns the SCEV unchanged. 9333 /// 9334 /// For example: when analyzing the memory access A[i][j][k] in this loop nest 9335 /// 9336 /// void foo(long n, long m, long o, double A[n][m][o]) { 9337 /// 9338 /// for (long i = 0; i < n; i++) 9339 /// for (long j = 0; j < m; j++) 9340 /// for (long k = 0; k < o; k++) 9341 /// A[i][j][k] = 1.0; 9342 /// } 9343 /// 9344 /// the delinearization input is the following AddRec SCEV: 9345 /// 9346 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> 9347 /// 9348 /// From this SCEV, we are able to say that the base offset of the access is %A 9349 /// because it appears as an offset that does not divide any of the strides in 9350 /// the loops: 9351 /// 9352 /// CHECK: Base offset: %A 9353 /// 9354 /// and then SCEV->delinearize determines the size of some of the dimensions of 9355 /// the array as these are the multiples by which the strides are happening: 9356 /// 9357 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. 9358 /// 9359 /// Note that the outermost dimension remains of UnknownSize because there are 9360 /// no strides that would help identifying the size of the last dimension: when 9361 /// the array has been statically allocated, one could compute the size of that 9362 /// dimension by dividing the overall size of the array by the size of the known 9363 /// dimensions: %m * %o * 8. 9364 /// 9365 /// Finally delinearize provides the access functions for the array reference 9366 /// that does correspond to A[i][j][k] of the above C testcase: 9367 /// 9368 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] 9369 /// 9370 /// The testcases are checking the output of a function pass: 9371 /// DelinearizationPass that walks through all loads and stores of a function 9372 /// asking for the SCEV of the memory access with respect to all enclosing 9373 /// loops, calling SCEV->delinearize on that and printing the results. 9374 9375 void ScalarEvolution::delinearize(const SCEV *Expr, 9376 SmallVectorImpl<const SCEV *> &Subscripts, 9377 SmallVectorImpl<const SCEV *> &Sizes, 9378 const SCEV *ElementSize) { 9379 // First step: collect parametric terms. 9380 SmallVector<const SCEV *, 4> Terms; 9381 collectParametricTerms(Expr, Terms); 9382 9383 if (Terms.empty()) 9384 return; 9385 9386 // Second step: find subscript sizes. 9387 findArrayDimensions(Terms, Sizes, ElementSize); 9388 9389 if (Sizes.empty()) 9390 return; 9391 9392 // Third step: compute the access functions for each subscript. 9393 computeAccessFunctions(Expr, Subscripts, Sizes); 9394 9395 if (Subscripts.empty()) 9396 return; 9397 9398 DEBUG({ 9399 dbgs() << "succeeded to delinearize " << *Expr << "\n"; 9400 dbgs() << "ArrayDecl[UnknownSize]"; 9401 for (const SCEV *S : Sizes) 9402 dbgs() << "[" << *S << "]"; 9403 9404 dbgs() << "\nArrayRef"; 9405 for (const SCEV *S : Subscripts) 9406 dbgs() << "[" << *S << "]"; 9407 dbgs() << "\n"; 9408 }); 9409 } 9410 9411 //===----------------------------------------------------------------------===// 9412 // SCEVCallbackVH Class Implementation 9413 //===----------------------------------------------------------------------===// 9414 9415 void ScalarEvolution::SCEVCallbackVH::deleted() { 9416 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 9417 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 9418 SE->ConstantEvolutionLoopExitValue.erase(PN); 9419 SE->eraseValueFromMap(getValPtr()); 9420 // this now dangles! 9421 } 9422 9423 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 9424 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 9425 9426 // Forget all the expressions associated with users of the old value, 9427 // so that future queries will recompute the expressions using the new 9428 // value. 9429 Value *Old = getValPtr(); 9430 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end()); 9431 SmallPtrSet<User *, 8> Visited; 9432 while (!Worklist.empty()) { 9433 User *U = Worklist.pop_back_val(); 9434 // Deleting the Old value will cause this to dangle. Postpone 9435 // that until everything else is done. 9436 if (U == Old) 9437 continue; 9438 if (!Visited.insert(U).second) 9439 continue; 9440 if (PHINode *PN = dyn_cast<PHINode>(U)) 9441 SE->ConstantEvolutionLoopExitValue.erase(PN); 9442 SE->eraseValueFromMap(U); 9443 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end()); 9444 } 9445 // Delete the Old value. 9446 if (PHINode *PN = dyn_cast<PHINode>(Old)) 9447 SE->ConstantEvolutionLoopExitValue.erase(PN); 9448 SE->eraseValueFromMap(Old); 9449 // this now dangles! 9450 } 9451 9452 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 9453 : CallbackVH(V), SE(se) {} 9454 9455 //===----------------------------------------------------------------------===// 9456 // ScalarEvolution Class Implementation 9457 //===----------------------------------------------------------------------===// 9458 9459 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 9460 AssumptionCache &AC, DominatorTree &DT, 9461 LoopInfo &LI) 9462 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 9463 CouldNotCompute(new SCEVCouldNotCompute()), 9464 WalkingBEDominatingConds(false), ProvingSplitPredicate(false), 9465 ValuesAtScopes(64), LoopDispositions(64), BlockDispositions(64), 9466 FirstUnknown(nullptr) { 9467 9468 // To use guards for proving predicates, we need to scan every instruction in 9469 // relevant basic blocks, and not just terminators. Doing this is a waste of 9470 // time if the IR does not actually contain any calls to 9471 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 9472 // 9473 // This pessimizes the case where a pass that preserves ScalarEvolution wants 9474 // to _add_ guards to the module when there weren't any before, and wants 9475 // ScalarEvolution to optimize based on those guards. For now we prefer to be 9476 // efficient in lieu of being smart in that rather obscure case. 9477 9478 auto *GuardDecl = F.getParent()->getFunction( 9479 Intrinsic::getName(Intrinsic::experimental_guard)); 9480 HasGuards = GuardDecl && !GuardDecl->use_empty(); 9481 } 9482 9483 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 9484 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 9485 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 9486 ValueExprMap(std::move(Arg.ValueExprMap)), 9487 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 9488 WalkingBEDominatingConds(false), ProvingSplitPredicate(false), 9489 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 9490 PredicatedBackedgeTakenCounts( 9491 std::move(Arg.PredicatedBackedgeTakenCounts)), 9492 ConstantEvolutionLoopExitValue( 9493 std::move(Arg.ConstantEvolutionLoopExitValue)), 9494 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 9495 LoopDispositions(std::move(Arg.LoopDispositions)), 9496 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 9497 BlockDispositions(std::move(Arg.BlockDispositions)), 9498 UnsignedRanges(std::move(Arg.UnsignedRanges)), 9499 SignedRanges(std::move(Arg.SignedRanges)), 9500 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 9501 UniquePreds(std::move(Arg.UniquePreds)), 9502 SCEVAllocator(std::move(Arg.SCEVAllocator)), 9503 FirstUnknown(Arg.FirstUnknown) { 9504 Arg.FirstUnknown = nullptr; 9505 } 9506 9507 ScalarEvolution::~ScalarEvolution() { 9508 // Iterate through all the SCEVUnknown instances and call their 9509 // destructors, so that they release their references to their values. 9510 for (SCEVUnknown *U = FirstUnknown; U;) { 9511 SCEVUnknown *Tmp = U; 9512 U = U->Next; 9513 Tmp->~SCEVUnknown(); 9514 } 9515 FirstUnknown = nullptr; 9516 9517 ExprValueMap.clear(); 9518 ValueExprMap.clear(); 9519 HasRecMap.clear(); 9520 9521 // Free any extra memory created for ExitNotTakenInfo in the unlikely event 9522 // that a loop had multiple computable exits. 9523 for (auto &BTCI : BackedgeTakenCounts) 9524 BTCI.second.clear(); 9525 for (auto &BTCI : PredicatedBackedgeTakenCounts) 9526 BTCI.second.clear(); 9527 9528 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 9529 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 9530 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 9531 } 9532 9533 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 9534 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 9535 } 9536 9537 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 9538 const Loop *L) { 9539 // Print all inner loops first 9540 for (Loop *I : *L) 9541 PrintLoopInfo(OS, SE, I); 9542 9543 OS << "Loop "; 9544 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 9545 OS << ": "; 9546 9547 SmallVector<BasicBlock *, 8> ExitBlocks; 9548 L->getExitBlocks(ExitBlocks); 9549 if (ExitBlocks.size() != 1) 9550 OS << "<multiple exits> "; 9551 9552 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 9553 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L); 9554 } else { 9555 OS << "Unpredictable backedge-taken count. "; 9556 } 9557 9558 OS << "\n" 9559 "Loop "; 9560 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 9561 OS << ": "; 9562 9563 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) { 9564 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L); 9565 if (SE->isBackedgeTakenCountMaxOrZero(L)) 9566 OS << ", actual taken count either this or zero."; 9567 } else { 9568 OS << "Unpredictable max backedge-taken count. "; 9569 } 9570 9571 OS << "\n" 9572 "Loop "; 9573 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 9574 OS << ": "; 9575 9576 SCEVUnionPredicate Pred; 9577 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); 9578 if (!isa<SCEVCouldNotCompute>(PBT)) { 9579 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 9580 OS << " Predicates:\n"; 9581 Pred.print(OS, 4); 9582 } else { 9583 OS << "Unpredictable predicated backedge-taken count. "; 9584 } 9585 OS << "\n"; 9586 } 9587 9588 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 9589 switch (LD) { 9590 case ScalarEvolution::LoopVariant: 9591 return "Variant"; 9592 case ScalarEvolution::LoopInvariant: 9593 return "Invariant"; 9594 case ScalarEvolution::LoopComputable: 9595 return "Computable"; 9596 } 9597 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 9598 } 9599 9600 void ScalarEvolution::print(raw_ostream &OS) const { 9601 // ScalarEvolution's implementation of the print method is to print 9602 // out SCEV values of all instructions that are interesting. Doing 9603 // this potentially causes it to create new SCEV objects though, 9604 // which technically conflicts with the const qualifier. This isn't 9605 // observable from outside the class though, so casting away the 9606 // const isn't dangerous. 9607 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 9608 9609 OS << "Classifying expressions for: "; 9610 F.printAsOperand(OS, /*PrintType=*/false); 9611 OS << "\n"; 9612 for (Instruction &I : instructions(F)) 9613 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 9614 OS << I << '\n'; 9615 OS << " --> "; 9616 const SCEV *SV = SE.getSCEV(&I); 9617 SV->print(OS); 9618 if (!isa<SCEVCouldNotCompute>(SV)) { 9619 OS << " U: "; 9620 SE.getUnsignedRange(SV).print(OS); 9621 OS << " S: "; 9622 SE.getSignedRange(SV).print(OS); 9623 } 9624 9625 const Loop *L = LI.getLoopFor(I.getParent()); 9626 9627 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 9628 if (AtUse != SV) { 9629 OS << " --> "; 9630 AtUse->print(OS); 9631 if (!isa<SCEVCouldNotCompute>(AtUse)) { 9632 OS << " U: "; 9633 SE.getUnsignedRange(AtUse).print(OS); 9634 OS << " S: "; 9635 SE.getSignedRange(AtUse).print(OS); 9636 } 9637 } 9638 9639 if (L) { 9640 OS << "\t\t" "Exits: "; 9641 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 9642 if (!SE.isLoopInvariant(ExitValue, L)) { 9643 OS << "<<Unknown>>"; 9644 } else { 9645 OS << *ExitValue; 9646 } 9647 9648 bool First = true; 9649 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 9650 if (First) { 9651 OS << "\t\t" "LoopDispositions: { "; 9652 First = false; 9653 } else { 9654 OS << ", "; 9655 } 9656 9657 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 9658 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 9659 } 9660 9661 for (auto *InnerL : depth_first(L)) { 9662 if (InnerL == L) 9663 continue; 9664 if (First) { 9665 OS << "\t\t" "LoopDispositions: { "; 9666 First = false; 9667 } else { 9668 OS << ", "; 9669 } 9670 9671 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 9672 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 9673 } 9674 9675 OS << " }"; 9676 } 9677 9678 OS << "\n"; 9679 } 9680 9681 OS << "Determining loop execution counts for: "; 9682 F.printAsOperand(OS, /*PrintType=*/false); 9683 OS << "\n"; 9684 for (Loop *I : LI) 9685 PrintLoopInfo(OS, &SE, I); 9686 } 9687 9688 ScalarEvolution::LoopDisposition 9689 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 9690 auto &Values = LoopDispositions[S]; 9691 for (auto &V : Values) { 9692 if (V.getPointer() == L) 9693 return V.getInt(); 9694 } 9695 Values.emplace_back(L, LoopVariant); 9696 LoopDisposition D = computeLoopDisposition(S, L); 9697 auto &Values2 = LoopDispositions[S]; 9698 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 9699 if (V.getPointer() == L) { 9700 V.setInt(D); 9701 break; 9702 } 9703 } 9704 return D; 9705 } 9706 9707 ScalarEvolution::LoopDisposition 9708 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 9709 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 9710 case scConstant: 9711 return LoopInvariant; 9712 case scTruncate: 9713 case scZeroExtend: 9714 case scSignExtend: 9715 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 9716 case scAddRecExpr: { 9717 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 9718 9719 // If L is the addrec's loop, it's computable. 9720 if (AR->getLoop() == L) 9721 return LoopComputable; 9722 9723 // Add recurrences are never invariant in the function-body (null loop). 9724 if (!L) 9725 return LoopVariant; 9726 9727 // This recurrence is variant w.r.t. L if L contains AR's loop. 9728 if (L->contains(AR->getLoop())) 9729 return LoopVariant; 9730 9731 // This recurrence is invariant w.r.t. L if AR's loop contains L. 9732 if (AR->getLoop()->contains(L)) 9733 return LoopInvariant; 9734 9735 // This recurrence is variant w.r.t. L if any of its operands 9736 // are variant. 9737 for (auto *Op : AR->operands()) 9738 if (!isLoopInvariant(Op, L)) 9739 return LoopVariant; 9740 9741 // Otherwise it's loop-invariant. 9742 return LoopInvariant; 9743 } 9744 case scAddExpr: 9745 case scMulExpr: 9746 case scUMaxExpr: 9747 case scSMaxExpr: { 9748 bool HasVarying = false; 9749 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 9750 LoopDisposition D = getLoopDisposition(Op, L); 9751 if (D == LoopVariant) 9752 return LoopVariant; 9753 if (D == LoopComputable) 9754 HasVarying = true; 9755 } 9756 return HasVarying ? LoopComputable : LoopInvariant; 9757 } 9758 case scUDivExpr: { 9759 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 9760 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 9761 if (LD == LoopVariant) 9762 return LoopVariant; 9763 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 9764 if (RD == LoopVariant) 9765 return LoopVariant; 9766 return (LD == LoopInvariant && RD == LoopInvariant) ? 9767 LoopInvariant : LoopComputable; 9768 } 9769 case scUnknown: 9770 // All non-instruction values are loop invariant. All instructions are loop 9771 // invariant if they are not contained in the specified loop. 9772 // Instructions are never considered invariant in the function body 9773 // (null loop) because they are defined within the "loop". 9774 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 9775 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 9776 return LoopInvariant; 9777 case scCouldNotCompute: 9778 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 9779 } 9780 llvm_unreachable("Unknown SCEV kind!"); 9781 } 9782 9783 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 9784 return getLoopDisposition(S, L) == LoopInvariant; 9785 } 9786 9787 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 9788 return getLoopDisposition(S, L) == LoopComputable; 9789 } 9790 9791 ScalarEvolution::BlockDisposition 9792 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 9793 auto &Values = BlockDispositions[S]; 9794 for (auto &V : Values) { 9795 if (V.getPointer() == BB) 9796 return V.getInt(); 9797 } 9798 Values.emplace_back(BB, DoesNotDominateBlock); 9799 BlockDisposition D = computeBlockDisposition(S, BB); 9800 auto &Values2 = BlockDispositions[S]; 9801 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 9802 if (V.getPointer() == BB) { 9803 V.setInt(D); 9804 break; 9805 } 9806 } 9807 return D; 9808 } 9809 9810 ScalarEvolution::BlockDisposition 9811 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 9812 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 9813 case scConstant: 9814 return ProperlyDominatesBlock; 9815 case scTruncate: 9816 case scZeroExtend: 9817 case scSignExtend: 9818 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 9819 case scAddRecExpr: { 9820 // This uses a "dominates" query instead of "properly dominates" query 9821 // to test for proper dominance too, because the instruction which 9822 // produces the addrec's value is a PHI, and a PHI effectively properly 9823 // dominates its entire containing block. 9824 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 9825 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 9826 return DoesNotDominateBlock; 9827 9828 // Fall through into SCEVNAryExpr handling. 9829 LLVM_FALLTHROUGH; 9830 } 9831 case scAddExpr: 9832 case scMulExpr: 9833 case scUMaxExpr: 9834 case scSMaxExpr: { 9835 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 9836 bool Proper = true; 9837 for (const SCEV *NAryOp : NAry->operands()) { 9838 BlockDisposition D = getBlockDisposition(NAryOp, BB); 9839 if (D == DoesNotDominateBlock) 9840 return DoesNotDominateBlock; 9841 if (D == DominatesBlock) 9842 Proper = false; 9843 } 9844 return Proper ? ProperlyDominatesBlock : DominatesBlock; 9845 } 9846 case scUDivExpr: { 9847 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 9848 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 9849 BlockDisposition LD = getBlockDisposition(LHS, BB); 9850 if (LD == DoesNotDominateBlock) 9851 return DoesNotDominateBlock; 9852 BlockDisposition RD = getBlockDisposition(RHS, BB); 9853 if (RD == DoesNotDominateBlock) 9854 return DoesNotDominateBlock; 9855 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 9856 ProperlyDominatesBlock : DominatesBlock; 9857 } 9858 case scUnknown: 9859 if (Instruction *I = 9860 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 9861 if (I->getParent() == BB) 9862 return DominatesBlock; 9863 if (DT.properlyDominates(I->getParent(), BB)) 9864 return ProperlyDominatesBlock; 9865 return DoesNotDominateBlock; 9866 } 9867 return ProperlyDominatesBlock; 9868 case scCouldNotCompute: 9869 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 9870 } 9871 llvm_unreachable("Unknown SCEV kind!"); 9872 } 9873 9874 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 9875 return getBlockDisposition(S, BB) >= DominatesBlock; 9876 } 9877 9878 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 9879 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 9880 } 9881 9882 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 9883 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); 9884 } 9885 9886 void ScalarEvolution::forgetMemoizedResults(const SCEV *S) { 9887 ValuesAtScopes.erase(S); 9888 LoopDispositions.erase(S); 9889 BlockDispositions.erase(S); 9890 UnsignedRanges.erase(S); 9891 SignedRanges.erase(S); 9892 ExprValueMap.erase(S); 9893 HasRecMap.erase(S); 9894 9895 auto RemoveSCEVFromBackedgeMap = 9896 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 9897 for (auto I = Map.begin(), E = Map.end(); I != E;) { 9898 BackedgeTakenInfo &BEInfo = I->second; 9899 if (BEInfo.hasOperand(S, this)) { 9900 BEInfo.clear(); 9901 Map.erase(I++); 9902 } else 9903 ++I; 9904 } 9905 }; 9906 9907 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); 9908 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); 9909 } 9910 9911 typedef DenseMap<const Loop *, std::string> VerifyMap; 9912 9913 /// replaceSubString - Replaces all occurrences of From in Str with To. 9914 static void replaceSubString(std::string &Str, StringRef From, StringRef To) { 9915 size_t Pos = 0; 9916 while ((Pos = Str.find(From, Pos)) != std::string::npos) { 9917 Str.replace(Pos, From.size(), To.data(), To.size()); 9918 Pos += To.size(); 9919 } 9920 } 9921 9922 /// getLoopBackedgeTakenCounts - Helper method for verifyAnalysis. 9923 static void 9924 getLoopBackedgeTakenCounts(Loop *L, VerifyMap &Map, ScalarEvolution &SE) { 9925 std::string &S = Map[L]; 9926 if (S.empty()) { 9927 raw_string_ostream OS(S); 9928 SE.getBackedgeTakenCount(L)->print(OS); 9929 9930 // false and 0 are semantically equivalent. This can happen in dead loops. 9931 replaceSubString(OS.str(), "false", "0"); 9932 // Remove wrap flags, their use in SCEV is highly fragile. 9933 // FIXME: Remove this when SCEV gets smarter about them. 9934 replaceSubString(OS.str(), "<nw>", ""); 9935 replaceSubString(OS.str(), "<nsw>", ""); 9936 replaceSubString(OS.str(), "<nuw>", ""); 9937 } 9938 9939 for (auto *R : reverse(*L)) 9940 getLoopBackedgeTakenCounts(R, Map, SE); // recurse. 9941 } 9942 9943 void ScalarEvolution::verify() const { 9944 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 9945 9946 // Gather stringified backedge taken counts for all loops using SCEV's caches. 9947 // FIXME: It would be much better to store actual values instead of strings, 9948 // but SCEV pointers will change if we drop the caches. 9949 VerifyMap BackedgeDumpsOld, BackedgeDumpsNew; 9950 for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I) 9951 getLoopBackedgeTakenCounts(*I, BackedgeDumpsOld, SE); 9952 9953 // Gather stringified backedge taken counts for all loops using a fresh 9954 // ScalarEvolution object. 9955 ScalarEvolution SE2(F, TLI, AC, DT, LI); 9956 for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I) 9957 getLoopBackedgeTakenCounts(*I, BackedgeDumpsNew, SE2); 9958 9959 // Now compare whether they're the same with and without caches. This allows 9960 // verifying that no pass changed the cache. 9961 assert(BackedgeDumpsOld.size() == BackedgeDumpsNew.size() && 9962 "New loops suddenly appeared!"); 9963 9964 for (VerifyMap::iterator OldI = BackedgeDumpsOld.begin(), 9965 OldE = BackedgeDumpsOld.end(), 9966 NewI = BackedgeDumpsNew.begin(); 9967 OldI != OldE; ++OldI, ++NewI) { 9968 assert(OldI->first == NewI->first && "Loop order changed!"); 9969 9970 // Compare the stringified SCEVs. We don't care if undef backedgetaken count 9971 // changes. 9972 // FIXME: We currently ignore SCEV changes from/to CouldNotCompute. This 9973 // means that a pass is buggy or SCEV has to learn a new pattern but is 9974 // usually not harmful. 9975 if (OldI->second != NewI->second && 9976 OldI->second.find("undef") == std::string::npos && 9977 NewI->second.find("undef") == std::string::npos && 9978 OldI->second != "***COULDNOTCOMPUTE***" && 9979 NewI->second != "***COULDNOTCOMPUTE***") { 9980 dbgs() << "SCEVValidator: SCEV for loop '" 9981 << OldI->first->getHeader()->getName() 9982 << "' changed from '" << OldI->second 9983 << "' to '" << NewI->second << "'!\n"; 9984 std::abort(); 9985 } 9986 } 9987 9988 // TODO: Verify more things. 9989 } 9990 9991 char ScalarEvolutionAnalysis::PassID; 9992 9993 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 9994 FunctionAnalysisManager &AM) { 9995 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 9996 AM.getResult<AssumptionAnalysis>(F), 9997 AM.getResult<DominatorTreeAnalysis>(F), 9998 AM.getResult<LoopAnalysis>(F)); 9999 } 10000 10001 PreservedAnalyses 10002 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 10003 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 10004 return PreservedAnalyses::all(); 10005 } 10006 10007 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 10008 "Scalar Evolution Analysis", false, true) 10009 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 10010 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 10011 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 10012 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 10013 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 10014 "Scalar Evolution Analysis", false, true) 10015 char ScalarEvolutionWrapperPass::ID = 0; 10016 10017 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 10018 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 10019 } 10020 10021 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 10022 SE.reset(new ScalarEvolution( 10023 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(), 10024 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 10025 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 10026 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 10027 return false; 10028 } 10029 10030 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 10031 10032 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 10033 SE->print(OS); 10034 } 10035 10036 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 10037 if (!VerifySCEV) 10038 return; 10039 10040 SE->verify(); 10041 } 10042 10043 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 10044 AU.setPreservesAll(); 10045 AU.addRequiredTransitive<AssumptionCacheTracker>(); 10046 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 10047 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 10048 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 10049 } 10050 10051 const SCEVPredicate * 10052 ScalarEvolution::getEqualPredicate(const SCEVUnknown *LHS, 10053 const SCEVConstant *RHS) { 10054 FoldingSetNodeID ID; 10055 // Unique this node based on the arguments 10056 ID.AddInteger(SCEVPredicate::P_Equal); 10057 ID.AddPointer(LHS); 10058 ID.AddPointer(RHS); 10059 void *IP = nullptr; 10060 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 10061 return S; 10062 SCEVEqualPredicate *Eq = new (SCEVAllocator) 10063 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 10064 UniquePreds.InsertNode(Eq, IP); 10065 return Eq; 10066 } 10067 10068 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 10069 const SCEVAddRecExpr *AR, 10070 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 10071 FoldingSetNodeID ID; 10072 // Unique this node based on the arguments 10073 ID.AddInteger(SCEVPredicate::P_Wrap); 10074 ID.AddPointer(AR); 10075 ID.AddInteger(AddedFlags); 10076 void *IP = nullptr; 10077 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 10078 return S; 10079 auto *OF = new (SCEVAllocator) 10080 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 10081 UniquePreds.InsertNode(OF, IP); 10082 return OF; 10083 } 10084 10085 namespace { 10086 10087 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 10088 public: 10089 /// Rewrites \p S in the context of a loop L and the SCEV predication 10090 /// infrastructure. 10091 /// 10092 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 10093 /// equivalences present in \p Pred. 10094 /// 10095 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 10096 /// \p NewPreds such that the result will be an AddRecExpr. 10097 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 10098 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 10099 SCEVUnionPredicate *Pred) { 10100 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 10101 return Rewriter.visit(S); 10102 } 10103 10104 SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 10105 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 10106 SCEVUnionPredicate *Pred) 10107 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 10108 10109 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 10110 if (Pred) { 10111 auto ExprPreds = Pred->getPredicatesForExpr(Expr); 10112 for (auto *Pred : ExprPreds) 10113 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) 10114 if (IPred->getLHS() == Expr) 10115 return IPred->getRHS(); 10116 } 10117 10118 return Expr; 10119 } 10120 10121 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 10122 const SCEV *Operand = visit(Expr->getOperand()); 10123 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 10124 if (AR && AR->getLoop() == L && AR->isAffine()) { 10125 // This couldn't be folded because the operand didn't have the nuw 10126 // flag. Add the nusw flag as an assumption that we could make. 10127 const SCEV *Step = AR->getStepRecurrence(SE); 10128 Type *Ty = Expr->getType(); 10129 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 10130 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 10131 SE.getSignExtendExpr(Step, Ty), L, 10132 AR->getNoWrapFlags()); 10133 } 10134 return SE.getZeroExtendExpr(Operand, Expr->getType()); 10135 } 10136 10137 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 10138 const SCEV *Operand = visit(Expr->getOperand()); 10139 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 10140 if (AR && AR->getLoop() == L && AR->isAffine()) { 10141 // This couldn't be folded because the operand didn't have the nsw 10142 // flag. Add the nssw flag as an assumption that we could make. 10143 const SCEV *Step = AR->getStepRecurrence(SE); 10144 Type *Ty = Expr->getType(); 10145 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 10146 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 10147 SE.getSignExtendExpr(Step, Ty), L, 10148 AR->getNoWrapFlags()); 10149 } 10150 return SE.getSignExtendExpr(Operand, Expr->getType()); 10151 } 10152 10153 private: 10154 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 10155 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 10156 auto *A = SE.getWrapPredicate(AR, AddedFlags); 10157 if (!NewPreds) { 10158 // Check if we've already made this assumption. 10159 return Pred && Pred->implies(A); 10160 } 10161 NewPreds->insert(A); 10162 return true; 10163 } 10164 10165 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 10166 SCEVUnionPredicate *Pred; 10167 const Loop *L; 10168 }; 10169 } // end anonymous namespace 10170 10171 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 10172 SCEVUnionPredicate &Preds) { 10173 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 10174 } 10175 10176 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 10177 const SCEV *S, const Loop *L, 10178 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 10179 10180 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 10181 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 10182 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 10183 10184 if (!AddRec) 10185 return nullptr; 10186 10187 // Since the transformation was successful, we can now transfer the SCEV 10188 // predicates. 10189 for (auto *P : TransformPreds) 10190 Preds.insert(P); 10191 10192 return AddRec; 10193 } 10194 10195 /// SCEV predicates 10196 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 10197 SCEVPredicateKind Kind) 10198 : FastID(ID), Kind(Kind) {} 10199 10200 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 10201 const SCEVUnknown *LHS, 10202 const SCEVConstant *RHS) 10203 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {} 10204 10205 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 10206 const auto *Op = dyn_cast<SCEVEqualPredicate>(N); 10207 10208 if (!Op) 10209 return false; 10210 10211 return Op->LHS == LHS && Op->RHS == RHS; 10212 } 10213 10214 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 10215 10216 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 10217 10218 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 10219 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 10220 } 10221 10222 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 10223 const SCEVAddRecExpr *AR, 10224 IncrementWrapFlags Flags) 10225 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 10226 10227 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 10228 10229 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 10230 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 10231 10232 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 10233 } 10234 10235 bool SCEVWrapPredicate::isAlwaysTrue() const { 10236 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 10237 IncrementWrapFlags IFlags = Flags; 10238 10239 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 10240 IFlags = clearFlags(IFlags, IncrementNSSW); 10241 10242 return IFlags == IncrementAnyWrap; 10243 } 10244 10245 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 10246 OS.indent(Depth) << *getExpr() << " Added Flags: "; 10247 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 10248 OS << "<nusw>"; 10249 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 10250 OS << "<nssw>"; 10251 OS << "\n"; 10252 } 10253 10254 SCEVWrapPredicate::IncrementWrapFlags 10255 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 10256 ScalarEvolution &SE) { 10257 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 10258 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 10259 10260 // We can safely transfer the NSW flag as NSSW. 10261 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 10262 ImpliedFlags = IncrementNSSW; 10263 10264 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 10265 // If the increment is positive, the SCEV NUW flag will also imply the 10266 // WrapPredicate NUSW flag. 10267 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 10268 if (Step->getValue()->getValue().isNonNegative()) 10269 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 10270 } 10271 10272 return ImpliedFlags; 10273 } 10274 10275 /// Union predicates don't get cached so create a dummy set ID for it. 10276 SCEVUnionPredicate::SCEVUnionPredicate() 10277 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 10278 10279 bool SCEVUnionPredicate::isAlwaysTrue() const { 10280 return all_of(Preds, 10281 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 10282 } 10283 10284 ArrayRef<const SCEVPredicate *> 10285 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 10286 auto I = SCEVToPreds.find(Expr); 10287 if (I == SCEVToPreds.end()) 10288 return ArrayRef<const SCEVPredicate *>(); 10289 return I->second; 10290 } 10291 10292 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 10293 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 10294 return all_of(Set->Preds, 10295 [this](const SCEVPredicate *I) { return this->implies(I); }); 10296 10297 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 10298 if (ScevPredsIt == SCEVToPreds.end()) 10299 return false; 10300 auto &SCEVPreds = ScevPredsIt->second; 10301 10302 return any_of(SCEVPreds, 10303 [N](const SCEVPredicate *I) { return I->implies(N); }); 10304 } 10305 10306 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 10307 10308 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 10309 for (auto Pred : Preds) 10310 Pred->print(OS, Depth); 10311 } 10312 10313 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 10314 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 10315 for (auto Pred : Set->Preds) 10316 add(Pred); 10317 return; 10318 } 10319 10320 if (implies(N)) 10321 return; 10322 10323 const SCEV *Key = N->getExpr(); 10324 assert(Key && "Only SCEVUnionPredicate doesn't have an " 10325 " associated expression!"); 10326 10327 SCEVToPreds[Key].push_back(N); 10328 Preds.push_back(N); 10329 } 10330 10331 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 10332 Loop &L) 10333 : SE(SE), L(L), Generation(0), BackedgeCount(nullptr) {} 10334 10335 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 10336 const SCEV *Expr = SE.getSCEV(V); 10337 RewriteEntry &Entry = RewriteMap[Expr]; 10338 10339 // If we already have an entry and the version matches, return it. 10340 if (Entry.second && Generation == Entry.first) 10341 return Entry.second; 10342 10343 // We found an entry but it's stale. Rewrite the stale entry 10344 // acording to the current predicate. 10345 if (Entry.second) 10346 Expr = Entry.second; 10347 10348 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 10349 Entry = {Generation, NewSCEV}; 10350 10351 return NewSCEV; 10352 } 10353 10354 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 10355 if (!BackedgeCount) { 10356 SCEVUnionPredicate BackedgePred; 10357 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); 10358 addPredicate(BackedgePred); 10359 } 10360 return BackedgeCount; 10361 } 10362 10363 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 10364 if (Preds.implies(&Pred)) 10365 return; 10366 Preds.add(&Pred); 10367 updateGeneration(); 10368 } 10369 10370 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 10371 return Preds; 10372 } 10373 10374 void PredicatedScalarEvolution::updateGeneration() { 10375 // If the generation number wrapped recompute everything. 10376 if (++Generation == 0) { 10377 for (auto &II : RewriteMap) { 10378 const SCEV *Rewritten = II.second.second; 10379 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 10380 } 10381 } 10382 } 10383 10384 void PredicatedScalarEvolution::setNoOverflow( 10385 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 10386 const SCEV *Expr = getSCEV(V); 10387 const auto *AR = cast<SCEVAddRecExpr>(Expr); 10388 10389 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 10390 10391 // Clear the statically implied flags. 10392 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 10393 addPredicate(*SE.getWrapPredicate(AR, Flags)); 10394 10395 auto II = FlagsMap.insert({V, Flags}); 10396 if (!II.second) 10397 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 10398 } 10399 10400 bool PredicatedScalarEvolution::hasNoOverflow( 10401 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 10402 const SCEV *Expr = getSCEV(V); 10403 const auto *AR = cast<SCEVAddRecExpr>(Expr); 10404 10405 Flags = SCEVWrapPredicate::clearFlags( 10406 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 10407 10408 auto II = FlagsMap.find(V); 10409 10410 if (II != FlagsMap.end()) 10411 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 10412 10413 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 10414 } 10415 10416 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 10417 const SCEV *Expr = this->getSCEV(V); 10418 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 10419 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 10420 10421 if (!New) 10422 return nullptr; 10423 10424 for (auto *P : NewPreds) 10425 Preds.add(P); 10426 10427 updateGeneration(); 10428 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 10429 return New; 10430 } 10431 10432 PredicatedScalarEvolution::PredicatedScalarEvolution( 10433 const PredicatedScalarEvolution &Init) 10434 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 10435 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 10436 for (const auto &I : Init.FlagsMap) 10437 FlagsMap.insert(I); 10438 } 10439 10440 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 10441 // For each block. 10442 for (auto *BB : L.getBlocks()) 10443 for (auto &I : *BB) { 10444 if (!SE.isSCEVable(I.getType())) 10445 continue; 10446 10447 auto *Expr = SE.getSCEV(&I); 10448 auto II = RewriteMap.find(Expr); 10449 10450 if (II == RewriteMap.end()) 10451 continue; 10452 10453 // Don't print things that are not interesting. 10454 if (II->second.second == Expr) 10455 continue; 10456 10457 OS.indent(Depth) << "[PSE]" << I << ":\n"; 10458 OS.indent(Depth + 2) << *Expr << "\n"; 10459 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 10460 } 10461 } 10462