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(GEPOperator *GEP, 3019 const SmallVectorImpl<const SCEV *> &IndexExprs) { 3020 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand()); 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 = GEP->isInBounds() ? SCEV::FlagNSW 3030 : SCEV::FlagAnyWrap; 3031 3032 const SCEV *TotalOffset = getZero(IntPtrTy); 3033 // The address space is unimportant. The first thing we do on CurTy is getting 3034 // its element type. 3035 Type *CurTy = PointerType::getUnqual(GEP->getSourceElementType()); 3036 for (const SCEV *IndexExpr : IndexExprs) { 3037 // Compute the (potentially symbolic) offset in bytes for this index. 3038 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 3039 // For a struct, add the member offset. 3040 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 3041 unsigned FieldNo = Index->getZExtValue(); 3042 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo); 3043 3044 // Add the field offset to the running total offset. 3045 TotalOffset = getAddExpr(TotalOffset, FieldOffset); 3046 3047 // Update CurTy to the type of the field at Index. 3048 CurTy = STy->getTypeAtIndex(Index); 3049 } else { 3050 // Update CurTy to its element type. 3051 CurTy = cast<SequentialType>(CurTy)->getElementType(); 3052 // For an array, add the element offset, explicitly scaled. 3053 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy); 3054 // Getelementptr indices are signed. 3055 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy); 3056 3057 // Multiply the index by the element size to compute the element offset. 3058 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap); 3059 3060 // Add the element offset to the running total offset. 3061 TotalOffset = getAddExpr(TotalOffset, LocalOffset); 3062 } 3063 } 3064 3065 // Add the total offset from all the GEP indices to the base. 3066 return getAddExpr(BaseExpr, TotalOffset, Wrap); 3067 } 3068 3069 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, 3070 const SCEV *RHS) { 3071 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3072 return getSMaxExpr(Ops); 3073 } 3074 3075 const SCEV * 3076 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3077 assert(!Ops.empty() && "Cannot get empty smax!"); 3078 if (Ops.size() == 1) return Ops[0]; 3079 #ifndef NDEBUG 3080 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3081 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3082 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3083 "SCEVSMaxExpr operand types don't match!"); 3084 #endif 3085 3086 // Sort by complexity, this groups all similar expression types together. 3087 GroupByComplexity(Ops, &LI); 3088 3089 // If there are any constants, fold them together. 3090 unsigned Idx = 0; 3091 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3092 ++Idx; 3093 assert(Idx < Ops.size()); 3094 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3095 // We found two constants, fold them together! 3096 ConstantInt *Fold = ConstantInt::get( 3097 getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt())); 3098 Ops[0] = getConstant(Fold); 3099 Ops.erase(Ops.begin()+1); // Erase the folded element 3100 if (Ops.size() == 1) return Ops[0]; 3101 LHSC = cast<SCEVConstant>(Ops[0]); 3102 } 3103 3104 // If we are left with a constant minimum-int, strip it off. 3105 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) { 3106 Ops.erase(Ops.begin()); 3107 --Idx; 3108 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) { 3109 // If we have an smax with a constant maximum-int, it will always be 3110 // maximum-int. 3111 return Ops[0]; 3112 } 3113 3114 if (Ops.size() == 1) return Ops[0]; 3115 } 3116 3117 // Find the first SMax 3118 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr) 3119 ++Idx; 3120 3121 // Check to see if one of the operands is an SMax. If so, expand its operands 3122 // onto our operand list, and recurse to simplify. 3123 if (Idx < Ops.size()) { 3124 bool DeletedSMax = false; 3125 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) { 3126 Ops.erase(Ops.begin()+Idx); 3127 Ops.append(SMax->op_begin(), SMax->op_end()); 3128 DeletedSMax = true; 3129 } 3130 3131 if (DeletedSMax) 3132 return getSMaxExpr(Ops); 3133 } 3134 3135 // Okay, check to see if the same value occurs in the operand list twice. If 3136 // so, delete one. Since we sorted the list, these values are required to 3137 // be adjacent. 3138 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 3139 // X smax Y smax Y --> X smax Y 3140 // X smax Y --> X, if X is always greater than Y 3141 if (Ops[i] == Ops[i+1] || 3142 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) { 3143 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); 3144 --i; --e; 3145 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) { 3146 Ops.erase(Ops.begin()+i, Ops.begin()+i+1); 3147 --i; --e; 3148 } 3149 3150 if (Ops.size() == 1) return Ops[0]; 3151 3152 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3153 3154 // Okay, it looks like we really DO need an smax expr. Check to see if we 3155 // already have one, otherwise create a new one. 3156 FoldingSetNodeID ID; 3157 ID.AddInteger(scSMaxExpr); 3158 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3159 ID.AddPointer(Ops[i]); 3160 void *IP = nullptr; 3161 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3162 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3163 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3164 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator), 3165 O, Ops.size()); 3166 UniqueSCEVs.InsertNode(S, IP); 3167 return S; 3168 } 3169 3170 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, 3171 const SCEV *RHS) { 3172 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3173 return getUMaxExpr(Ops); 3174 } 3175 3176 const SCEV * 3177 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3178 assert(!Ops.empty() && "Cannot get empty umax!"); 3179 if (Ops.size() == 1) return Ops[0]; 3180 #ifndef NDEBUG 3181 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3182 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3183 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3184 "SCEVUMaxExpr operand types don't match!"); 3185 #endif 3186 3187 // Sort by complexity, this groups all similar expression types together. 3188 GroupByComplexity(Ops, &LI); 3189 3190 // If there are any constants, fold them together. 3191 unsigned Idx = 0; 3192 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3193 ++Idx; 3194 assert(Idx < Ops.size()); 3195 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3196 // We found two constants, fold them together! 3197 ConstantInt *Fold = ConstantInt::get( 3198 getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt())); 3199 Ops[0] = getConstant(Fold); 3200 Ops.erase(Ops.begin()+1); // Erase the folded element 3201 if (Ops.size() == 1) return Ops[0]; 3202 LHSC = cast<SCEVConstant>(Ops[0]); 3203 } 3204 3205 // If we are left with a constant minimum-int, strip it off. 3206 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) { 3207 Ops.erase(Ops.begin()); 3208 --Idx; 3209 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) { 3210 // If we have an umax with a constant maximum-int, it will always be 3211 // maximum-int. 3212 return Ops[0]; 3213 } 3214 3215 if (Ops.size() == 1) return Ops[0]; 3216 } 3217 3218 // Find the first UMax 3219 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr) 3220 ++Idx; 3221 3222 // Check to see if one of the operands is a UMax. If so, expand its operands 3223 // onto our operand list, and recurse to simplify. 3224 if (Idx < Ops.size()) { 3225 bool DeletedUMax = false; 3226 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) { 3227 Ops.erase(Ops.begin()+Idx); 3228 Ops.append(UMax->op_begin(), UMax->op_end()); 3229 DeletedUMax = true; 3230 } 3231 3232 if (DeletedUMax) 3233 return getUMaxExpr(Ops); 3234 } 3235 3236 // Okay, check to see if the same value occurs in the operand list twice. If 3237 // so, delete one. Since we sorted the list, these values are required to 3238 // be adjacent. 3239 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 3240 // X umax Y umax Y --> X umax Y 3241 // X umax Y --> X, if X is always greater than Y 3242 if (Ops[i] == Ops[i+1] || 3243 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) { 3244 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); 3245 --i; --e; 3246 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) { 3247 Ops.erase(Ops.begin()+i, Ops.begin()+i+1); 3248 --i; --e; 3249 } 3250 3251 if (Ops.size() == 1) return Ops[0]; 3252 3253 assert(!Ops.empty() && "Reduced umax down to nothing!"); 3254 3255 // Okay, it looks like we really DO need a umax expr. Check to see if we 3256 // already have one, otherwise create a new one. 3257 FoldingSetNodeID ID; 3258 ID.AddInteger(scUMaxExpr); 3259 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3260 ID.AddPointer(Ops[i]); 3261 void *IP = nullptr; 3262 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3263 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3264 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3265 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator), 3266 O, Ops.size()); 3267 UniqueSCEVs.InsertNode(S, IP); 3268 return S; 3269 } 3270 3271 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 3272 const SCEV *RHS) { 3273 // ~smax(~x, ~y) == smin(x, y). 3274 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS))); 3275 } 3276 3277 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, 3278 const SCEV *RHS) { 3279 // ~umax(~x, ~y) == umin(x, y) 3280 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS))); 3281 } 3282 3283 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 3284 // We can bypass creating a target-independent 3285 // constant expression and then folding it back into a ConstantInt. 3286 // This is just a compile-time optimization. 3287 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 3288 } 3289 3290 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 3291 StructType *STy, 3292 unsigned FieldNo) { 3293 // We can bypass creating a target-independent 3294 // constant expression and then folding it back into a ConstantInt. 3295 // This is just a compile-time optimization. 3296 return getConstant( 3297 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 3298 } 3299 3300 const SCEV *ScalarEvolution::getUnknown(Value *V) { 3301 // Don't attempt to do anything other than create a SCEVUnknown object 3302 // here. createSCEV only calls getUnknown after checking for all other 3303 // interesting possibilities, and any other code that calls getUnknown 3304 // is doing so in order to hide a value from SCEV canonicalization. 3305 3306 FoldingSetNodeID ID; 3307 ID.AddInteger(scUnknown); 3308 ID.AddPointer(V); 3309 void *IP = nullptr; 3310 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 3311 assert(cast<SCEVUnknown>(S)->getValue() == V && 3312 "Stale SCEVUnknown in uniquing map!"); 3313 return S; 3314 } 3315 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 3316 FirstUnknown); 3317 FirstUnknown = cast<SCEVUnknown>(S); 3318 UniqueSCEVs.InsertNode(S, IP); 3319 return S; 3320 } 3321 3322 //===----------------------------------------------------------------------===// 3323 // Basic SCEV Analysis and PHI Idiom Recognition Code 3324 // 3325 3326 /// Test if values of the given type are analyzable within the SCEV 3327 /// framework. This primarily includes integer types, and it can optionally 3328 /// include pointer types if the ScalarEvolution class has access to 3329 /// target-specific information. 3330 bool ScalarEvolution::isSCEVable(Type *Ty) const { 3331 // Integers and pointers are always SCEVable. 3332 return Ty->isIntegerTy() || Ty->isPointerTy(); 3333 } 3334 3335 /// Return the size in bits of the specified type, for which isSCEVable must 3336 /// return true. 3337 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 3338 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3339 return getDataLayout().getTypeSizeInBits(Ty); 3340 } 3341 3342 /// Return a type with the same bitwidth as the given type and which represents 3343 /// how SCEV will treat the given type, for which isSCEVable must return 3344 /// true. For pointer types, this is the pointer-sized integer type. 3345 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 3346 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3347 3348 if (Ty->isIntegerTy()) 3349 return Ty; 3350 3351 // The only other support type is pointer. 3352 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 3353 return getDataLayout().getIntPtrType(Ty); 3354 } 3355 3356 const SCEV *ScalarEvolution::getCouldNotCompute() { 3357 return CouldNotCompute.get(); 3358 } 3359 3360 bool ScalarEvolution::checkValidity(const SCEV *S) const { 3361 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) { 3362 auto *SU = dyn_cast<SCEVUnknown>(S); 3363 return SU && SU->getValue() == nullptr; 3364 }); 3365 3366 return !ContainsNulls; 3367 } 3368 3369 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 3370 HasRecMapType::iterator I = HasRecMap.find(S); 3371 if (I != HasRecMap.end()) 3372 return I->second; 3373 3374 bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>); 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, IndexExprs); 4378 } 4379 4380 uint32_t 4381 ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 4382 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 4383 return C->getAPInt().countTrailingZeros(); 4384 4385 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 4386 return std::min(GetMinTrailingZeros(T->getOperand()), 4387 (uint32_t)getTypeSizeInBits(T->getType())); 4388 4389 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 4390 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 4391 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ? 4392 getTypeSizeInBits(E->getType()) : OpRes; 4393 } 4394 4395 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 4396 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 4397 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ? 4398 getTypeSizeInBits(E->getType()) : OpRes; 4399 } 4400 4401 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 4402 // The result is the min of all operands results. 4403 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 4404 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 4405 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 4406 return MinOpRes; 4407 } 4408 4409 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 4410 // The result is the sum of all operands results. 4411 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 4412 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 4413 for (unsigned i = 1, e = M->getNumOperands(); 4414 SumOpRes != BitWidth && i != e; ++i) 4415 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), 4416 BitWidth); 4417 return SumOpRes; 4418 } 4419 4420 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 4421 // The result is the min of all operands results. 4422 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 4423 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 4424 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 4425 return MinOpRes; 4426 } 4427 4428 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 4429 // The result is the min of all operands results. 4430 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 4431 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 4432 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 4433 return MinOpRes; 4434 } 4435 4436 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 4437 // The result is the min of all operands results. 4438 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 4439 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 4440 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 4441 return MinOpRes; 4442 } 4443 4444 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 4445 // For a SCEVUnknown, ask ValueTracking. 4446 unsigned BitWidth = getTypeSizeInBits(U->getType()); 4447 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0); 4448 computeKnownBits(U->getValue(), Zeros, Ones, getDataLayout(), 0, &AC, 4449 nullptr, &DT); 4450 return Zeros.countTrailingOnes(); 4451 } 4452 4453 // SCEVUDivExpr 4454 return 0; 4455 } 4456 4457 /// Helper method to assign a range to V from metadata present in the IR. 4458 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 4459 if (Instruction *I = dyn_cast<Instruction>(V)) 4460 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 4461 return getConstantRangeFromMetadata(*MD); 4462 4463 return None; 4464 } 4465 4466 /// Determine the range for a particular SCEV. If SignHint is 4467 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 4468 /// with a "cleaner" unsigned (resp. signed) representation. 4469 ConstantRange 4470 ScalarEvolution::getRange(const SCEV *S, 4471 ScalarEvolution::RangeSignHint SignHint) { 4472 DenseMap<const SCEV *, ConstantRange> &Cache = 4473 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 4474 : SignedRanges; 4475 4476 // See if we've computed this range already. 4477 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 4478 if (I != Cache.end()) 4479 return I->second; 4480 4481 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 4482 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 4483 4484 unsigned BitWidth = getTypeSizeInBits(S->getType()); 4485 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 4486 4487 // If the value has known zeros, the maximum value will have those known zeros 4488 // as well. 4489 uint32_t TZ = GetMinTrailingZeros(S); 4490 if (TZ != 0) { 4491 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 4492 ConservativeResult = 4493 ConstantRange(APInt::getMinValue(BitWidth), 4494 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 4495 else 4496 ConservativeResult = ConstantRange( 4497 APInt::getSignedMinValue(BitWidth), 4498 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 4499 } 4500 4501 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 4502 ConstantRange X = getRange(Add->getOperand(0), SignHint); 4503 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 4504 X = X.add(getRange(Add->getOperand(i), SignHint)); 4505 return setRange(Add, SignHint, ConservativeResult.intersectWith(X)); 4506 } 4507 4508 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 4509 ConstantRange X = getRange(Mul->getOperand(0), SignHint); 4510 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 4511 X = X.multiply(getRange(Mul->getOperand(i), SignHint)); 4512 return setRange(Mul, SignHint, ConservativeResult.intersectWith(X)); 4513 } 4514 4515 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 4516 ConstantRange X = getRange(SMax->getOperand(0), SignHint); 4517 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 4518 X = X.smax(getRange(SMax->getOperand(i), SignHint)); 4519 return setRange(SMax, SignHint, ConservativeResult.intersectWith(X)); 4520 } 4521 4522 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 4523 ConstantRange X = getRange(UMax->getOperand(0), SignHint); 4524 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 4525 X = X.umax(getRange(UMax->getOperand(i), SignHint)); 4526 return setRange(UMax, SignHint, ConservativeResult.intersectWith(X)); 4527 } 4528 4529 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 4530 ConstantRange X = getRange(UDiv->getLHS(), SignHint); 4531 ConstantRange Y = getRange(UDiv->getRHS(), SignHint); 4532 return setRange(UDiv, SignHint, 4533 ConservativeResult.intersectWith(X.udiv(Y))); 4534 } 4535 4536 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 4537 ConstantRange X = getRange(ZExt->getOperand(), SignHint); 4538 return setRange(ZExt, SignHint, 4539 ConservativeResult.intersectWith(X.zeroExtend(BitWidth))); 4540 } 4541 4542 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 4543 ConstantRange X = getRange(SExt->getOperand(), SignHint); 4544 return setRange(SExt, SignHint, 4545 ConservativeResult.intersectWith(X.signExtend(BitWidth))); 4546 } 4547 4548 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 4549 ConstantRange X = getRange(Trunc->getOperand(), SignHint); 4550 return setRange(Trunc, SignHint, 4551 ConservativeResult.intersectWith(X.truncate(BitWidth))); 4552 } 4553 4554 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 4555 // If there's no unsigned wrap, the value will never be less than its 4556 // initial value. 4557 if (AddRec->hasNoUnsignedWrap()) 4558 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart())) 4559 if (!C->getValue()->isZero()) 4560 ConservativeResult = ConservativeResult.intersectWith( 4561 ConstantRange(C->getAPInt(), APInt(BitWidth, 0))); 4562 4563 // If there's no signed wrap, and all the operands have the same sign or 4564 // zero, the value won't ever change sign. 4565 if (AddRec->hasNoSignedWrap()) { 4566 bool AllNonNeg = true; 4567 bool AllNonPos = true; 4568 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 4569 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false; 4570 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false; 4571 } 4572 if (AllNonNeg) 4573 ConservativeResult = ConservativeResult.intersectWith( 4574 ConstantRange(APInt(BitWidth, 0), 4575 APInt::getSignedMinValue(BitWidth))); 4576 else if (AllNonPos) 4577 ConservativeResult = ConservativeResult.intersectWith( 4578 ConstantRange(APInt::getSignedMinValue(BitWidth), 4579 APInt(BitWidth, 1))); 4580 } 4581 4582 // TODO: non-affine addrec 4583 if (AddRec->isAffine()) { 4584 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop()); 4585 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 4586 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 4587 auto RangeFromAffine = getRangeForAffineAR( 4588 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 4589 BitWidth); 4590 if (!RangeFromAffine.isFullSet()) 4591 ConservativeResult = 4592 ConservativeResult.intersectWith(RangeFromAffine); 4593 4594 auto RangeFromFactoring = getRangeViaFactoring( 4595 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 4596 BitWidth); 4597 if (!RangeFromFactoring.isFullSet()) 4598 ConservativeResult = 4599 ConservativeResult.intersectWith(RangeFromFactoring); 4600 } 4601 } 4602 4603 return setRange(AddRec, SignHint, ConservativeResult); 4604 } 4605 4606 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 4607 // Check if the IR explicitly contains !range metadata. 4608 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 4609 if (MDRange.hasValue()) 4610 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue()); 4611 4612 // Split here to avoid paying the compile-time cost of calling both 4613 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted 4614 // if needed. 4615 const DataLayout &DL = getDataLayout(); 4616 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) { 4617 // For a SCEVUnknown, ask ValueTracking. 4618 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0); 4619 computeKnownBits(U->getValue(), Zeros, Ones, DL, 0, &AC, nullptr, &DT); 4620 if (Ones != ~Zeros + 1) 4621 ConservativeResult = 4622 ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1)); 4623 } else { 4624 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED && 4625 "generalize as needed!"); 4626 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 4627 if (NS > 1) 4628 ConservativeResult = ConservativeResult.intersectWith( 4629 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 4630 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1)); 4631 } 4632 4633 return setRange(U, SignHint, ConservativeResult); 4634 } 4635 4636 return setRange(S, SignHint, ConservativeResult); 4637 } 4638 4639 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 4640 const SCEV *Step, 4641 const SCEV *MaxBECount, 4642 unsigned BitWidth) { 4643 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 4644 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 4645 "Precondition!"); 4646 4647 ConstantRange Result(BitWidth, /* isFullSet = */ true); 4648 4649 // Check for overflow. This must be done with ConstantRange arithmetic 4650 // because we could be called from within the ScalarEvolution overflow 4651 // checking code. 4652 4653 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 4654 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount); 4655 ConstantRange ZExtMaxBECountRange = 4656 MaxBECountRange.zextOrTrunc(BitWidth * 2 + 1); 4657 4658 ConstantRange StepSRange = getSignedRange(Step); 4659 ConstantRange SExtStepSRange = StepSRange.sextOrTrunc(BitWidth * 2 + 1); 4660 4661 ConstantRange StartURange = getUnsignedRange(Start); 4662 ConstantRange EndURange = 4663 StartURange.add(MaxBECountRange.multiply(StepSRange)); 4664 4665 // Check for unsigned overflow. 4666 ConstantRange ZExtStartURange = StartURange.zextOrTrunc(BitWidth * 2 + 1); 4667 ConstantRange ZExtEndURange = EndURange.zextOrTrunc(BitWidth * 2 + 1); 4668 if (ZExtStartURange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) == 4669 ZExtEndURange) { 4670 APInt Min = APIntOps::umin(StartURange.getUnsignedMin(), 4671 EndURange.getUnsignedMin()); 4672 APInt Max = APIntOps::umax(StartURange.getUnsignedMax(), 4673 EndURange.getUnsignedMax()); 4674 bool IsFullRange = Min.isMinValue() && Max.isMaxValue(); 4675 if (!IsFullRange) 4676 Result = 4677 Result.intersectWith(ConstantRange(Min, Max + 1)); 4678 } 4679 4680 ConstantRange StartSRange = getSignedRange(Start); 4681 ConstantRange EndSRange = 4682 StartSRange.add(MaxBECountRange.multiply(StepSRange)); 4683 4684 // Check for signed overflow. This must be done with ConstantRange 4685 // arithmetic because we could be called from within the ScalarEvolution 4686 // overflow checking code. 4687 ConstantRange SExtStartSRange = StartSRange.sextOrTrunc(BitWidth * 2 + 1); 4688 ConstantRange SExtEndSRange = EndSRange.sextOrTrunc(BitWidth * 2 + 1); 4689 if (SExtStartSRange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) == 4690 SExtEndSRange) { 4691 APInt Min = 4692 APIntOps::smin(StartSRange.getSignedMin(), EndSRange.getSignedMin()); 4693 APInt Max = 4694 APIntOps::smax(StartSRange.getSignedMax(), EndSRange.getSignedMax()); 4695 bool IsFullRange = Min.isMinSignedValue() && Max.isMaxSignedValue(); 4696 if (!IsFullRange) 4697 Result = 4698 Result.intersectWith(ConstantRange(Min, Max + 1)); 4699 } 4700 4701 return Result; 4702 } 4703 4704 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 4705 const SCEV *Step, 4706 const SCEV *MaxBECount, 4707 unsigned BitWidth) { 4708 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 4709 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 4710 4711 struct SelectPattern { 4712 Value *Condition = nullptr; 4713 APInt TrueValue; 4714 APInt FalseValue; 4715 4716 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 4717 const SCEV *S) { 4718 Optional<unsigned> CastOp; 4719 APInt Offset(BitWidth, 0); 4720 4721 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 4722 "Should be!"); 4723 4724 // Peel off a constant offset: 4725 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 4726 // In the future we could consider being smarter here and handle 4727 // {Start+Step,+,Step} too. 4728 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 4729 return; 4730 4731 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 4732 S = SA->getOperand(1); 4733 } 4734 4735 // Peel off a cast operation 4736 if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) { 4737 CastOp = SCast->getSCEVType(); 4738 S = SCast->getOperand(); 4739 } 4740 4741 using namespace llvm::PatternMatch; 4742 4743 auto *SU = dyn_cast<SCEVUnknown>(S); 4744 const APInt *TrueVal, *FalseVal; 4745 if (!SU || 4746 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 4747 m_APInt(FalseVal)))) { 4748 Condition = nullptr; 4749 return; 4750 } 4751 4752 TrueValue = *TrueVal; 4753 FalseValue = *FalseVal; 4754 4755 // Re-apply the cast we peeled off earlier 4756 if (CastOp.hasValue()) 4757 switch (*CastOp) { 4758 default: 4759 llvm_unreachable("Unknown SCEV cast type!"); 4760 4761 case scTruncate: 4762 TrueValue = TrueValue.trunc(BitWidth); 4763 FalseValue = FalseValue.trunc(BitWidth); 4764 break; 4765 case scZeroExtend: 4766 TrueValue = TrueValue.zext(BitWidth); 4767 FalseValue = FalseValue.zext(BitWidth); 4768 break; 4769 case scSignExtend: 4770 TrueValue = TrueValue.sext(BitWidth); 4771 FalseValue = FalseValue.sext(BitWidth); 4772 break; 4773 } 4774 4775 // Re-apply the constant offset we peeled off earlier 4776 TrueValue += Offset; 4777 FalseValue += Offset; 4778 } 4779 4780 bool isRecognized() { return Condition != nullptr; } 4781 }; 4782 4783 SelectPattern StartPattern(*this, BitWidth, Start); 4784 if (!StartPattern.isRecognized()) 4785 return ConstantRange(BitWidth, /* isFullSet = */ true); 4786 4787 SelectPattern StepPattern(*this, BitWidth, Step); 4788 if (!StepPattern.isRecognized()) 4789 return ConstantRange(BitWidth, /* isFullSet = */ true); 4790 4791 if (StartPattern.Condition != StepPattern.Condition) { 4792 // We don't handle this case today; but we could, by considering four 4793 // possibilities below instead of two. I'm not sure if there are cases where 4794 // that will help over what getRange already does, though. 4795 return ConstantRange(BitWidth, /* isFullSet = */ true); 4796 } 4797 4798 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 4799 // construct arbitrary general SCEV expressions here. This function is called 4800 // from deep in the call stack, and calling getSCEV (on a sext instruction, 4801 // say) can end up caching a suboptimal value. 4802 4803 // FIXME: without the explicit `this` receiver below, MSVC errors out with 4804 // C2352 and C2512 (otherwise it isn't needed). 4805 4806 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 4807 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 4808 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 4809 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 4810 4811 ConstantRange TrueRange = 4812 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 4813 ConstantRange FalseRange = 4814 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 4815 4816 return TrueRange.unionWith(FalseRange); 4817 } 4818 4819 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 4820 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 4821 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 4822 4823 // Return early if there are no flags to propagate to the SCEV. 4824 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 4825 if (BinOp->hasNoUnsignedWrap()) 4826 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 4827 if (BinOp->hasNoSignedWrap()) 4828 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 4829 if (Flags == SCEV::FlagAnyWrap) 4830 return SCEV::FlagAnyWrap; 4831 4832 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 4833 } 4834 4835 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 4836 // Here we check that I is in the header of the innermost loop containing I, 4837 // since we only deal with instructions in the loop header. The actual loop we 4838 // need to check later will come from an add recurrence, but getting that 4839 // requires computing the SCEV of the operands, which can be expensive. This 4840 // check we can do cheaply to rule out some cases early. 4841 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent()); 4842 if (InnermostContainingLoop == nullptr || 4843 InnermostContainingLoop->getHeader() != I->getParent()) 4844 return false; 4845 4846 // Only proceed if we can prove that I does not yield poison. 4847 if (!isKnownNotFullPoison(I)) return false; 4848 4849 // At this point we know that if I is executed, then it does not wrap 4850 // according to at least one of NSW or NUW. If I is not executed, then we do 4851 // not know if the calculation that I represents would wrap. Multiple 4852 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 4853 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 4854 // derived from other instructions that map to the same SCEV. We cannot make 4855 // that guarantee for cases where I is not executed. So we need to find the 4856 // loop that I is considered in relation to and prove that I is executed for 4857 // every iteration of that loop. That implies that the value that I 4858 // calculates does not wrap anywhere in the loop, so then we can apply the 4859 // flags to the SCEV. 4860 // 4861 // We check isLoopInvariant to disambiguate in case we are adding recurrences 4862 // from different loops, so that we know which loop to prove that I is 4863 // executed in. 4864 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) { 4865 // I could be an extractvalue from a call to an overflow intrinsic. 4866 // TODO: We can do better here in some cases. 4867 if (!isSCEVable(I->getOperand(OpIndex)->getType())) 4868 return false; 4869 const SCEV *Op = getSCEV(I->getOperand(OpIndex)); 4870 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 4871 bool AllOtherOpsLoopInvariant = true; 4872 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands(); 4873 ++OtherOpIndex) { 4874 if (OtherOpIndex != OpIndex) { 4875 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex)); 4876 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) { 4877 AllOtherOpsLoopInvariant = false; 4878 break; 4879 } 4880 } 4881 } 4882 if (AllOtherOpsLoopInvariant && 4883 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop())) 4884 return true; 4885 } 4886 } 4887 return false; 4888 } 4889 4890 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 4891 // If we know that \c I can never be poison period, then that's enough. 4892 if (isSCEVExprNeverPoison(I)) 4893 return true; 4894 4895 // For an add recurrence specifically, we assume that infinite loops without 4896 // side effects are undefined behavior, and then reason as follows: 4897 // 4898 // If the add recurrence is poison in any iteration, it is poison on all 4899 // future iterations (since incrementing poison yields poison). If the result 4900 // of the add recurrence is fed into the loop latch condition and the loop 4901 // does not contain any throws or exiting blocks other than the latch, we now 4902 // have the ability to "choose" whether the backedge is taken or not (by 4903 // choosing a sufficiently evil value for the poison feeding into the branch) 4904 // for every iteration including and after the one in which \p I first became 4905 // poison. There are two possibilities (let's call the iteration in which \p 4906 // I first became poison as K): 4907 // 4908 // 1. In the set of iterations including and after K, the loop body executes 4909 // no side effects. In this case executing the backege an infinte number 4910 // of times will yield undefined behavior. 4911 // 4912 // 2. In the set of iterations including and after K, the loop body executes 4913 // at least one side effect. In this case, that specific instance of side 4914 // effect is control dependent on poison, which also yields undefined 4915 // behavior. 4916 4917 auto *ExitingBB = L->getExitingBlock(); 4918 auto *LatchBB = L->getLoopLatch(); 4919 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 4920 return false; 4921 4922 SmallPtrSet<const Instruction *, 16> Pushed; 4923 SmallVector<const Instruction *, 8> PoisonStack; 4924 4925 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 4926 // things that are known to be fully poison under that assumption go on the 4927 // PoisonStack. 4928 Pushed.insert(I); 4929 PoisonStack.push_back(I); 4930 4931 bool LatchControlDependentOnPoison = false; 4932 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 4933 const Instruction *Poison = PoisonStack.pop_back_val(); 4934 4935 for (auto *PoisonUser : Poison->users()) { 4936 if (propagatesFullPoison(cast<Instruction>(PoisonUser))) { 4937 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 4938 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 4939 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 4940 assert(BI->isConditional() && "Only possibility!"); 4941 if (BI->getParent() == LatchBB) { 4942 LatchControlDependentOnPoison = true; 4943 break; 4944 } 4945 } 4946 } 4947 } 4948 4949 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 4950 } 4951 4952 ScalarEvolution::LoopProperties 4953 ScalarEvolution::getLoopProperties(const Loop *L) { 4954 typedef ScalarEvolution::LoopProperties LoopProperties; 4955 4956 auto Itr = LoopPropertiesCache.find(L); 4957 if (Itr == LoopPropertiesCache.end()) { 4958 auto HasSideEffects = [](Instruction *I) { 4959 if (auto *SI = dyn_cast<StoreInst>(I)) 4960 return !SI->isSimple(); 4961 4962 return I->mayHaveSideEffects(); 4963 }; 4964 4965 LoopProperties LP = {/* HasNoAbnormalExits */ true, 4966 /*HasNoSideEffects*/ true}; 4967 4968 for (auto *BB : L->getBlocks()) 4969 for (auto &I : *BB) { 4970 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 4971 LP.HasNoAbnormalExits = false; 4972 if (HasSideEffects(&I)) 4973 LP.HasNoSideEffects = false; 4974 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 4975 break; // We're already as pessimistic as we can get. 4976 } 4977 4978 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 4979 assert(InsertPair.second && "We just checked!"); 4980 Itr = InsertPair.first; 4981 } 4982 4983 return Itr->second; 4984 } 4985 4986 const SCEV *ScalarEvolution::createSCEV(Value *V) { 4987 if (!isSCEVable(V->getType())) 4988 return getUnknown(V); 4989 4990 if (Instruction *I = dyn_cast<Instruction>(V)) { 4991 // Don't attempt to analyze instructions in blocks that aren't 4992 // reachable. Such instructions don't matter, and they aren't required 4993 // to obey basic rules for definitions dominating uses which this 4994 // analysis depends on. 4995 if (!DT.isReachableFromEntry(I->getParent())) 4996 return getUnknown(V); 4997 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 4998 return getConstant(CI); 4999 else if (isa<ConstantPointerNull>(V)) 5000 return getZero(V->getType()); 5001 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 5002 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 5003 else if (!isa<ConstantExpr>(V)) 5004 return getUnknown(V); 5005 5006 Operator *U = cast<Operator>(V); 5007 if (auto BO = MatchBinaryOp(U, DT)) { 5008 switch (BO->Opcode) { 5009 case Instruction::Add: { 5010 // The simple thing to do would be to just call getSCEV on both operands 5011 // and call getAddExpr with the result. However if we're looking at a 5012 // bunch of things all added together, this can be quite inefficient, 5013 // because it leads to N-1 getAddExpr calls for N ultimate operands. 5014 // Instead, gather up all the operands and make a single getAddExpr call. 5015 // LLVM IR canonical form means we need only traverse the left operands. 5016 SmallVector<const SCEV *, 4> AddOps; 5017 do { 5018 if (BO->Op) { 5019 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 5020 AddOps.push_back(OpSCEV); 5021 break; 5022 } 5023 5024 // If a NUW or NSW flag can be applied to the SCEV for this 5025 // addition, then compute the SCEV for this addition by itself 5026 // with a separate call to getAddExpr. We need to do that 5027 // instead of pushing the operands of the addition onto AddOps, 5028 // since the flags are only known to apply to this particular 5029 // addition - they may not apply to other additions that can be 5030 // formed with operands from AddOps. 5031 const SCEV *RHS = getSCEV(BO->RHS); 5032 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 5033 if (Flags != SCEV::FlagAnyWrap) { 5034 const SCEV *LHS = getSCEV(BO->LHS); 5035 if (BO->Opcode == Instruction::Sub) 5036 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 5037 else 5038 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 5039 break; 5040 } 5041 } 5042 5043 if (BO->Opcode == Instruction::Sub) 5044 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 5045 else 5046 AddOps.push_back(getSCEV(BO->RHS)); 5047 5048 auto NewBO = MatchBinaryOp(BO->LHS, DT); 5049 if (!NewBO || (NewBO->Opcode != Instruction::Add && 5050 NewBO->Opcode != Instruction::Sub)) { 5051 AddOps.push_back(getSCEV(BO->LHS)); 5052 break; 5053 } 5054 BO = NewBO; 5055 } while (true); 5056 5057 return getAddExpr(AddOps); 5058 } 5059 5060 case Instruction::Mul: { 5061 SmallVector<const SCEV *, 4> MulOps; 5062 do { 5063 if (BO->Op) { 5064 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 5065 MulOps.push_back(OpSCEV); 5066 break; 5067 } 5068 5069 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 5070 if (Flags != SCEV::FlagAnyWrap) { 5071 MulOps.push_back( 5072 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 5073 break; 5074 } 5075 } 5076 5077 MulOps.push_back(getSCEV(BO->RHS)); 5078 auto NewBO = MatchBinaryOp(BO->LHS, DT); 5079 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 5080 MulOps.push_back(getSCEV(BO->LHS)); 5081 break; 5082 } 5083 BO = NewBO; 5084 } while (true); 5085 5086 return getMulExpr(MulOps); 5087 } 5088 case Instruction::UDiv: 5089 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 5090 case Instruction::Sub: { 5091 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5092 if (BO->Op) 5093 Flags = getNoWrapFlagsFromUB(BO->Op); 5094 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 5095 } 5096 case Instruction::And: 5097 // For an expression like x&255 that merely masks off the high bits, 5098 // use zext(trunc(x)) as the SCEV expression. 5099 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 5100 if (CI->isNullValue()) 5101 return getSCEV(BO->RHS); 5102 if (CI->isAllOnesValue()) 5103 return getSCEV(BO->LHS); 5104 const APInt &A = CI->getValue(); 5105 5106 // Instcombine's ShrinkDemandedConstant may strip bits out of 5107 // constants, obscuring what would otherwise be a low-bits mask. 5108 // Use computeKnownBits to compute what ShrinkDemandedConstant 5109 // knew about to reconstruct a low-bits mask value. 5110 unsigned LZ = A.countLeadingZeros(); 5111 unsigned TZ = A.countTrailingZeros(); 5112 unsigned BitWidth = A.getBitWidth(); 5113 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0); 5114 computeKnownBits(BO->LHS, KnownZero, KnownOne, getDataLayout(), 5115 0, &AC, nullptr, &DT); 5116 5117 APInt EffectiveMask = 5118 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 5119 if ((LZ != 0 || TZ != 0) && !((~A & ~KnownZero) & EffectiveMask)) { 5120 const SCEV *MulCount = getConstant(ConstantInt::get( 5121 getContext(), APInt::getOneBitSet(BitWidth, TZ))); 5122 return getMulExpr( 5123 getZeroExtendExpr( 5124 getTruncateExpr( 5125 getUDivExactExpr(getSCEV(BO->LHS), MulCount), 5126 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 5127 BO->LHS->getType()), 5128 MulCount); 5129 } 5130 } 5131 break; 5132 5133 case Instruction::Or: 5134 // If the RHS of the Or is a constant, we may have something like: 5135 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 5136 // optimizations will transparently handle this case. 5137 // 5138 // In order for this transformation to be safe, the LHS must be of the 5139 // form X*(2^n) and the Or constant must be less than 2^n. 5140 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 5141 const SCEV *LHS = getSCEV(BO->LHS); 5142 const APInt &CIVal = CI->getValue(); 5143 if (GetMinTrailingZeros(LHS) >= 5144 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 5145 // Build a plain add SCEV. 5146 const SCEV *S = getAddExpr(LHS, getSCEV(CI)); 5147 // If the LHS of the add was an addrec and it has no-wrap flags, 5148 // transfer the no-wrap flags, since an or won't introduce a wrap. 5149 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) { 5150 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS); 5151 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags( 5152 OldAR->getNoWrapFlags()); 5153 } 5154 return S; 5155 } 5156 } 5157 break; 5158 5159 case Instruction::Xor: 5160 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 5161 // If the RHS of xor is -1, then this is a not operation. 5162 if (CI->isAllOnesValue()) 5163 return getNotSCEV(getSCEV(BO->LHS)); 5164 5165 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 5166 // This is a variant of the check for xor with -1, and it handles 5167 // the case where instcombine has trimmed non-demanded bits out 5168 // of an xor with -1. 5169 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 5170 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 5171 if (LBO->getOpcode() == Instruction::And && 5172 LCI->getValue() == CI->getValue()) 5173 if (const SCEVZeroExtendExpr *Z = 5174 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 5175 Type *UTy = BO->LHS->getType(); 5176 const SCEV *Z0 = Z->getOperand(); 5177 Type *Z0Ty = Z0->getType(); 5178 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 5179 5180 // If C is a low-bits mask, the zero extend is serving to 5181 // mask off the high bits. Complement the operand and 5182 // re-apply the zext. 5183 if (APIntOps::isMask(Z0TySize, CI->getValue())) 5184 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 5185 5186 // If C is a single bit, it may be in the sign-bit position 5187 // before the zero-extend. In this case, represent the xor 5188 // using an add, which is equivalent, and re-apply the zext. 5189 APInt Trunc = CI->getValue().trunc(Z0TySize); 5190 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 5191 Trunc.isSignBit()) 5192 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 5193 UTy); 5194 } 5195 } 5196 break; 5197 5198 case Instruction::Shl: 5199 // Turn shift left of a constant amount into a multiply. 5200 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 5201 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 5202 5203 // If the shift count is not less than the bitwidth, the result of 5204 // the shift is undefined. Don't try to analyze it, because the 5205 // resolution chosen here may differ from the resolution chosen in 5206 // other parts of the compiler. 5207 if (SA->getValue().uge(BitWidth)) 5208 break; 5209 5210 // It is currently not resolved how to interpret NSW for left 5211 // shift by BitWidth - 1, so we avoid applying flags in that 5212 // case. Remove this check (or this comment) once the situation 5213 // is resolved. See 5214 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html 5215 // and http://reviews.llvm.org/D8890 . 5216 auto Flags = SCEV::FlagAnyWrap; 5217 if (BO->Op && SA->getValue().ult(BitWidth - 1)) 5218 Flags = getNoWrapFlagsFromUB(BO->Op); 5219 5220 Constant *X = ConstantInt::get(getContext(), 5221 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 5222 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 5223 } 5224 break; 5225 5226 case Instruction::AShr: 5227 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression. 5228 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) 5229 if (Operator *L = dyn_cast<Operator>(BO->LHS)) 5230 if (L->getOpcode() == Instruction::Shl && 5231 L->getOperand(1) == BO->RHS) { 5232 uint64_t BitWidth = getTypeSizeInBits(BO->LHS->getType()); 5233 5234 // If the shift count is not less than the bitwidth, the result of 5235 // the shift is undefined. Don't try to analyze it, because the 5236 // resolution chosen here may differ from the resolution chosen in 5237 // other parts of the compiler. 5238 if (CI->getValue().uge(BitWidth)) 5239 break; 5240 5241 uint64_t Amt = BitWidth - CI->getZExtValue(); 5242 if (Amt == BitWidth) 5243 return getSCEV(L->getOperand(0)); // shift by zero --> noop 5244 return getSignExtendExpr( 5245 getTruncateExpr(getSCEV(L->getOperand(0)), 5246 IntegerType::get(getContext(), Amt)), 5247 BO->LHS->getType()); 5248 } 5249 break; 5250 } 5251 } 5252 5253 switch (U->getOpcode()) { 5254 case Instruction::Trunc: 5255 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 5256 5257 case Instruction::ZExt: 5258 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 5259 5260 case Instruction::SExt: 5261 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 5262 5263 case Instruction::BitCast: 5264 // BitCasts are no-op casts so we just eliminate the cast. 5265 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 5266 return getSCEV(U->getOperand(0)); 5267 break; 5268 5269 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can 5270 // lead to pointer expressions which cannot safely be expanded to GEPs, 5271 // because ScalarEvolution doesn't respect the GEP aliasing rules when 5272 // simplifying integer expressions. 5273 5274 case Instruction::GetElementPtr: 5275 return createNodeForGEP(cast<GEPOperator>(U)); 5276 5277 case Instruction::PHI: 5278 return createNodeForPHI(cast<PHINode>(U)); 5279 5280 case Instruction::Select: 5281 // U can also be a select constant expr, which let fall through. Since 5282 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 5283 // constant expressions cannot have instructions as operands, we'd have 5284 // returned getUnknown for a select constant expressions anyway. 5285 if (isa<Instruction>(U)) 5286 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 5287 U->getOperand(1), U->getOperand(2)); 5288 break; 5289 5290 case Instruction::Call: 5291 case Instruction::Invoke: 5292 if (Value *RV = CallSite(U).getReturnedArgOperand()) 5293 return getSCEV(RV); 5294 break; 5295 } 5296 5297 return getUnknown(V); 5298 } 5299 5300 5301 5302 //===----------------------------------------------------------------------===// 5303 // Iteration Count Computation Code 5304 // 5305 5306 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 5307 if (!ExitCount) 5308 return 0; 5309 5310 ConstantInt *ExitConst = ExitCount->getValue(); 5311 5312 // Guard against huge trip counts. 5313 if (ExitConst->getValue().getActiveBits() > 32) 5314 return 0; 5315 5316 // In case of integer overflow, this returns 0, which is correct. 5317 return ((unsigned)ExitConst->getZExtValue()) + 1; 5318 } 5319 5320 unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L) { 5321 if (BasicBlock *ExitingBB = L->getExitingBlock()) 5322 return getSmallConstantTripCount(L, ExitingBB); 5323 5324 // No trip count information for multiple exits. 5325 return 0; 5326 } 5327 5328 unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L, 5329 BasicBlock *ExitingBlock) { 5330 assert(ExitingBlock && "Must pass a non-null exiting block!"); 5331 assert(L->isLoopExiting(ExitingBlock) && 5332 "Exiting block must actually branch out of the loop!"); 5333 const SCEVConstant *ExitCount = 5334 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 5335 return getConstantTripCount(ExitCount); 5336 } 5337 5338 unsigned ScalarEvolution::getSmallConstantMaxTripCount(Loop *L) { 5339 const auto *MaxExitCount = 5340 dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L)); 5341 return getConstantTripCount(MaxExitCount); 5342 } 5343 5344 unsigned ScalarEvolution::getSmallConstantTripMultiple(Loop *L) { 5345 if (BasicBlock *ExitingBB = L->getExitingBlock()) 5346 return getSmallConstantTripMultiple(L, ExitingBB); 5347 5348 // No trip multiple information for multiple exits. 5349 return 0; 5350 } 5351 5352 /// Returns the largest constant divisor of the trip count of this loop as a 5353 /// normal unsigned value, if possible. This means that the actual trip count is 5354 /// always a multiple of the returned value (don't forget the trip count could 5355 /// very well be zero as well!). 5356 /// 5357 /// Returns 1 if the trip count is unknown or not guaranteed to be the 5358 /// multiple of a constant (which is also the case if the trip count is simply 5359 /// constant, use getSmallConstantTripCount for that case), Will also return 1 5360 /// if the trip count is very large (>= 2^32). 5361 /// 5362 /// As explained in the comments for getSmallConstantTripCount, this assumes 5363 /// that control exits the loop via ExitingBlock. 5364 unsigned 5365 ScalarEvolution::getSmallConstantTripMultiple(Loop *L, 5366 BasicBlock *ExitingBlock) { 5367 assert(ExitingBlock && "Must pass a non-null exiting block!"); 5368 assert(L->isLoopExiting(ExitingBlock) && 5369 "Exiting block must actually branch out of the loop!"); 5370 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 5371 if (ExitCount == getCouldNotCompute()) 5372 return 1; 5373 5374 // Get the trip count from the BE count by adding 1. 5375 const SCEV *TCMul = getAddExpr(ExitCount, getOne(ExitCount->getType())); 5376 // FIXME: SCEV distributes multiplication as V1*C1 + V2*C1. We could attempt 5377 // to factor simple cases. 5378 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(TCMul)) 5379 TCMul = Mul->getOperand(0); 5380 5381 const SCEVConstant *MulC = dyn_cast<SCEVConstant>(TCMul); 5382 if (!MulC) 5383 return 1; 5384 5385 ConstantInt *Result = MulC->getValue(); 5386 5387 // Guard against huge trip counts (this requires checking 5388 // for zero to handle the case where the trip count == -1 and the 5389 // addition wraps). 5390 if (!Result || Result->getValue().getActiveBits() > 32 || 5391 Result->getValue().getActiveBits() == 0) 5392 return 1; 5393 5394 return (unsigned)Result->getZExtValue(); 5395 } 5396 5397 /// Get the expression for the number of loop iterations for which this loop is 5398 /// guaranteed not to exit via ExitingBlock. Otherwise return 5399 /// SCEVCouldNotCompute. 5400 const SCEV *ScalarEvolution::getExitCount(Loop *L, BasicBlock *ExitingBlock) { 5401 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 5402 } 5403 5404 const SCEV * 5405 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 5406 SCEVUnionPredicate &Preds) { 5407 return getPredicatedBackedgeTakenInfo(L).getExact(this, &Preds); 5408 } 5409 5410 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) { 5411 return getBackedgeTakenInfo(L).getExact(this); 5412 } 5413 5414 /// Similar to getBackedgeTakenCount, except return the least SCEV value that is 5415 /// known never to be less than the actual backedge taken count. 5416 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) { 5417 return getBackedgeTakenInfo(L).getMax(this); 5418 } 5419 5420 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 5421 return getBackedgeTakenInfo(L).isMaxOrZero(this); 5422 } 5423 5424 /// Push PHI nodes in the header of the given loop onto the given Worklist. 5425 static void 5426 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { 5427 BasicBlock *Header = L->getHeader(); 5428 5429 // Push all Loop-header PHIs onto the Worklist stack. 5430 for (BasicBlock::iterator I = Header->begin(); 5431 PHINode *PN = dyn_cast<PHINode>(I); ++I) 5432 Worklist.push_back(PN); 5433 } 5434 5435 const ScalarEvolution::BackedgeTakenInfo & 5436 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 5437 auto &BTI = getBackedgeTakenInfo(L); 5438 if (BTI.hasFullInfo()) 5439 return BTI; 5440 5441 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 5442 5443 if (!Pair.second) 5444 return Pair.first->second; 5445 5446 BackedgeTakenInfo Result = 5447 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 5448 5449 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 5450 } 5451 5452 const ScalarEvolution::BackedgeTakenInfo & 5453 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 5454 // Initially insert an invalid entry for this loop. If the insertion 5455 // succeeds, proceed to actually compute a backedge-taken count and 5456 // update the value. The temporary CouldNotCompute value tells SCEV 5457 // code elsewhere that it shouldn't attempt to request a new 5458 // backedge-taken count, which could result in infinite recursion. 5459 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 5460 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 5461 if (!Pair.second) 5462 return Pair.first->second; 5463 5464 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 5465 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 5466 // must be cleared in this scope. 5467 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 5468 5469 if (Result.getExact(this) != getCouldNotCompute()) { 5470 assert(isLoopInvariant(Result.getExact(this), L) && 5471 isLoopInvariant(Result.getMax(this), L) && 5472 "Computed backedge-taken count isn't loop invariant for loop!"); 5473 ++NumTripCountsComputed; 5474 } 5475 else if (Result.getMax(this) == getCouldNotCompute() && 5476 isa<PHINode>(L->getHeader()->begin())) { 5477 // Only count loops that have phi nodes as not being computable. 5478 ++NumTripCountsNotComputed; 5479 } 5480 5481 // Now that we know more about the trip count for this loop, forget any 5482 // existing SCEV values for PHI nodes in this loop since they are only 5483 // conservative estimates made without the benefit of trip count 5484 // information. This is similar to the code in forgetLoop, except that 5485 // it handles SCEVUnknown PHI nodes specially. 5486 if (Result.hasAnyInfo()) { 5487 SmallVector<Instruction *, 16> Worklist; 5488 PushLoopPHIs(L, Worklist); 5489 5490 SmallPtrSet<Instruction *, 8> Visited; 5491 while (!Worklist.empty()) { 5492 Instruction *I = Worklist.pop_back_val(); 5493 if (!Visited.insert(I).second) 5494 continue; 5495 5496 ValueExprMapType::iterator It = 5497 ValueExprMap.find_as(static_cast<Value *>(I)); 5498 if (It != ValueExprMap.end()) { 5499 const SCEV *Old = It->second; 5500 5501 // SCEVUnknown for a PHI either means that it has an unrecognized 5502 // structure, or it's a PHI that's in the progress of being computed 5503 // by createNodeForPHI. In the former case, additional loop trip 5504 // count information isn't going to change anything. In the later 5505 // case, createNodeForPHI will perform the necessary updates on its 5506 // own when it gets to that point. 5507 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 5508 eraseValueFromMap(It->first); 5509 forgetMemoizedResults(Old); 5510 } 5511 if (PHINode *PN = dyn_cast<PHINode>(I)) 5512 ConstantEvolutionLoopExitValue.erase(PN); 5513 } 5514 5515 PushDefUseChildren(I, Worklist); 5516 } 5517 } 5518 5519 // Re-lookup the insert position, since the call to 5520 // computeBackedgeTakenCount above could result in a 5521 // recusive call to getBackedgeTakenInfo (on a different 5522 // loop), which would invalidate the iterator computed 5523 // earlier. 5524 return BackedgeTakenCounts.find(L)->second = std::move(Result); 5525 } 5526 5527 void ScalarEvolution::forgetLoop(const Loop *L) { 5528 // Drop any stored trip count value. 5529 auto RemoveLoopFromBackedgeMap = 5530 [L](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 5531 auto BTCPos = Map.find(L); 5532 if (BTCPos != Map.end()) { 5533 BTCPos->second.clear(); 5534 Map.erase(BTCPos); 5535 } 5536 }; 5537 5538 RemoveLoopFromBackedgeMap(BackedgeTakenCounts); 5539 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts); 5540 5541 // Drop information about expressions based on loop-header PHIs. 5542 SmallVector<Instruction *, 16> Worklist; 5543 PushLoopPHIs(L, Worklist); 5544 5545 SmallPtrSet<Instruction *, 8> Visited; 5546 while (!Worklist.empty()) { 5547 Instruction *I = Worklist.pop_back_val(); 5548 if (!Visited.insert(I).second) 5549 continue; 5550 5551 ValueExprMapType::iterator It = 5552 ValueExprMap.find_as(static_cast<Value *>(I)); 5553 if (It != ValueExprMap.end()) { 5554 eraseValueFromMap(It->first); 5555 forgetMemoizedResults(It->second); 5556 if (PHINode *PN = dyn_cast<PHINode>(I)) 5557 ConstantEvolutionLoopExitValue.erase(PN); 5558 } 5559 5560 PushDefUseChildren(I, Worklist); 5561 } 5562 5563 // Forget all contained loops too, to avoid dangling entries in the 5564 // ValuesAtScopes map. 5565 for (Loop *I : *L) 5566 forgetLoop(I); 5567 5568 LoopPropertiesCache.erase(L); 5569 } 5570 5571 void ScalarEvolution::forgetValue(Value *V) { 5572 Instruction *I = dyn_cast<Instruction>(V); 5573 if (!I) return; 5574 5575 // Drop information about expressions based on loop-header PHIs. 5576 SmallVector<Instruction *, 16> Worklist; 5577 Worklist.push_back(I); 5578 5579 SmallPtrSet<Instruction *, 8> Visited; 5580 while (!Worklist.empty()) { 5581 I = Worklist.pop_back_val(); 5582 if (!Visited.insert(I).second) 5583 continue; 5584 5585 ValueExprMapType::iterator It = 5586 ValueExprMap.find_as(static_cast<Value *>(I)); 5587 if (It != ValueExprMap.end()) { 5588 eraseValueFromMap(It->first); 5589 forgetMemoizedResults(It->second); 5590 if (PHINode *PN = dyn_cast<PHINode>(I)) 5591 ConstantEvolutionLoopExitValue.erase(PN); 5592 } 5593 5594 PushDefUseChildren(I, Worklist); 5595 } 5596 } 5597 5598 /// Get the exact loop backedge taken count considering all loop exits. A 5599 /// computable result can only be returned for loops with a single exit. 5600 /// Returning the minimum taken count among all exits is incorrect because one 5601 /// of the loop's exit limit's may have been skipped. howFarToZero assumes that 5602 /// the limit of each loop test is never skipped. This is a valid assumption as 5603 /// long as the loop exits via that test. For precise results, it is the 5604 /// caller's responsibility to specify the relevant loop exit using 5605 /// getExact(ExitingBlock, SE). 5606 const SCEV * 5607 ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE, 5608 SCEVUnionPredicate *Preds) const { 5609 // If any exits were not computable, the loop is not computable. 5610 if (!isComplete() || ExitNotTaken.empty()) 5611 return SE->getCouldNotCompute(); 5612 5613 const SCEV *BECount = nullptr; 5614 for (auto &ENT : ExitNotTaken) { 5615 assert(ENT.ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV"); 5616 5617 if (!BECount) 5618 BECount = ENT.ExactNotTaken; 5619 else if (BECount != ENT.ExactNotTaken) 5620 return SE->getCouldNotCompute(); 5621 if (Preds && !ENT.hasAlwaysTruePredicate()) 5622 Preds->add(ENT.Predicate.get()); 5623 5624 assert((Preds || ENT.hasAlwaysTruePredicate()) && 5625 "Predicate should be always true!"); 5626 } 5627 5628 assert(BECount && "Invalid not taken count for loop exit"); 5629 return BECount; 5630 } 5631 5632 /// Get the exact not taken count for this loop exit. 5633 const SCEV * 5634 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock, 5635 ScalarEvolution *SE) const { 5636 for (auto &ENT : ExitNotTaken) 5637 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 5638 return ENT.ExactNotTaken; 5639 5640 return SE->getCouldNotCompute(); 5641 } 5642 5643 /// getMax - Get the max backedge taken count for the loop. 5644 const SCEV * 5645 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const { 5646 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 5647 return !ENT.hasAlwaysTruePredicate(); 5648 }; 5649 5650 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax()) 5651 return SE->getCouldNotCompute(); 5652 5653 return getMax(); 5654 } 5655 5656 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const { 5657 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 5658 return !ENT.hasAlwaysTruePredicate(); 5659 }; 5660 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 5661 } 5662 5663 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S, 5664 ScalarEvolution *SE) const { 5665 if (getMax() && getMax() != SE->getCouldNotCompute() && 5666 SE->hasOperand(getMax(), S)) 5667 return true; 5668 5669 for (auto &ENT : ExitNotTaken) 5670 if (ENT.ExactNotTaken != SE->getCouldNotCompute() && 5671 SE->hasOperand(ENT.ExactNotTaken, S)) 5672 return true; 5673 5674 return false; 5675 } 5676 5677 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 5678 /// computable exit into a persistent ExitNotTakenInfo array. 5679 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 5680 SmallVectorImpl<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> 5681 &&ExitCounts, 5682 bool Complete, const SCEV *MaxCount, bool MaxOrZero) 5683 : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) { 5684 typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo; 5685 ExitNotTaken.reserve(ExitCounts.size()); 5686 std::transform( 5687 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 5688 [&](const EdgeExitInfo &EEI) { 5689 BasicBlock *ExitBB = EEI.first; 5690 const ExitLimit &EL = EEI.second; 5691 if (EL.Predicates.empty()) 5692 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr); 5693 5694 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); 5695 for (auto *Pred : EL.Predicates) 5696 Predicate->add(Pred); 5697 5698 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate)); 5699 }); 5700 } 5701 5702 /// Invalidate this result and free the ExitNotTakenInfo array. 5703 void ScalarEvolution::BackedgeTakenInfo::clear() { 5704 ExitNotTaken.clear(); 5705 } 5706 5707 /// Compute the number of times the backedge of the specified loop will execute. 5708 ScalarEvolution::BackedgeTakenInfo 5709 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 5710 bool AllowPredicates) { 5711 SmallVector<BasicBlock *, 8> ExitingBlocks; 5712 L->getExitingBlocks(ExitingBlocks); 5713 5714 typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo; 5715 5716 SmallVector<EdgeExitInfo, 4> ExitCounts; 5717 bool CouldComputeBECount = true; 5718 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 5719 const SCEV *MustExitMaxBECount = nullptr; 5720 const SCEV *MayExitMaxBECount = nullptr; 5721 bool MustExitMaxOrZero = false; 5722 5723 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 5724 // and compute maxBECount. 5725 // Do a union of all the predicates here. 5726 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 5727 BasicBlock *ExitBB = ExitingBlocks[i]; 5728 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 5729 5730 assert((AllowPredicates || EL.Predicates.empty()) && 5731 "Predicated exit limit when predicates are not allowed!"); 5732 5733 // 1. For each exit that can be computed, add an entry to ExitCounts. 5734 // CouldComputeBECount is true only if all exits can be computed. 5735 if (EL.ExactNotTaken == getCouldNotCompute()) 5736 // We couldn't compute an exact value for this exit, so 5737 // we won't be able to compute an exact value for the loop. 5738 CouldComputeBECount = false; 5739 else 5740 ExitCounts.emplace_back(ExitBB, EL); 5741 5742 // 2. Derive the loop's MaxBECount from each exit's max number of 5743 // non-exiting iterations. Partition the loop exits into two kinds: 5744 // LoopMustExits and LoopMayExits. 5745 // 5746 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 5747 // is a LoopMayExit. If any computable LoopMustExit is found, then 5748 // MaxBECount is the minimum EL.MaxNotTaken of computable 5749 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 5750 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 5751 // computable EL.MaxNotTaken. 5752 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 5753 DT.dominates(ExitBB, Latch)) { 5754 if (!MustExitMaxBECount) { 5755 MustExitMaxBECount = EL.MaxNotTaken; 5756 MustExitMaxOrZero = EL.MaxOrZero; 5757 } else { 5758 MustExitMaxBECount = 5759 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 5760 } 5761 } else if (MayExitMaxBECount != getCouldNotCompute()) { 5762 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 5763 MayExitMaxBECount = EL.MaxNotTaken; 5764 else { 5765 MayExitMaxBECount = 5766 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 5767 } 5768 } 5769 } 5770 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 5771 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 5772 // The loop backedge will be taken the maximum or zero times if there's 5773 // a single exit that must be taken the maximum or zero times. 5774 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 5775 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 5776 MaxBECount, MaxOrZero); 5777 } 5778 5779 ScalarEvolution::ExitLimit 5780 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 5781 bool AllowPredicates) { 5782 5783 // Okay, we've chosen an exiting block. See what condition causes us to exit 5784 // at this block and remember the exit block and whether all other targets 5785 // lead to the loop header. 5786 bool MustExecuteLoopHeader = true; 5787 BasicBlock *Exit = nullptr; 5788 for (auto *SBB : successors(ExitingBlock)) 5789 if (!L->contains(SBB)) { 5790 if (Exit) // Multiple exit successors. 5791 return getCouldNotCompute(); 5792 Exit = SBB; 5793 } else if (SBB != L->getHeader()) { 5794 MustExecuteLoopHeader = false; 5795 } 5796 5797 // At this point, we know we have a conditional branch that determines whether 5798 // the loop is exited. However, we don't know if the branch is executed each 5799 // time through the loop. If not, then the execution count of the branch will 5800 // not be equal to the trip count of the loop. 5801 // 5802 // Currently we check for this by checking to see if the Exit branch goes to 5803 // the loop header. If so, we know it will always execute the same number of 5804 // times as the loop. We also handle the case where the exit block *is* the 5805 // loop header. This is common for un-rotated loops. 5806 // 5807 // If both of those tests fail, walk up the unique predecessor chain to the 5808 // header, stopping if there is an edge that doesn't exit the loop. If the 5809 // header is reached, the execution count of the branch will be equal to the 5810 // trip count of the loop. 5811 // 5812 // More extensive analysis could be done to handle more cases here. 5813 // 5814 if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) { 5815 // The simple checks failed, try climbing the unique predecessor chain 5816 // up to the header. 5817 bool Ok = false; 5818 for (BasicBlock *BB = ExitingBlock; BB; ) { 5819 BasicBlock *Pred = BB->getUniquePredecessor(); 5820 if (!Pred) 5821 return getCouldNotCompute(); 5822 TerminatorInst *PredTerm = Pred->getTerminator(); 5823 for (const BasicBlock *PredSucc : PredTerm->successors()) { 5824 if (PredSucc == BB) 5825 continue; 5826 // If the predecessor has a successor that isn't BB and isn't 5827 // outside the loop, assume the worst. 5828 if (L->contains(PredSucc)) 5829 return getCouldNotCompute(); 5830 } 5831 if (Pred == L->getHeader()) { 5832 Ok = true; 5833 break; 5834 } 5835 BB = Pred; 5836 } 5837 if (!Ok) 5838 return getCouldNotCompute(); 5839 } 5840 5841 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 5842 TerminatorInst *Term = ExitingBlock->getTerminator(); 5843 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 5844 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 5845 // Proceed to the next level to examine the exit condition expression. 5846 return computeExitLimitFromCond( 5847 L, BI->getCondition(), BI->getSuccessor(0), BI->getSuccessor(1), 5848 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 5849 } 5850 5851 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) 5852 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 5853 /*ControlsExit=*/IsOnlyExit); 5854 5855 return getCouldNotCompute(); 5856 } 5857 5858 ScalarEvolution::ExitLimit 5859 ScalarEvolution::computeExitLimitFromCond(const Loop *L, 5860 Value *ExitCond, 5861 BasicBlock *TBB, 5862 BasicBlock *FBB, 5863 bool ControlsExit, 5864 bool AllowPredicates) { 5865 // Check if the controlling expression for this loop is an And or Or. 5866 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) { 5867 if (BO->getOpcode() == Instruction::And) { 5868 // Recurse on the operands of the and. 5869 bool EitherMayExit = L->contains(TBB); 5870 ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB, 5871 ControlsExit && !EitherMayExit, 5872 AllowPredicates); 5873 ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB, 5874 ControlsExit && !EitherMayExit, 5875 AllowPredicates); 5876 const SCEV *BECount = getCouldNotCompute(); 5877 const SCEV *MaxBECount = getCouldNotCompute(); 5878 if (EitherMayExit) { 5879 // Both conditions must be true for the loop to continue executing. 5880 // Choose the less conservative count. 5881 if (EL0.ExactNotTaken == getCouldNotCompute() || 5882 EL1.ExactNotTaken == getCouldNotCompute()) 5883 BECount = getCouldNotCompute(); 5884 else 5885 BECount = 5886 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 5887 if (EL0.MaxNotTaken == getCouldNotCompute()) 5888 MaxBECount = EL1.MaxNotTaken; 5889 else if (EL1.MaxNotTaken == getCouldNotCompute()) 5890 MaxBECount = EL0.MaxNotTaken; 5891 else 5892 MaxBECount = 5893 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 5894 } else { 5895 // Both conditions must be true at the same time for the loop to exit. 5896 // For now, be conservative. 5897 assert(L->contains(FBB) && "Loop block has no successor in loop!"); 5898 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 5899 MaxBECount = EL0.MaxNotTaken; 5900 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 5901 BECount = EL0.ExactNotTaken; 5902 } 5903 5904 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 5905 // to be more aggressive when computing BECount than when computing 5906 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 5907 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 5908 // to not. 5909 if (isa<SCEVCouldNotCompute>(MaxBECount) && 5910 !isa<SCEVCouldNotCompute>(BECount)) 5911 MaxBECount = BECount; 5912 5913 return ExitLimit(BECount, MaxBECount, false, 5914 {&EL0.Predicates, &EL1.Predicates}); 5915 } 5916 if (BO->getOpcode() == Instruction::Or) { 5917 // Recurse on the operands of the or. 5918 bool EitherMayExit = L->contains(FBB); 5919 ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB, 5920 ControlsExit && !EitherMayExit, 5921 AllowPredicates); 5922 ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB, 5923 ControlsExit && !EitherMayExit, 5924 AllowPredicates); 5925 const SCEV *BECount = getCouldNotCompute(); 5926 const SCEV *MaxBECount = getCouldNotCompute(); 5927 if (EitherMayExit) { 5928 // Both conditions must be false for the loop to continue executing. 5929 // Choose the less conservative count. 5930 if (EL0.ExactNotTaken == getCouldNotCompute() || 5931 EL1.ExactNotTaken == getCouldNotCompute()) 5932 BECount = getCouldNotCompute(); 5933 else 5934 BECount = 5935 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 5936 if (EL0.MaxNotTaken == getCouldNotCompute()) 5937 MaxBECount = EL1.MaxNotTaken; 5938 else if (EL1.MaxNotTaken == getCouldNotCompute()) 5939 MaxBECount = EL0.MaxNotTaken; 5940 else 5941 MaxBECount = 5942 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 5943 } else { 5944 // Both conditions must be false at the same time for the loop to exit. 5945 // For now, be conservative. 5946 assert(L->contains(TBB) && "Loop block has no successor in loop!"); 5947 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 5948 MaxBECount = EL0.MaxNotTaken; 5949 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 5950 BECount = EL0.ExactNotTaken; 5951 } 5952 5953 return ExitLimit(BECount, MaxBECount, false, 5954 {&EL0.Predicates, &EL1.Predicates}); 5955 } 5956 } 5957 5958 // With an icmp, it may be feasible to compute an exact backedge-taken count. 5959 // Proceed to the next level to examine the icmp. 5960 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 5961 ExitLimit EL = 5962 computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit); 5963 if (EL.hasFullInfo() || !AllowPredicates) 5964 return EL; 5965 5966 // Try again, but use SCEV predicates this time. 5967 return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit, 5968 /*AllowPredicates=*/true); 5969 } 5970 5971 // Check for a constant condition. These are normally stripped out by 5972 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 5973 // preserve the CFG and is temporarily leaving constant conditions 5974 // in place. 5975 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 5976 if (L->contains(FBB) == !CI->getZExtValue()) 5977 // The backedge is always taken. 5978 return getCouldNotCompute(); 5979 else 5980 // The backedge is never taken. 5981 return getZero(CI->getType()); 5982 } 5983 5984 // If it's not an integer or pointer comparison then compute it the hard way. 5985 return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB)); 5986 } 5987 5988 ScalarEvolution::ExitLimit 5989 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 5990 ICmpInst *ExitCond, 5991 BasicBlock *TBB, 5992 BasicBlock *FBB, 5993 bool ControlsExit, 5994 bool AllowPredicates) { 5995 5996 // If the condition was exit on true, convert the condition to exit on false 5997 ICmpInst::Predicate Cond; 5998 if (!L->contains(FBB)) 5999 Cond = ExitCond->getPredicate(); 6000 else 6001 Cond = ExitCond->getInversePredicate(); 6002 6003 // Handle common loops like: for (X = "string"; *X; ++X) 6004 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 6005 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 6006 ExitLimit ItCnt = 6007 computeLoadConstantCompareExitLimit(LI, RHS, L, Cond); 6008 if (ItCnt.hasAnyInfo()) 6009 return ItCnt; 6010 } 6011 6012 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 6013 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 6014 6015 // Try to evaluate any dependencies out of the loop. 6016 LHS = getSCEVAtScope(LHS, L); 6017 RHS = getSCEVAtScope(RHS, L); 6018 6019 // At this point, we would like to compute how many iterations of the 6020 // loop the predicate will return true for these inputs. 6021 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 6022 // If there is a loop-invariant, force it into the RHS. 6023 std::swap(LHS, RHS); 6024 Cond = ICmpInst::getSwappedPredicate(Cond); 6025 } 6026 6027 // Simplify the operands before analyzing them. 6028 (void)SimplifyICmpOperands(Cond, LHS, RHS); 6029 6030 // If we have a comparison of a chrec against a constant, try to use value 6031 // ranges to answer this query. 6032 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 6033 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 6034 if (AddRec->getLoop() == L) { 6035 // Form the constant range. 6036 ConstantRange CompRange = 6037 ConstantRange::makeExactICmpRegion(Cond, RHSC->getAPInt()); 6038 6039 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 6040 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 6041 } 6042 6043 switch (Cond) { 6044 case ICmpInst::ICMP_NE: { // while (X != Y) 6045 // Convert to: while (X-Y != 0) 6046 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 6047 AllowPredicates); 6048 if (EL.hasAnyInfo()) return EL; 6049 break; 6050 } 6051 case ICmpInst::ICMP_EQ: { // while (X == Y) 6052 // Convert to: while (X-Y == 0) 6053 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 6054 if (EL.hasAnyInfo()) return EL; 6055 break; 6056 } 6057 case ICmpInst::ICMP_SLT: 6058 case ICmpInst::ICMP_ULT: { // while (X < Y) 6059 bool IsSigned = Cond == ICmpInst::ICMP_SLT; 6060 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 6061 AllowPredicates); 6062 if (EL.hasAnyInfo()) return EL; 6063 break; 6064 } 6065 case ICmpInst::ICMP_SGT: 6066 case ICmpInst::ICMP_UGT: { // while (X > Y) 6067 bool IsSigned = Cond == ICmpInst::ICMP_SGT; 6068 ExitLimit EL = 6069 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 6070 AllowPredicates); 6071 if (EL.hasAnyInfo()) return EL; 6072 break; 6073 } 6074 default: 6075 break; 6076 } 6077 6078 auto *ExhaustiveCount = 6079 computeExitCountExhaustively(L, ExitCond, !L->contains(TBB)); 6080 6081 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 6082 return ExhaustiveCount; 6083 6084 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 6085 ExitCond->getOperand(1), L, Cond); 6086 } 6087 6088 ScalarEvolution::ExitLimit 6089 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 6090 SwitchInst *Switch, 6091 BasicBlock *ExitingBlock, 6092 bool ControlsExit) { 6093 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 6094 6095 // Give up if the exit is the default dest of a switch. 6096 if (Switch->getDefaultDest() == ExitingBlock) 6097 return getCouldNotCompute(); 6098 6099 assert(L->contains(Switch->getDefaultDest()) && 6100 "Default case must not exit the loop!"); 6101 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 6102 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 6103 6104 // while (X != Y) --> while (X-Y != 0) 6105 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 6106 if (EL.hasAnyInfo()) 6107 return EL; 6108 6109 return getCouldNotCompute(); 6110 } 6111 6112 static ConstantInt * 6113 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 6114 ScalarEvolution &SE) { 6115 const SCEV *InVal = SE.getConstant(C); 6116 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 6117 assert(isa<SCEVConstant>(Val) && 6118 "Evaluation of SCEV at constant didn't fold correctly?"); 6119 return cast<SCEVConstant>(Val)->getValue(); 6120 } 6121 6122 /// Given an exit condition of 'icmp op load X, cst', try to see if we can 6123 /// compute the backedge execution count. 6124 ScalarEvolution::ExitLimit 6125 ScalarEvolution::computeLoadConstantCompareExitLimit( 6126 LoadInst *LI, 6127 Constant *RHS, 6128 const Loop *L, 6129 ICmpInst::Predicate predicate) { 6130 6131 if (LI->isVolatile()) return getCouldNotCompute(); 6132 6133 // Check to see if the loaded pointer is a getelementptr of a global. 6134 // TODO: Use SCEV instead of manually grubbing with GEPs. 6135 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 6136 if (!GEP) return getCouldNotCompute(); 6137 6138 // Make sure that it is really a constant global we are gepping, with an 6139 // initializer, and make sure the first IDX is really 0. 6140 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 6141 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || 6142 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 6143 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 6144 return getCouldNotCompute(); 6145 6146 // Okay, we allow one non-constant index into the GEP instruction. 6147 Value *VarIdx = nullptr; 6148 std::vector<Constant*> Indexes; 6149 unsigned VarIdxNum = 0; 6150 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 6151 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 6152 Indexes.push_back(CI); 6153 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 6154 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. 6155 VarIdx = GEP->getOperand(i); 6156 VarIdxNum = i-2; 6157 Indexes.push_back(nullptr); 6158 } 6159 6160 // Loop-invariant loads may be a byproduct of loop optimization. Skip them. 6161 if (!VarIdx) 6162 return getCouldNotCompute(); 6163 6164 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 6165 // Check to see if X is a loop variant variable value now. 6166 const SCEV *Idx = getSCEV(VarIdx); 6167 Idx = getSCEVAtScope(Idx, L); 6168 6169 // We can only recognize very limited forms of loop index expressions, in 6170 // particular, only affine AddRec's like {C1,+,C2}. 6171 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 6172 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) || 6173 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 6174 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 6175 return getCouldNotCompute(); 6176 6177 unsigned MaxSteps = MaxBruteForceIterations; 6178 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 6179 ConstantInt *ItCst = ConstantInt::get( 6180 cast<IntegerType>(IdxExpr->getType()), IterationNum); 6181 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 6182 6183 // Form the GEP offset. 6184 Indexes[VarIdxNum] = Val; 6185 6186 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), 6187 Indexes); 6188 if (!Result) break; // Cannot compute! 6189 6190 // Evaluate the condition for this iteration. 6191 Result = ConstantExpr::getICmp(predicate, Result, RHS); 6192 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 6193 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 6194 ++NumArrayLenItCounts; 6195 return getConstant(ItCst); // Found terminating iteration! 6196 } 6197 } 6198 return getCouldNotCompute(); 6199 } 6200 6201 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 6202 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 6203 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 6204 if (!RHS) 6205 return getCouldNotCompute(); 6206 6207 const BasicBlock *Latch = L->getLoopLatch(); 6208 if (!Latch) 6209 return getCouldNotCompute(); 6210 6211 const BasicBlock *Predecessor = L->getLoopPredecessor(); 6212 if (!Predecessor) 6213 return getCouldNotCompute(); 6214 6215 // Return true if V is of the form "LHS `shift_op` <positive constant>". 6216 // Return LHS in OutLHS and shift_opt in OutOpCode. 6217 auto MatchPositiveShift = 6218 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 6219 6220 using namespace PatternMatch; 6221 6222 ConstantInt *ShiftAmt; 6223 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 6224 OutOpCode = Instruction::LShr; 6225 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 6226 OutOpCode = Instruction::AShr; 6227 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 6228 OutOpCode = Instruction::Shl; 6229 else 6230 return false; 6231 6232 return ShiftAmt->getValue().isStrictlyPositive(); 6233 }; 6234 6235 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 6236 // 6237 // loop: 6238 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 6239 // %iv.shifted = lshr i32 %iv, <positive constant> 6240 // 6241 // Return true on a succesful match. Return the corresponding PHI node (%iv 6242 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 6243 auto MatchShiftRecurrence = 6244 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 6245 Optional<Instruction::BinaryOps> PostShiftOpCode; 6246 6247 { 6248 Instruction::BinaryOps OpC; 6249 Value *V; 6250 6251 // If we encounter a shift instruction, "peel off" the shift operation, 6252 // and remember that we did so. Later when we inspect %iv's backedge 6253 // value, we will make sure that the backedge value uses the same 6254 // operation. 6255 // 6256 // Note: the peeled shift operation does not have to be the same 6257 // instruction as the one feeding into the PHI's backedge value. We only 6258 // really care about it being the same *kind* of shift instruction -- 6259 // that's all that is required for our later inferences to hold. 6260 if (MatchPositiveShift(LHS, V, OpC)) { 6261 PostShiftOpCode = OpC; 6262 LHS = V; 6263 } 6264 } 6265 6266 PNOut = dyn_cast<PHINode>(LHS); 6267 if (!PNOut || PNOut->getParent() != L->getHeader()) 6268 return false; 6269 6270 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 6271 Value *OpLHS; 6272 6273 return 6274 // The backedge value for the PHI node must be a shift by a positive 6275 // amount 6276 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 6277 6278 // of the PHI node itself 6279 OpLHS == PNOut && 6280 6281 // and the kind of shift should be match the kind of shift we peeled 6282 // off, if any. 6283 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 6284 }; 6285 6286 PHINode *PN; 6287 Instruction::BinaryOps OpCode; 6288 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 6289 return getCouldNotCompute(); 6290 6291 const DataLayout &DL = getDataLayout(); 6292 6293 // The key rationale for this optimization is that for some kinds of shift 6294 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 6295 // within a finite number of iterations. If the condition guarding the 6296 // backedge (in the sense that the backedge is taken if the condition is true) 6297 // is false for the value the shift recurrence stabilizes to, then we know 6298 // that the backedge is taken only a finite number of times. 6299 6300 ConstantInt *StableValue = nullptr; 6301 switch (OpCode) { 6302 default: 6303 llvm_unreachable("Impossible case!"); 6304 6305 case Instruction::AShr: { 6306 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 6307 // bitwidth(K) iterations. 6308 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 6309 bool KnownZero, KnownOne; 6310 ComputeSignBit(FirstValue, KnownZero, KnownOne, DL, 0, nullptr, 6311 Predecessor->getTerminator(), &DT); 6312 auto *Ty = cast<IntegerType>(RHS->getType()); 6313 if (KnownZero) 6314 StableValue = ConstantInt::get(Ty, 0); 6315 else if (KnownOne) 6316 StableValue = ConstantInt::get(Ty, -1, true); 6317 else 6318 return getCouldNotCompute(); 6319 6320 break; 6321 } 6322 case Instruction::LShr: 6323 case Instruction::Shl: 6324 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 6325 // stabilize to 0 in at most bitwidth(K) iterations. 6326 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 6327 break; 6328 } 6329 6330 auto *Result = 6331 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 6332 assert(Result->getType()->isIntegerTy(1) && 6333 "Otherwise cannot be an operand to a branch instruction"); 6334 6335 if (Result->isZeroValue()) { 6336 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 6337 const SCEV *UpperBound = 6338 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 6339 return ExitLimit(getCouldNotCompute(), UpperBound, false); 6340 } 6341 6342 return getCouldNotCompute(); 6343 } 6344 6345 /// Return true if we can constant fold an instruction of the specified type, 6346 /// assuming that all operands were constants. 6347 static bool CanConstantFold(const Instruction *I) { 6348 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 6349 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 6350 isa<LoadInst>(I)) 6351 return true; 6352 6353 if (const CallInst *CI = dyn_cast<CallInst>(I)) 6354 if (const Function *F = CI->getCalledFunction()) 6355 return canConstantFoldCallTo(F); 6356 return false; 6357 } 6358 6359 /// Determine whether this instruction can constant evolve within this loop 6360 /// assuming its operands can all constant evolve. 6361 static bool canConstantEvolve(Instruction *I, const Loop *L) { 6362 // An instruction outside of the loop can't be derived from a loop PHI. 6363 if (!L->contains(I)) return false; 6364 6365 if (isa<PHINode>(I)) { 6366 // We don't currently keep track of the control flow needed to evaluate 6367 // PHIs, so we cannot handle PHIs inside of loops. 6368 return L->getHeader() == I->getParent(); 6369 } 6370 6371 // If we won't be able to constant fold this expression even if the operands 6372 // are constants, bail early. 6373 return CanConstantFold(I); 6374 } 6375 6376 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 6377 /// recursing through each instruction operand until reaching a loop header phi. 6378 static PHINode * 6379 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 6380 DenseMap<Instruction *, PHINode *> &PHIMap) { 6381 6382 // Otherwise, we can evaluate this instruction if all of its operands are 6383 // constant or derived from a PHI node themselves. 6384 PHINode *PHI = nullptr; 6385 for (Value *Op : UseInst->operands()) { 6386 if (isa<Constant>(Op)) continue; 6387 6388 Instruction *OpInst = dyn_cast<Instruction>(Op); 6389 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 6390 6391 PHINode *P = dyn_cast<PHINode>(OpInst); 6392 if (!P) 6393 // If this operand is already visited, reuse the prior result. 6394 // We may have P != PHI if this is the deepest point at which the 6395 // inconsistent paths meet. 6396 P = PHIMap.lookup(OpInst); 6397 if (!P) { 6398 // Recurse and memoize the results, whether a phi is found or not. 6399 // This recursive call invalidates pointers into PHIMap. 6400 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap); 6401 PHIMap[OpInst] = P; 6402 } 6403 if (!P) 6404 return nullptr; // Not evolving from PHI 6405 if (PHI && PHI != P) 6406 return nullptr; // Evolving from multiple different PHIs. 6407 PHI = P; 6408 } 6409 // This is a expression evolving from a constant PHI! 6410 return PHI; 6411 } 6412 6413 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 6414 /// in the loop that V is derived from. We allow arbitrary operations along the 6415 /// way, but the operands of an operation must either be constants or a value 6416 /// derived from a constant PHI. If this expression does not fit with these 6417 /// constraints, return null. 6418 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 6419 Instruction *I = dyn_cast<Instruction>(V); 6420 if (!I || !canConstantEvolve(I, L)) return nullptr; 6421 6422 if (PHINode *PN = dyn_cast<PHINode>(I)) 6423 return PN; 6424 6425 // Record non-constant instructions contained by the loop. 6426 DenseMap<Instruction *, PHINode *> PHIMap; 6427 return getConstantEvolvingPHIOperands(I, L, PHIMap); 6428 } 6429 6430 /// EvaluateExpression - Given an expression that passes the 6431 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 6432 /// in the loop has the value PHIVal. If we can't fold this expression for some 6433 /// reason, return null. 6434 static Constant *EvaluateExpression(Value *V, const Loop *L, 6435 DenseMap<Instruction *, Constant *> &Vals, 6436 const DataLayout &DL, 6437 const TargetLibraryInfo *TLI) { 6438 // Convenient constant check, but redundant for recursive calls. 6439 if (Constant *C = dyn_cast<Constant>(V)) return C; 6440 Instruction *I = dyn_cast<Instruction>(V); 6441 if (!I) return nullptr; 6442 6443 if (Constant *C = Vals.lookup(I)) return C; 6444 6445 // An instruction inside the loop depends on a value outside the loop that we 6446 // weren't given a mapping for, or a value such as a call inside the loop. 6447 if (!canConstantEvolve(I, L)) return nullptr; 6448 6449 // An unmapped PHI can be due to a branch or another loop inside this loop, 6450 // or due to this not being the initial iteration through a loop where we 6451 // couldn't compute the evolution of this particular PHI last time. 6452 if (isa<PHINode>(I)) return nullptr; 6453 6454 std::vector<Constant*> Operands(I->getNumOperands()); 6455 6456 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 6457 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 6458 if (!Operand) { 6459 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 6460 if (!Operands[i]) return nullptr; 6461 continue; 6462 } 6463 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 6464 Vals[Operand] = C; 6465 if (!C) return nullptr; 6466 Operands[i] = C; 6467 } 6468 6469 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 6470 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 6471 Operands[1], DL, TLI); 6472 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 6473 if (!LI->isVolatile()) 6474 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 6475 } 6476 return ConstantFoldInstOperands(I, Operands, DL, TLI); 6477 } 6478 6479 6480 // If every incoming value to PN except the one for BB is a specific Constant, 6481 // return that, else return nullptr. 6482 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 6483 Constant *IncomingVal = nullptr; 6484 6485 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 6486 if (PN->getIncomingBlock(i) == BB) 6487 continue; 6488 6489 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 6490 if (!CurrentVal) 6491 return nullptr; 6492 6493 if (IncomingVal != CurrentVal) { 6494 if (IncomingVal) 6495 return nullptr; 6496 IncomingVal = CurrentVal; 6497 } 6498 } 6499 6500 return IncomingVal; 6501 } 6502 6503 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 6504 /// in the header of its containing loop, we know the loop executes a 6505 /// constant number of times, and the PHI node is just a recurrence 6506 /// involving constants, fold it. 6507 Constant * 6508 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 6509 const APInt &BEs, 6510 const Loop *L) { 6511 auto I = ConstantEvolutionLoopExitValue.find(PN); 6512 if (I != ConstantEvolutionLoopExitValue.end()) 6513 return I->second; 6514 6515 if (BEs.ugt(MaxBruteForceIterations)) 6516 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 6517 6518 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 6519 6520 DenseMap<Instruction *, Constant *> CurrentIterVals; 6521 BasicBlock *Header = L->getHeader(); 6522 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 6523 6524 BasicBlock *Latch = L->getLoopLatch(); 6525 if (!Latch) 6526 return nullptr; 6527 6528 for (auto &I : *Header) { 6529 PHINode *PHI = dyn_cast<PHINode>(&I); 6530 if (!PHI) break; 6531 auto *StartCST = getOtherIncomingValue(PHI, Latch); 6532 if (!StartCST) continue; 6533 CurrentIterVals[PHI] = StartCST; 6534 } 6535 if (!CurrentIterVals.count(PN)) 6536 return RetVal = nullptr; 6537 6538 Value *BEValue = PN->getIncomingValueForBlock(Latch); 6539 6540 // Execute the loop symbolically to determine the exit value. 6541 if (BEs.getActiveBits() >= 32) 6542 return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it! 6543 6544 unsigned NumIterations = BEs.getZExtValue(); // must be in range 6545 unsigned IterationNum = 0; 6546 const DataLayout &DL = getDataLayout(); 6547 for (; ; ++IterationNum) { 6548 if (IterationNum == NumIterations) 6549 return RetVal = CurrentIterVals[PN]; // Got exit value! 6550 6551 // Compute the value of the PHIs for the next iteration. 6552 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 6553 DenseMap<Instruction *, Constant *> NextIterVals; 6554 Constant *NextPHI = 6555 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 6556 if (!NextPHI) 6557 return nullptr; // Couldn't evaluate! 6558 NextIterVals[PN] = NextPHI; 6559 6560 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 6561 6562 // Also evaluate the other PHI nodes. However, we don't get to stop if we 6563 // cease to be able to evaluate one of them or if they stop evolving, 6564 // because that doesn't necessarily prevent us from computing PN. 6565 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 6566 for (const auto &I : CurrentIterVals) { 6567 PHINode *PHI = dyn_cast<PHINode>(I.first); 6568 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 6569 PHIsToCompute.emplace_back(PHI, I.second); 6570 } 6571 // We use two distinct loops because EvaluateExpression may invalidate any 6572 // iterators into CurrentIterVals. 6573 for (const auto &I : PHIsToCompute) { 6574 PHINode *PHI = I.first; 6575 Constant *&NextPHI = NextIterVals[PHI]; 6576 if (!NextPHI) { // Not already computed. 6577 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 6578 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 6579 } 6580 if (NextPHI != I.second) 6581 StoppedEvolving = false; 6582 } 6583 6584 // If all entries in CurrentIterVals == NextIterVals then we can stop 6585 // iterating, the loop can't continue to change. 6586 if (StoppedEvolving) 6587 return RetVal = CurrentIterVals[PN]; 6588 6589 CurrentIterVals.swap(NextIterVals); 6590 } 6591 } 6592 6593 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 6594 Value *Cond, 6595 bool ExitWhen) { 6596 PHINode *PN = getConstantEvolvingPHI(Cond, L); 6597 if (!PN) return getCouldNotCompute(); 6598 6599 // If the loop is canonicalized, the PHI will have exactly two entries. 6600 // That's the only form we support here. 6601 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 6602 6603 DenseMap<Instruction *, Constant *> CurrentIterVals; 6604 BasicBlock *Header = L->getHeader(); 6605 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 6606 6607 BasicBlock *Latch = L->getLoopLatch(); 6608 assert(Latch && "Should follow from NumIncomingValues == 2!"); 6609 6610 for (auto &I : *Header) { 6611 PHINode *PHI = dyn_cast<PHINode>(&I); 6612 if (!PHI) 6613 break; 6614 auto *StartCST = getOtherIncomingValue(PHI, Latch); 6615 if (!StartCST) continue; 6616 CurrentIterVals[PHI] = StartCST; 6617 } 6618 if (!CurrentIterVals.count(PN)) 6619 return getCouldNotCompute(); 6620 6621 // Okay, we find a PHI node that defines the trip count of this loop. Execute 6622 // the loop symbolically to determine when the condition gets a value of 6623 // "ExitWhen". 6624 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 6625 const DataLayout &DL = getDataLayout(); 6626 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 6627 auto *CondVal = dyn_cast_or_null<ConstantInt>( 6628 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 6629 6630 // Couldn't symbolically evaluate. 6631 if (!CondVal) return getCouldNotCompute(); 6632 6633 if (CondVal->getValue() == uint64_t(ExitWhen)) { 6634 ++NumBruteForceTripCountsComputed; 6635 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 6636 } 6637 6638 // Update all the PHI nodes for the next iteration. 6639 DenseMap<Instruction *, Constant *> NextIterVals; 6640 6641 // Create a list of which PHIs we need to compute. We want to do this before 6642 // calling EvaluateExpression on them because that may invalidate iterators 6643 // into CurrentIterVals. 6644 SmallVector<PHINode *, 8> PHIsToCompute; 6645 for (const auto &I : CurrentIterVals) { 6646 PHINode *PHI = dyn_cast<PHINode>(I.first); 6647 if (!PHI || PHI->getParent() != Header) continue; 6648 PHIsToCompute.push_back(PHI); 6649 } 6650 for (PHINode *PHI : PHIsToCompute) { 6651 Constant *&NextPHI = NextIterVals[PHI]; 6652 if (NextPHI) continue; // Already computed! 6653 6654 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 6655 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 6656 } 6657 CurrentIterVals.swap(NextIterVals); 6658 } 6659 6660 // Too many iterations were needed to evaluate. 6661 return getCouldNotCompute(); 6662 } 6663 6664 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 6665 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 6666 ValuesAtScopes[V]; 6667 // Check to see if we've folded this expression at this loop before. 6668 for (auto &LS : Values) 6669 if (LS.first == L) 6670 return LS.second ? LS.second : V; 6671 6672 Values.emplace_back(L, nullptr); 6673 6674 // Otherwise compute it. 6675 const SCEV *C = computeSCEVAtScope(V, L); 6676 for (auto &LS : reverse(ValuesAtScopes[V])) 6677 if (LS.first == L) { 6678 LS.second = C; 6679 break; 6680 } 6681 return C; 6682 } 6683 6684 /// This builds up a Constant using the ConstantExpr interface. That way, we 6685 /// will return Constants for objects which aren't represented by a 6686 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 6687 /// Returns NULL if the SCEV isn't representable as a Constant. 6688 static Constant *BuildConstantFromSCEV(const SCEV *V) { 6689 switch (static_cast<SCEVTypes>(V->getSCEVType())) { 6690 case scCouldNotCompute: 6691 case scAddRecExpr: 6692 break; 6693 case scConstant: 6694 return cast<SCEVConstant>(V)->getValue(); 6695 case scUnknown: 6696 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 6697 case scSignExtend: { 6698 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 6699 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 6700 return ConstantExpr::getSExt(CastOp, SS->getType()); 6701 break; 6702 } 6703 case scZeroExtend: { 6704 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 6705 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 6706 return ConstantExpr::getZExt(CastOp, SZ->getType()); 6707 break; 6708 } 6709 case scTruncate: { 6710 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 6711 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 6712 return ConstantExpr::getTrunc(CastOp, ST->getType()); 6713 break; 6714 } 6715 case scAddExpr: { 6716 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 6717 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 6718 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 6719 unsigned AS = PTy->getAddressSpace(); 6720 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 6721 C = ConstantExpr::getBitCast(C, DestPtrTy); 6722 } 6723 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 6724 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 6725 if (!C2) return nullptr; 6726 6727 // First pointer! 6728 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 6729 unsigned AS = C2->getType()->getPointerAddressSpace(); 6730 std::swap(C, C2); 6731 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 6732 // The offsets have been converted to bytes. We can add bytes to an 6733 // i8* by GEP with the byte count in the first index. 6734 C = ConstantExpr::getBitCast(C, DestPtrTy); 6735 } 6736 6737 // Don't bother trying to sum two pointers. We probably can't 6738 // statically compute a load that results from it anyway. 6739 if (C2->getType()->isPointerTy()) 6740 return nullptr; 6741 6742 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 6743 if (PTy->getElementType()->isStructTy()) 6744 C2 = ConstantExpr::getIntegerCast( 6745 C2, Type::getInt32Ty(C->getContext()), true); 6746 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); 6747 } else 6748 C = ConstantExpr::getAdd(C, C2); 6749 } 6750 return C; 6751 } 6752 break; 6753 } 6754 case scMulExpr: { 6755 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 6756 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 6757 // Don't bother with pointers at all. 6758 if (C->getType()->isPointerTy()) return nullptr; 6759 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 6760 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 6761 if (!C2 || C2->getType()->isPointerTy()) return nullptr; 6762 C = ConstantExpr::getMul(C, C2); 6763 } 6764 return C; 6765 } 6766 break; 6767 } 6768 case scUDivExpr: { 6769 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 6770 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 6771 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 6772 if (LHS->getType() == RHS->getType()) 6773 return ConstantExpr::getUDiv(LHS, RHS); 6774 break; 6775 } 6776 case scSMaxExpr: 6777 case scUMaxExpr: 6778 break; // TODO: smax, umax. 6779 } 6780 return nullptr; 6781 } 6782 6783 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 6784 if (isa<SCEVConstant>(V)) return V; 6785 6786 // If this instruction is evolved from a constant-evolving PHI, compute the 6787 // exit value from the loop without using SCEVs. 6788 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 6789 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 6790 const Loop *LI = this->LI[I->getParent()]; 6791 if (LI && LI->getParentLoop() == L) // Looking for loop exit value. 6792 if (PHINode *PN = dyn_cast<PHINode>(I)) 6793 if (PN->getParent() == LI->getHeader()) { 6794 // Okay, there is no closed form solution for the PHI node. Check 6795 // to see if the loop that contains it has a known backedge-taken 6796 // count. If so, we may be able to force computation of the exit 6797 // value. 6798 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI); 6799 if (const SCEVConstant *BTCC = 6800 dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 6801 // Okay, we know how many times the containing loop executes. If 6802 // this is a constant evolving PHI node, get the final value at 6803 // the specified iteration number. 6804 Constant *RV = 6805 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI); 6806 if (RV) return getSCEV(RV); 6807 } 6808 } 6809 6810 // Okay, this is an expression that we cannot symbolically evaluate 6811 // into a SCEV. Check to see if it's possible to symbolically evaluate 6812 // the arguments into constants, and if so, try to constant propagate the 6813 // result. This is particularly useful for computing loop exit values. 6814 if (CanConstantFold(I)) { 6815 SmallVector<Constant *, 4> Operands; 6816 bool MadeImprovement = false; 6817 for (Value *Op : I->operands()) { 6818 if (Constant *C = dyn_cast<Constant>(Op)) { 6819 Operands.push_back(C); 6820 continue; 6821 } 6822 6823 // If any of the operands is non-constant and if they are 6824 // non-integer and non-pointer, don't even try to analyze them 6825 // with scev techniques. 6826 if (!isSCEVable(Op->getType())) 6827 return V; 6828 6829 const SCEV *OrigV = getSCEV(Op); 6830 const SCEV *OpV = getSCEVAtScope(OrigV, L); 6831 MadeImprovement |= OrigV != OpV; 6832 6833 Constant *C = BuildConstantFromSCEV(OpV); 6834 if (!C) return V; 6835 if (C->getType() != Op->getType()) 6836 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 6837 Op->getType(), 6838 false), 6839 C, Op->getType()); 6840 Operands.push_back(C); 6841 } 6842 6843 // Check to see if getSCEVAtScope actually made an improvement. 6844 if (MadeImprovement) { 6845 Constant *C = nullptr; 6846 const DataLayout &DL = getDataLayout(); 6847 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 6848 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 6849 Operands[1], DL, &TLI); 6850 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) { 6851 if (!LI->isVolatile()) 6852 C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 6853 } else 6854 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 6855 if (!C) return V; 6856 return getSCEV(C); 6857 } 6858 } 6859 } 6860 6861 // This is some other type of SCEVUnknown, just return it. 6862 return V; 6863 } 6864 6865 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 6866 // Avoid performing the look-up in the common case where the specified 6867 // expression has no loop-variant portions. 6868 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 6869 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 6870 if (OpAtScope != Comm->getOperand(i)) { 6871 // Okay, at least one of these operands is loop variant but might be 6872 // foldable. Build a new instance of the folded commutative expression. 6873 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 6874 Comm->op_begin()+i); 6875 NewOps.push_back(OpAtScope); 6876 6877 for (++i; i != e; ++i) { 6878 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 6879 NewOps.push_back(OpAtScope); 6880 } 6881 if (isa<SCEVAddExpr>(Comm)) 6882 return getAddExpr(NewOps); 6883 if (isa<SCEVMulExpr>(Comm)) 6884 return getMulExpr(NewOps); 6885 if (isa<SCEVSMaxExpr>(Comm)) 6886 return getSMaxExpr(NewOps); 6887 if (isa<SCEVUMaxExpr>(Comm)) 6888 return getUMaxExpr(NewOps); 6889 llvm_unreachable("Unknown commutative SCEV type!"); 6890 } 6891 } 6892 // If we got here, all operands are loop invariant. 6893 return Comm; 6894 } 6895 6896 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 6897 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 6898 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 6899 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 6900 return Div; // must be loop invariant 6901 return getUDivExpr(LHS, RHS); 6902 } 6903 6904 // If this is a loop recurrence for a loop that does not contain L, then we 6905 // are dealing with the final value computed by the loop. 6906 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 6907 // First, attempt to evaluate each operand. 6908 // Avoid performing the look-up in the common case where the specified 6909 // expression has no loop-variant portions. 6910 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 6911 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 6912 if (OpAtScope == AddRec->getOperand(i)) 6913 continue; 6914 6915 // Okay, at least one of these operands is loop variant but might be 6916 // foldable. Build a new instance of the folded commutative expression. 6917 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 6918 AddRec->op_begin()+i); 6919 NewOps.push_back(OpAtScope); 6920 for (++i; i != e; ++i) 6921 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 6922 6923 const SCEV *FoldedRec = 6924 getAddRecExpr(NewOps, AddRec->getLoop(), 6925 AddRec->getNoWrapFlags(SCEV::FlagNW)); 6926 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 6927 // The addrec may be folded to a nonrecurrence, for example, if the 6928 // induction variable is multiplied by zero after constant folding. Go 6929 // ahead and return the folded value. 6930 if (!AddRec) 6931 return FoldedRec; 6932 break; 6933 } 6934 6935 // If the scope is outside the addrec's loop, evaluate it by using the 6936 // loop exit value of the addrec. 6937 if (!AddRec->getLoop()->contains(L)) { 6938 // To evaluate this recurrence, we need to know how many times the AddRec 6939 // loop iterates. Compute this now. 6940 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 6941 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 6942 6943 // Then, evaluate the AddRec. 6944 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 6945 } 6946 6947 return AddRec; 6948 } 6949 6950 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 6951 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 6952 if (Op == Cast->getOperand()) 6953 return Cast; // must be loop invariant 6954 return getZeroExtendExpr(Op, Cast->getType()); 6955 } 6956 6957 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 6958 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 6959 if (Op == Cast->getOperand()) 6960 return Cast; // must be loop invariant 6961 return getSignExtendExpr(Op, Cast->getType()); 6962 } 6963 6964 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 6965 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 6966 if (Op == Cast->getOperand()) 6967 return Cast; // must be loop invariant 6968 return getTruncateExpr(Op, Cast->getType()); 6969 } 6970 6971 llvm_unreachable("Unknown SCEV type!"); 6972 } 6973 6974 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 6975 return getSCEVAtScope(getSCEV(V), L); 6976 } 6977 6978 /// Finds the minimum unsigned root of the following equation: 6979 /// 6980 /// A * X = B (mod N) 6981 /// 6982 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 6983 /// A and B isn't important. 6984 /// 6985 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 6986 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B, 6987 ScalarEvolution &SE) { 6988 uint32_t BW = A.getBitWidth(); 6989 assert(BW == B.getBitWidth() && "Bit widths must be the same."); 6990 assert(A != 0 && "A must be non-zero."); 6991 6992 // 1. D = gcd(A, N) 6993 // 6994 // The gcd of A and N may have only one prime factor: 2. The number of 6995 // trailing zeros in A is its multiplicity 6996 uint32_t Mult2 = A.countTrailingZeros(); 6997 // D = 2^Mult2 6998 6999 // 2. Check if B is divisible by D. 7000 // 7001 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 7002 // is not less than multiplicity of this prime factor for D. 7003 if (B.countTrailingZeros() < Mult2) 7004 return SE.getCouldNotCompute(); 7005 7006 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 7007 // modulo (N / D). 7008 // 7009 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this 7010 // bit width during computations. 7011 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 7012 APInt Mod(BW + 1, 0); 7013 Mod.setBit(BW - Mult2); // Mod = N / D 7014 APInt I = AD.multiplicativeInverse(Mod); 7015 7016 // 4. Compute the minimum unsigned root of the equation: 7017 // I * (B / D) mod (N / D) 7018 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod); 7019 7020 // The result is guaranteed to be less than 2^BW so we may truncate it to BW 7021 // bits. 7022 return SE.getConstant(Result.trunc(BW)); 7023 } 7024 7025 /// Find the roots of the quadratic equation for the given quadratic chrec 7026 /// {L,+,M,+,N}. This returns either the two roots (which might be the same) or 7027 /// two SCEVCouldNotCompute objects. 7028 /// 7029 static Optional<std::pair<const SCEVConstant *,const SCEVConstant *>> 7030 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 7031 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 7032 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 7033 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 7034 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 7035 7036 // We currently can only solve this if the coefficients are constants. 7037 if (!LC || !MC || !NC) 7038 return None; 7039 7040 uint32_t BitWidth = LC->getAPInt().getBitWidth(); 7041 const APInt &L = LC->getAPInt(); 7042 const APInt &M = MC->getAPInt(); 7043 const APInt &N = NC->getAPInt(); 7044 APInt Two(BitWidth, 2); 7045 APInt Four(BitWidth, 4); 7046 7047 { 7048 using namespace APIntOps; 7049 const APInt& C = L; 7050 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C 7051 // The B coefficient is M-N/2 7052 APInt B(M); 7053 B -= sdiv(N,Two); 7054 7055 // The A coefficient is N/2 7056 APInt A(N.sdiv(Two)); 7057 7058 // Compute the B^2-4ac term. 7059 APInt SqrtTerm(B); 7060 SqrtTerm *= B; 7061 SqrtTerm -= Four * (A * C); 7062 7063 if (SqrtTerm.isNegative()) { 7064 // The loop is provably infinite. 7065 return None; 7066 } 7067 7068 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest 7069 // integer value or else APInt::sqrt() will assert. 7070 APInt SqrtVal(SqrtTerm.sqrt()); 7071 7072 // Compute the two solutions for the quadratic formula. 7073 // The divisions must be performed as signed divisions. 7074 APInt NegB(-B); 7075 APInt TwoA(A << 1); 7076 if (TwoA.isMinValue()) 7077 return None; 7078 7079 LLVMContext &Context = SE.getContext(); 7080 7081 ConstantInt *Solution1 = 7082 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA)); 7083 ConstantInt *Solution2 = 7084 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA)); 7085 7086 return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)), 7087 cast<SCEVConstant>(SE.getConstant(Solution2))); 7088 } // end APIntOps namespace 7089 } 7090 7091 ScalarEvolution::ExitLimit 7092 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 7093 bool AllowPredicates) { 7094 7095 // This is only used for loops with a "x != y" exit test. The exit condition 7096 // is now expressed as a single expression, V = x-y. So the exit test is 7097 // effectively V != 0. We know and take advantage of the fact that this 7098 // expression only being used in a comparison by zero context. 7099 7100 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 7101 // If the value is a constant 7102 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 7103 // If the value is already zero, the branch will execute zero times. 7104 if (C->getValue()->isZero()) return C; 7105 return getCouldNotCompute(); // Otherwise it will loop infinitely. 7106 } 7107 7108 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V); 7109 if (!AddRec && AllowPredicates) 7110 // Try to make this an AddRec using runtime tests, in the first X 7111 // iterations of this loop, where X is the SCEV expression found by the 7112 // algorithm below. 7113 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 7114 7115 if (!AddRec || AddRec->getLoop() != L) 7116 return getCouldNotCompute(); 7117 7118 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 7119 // the quadratic equation to solve it. 7120 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 7121 if (auto Roots = SolveQuadraticEquation(AddRec, *this)) { 7122 const SCEVConstant *R1 = Roots->first; 7123 const SCEVConstant *R2 = Roots->second; 7124 // Pick the smallest positive root value. 7125 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp( 7126 CmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) { 7127 if (!CB->getZExtValue()) 7128 std::swap(R1, R2); // R1 is the minimum root now. 7129 7130 // We can only use this value if the chrec ends up with an exact zero 7131 // value at this index. When solving for "X*X != 5", for example, we 7132 // should not accept a root of 2. 7133 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this); 7134 if (Val->isZero()) 7135 // We found a quadratic root! 7136 return ExitLimit(R1, R1, false, Predicates); 7137 } 7138 } 7139 return getCouldNotCompute(); 7140 } 7141 7142 // Otherwise we can only handle this if it is affine. 7143 if (!AddRec->isAffine()) 7144 return getCouldNotCompute(); 7145 7146 // If this is an affine expression, the execution count of this branch is 7147 // the minimum unsigned root of the following equation: 7148 // 7149 // Start + Step*N = 0 (mod 2^BW) 7150 // 7151 // equivalent to: 7152 // 7153 // Step*N = -Start (mod 2^BW) 7154 // 7155 // where BW is the common bit width of Start and Step. 7156 7157 // Get the initial value for the loop. 7158 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 7159 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 7160 7161 // For now we handle only constant steps. 7162 // 7163 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 7164 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 7165 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 7166 // We have not yet seen any such cases. 7167 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 7168 if (!StepC || StepC->getValue()->equalsInt(0)) 7169 return getCouldNotCompute(); 7170 7171 // For positive steps (counting up until unsigned overflow): 7172 // N = -Start/Step (as unsigned) 7173 // For negative steps (counting down to zero): 7174 // N = Start/-Step 7175 // First compute the unsigned distance from zero in the direction of Step. 7176 bool CountDown = StepC->getAPInt().isNegative(); 7177 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 7178 7179 // Handle unitary steps, which cannot wraparound. 7180 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 7181 // N = Distance (as unsigned) 7182 if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) { 7183 ConstantRange CR = getUnsignedRange(Start); 7184 const SCEV *MaxBECount; 7185 if (!CountDown && CR.getUnsignedMin().isMinValue()) 7186 // When counting up, the worst starting value is 1, not 0. 7187 MaxBECount = CR.getUnsignedMax().isMinValue() 7188 ? getConstant(APInt::getMinValue(CR.getBitWidth())) 7189 : getConstant(APInt::getMaxValue(CR.getBitWidth())); 7190 else 7191 MaxBECount = getConstant(CountDown ? CR.getUnsignedMax() 7192 : -CR.getUnsignedMin()); 7193 return ExitLimit(Distance, MaxBECount, false, Predicates); 7194 } 7195 7196 // As a special case, handle the instance where Step is a positive power of 7197 // two. In this case, determining whether Step divides Distance evenly can be 7198 // done by counting and comparing the number of trailing zeros of Step and 7199 // Distance. 7200 if (!CountDown) { 7201 const APInt &StepV = StepC->getAPInt(); 7202 // StepV.isPowerOf2() returns true if StepV is an positive power of two. It 7203 // also returns true if StepV is maximally negative (eg, INT_MIN), but that 7204 // case is not handled as this code is guarded by !CountDown. 7205 if (StepV.isPowerOf2() && 7206 GetMinTrailingZeros(Distance) >= StepV.countTrailingZeros()) { 7207 // Here we've constrained the equation to be of the form 7208 // 7209 // 2^(N + k) * Distance' = (StepV == 2^N) * X (mod 2^W) ... (0) 7210 // 7211 // where we're operating on a W bit wide integer domain and k is 7212 // non-negative. The smallest unsigned solution for X is the trip count. 7213 // 7214 // (0) is equivalent to: 7215 // 7216 // 2^(N + k) * Distance' - 2^N * X = L * 2^W 7217 // <=> 2^N(2^k * Distance' - X) = L * 2^(W - N) * 2^N 7218 // <=> 2^k * Distance' - X = L * 2^(W - N) 7219 // <=> 2^k * Distance' = L * 2^(W - N) + X ... (1) 7220 // 7221 // The smallest X satisfying (1) is unsigned remainder of dividing the LHS 7222 // by 2^(W - N). 7223 // 7224 // <=> X = 2^k * Distance' URem 2^(W - N) ... (2) 7225 // 7226 // E.g. say we're solving 7227 // 7228 // 2 * Val = 2 * X (in i8) ... (3) 7229 // 7230 // then from (2), we get X = Val URem i8 128 (k = 0 in this case). 7231 // 7232 // Note: It is tempting to solve (3) by setting X = Val, but Val is not 7233 // necessarily the smallest unsigned value of X that satisfies (3). 7234 // E.g. if Val is i8 -127 then the smallest value of X that satisfies (3) 7235 // is i8 1, not i8 -127 7236 7237 const auto *ModuloResult = getUDivExactExpr(Distance, Step); 7238 7239 // Since SCEV does not have a URem node, we construct one using a truncate 7240 // and a zero extend. 7241 7242 unsigned NarrowWidth = StepV.getBitWidth() - StepV.countTrailingZeros(); 7243 auto *NarrowTy = IntegerType::get(getContext(), NarrowWidth); 7244 auto *WideTy = Distance->getType(); 7245 7246 const SCEV *Limit = 7247 getZeroExtendExpr(getTruncateExpr(ModuloResult, NarrowTy), WideTy); 7248 return ExitLimit(Limit, Limit, false, Predicates); 7249 } 7250 } 7251 7252 // If the condition controls loop exit (the loop exits only if the expression 7253 // is true) and the addition is no-wrap we can use unsigned divide to 7254 // compute the backedge count. In this case, the step may not divide the 7255 // distance, but we don't care because if the condition is "missed" the loop 7256 // will have undefined behavior due to wrapping. 7257 if (ControlsExit && AddRec->hasNoSelfWrap() && 7258 loopHasNoAbnormalExits(AddRec->getLoop())) { 7259 const SCEV *Exact = 7260 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 7261 return ExitLimit(Exact, Exact, false, Predicates); 7262 } 7263 7264 // Then, try to solve the above equation provided that Start is constant. 7265 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) { 7266 const SCEV *E = SolveLinEquationWithOverflow( 7267 StepC->getValue()->getValue(), -StartC->getValue()->getValue(), *this); 7268 return ExitLimit(E, E, false, Predicates); 7269 } 7270 return getCouldNotCompute(); 7271 } 7272 7273 ScalarEvolution::ExitLimit 7274 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 7275 // Loops that look like: while (X == 0) are very strange indeed. We don't 7276 // handle them yet except for the trivial case. This could be expanded in the 7277 // future as needed. 7278 7279 // If the value is a constant, check to see if it is known to be non-zero 7280 // already. If so, the backedge will execute zero times. 7281 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 7282 if (!C->getValue()->isNullValue()) 7283 return getZero(C->getType()); 7284 return getCouldNotCompute(); // Otherwise it will loop infinitely. 7285 } 7286 7287 // We could implement others, but I really doubt anyone writes loops like 7288 // this, and if they did, they would already be constant folded. 7289 return getCouldNotCompute(); 7290 } 7291 7292 std::pair<BasicBlock *, BasicBlock *> 7293 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) { 7294 // If the block has a unique predecessor, then there is no path from the 7295 // predecessor to the block that does not go through the direct edge 7296 // from the predecessor to the block. 7297 if (BasicBlock *Pred = BB->getSinglePredecessor()) 7298 return {Pred, BB}; 7299 7300 // A loop's header is defined to be a block that dominates the loop. 7301 // If the header has a unique predecessor outside the loop, it must be 7302 // a block that has exactly one successor that can reach the loop. 7303 if (Loop *L = LI.getLoopFor(BB)) 7304 return {L->getLoopPredecessor(), L->getHeader()}; 7305 7306 return {nullptr, nullptr}; 7307 } 7308 7309 /// SCEV structural equivalence is usually sufficient for testing whether two 7310 /// expressions are equal, however for the purposes of looking for a condition 7311 /// guarding a loop, it can be useful to be a little more general, since a 7312 /// front-end may have replicated the controlling expression. 7313 /// 7314 static bool HasSameValue(const SCEV *A, const SCEV *B) { 7315 // Quick check to see if they are the same SCEV. 7316 if (A == B) return true; 7317 7318 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 7319 // Not all instructions that are "identical" compute the same value. For 7320 // instance, two distinct alloca instructions allocating the same type are 7321 // identical and do not read memory; but compute distinct values. 7322 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 7323 }; 7324 7325 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 7326 // two different instructions with the same value. Check for this case. 7327 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 7328 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 7329 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 7330 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 7331 if (ComputesEqualValues(AI, BI)) 7332 return true; 7333 7334 // Otherwise assume they may have a different value. 7335 return false; 7336 } 7337 7338 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 7339 const SCEV *&LHS, const SCEV *&RHS, 7340 unsigned Depth) { 7341 bool Changed = false; 7342 7343 // If we hit the max recursion limit bail out. 7344 if (Depth >= 3) 7345 return false; 7346 7347 // Canonicalize a constant to the right side. 7348 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 7349 // Check for both operands constant. 7350 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 7351 if (ConstantExpr::getICmp(Pred, 7352 LHSC->getValue(), 7353 RHSC->getValue())->isNullValue()) 7354 goto trivially_false; 7355 else 7356 goto trivially_true; 7357 } 7358 // Otherwise swap the operands to put the constant on the right. 7359 std::swap(LHS, RHS); 7360 Pred = ICmpInst::getSwappedPredicate(Pred); 7361 Changed = true; 7362 } 7363 7364 // If we're comparing an addrec with a value which is loop-invariant in the 7365 // addrec's loop, put the addrec on the left. Also make a dominance check, 7366 // as both operands could be addrecs loop-invariant in each other's loop. 7367 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 7368 const Loop *L = AR->getLoop(); 7369 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 7370 std::swap(LHS, RHS); 7371 Pred = ICmpInst::getSwappedPredicate(Pred); 7372 Changed = true; 7373 } 7374 } 7375 7376 // If there's a constant operand, canonicalize comparisons with boundary 7377 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 7378 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 7379 const APInt &RA = RC->getAPInt(); 7380 7381 bool SimplifiedByConstantRange = false; 7382 7383 if (!ICmpInst::isEquality(Pred)) { 7384 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 7385 if (ExactCR.isFullSet()) 7386 goto trivially_true; 7387 else if (ExactCR.isEmptySet()) 7388 goto trivially_false; 7389 7390 APInt NewRHS; 7391 CmpInst::Predicate NewPred; 7392 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 7393 ICmpInst::isEquality(NewPred)) { 7394 // We were able to convert an inequality to an equality. 7395 Pred = NewPred; 7396 RHS = getConstant(NewRHS); 7397 Changed = SimplifiedByConstantRange = true; 7398 } 7399 } 7400 7401 if (!SimplifiedByConstantRange) { 7402 switch (Pred) { 7403 default: 7404 break; 7405 case ICmpInst::ICMP_EQ: 7406 case ICmpInst::ICMP_NE: 7407 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 7408 if (!RA) 7409 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 7410 if (const SCEVMulExpr *ME = 7411 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 7412 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 7413 ME->getOperand(0)->isAllOnesValue()) { 7414 RHS = AE->getOperand(1); 7415 LHS = ME->getOperand(1); 7416 Changed = true; 7417 } 7418 break; 7419 7420 7421 // The "Should have been caught earlier!" messages refer to the fact 7422 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 7423 // should have fired on the corresponding cases, and canonicalized the 7424 // check to trivially_true or trivially_false. 7425 7426 case ICmpInst::ICMP_UGE: 7427 assert(!RA.isMinValue() && "Should have been caught earlier!"); 7428 Pred = ICmpInst::ICMP_UGT; 7429 RHS = getConstant(RA - 1); 7430 Changed = true; 7431 break; 7432 case ICmpInst::ICMP_ULE: 7433 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 7434 Pred = ICmpInst::ICMP_ULT; 7435 RHS = getConstant(RA + 1); 7436 Changed = true; 7437 break; 7438 case ICmpInst::ICMP_SGE: 7439 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 7440 Pred = ICmpInst::ICMP_SGT; 7441 RHS = getConstant(RA - 1); 7442 Changed = true; 7443 break; 7444 case ICmpInst::ICMP_SLE: 7445 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 7446 Pred = ICmpInst::ICMP_SLT; 7447 RHS = getConstant(RA + 1); 7448 Changed = true; 7449 break; 7450 } 7451 } 7452 } 7453 7454 // Check for obvious equality. 7455 if (HasSameValue(LHS, RHS)) { 7456 if (ICmpInst::isTrueWhenEqual(Pred)) 7457 goto trivially_true; 7458 if (ICmpInst::isFalseWhenEqual(Pred)) 7459 goto trivially_false; 7460 } 7461 7462 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 7463 // adding or subtracting 1 from one of the operands. 7464 switch (Pred) { 7465 case ICmpInst::ICMP_SLE: 7466 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) { 7467 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 7468 SCEV::FlagNSW); 7469 Pred = ICmpInst::ICMP_SLT; 7470 Changed = true; 7471 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) { 7472 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 7473 SCEV::FlagNSW); 7474 Pred = ICmpInst::ICMP_SLT; 7475 Changed = true; 7476 } 7477 break; 7478 case ICmpInst::ICMP_SGE: 7479 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) { 7480 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 7481 SCEV::FlagNSW); 7482 Pred = ICmpInst::ICMP_SGT; 7483 Changed = true; 7484 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) { 7485 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 7486 SCEV::FlagNSW); 7487 Pred = ICmpInst::ICMP_SGT; 7488 Changed = true; 7489 } 7490 break; 7491 case ICmpInst::ICMP_ULE: 7492 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) { 7493 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 7494 SCEV::FlagNUW); 7495 Pred = ICmpInst::ICMP_ULT; 7496 Changed = true; 7497 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) { 7498 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 7499 Pred = ICmpInst::ICMP_ULT; 7500 Changed = true; 7501 } 7502 break; 7503 case ICmpInst::ICMP_UGE: 7504 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) { 7505 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 7506 Pred = ICmpInst::ICMP_UGT; 7507 Changed = true; 7508 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) { 7509 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 7510 SCEV::FlagNUW); 7511 Pred = ICmpInst::ICMP_UGT; 7512 Changed = true; 7513 } 7514 break; 7515 default: 7516 break; 7517 } 7518 7519 // TODO: More simplifications are possible here. 7520 7521 // Recursively simplify until we either hit a recursion limit or nothing 7522 // changes. 7523 if (Changed) 7524 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 7525 7526 return Changed; 7527 7528 trivially_true: 7529 // Return 0 == 0. 7530 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 7531 Pred = ICmpInst::ICMP_EQ; 7532 return true; 7533 7534 trivially_false: 7535 // Return 0 != 0. 7536 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 7537 Pred = ICmpInst::ICMP_NE; 7538 return true; 7539 } 7540 7541 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 7542 return getSignedRange(S).getSignedMax().isNegative(); 7543 } 7544 7545 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 7546 return getSignedRange(S).getSignedMin().isStrictlyPositive(); 7547 } 7548 7549 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 7550 return !getSignedRange(S).getSignedMin().isNegative(); 7551 } 7552 7553 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 7554 return !getSignedRange(S).getSignedMax().isStrictlyPositive(); 7555 } 7556 7557 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 7558 return isKnownNegative(S) || isKnownPositive(S); 7559 } 7560 7561 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 7562 const SCEV *LHS, const SCEV *RHS) { 7563 // Canonicalize the inputs first. 7564 (void)SimplifyICmpOperands(Pred, LHS, RHS); 7565 7566 // If LHS or RHS is an addrec, check to see if the condition is true in 7567 // every iteration of the loop. 7568 // If LHS and RHS are both addrec, both conditions must be true in 7569 // every iteration of the loop. 7570 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 7571 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 7572 bool LeftGuarded = false; 7573 bool RightGuarded = false; 7574 if (LAR) { 7575 const Loop *L = LAR->getLoop(); 7576 if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) && 7577 isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) { 7578 if (!RAR) return true; 7579 LeftGuarded = true; 7580 } 7581 } 7582 if (RAR) { 7583 const Loop *L = RAR->getLoop(); 7584 if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) && 7585 isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) { 7586 if (!LAR) return true; 7587 RightGuarded = true; 7588 } 7589 } 7590 if (LeftGuarded && RightGuarded) 7591 return true; 7592 7593 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 7594 return true; 7595 7596 // Otherwise see what can be done with known constant ranges. 7597 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS); 7598 } 7599 7600 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS, 7601 ICmpInst::Predicate Pred, 7602 bool &Increasing) { 7603 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing); 7604 7605 #ifndef NDEBUG 7606 // Verify an invariant: inverting the predicate should turn a monotonically 7607 // increasing change to a monotonically decreasing one, and vice versa. 7608 bool IncreasingSwapped; 7609 bool ResultSwapped = isMonotonicPredicateImpl( 7610 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped); 7611 7612 assert(Result == ResultSwapped && "should be able to analyze both!"); 7613 if (ResultSwapped) 7614 assert(Increasing == !IncreasingSwapped && 7615 "monotonicity should flip as we flip the predicate"); 7616 #endif 7617 7618 return Result; 7619 } 7620 7621 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS, 7622 ICmpInst::Predicate Pred, 7623 bool &Increasing) { 7624 7625 // A zero step value for LHS means the induction variable is essentially a 7626 // loop invariant value. We don't really depend on the predicate actually 7627 // flipping from false to true (for increasing predicates, and the other way 7628 // around for decreasing predicates), all we care about is that *if* the 7629 // predicate changes then it only changes from false to true. 7630 // 7631 // A zero step value in itself is not very useful, but there may be places 7632 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 7633 // as general as possible. 7634 7635 switch (Pred) { 7636 default: 7637 return false; // Conservative answer 7638 7639 case ICmpInst::ICMP_UGT: 7640 case ICmpInst::ICMP_UGE: 7641 case ICmpInst::ICMP_ULT: 7642 case ICmpInst::ICMP_ULE: 7643 if (!LHS->hasNoUnsignedWrap()) 7644 return false; 7645 7646 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE; 7647 return true; 7648 7649 case ICmpInst::ICMP_SGT: 7650 case ICmpInst::ICMP_SGE: 7651 case ICmpInst::ICMP_SLT: 7652 case ICmpInst::ICMP_SLE: { 7653 if (!LHS->hasNoSignedWrap()) 7654 return false; 7655 7656 const SCEV *Step = LHS->getStepRecurrence(*this); 7657 7658 if (isKnownNonNegative(Step)) { 7659 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE; 7660 return true; 7661 } 7662 7663 if (isKnownNonPositive(Step)) { 7664 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE; 7665 return true; 7666 } 7667 7668 return false; 7669 } 7670 7671 } 7672 7673 llvm_unreachable("switch has default clause!"); 7674 } 7675 7676 bool ScalarEvolution::isLoopInvariantPredicate( 7677 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 7678 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS, 7679 const SCEV *&InvariantRHS) { 7680 7681 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 7682 if (!isLoopInvariant(RHS, L)) { 7683 if (!isLoopInvariant(LHS, L)) 7684 return false; 7685 7686 std::swap(LHS, RHS); 7687 Pred = ICmpInst::getSwappedPredicate(Pred); 7688 } 7689 7690 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 7691 if (!ArLHS || ArLHS->getLoop() != L) 7692 return false; 7693 7694 bool Increasing; 7695 if (!isMonotonicPredicate(ArLHS, Pred, Increasing)) 7696 return false; 7697 7698 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 7699 // true as the loop iterates, and the backedge is control dependent on 7700 // "ArLHS `Pred` RHS" == true then we can reason as follows: 7701 // 7702 // * if the predicate was false in the first iteration then the predicate 7703 // is never evaluated again, since the loop exits without taking the 7704 // backedge. 7705 // * if the predicate was true in the first iteration then it will 7706 // continue to be true for all future iterations since it is 7707 // monotonically increasing. 7708 // 7709 // For both the above possibilities, we can replace the loop varying 7710 // predicate with its value on the first iteration of the loop (which is 7711 // loop invariant). 7712 // 7713 // A similar reasoning applies for a monotonically decreasing predicate, by 7714 // replacing true with false and false with true in the above two bullets. 7715 7716 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 7717 7718 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 7719 return false; 7720 7721 InvariantPred = Pred; 7722 InvariantLHS = ArLHS->getStart(); 7723 InvariantRHS = RHS; 7724 return true; 7725 } 7726 7727 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 7728 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 7729 if (HasSameValue(LHS, RHS)) 7730 return ICmpInst::isTrueWhenEqual(Pred); 7731 7732 // This code is split out from isKnownPredicate because it is called from 7733 // within isLoopEntryGuardedByCond. 7734 7735 auto CheckRanges = 7736 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) { 7737 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS) 7738 .contains(RangeLHS); 7739 }; 7740 7741 // The check at the top of the function catches the case where the values are 7742 // known to be equal. 7743 if (Pred == CmpInst::ICMP_EQ) 7744 return false; 7745 7746 if (Pred == CmpInst::ICMP_NE) 7747 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 7748 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) || 7749 isKnownNonZero(getMinusSCEV(LHS, RHS)); 7750 7751 if (CmpInst::isSigned(Pred)) 7752 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 7753 7754 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 7755 } 7756 7757 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 7758 const SCEV *LHS, 7759 const SCEV *RHS) { 7760 7761 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer. 7762 // Return Y via OutY. 7763 auto MatchBinaryAddToConst = 7764 [this](const SCEV *Result, const SCEV *X, APInt &OutY, 7765 SCEV::NoWrapFlags ExpectedFlags) { 7766 const SCEV *NonConstOp, *ConstOp; 7767 SCEV::NoWrapFlags FlagsPresent; 7768 7769 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) || 7770 !isa<SCEVConstant>(ConstOp) || NonConstOp != X) 7771 return false; 7772 7773 OutY = cast<SCEVConstant>(ConstOp)->getAPInt(); 7774 return (FlagsPresent & ExpectedFlags) == ExpectedFlags; 7775 }; 7776 7777 APInt C; 7778 7779 switch (Pred) { 7780 default: 7781 break; 7782 7783 case ICmpInst::ICMP_SGE: 7784 std::swap(LHS, RHS); 7785 case ICmpInst::ICMP_SLE: 7786 // X s<= (X + C)<nsw> if C >= 0 7787 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative()) 7788 return true; 7789 7790 // (X + C)<nsw> s<= X if C <= 0 7791 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && 7792 !C.isStrictlyPositive()) 7793 return true; 7794 break; 7795 7796 case ICmpInst::ICMP_SGT: 7797 std::swap(LHS, RHS); 7798 case ICmpInst::ICMP_SLT: 7799 // X s< (X + C)<nsw> if C > 0 7800 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && 7801 C.isStrictlyPositive()) 7802 return true; 7803 7804 // (X + C)<nsw> s< X if C < 0 7805 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative()) 7806 return true; 7807 break; 7808 } 7809 7810 return false; 7811 } 7812 7813 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 7814 const SCEV *LHS, 7815 const SCEV *RHS) { 7816 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 7817 return false; 7818 7819 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 7820 // the stack can result in exponential time complexity. 7821 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 7822 7823 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 7824 // 7825 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 7826 // isKnownPredicate. isKnownPredicate is more powerful, but also more 7827 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 7828 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 7829 // use isKnownPredicate later if needed. 7830 return isKnownNonNegative(RHS) && 7831 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 7832 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 7833 } 7834 7835 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB, 7836 ICmpInst::Predicate Pred, 7837 const SCEV *LHS, const SCEV *RHS) { 7838 // No need to even try if we know the module has no guards. 7839 if (!HasGuards) 7840 return false; 7841 7842 return any_of(*BB, [&](Instruction &I) { 7843 using namespace llvm::PatternMatch; 7844 7845 Value *Condition; 7846 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 7847 m_Value(Condition))) && 7848 isImpliedCond(Pred, LHS, RHS, Condition, false); 7849 }); 7850 } 7851 7852 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 7853 /// protected by a conditional between LHS and RHS. This is used to 7854 /// to eliminate casts. 7855 bool 7856 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 7857 ICmpInst::Predicate Pred, 7858 const SCEV *LHS, const SCEV *RHS) { 7859 // Interpret a null as meaning no loop, where there is obviously no guard 7860 // (interprocedural conditions notwithstanding). 7861 if (!L) return true; 7862 7863 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS)) 7864 return true; 7865 7866 BasicBlock *Latch = L->getLoopLatch(); 7867 if (!Latch) 7868 return false; 7869 7870 BranchInst *LoopContinuePredicate = 7871 dyn_cast<BranchInst>(Latch->getTerminator()); 7872 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 7873 isImpliedCond(Pred, LHS, RHS, 7874 LoopContinuePredicate->getCondition(), 7875 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 7876 return true; 7877 7878 // We don't want more than one activation of the following loops on the stack 7879 // -- that can lead to O(n!) time complexity. 7880 if (WalkingBEDominatingConds) 7881 return false; 7882 7883 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 7884 7885 // See if we can exploit a trip count to prove the predicate. 7886 const auto &BETakenInfo = getBackedgeTakenInfo(L); 7887 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 7888 if (LatchBECount != getCouldNotCompute()) { 7889 // We know that Latch branches back to the loop header exactly 7890 // LatchBECount times. This means the backdege condition at Latch is 7891 // equivalent to "{0,+,1} u< LatchBECount". 7892 Type *Ty = LatchBECount->getType(); 7893 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 7894 const SCEV *LoopCounter = 7895 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 7896 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 7897 LatchBECount)) 7898 return true; 7899 } 7900 7901 // Check conditions due to any @llvm.assume intrinsics. 7902 for (auto &AssumeVH : AC.assumptions()) { 7903 if (!AssumeVH) 7904 continue; 7905 auto *CI = cast<CallInst>(AssumeVH); 7906 if (!DT.dominates(CI, Latch->getTerminator())) 7907 continue; 7908 7909 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 7910 return true; 7911 } 7912 7913 // If the loop is not reachable from the entry block, we risk running into an 7914 // infinite loop as we walk up into the dom tree. These loops do not matter 7915 // anyway, so we just return a conservative answer when we see them. 7916 if (!DT.isReachableFromEntry(L->getHeader())) 7917 return false; 7918 7919 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 7920 return true; 7921 7922 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 7923 DTN != HeaderDTN; DTN = DTN->getIDom()) { 7924 7925 assert(DTN && "should reach the loop header before reaching the root!"); 7926 7927 BasicBlock *BB = DTN->getBlock(); 7928 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 7929 return true; 7930 7931 BasicBlock *PBB = BB->getSinglePredecessor(); 7932 if (!PBB) 7933 continue; 7934 7935 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 7936 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 7937 continue; 7938 7939 Value *Condition = ContinuePredicate->getCondition(); 7940 7941 // If we have an edge `E` within the loop body that dominates the only 7942 // latch, the condition guarding `E` also guards the backedge. This 7943 // reasoning works only for loops with a single latch. 7944 7945 BasicBlockEdge DominatingEdge(PBB, BB); 7946 if (DominatingEdge.isSingleEdge()) { 7947 // We're constructively (and conservatively) enumerating edges within the 7948 // loop body that dominate the latch. The dominator tree better agree 7949 // with us on this: 7950 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 7951 7952 if (isImpliedCond(Pred, LHS, RHS, Condition, 7953 BB != ContinuePredicate->getSuccessor(0))) 7954 return true; 7955 } 7956 } 7957 7958 return false; 7959 } 7960 7961 bool 7962 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 7963 ICmpInst::Predicate Pred, 7964 const SCEV *LHS, const SCEV *RHS) { 7965 // Interpret a null as meaning no loop, where there is obviously no guard 7966 // (interprocedural conditions notwithstanding). 7967 if (!L) return false; 7968 7969 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS)) 7970 return true; 7971 7972 // Starting at the loop predecessor, climb up the predecessor chain, as long 7973 // as there are predecessors that can be found that have unique successors 7974 // leading to the original header. 7975 for (std::pair<BasicBlock *, BasicBlock *> 7976 Pair(L->getLoopPredecessor(), L->getHeader()); 7977 Pair.first; 7978 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 7979 7980 if (isImpliedViaGuard(Pair.first, Pred, LHS, RHS)) 7981 return true; 7982 7983 BranchInst *LoopEntryPredicate = 7984 dyn_cast<BranchInst>(Pair.first->getTerminator()); 7985 if (!LoopEntryPredicate || 7986 LoopEntryPredicate->isUnconditional()) 7987 continue; 7988 7989 if (isImpliedCond(Pred, LHS, RHS, 7990 LoopEntryPredicate->getCondition(), 7991 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 7992 return true; 7993 } 7994 7995 // Check conditions due to any @llvm.assume intrinsics. 7996 for (auto &AssumeVH : AC.assumptions()) { 7997 if (!AssumeVH) 7998 continue; 7999 auto *CI = cast<CallInst>(AssumeVH); 8000 if (!DT.dominates(CI, L->getHeader())) 8001 continue; 8002 8003 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 8004 return true; 8005 } 8006 8007 return false; 8008 } 8009 8010 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, 8011 const SCEV *LHS, const SCEV *RHS, 8012 Value *FoundCondValue, 8013 bool Inverse) { 8014 if (!PendingLoopPredicates.insert(FoundCondValue).second) 8015 return false; 8016 8017 auto ClearOnExit = 8018 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 8019 8020 // Recursively handle And and Or conditions. 8021 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) { 8022 if (BO->getOpcode() == Instruction::And) { 8023 if (!Inverse) 8024 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 8025 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 8026 } else if (BO->getOpcode() == Instruction::Or) { 8027 if (Inverse) 8028 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 8029 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 8030 } 8031 } 8032 8033 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 8034 if (!ICI) return false; 8035 8036 // Now that we found a conditional branch that dominates the loop or controls 8037 // the loop latch. Check to see if it is the comparison we are looking for. 8038 ICmpInst::Predicate FoundPred; 8039 if (Inverse) 8040 FoundPred = ICI->getInversePredicate(); 8041 else 8042 FoundPred = ICI->getPredicate(); 8043 8044 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 8045 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 8046 8047 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS); 8048 } 8049 8050 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 8051 const SCEV *RHS, 8052 ICmpInst::Predicate FoundPred, 8053 const SCEV *FoundLHS, 8054 const SCEV *FoundRHS) { 8055 // Balance the types. 8056 if (getTypeSizeInBits(LHS->getType()) < 8057 getTypeSizeInBits(FoundLHS->getType())) { 8058 if (CmpInst::isSigned(Pred)) { 8059 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 8060 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 8061 } else { 8062 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 8063 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 8064 } 8065 } else if (getTypeSizeInBits(LHS->getType()) > 8066 getTypeSizeInBits(FoundLHS->getType())) { 8067 if (CmpInst::isSigned(FoundPred)) { 8068 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 8069 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 8070 } else { 8071 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 8072 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 8073 } 8074 } 8075 8076 // Canonicalize the query to match the way instcombine will have 8077 // canonicalized the comparison. 8078 if (SimplifyICmpOperands(Pred, LHS, RHS)) 8079 if (LHS == RHS) 8080 return CmpInst::isTrueWhenEqual(Pred); 8081 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 8082 if (FoundLHS == FoundRHS) 8083 return CmpInst::isFalseWhenEqual(FoundPred); 8084 8085 // Check to see if we can make the LHS or RHS match. 8086 if (LHS == FoundRHS || RHS == FoundLHS) { 8087 if (isa<SCEVConstant>(RHS)) { 8088 std::swap(FoundLHS, FoundRHS); 8089 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 8090 } else { 8091 std::swap(LHS, RHS); 8092 Pred = ICmpInst::getSwappedPredicate(Pred); 8093 } 8094 } 8095 8096 // Check whether the found predicate is the same as the desired predicate. 8097 if (FoundPred == Pred) 8098 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 8099 8100 // Check whether swapping the found predicate makes it the same as the 8101 // desired predicate. 8102 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 8103 if (isa<SCEVConstant>(RHS)) 8104 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS); 8105 else 8106 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), 8107 RHS, LHS, FoundLHS, FoundRHS); 8108 } 8109 8110 // Unsigned comparison is the same as signed comparison when both the operands 8111 // are non-negative. 8112 if (CmpInst::isUnsigned(FoundPred) && 8113 CmpInst::getSignedPredicate(FoundPred) == Pred && 8114 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) 8115 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 8116 8117 // Check if we can make progress by sharpening ranges. 8118 if (FoundPred == ICmpInst::ICMP_NE && 8119 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 8120 8121 const SCEVConstant *C = nullptr; 8122 const SCEV *V = nullptr; 8123 8124 if (isa<SCEVConstant>(FoundLHS)) { 8125 C = cast<SCEVConstant>(FoundLHS); 8126 V = FoundRHS; 8127 } else { 8128 C = cast<SCEVConstant>(FoundRHS); 8129 V = FoundLHS; 8130 } 8131 8132 // The guarding predicate tells us that C != V. If the known range 8133 // of V is [C, t), we can sharpen the range to [C + 1, t). The 8134 // range we consider has to correspond to same signedness as the 8135 // predicate we're interested in folding. 8136 8137 APInt Min = ICmpInst::isSigned(Pred) ? 8138 getSignedRange(V).getSignedMin() : getUnsignedRange(V).getUnsignedMin(); 8139 8140 if (Min == C->getAPInt()) { 8141 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 8142 // This is true even if (Min + 1) wraps around -- in case of 8143 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 8144 8145 APInt SharperMin = Min + 1; 8146 8147 switch (Pred) { 8148 case ICmpInst::ICMP_SGE: 8149 case ICmpInst::ICMP_UGE: 8150 // We know V `Pred` SharperMin. If this implies LHS `Pred` 8151 // RHS, we're done. 8152 if (isImpliedCondOperands(Pred, LHS, RHS, V, 8153 getConstant(SharperMin))) 8154 return true; 8155 8156 case ICmpInst::ICMP_SGT: 8157 case ICmpInst::ICMP_UGT: 8158 // We know from the range information that (V `Pred` Min || 8159 // V == Min). We know from the guarding condition that !(V 8160 // == Min). This gives us 8161 // 8162 // V `Pred` Min || V == Min && !(V == Min) 8163 // => V `Pred` Min 8164 // 8165 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 8166 8167 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min))) 8168 return true; 8169 8170 default: 8171 // No change 8172 break; 8173 } 8174 } 8175 } 8176 8177 // Check whether the actual condition is beyond sufficient. 8178 if (FoundPred == ICmpInst::ICMP_EQ) 8179 if (ICmpInst::isTrueWhenEqual(Pred)) 8180 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS)) 8181 return true; 8182 if (Pred == ICmpInst::ICMP_NE) 8183 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 8184 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS)) 8185 return true; 8186 8187 // Otherwise assume the worst. 8188 return false; 8189 } 8190 8191 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 8192 const SCEV *&L, const SCEV *&R, 8193 SCEV::NoWrapFlags &Flags) { 8194 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 8195 if (!AE || AE->getNumOperands() != 2) 8196 return false; 8197 8198 L = AE->getOperand(0); 8199 R = AE->getOperand(1); 8200 Flags = AE->getNoWrapFlags(); 8201 return true; 8202 } 8203 8204 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 8205 const SCEV *Less) { 8206 // We avoid subtracting expressions here because this function is usually 8207 // fairly deep in the call stack (i.e. is called many times). 8208 8209 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 8210 const auto *LAR = cast<SCEVAddRecExpr>(Less); 8211 const auto *MAR = cast<SCEVAddRecExpr>(More); 8212 8213 if (LAR->getLoop() != MAR->getLoop()) 8214 return None; 8215 8216 // We look at affine expressions only; not for correctness but to keep 8217 // getStepRecurrence cheap. 8218 if (!LAR->isAffine() || !MAR->isAffine()) 8219 return None; 8220 8221 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 8222 return None; 8223 8224 Less = LAR->getStart(); 8225 More = MAR->getStart(); 8226 8227 // fall through 8228 } 8229 8230 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 8231 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 8232 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 8233 return M - L; 8234 } 8235 8236 const SCEV *L, *R; 8237 SCEV::NoWrapFlags Flags; 8238 if (splitBinaryAdd(Less, L, R, Flags)) 8239 if (const auto *LC = dyn_cast<SCEVConstant>(L)) 8240 if (R == More) 8241 return -(LC->getAPInt()); 8242 8243 if (splitBinaryAdd(More, L, R, Flags)) 8244 if (const auto *LC = dyn_cast<SCEVConstant>(L)) 8245 if (R == Less) 8246 return LC->getAPInt(); 8247 8248 return None; 8249 } 8250 8251 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 8252 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 8253 const SCEV *FoundLHS, const SCEV *FoundRHS) { 8254 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 8255 return false; 8256 8257 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 8258 if (!AddRecLHS) 8259 return false; 8260 8261 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 8262 if (!AddRecFoundLHS) 8263 return false; 8264 8265 // We'd like to let SCEV reason about control dependencies, so we constrain 8266 // both the inequalities to be about add recurrences on the same loop. This 8267 // way we can use isLoopEntryGuardedByCond later. 8268 8269 const Loop *L = AddRecFoundLHS->getLoop(); 8270 if (L != AddRecLHS->getLoop()) 8271 return false; 8272 8273 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 8274 // 8275 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 8276 // ... (2) 8277 // 8278 // Informal proof for (2), assuming (1) [*]: 8279 // 8280 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 8281 // 8282 // Then 8283 // 8284 // FoundLHS s< FoundRHS s< INT_MIN - C 8285 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 8286 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 8287 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 8288 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 8289 // <=> FoundLHS + C s< FoundRHS + C 8290 // 8291 // [*]: (1) can be proved by ruling out overflow. 8292 // 8293 // [**]: This can be proved by analyzing all the four possibilities: 8294 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 8295 // (A s>= 0, B s>= 0). 8296 // 8297 // Note: 8298 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 8299 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 8300 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 8301 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 8302 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 8303 // C)". 8304 8305 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 8306 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 8307 if (!LDiff || !RDiff || *LDiff != *RDiff) 8308 return false; 8309 8310 if (LDiff->isMinValue()) 8311 return true; 8312 8313 APInt FoundRHSLimit; 8314 8315 if (Pred == CmpInst::ICMP_ULT) { 8316 FoundRHSLimit = -(*RDiff); 8317 } else { 8318 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 8319 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 8320 } 8321 8322 // Try to prove (1) or (2), as needed. 8323 return isLoopEntryGuardedByCond(L, Pred, FoundRHS, 8324 getConstant(FoundRHSLimit)); 8325 } 8326 8327 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 8328 const SCEV *LHS, const SCEV *RHS, 8329 const SCEV *FoundLHS, 8330 const SCEV *FoundRHS) { 8331 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 8332 return true; 8333 8334 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 8335 return true; 8336 8337 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 8338 FoundLHS, FoundRHS) || 8339 // ~x < ~y --> x > y 8340 isImpliedCondOperandsHelper(Pred, LHS, RHS, 8341 getNotSCEV(FoundRHS), 8342 getNotSCEV(FoundLHS)); 8343 } 8344 8345 8346 /// If Expr computes ~A, return A else return nullptr 8347 static const SCEV *MatchNotExpr(const SCEV *Expr) { 8348 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 8349 if (!Add || Add->getNumOperands() != 2 || 8350 !Add->getOperand(0)->isAllOnesValue()) 8351 return nullptr; 8352 8353 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 8354 if (!AddRHS || AddRHS->getNumOperands() != 2 || 8355 !AddRHS->getOperand(0)->isAllOnesValue()) 8356 return nullptr; 8357 8358 return AddRHS->getOperand(1); 8359 } 8360 8361 8362 /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values? 8363 template<typename MaxExprType> 8364 static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr, 8365 const SCEV *Candidate) { 8366 const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr); 8367 if (!MaxExpr) return false; 8368 8369 return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end(); 8370 } 8371 8372 8373 /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values? 8374 template<typename MaxExprType> 8375 static bool IsMinConsistingOf(ScalarEvolution &SE, 8376 const SCEV *MaybeMinExpr, 8377 const SCEV *Candidate) { 8378 const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr); 8379 if (!MaybeMaxExpr) 8380 return false; 8381 8382 return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate)); 8383 } 8384 8385 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 8386 ICmpInst::Predicate Pred, 8387 const SCEV *LHS, const SCEV *RHS) { 8388 8389 // If both sides are affine addrecs for the same loop, with equal 8390 // steps, and we know the recurrences don't wrap, then we only 8391 // need to check the predicate on the starting values. 8392 8393 if (!ICmpInst::isRelational(Pred)) 8394 return false; 8395 8396 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 8397 if (!LAR) 8398 return false; 8399 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 8400 if (!RAR) 8401 return false; 8402 if (LAR->getLoop() != RAR->getLoop()) 8403 return false; 8404 if (!LAR->isAffine() || !RAR->isAffine()) 8405 return false; 8406 8407 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 8408 return false; 8409 8410 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 8411 SCEV::FlagNSW : SCEV::FlagNUW; 8412 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 8413 return false; 8414 8415 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 8416 } 8417 8418 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 8419 /// expression? 8420 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 8421 ICmpInst::Predicate Pred, 8422 const SCEV *LHS, const SCEV *RHS) { 8423 switch (Pred) { 8424 default: 8425 return false; 8426 8427 case ICmpInst::ICMP_SGE: 8428 std::swap(LHS, RHS); 8429 LLVM_FALLTHROUGH; 8430 case ICmpInst::ICMP_SLE: 8431 return 8432 // min(A, ...) <= A 8433 IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) || 8434 // A <= max(A, ...) 8435 IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 8436 8437 case ICmpInst::ICMP_UGE: 8438 std::swap(LHS, RHS); 8439 LLVM_FALLTHROUGH; 8440 case ICmpInst::ICMP_ULE: 8441 return 8442 // min(A, ...) <= A 8443 IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) || 8444 // A <= max(A, ...) 8445 IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 8446 } 8447 8448 llvm_unreachable("covered switch fell through?!"); 8449 } 8450 8451 bool 8452 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 8453 const SCEV *LHS, const SCEV *RHS, 8454 const SCEV *FoundLHS, 8455 const SCEV *FoundRHS) { 8456 auto IsKnownPredicateFull = 8457 [this](ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 8458 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 8459 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 8460 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 8461 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 8462 }; 8463 8464 switch (Pred) { 8465 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 8466 case ICmpInst::ICMP_EQ: 8467 case ICmpInst::ICMP_NE: 8468 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 8469 return true; 8470 break; 8471 case ICmpInst::ICMP_SLT: 8472 case ICmpInst::ICMP_SLE: 8473 if (IsKnownPredicateFull(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 8474 IsKnownPredicateFull(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 8475 return true; 8476 break; 8477 case ICmpInst::ICMP_SGT: 8478 case ICmpInst::ICMP_SGE: 8479 if (IsKnownPredicateFull(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 8480 IsKnownPredicateFull(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 8481 return true; 8482 break; 8483 case ICmpInst::ICMP_ULT: 8484 case ICmpInst::ICMP_ULE: 8485 if (IsKnownPredicateFull(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 8486 IsKnownPredicateFull(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 8487 return true; 8488 break; 8489 case ICmpInst::ICMP_UGT: 8490 case ICmpInst::ICMP_UGE: 8491 if (IsKnownPredicateFull(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 8492 IsKnownPredicateFull(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 8493 return true; 8494 break; 8495 } 8496 8497 return false; 8498 } 8499 8500 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 8501 const SCEV *LHS, 8502 const SCEV *RHS, 8503 const SCEV *FoundLHS, 8504 const SCEV *FoundRHS) { 8505 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 8506 // The restriction on `FoundRHS` be lifted easily -- it exists only to 8507 // reduce the compile time impact of this optimization. 8508 return false; 8509 8510 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 8511 if (!Addend) 8512 return false; 8513 8514 APInt ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 8515 8516 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 8517 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 8518 ConstantRange FoundLHSRange = 8519 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); 8520 8521 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 8522 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 8523 8524 // We can also compute the range of values for `LHS` that satisfy the 8525 // consequent, "`LHS` `Pred` `RHS`": 8526 APInt ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 8527 ConstantRange SatisfyingLHSRange = 8528 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS); 8529 8530 // The antecedent implies the consequent if every value of `LHS` that 8531 // satisfies the antecedent also satisfies the consequent. 8532 return SatisfyingLHSRange.contains(LHSRange); 8533 } 8534 8535 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 8536 bool IsSigned, bool NoWrap) { 8537 assert(isKnownPositive(Stride) && "Positive stride expected!"); 8538 8539 if (NoWrap) return false; 8540 8541 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 8542 const SCEV *One = getOne(Stride->getType()); 8543 8544 if (IsSigned) { 8545 APInt MaxRHS = getSignedRange(RHS).getSignedMax(); 8546 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 8547 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One)) 8548 .getSignedMax(); 8549 8550 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 8551 return (MaxValue - MaxStrideMinusOne).slt(MaxRHS); 8552 } 8553 8554 APInt MaxRHS = getUnsignedRange(RHS).getUnsignedMax(); 8555 APInt MaxValue = APInt::getMaxValue(BitWidth); 8556 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One)) 8557 .getUnsignedMax(); 8558 8559 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 8560 return (MaxValue - MaxStrideMinusOne).ult(MaxRHS); 8561 } 8562 8563 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 8564 bool IsSigned, bool NoWrap) { 8565 if (NoWrap) return false; 8566 8567 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 8568 const SCEV *One = getOne(Stride->getType()); 8569 8570 if (IsSigned) { 8571 APInt MinRHS = getSignedRange(RHS).getSignedMin(); 8572 APInt MinValue = APInt::getSignedMinValue(BitWidth); 8573 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One)) 8574 .getSignedMax(); 8575 8576 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 8577 return (MinValue + MaxStrideMinusOne).sgt(MinRHS); 8578 } 8579 8580 APInt MinRHS = getUnsignedRange(RHS).getUnsignedMin(); 8581 APInt MinValue = APInt::getMinValue(BitWidth); 8582 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One)) 8583 .getUnsignedMax(); 8584 8585 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 8586 return (MinValue + MaxStrideMinusOne).ugt(MinRHS); 8587 } 8588 8589 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step, 8590 bool Equality) { 8591 const SCEV *One = getOne(Step->getType()); 8592 Delta = Equality ? getAddExpr(Delta, Step) 8593 : getAddExpr(Delta, getMinusSCEV(Step, One)); 8594 return getUDivExpr(Delta, Step); 8595 } 8596 8597 ScalarEvolution::ExitLimit 8598 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 8599 const Loop *L, bool IsSigned, 8600 bool ControlsExit, bool AllowPredicates) { 8601 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 8602 // We handle only IV < Invariant 8603 if (!isLoopInvariant(RHS, L)) 8604 return getCouldNotCompute(); 8605 8606 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 8607 bool PredicatedIV = false; 8608 8609 if (!IV && AllowPredicates) { 8610 // Try to make this an AddRec using runtime tests, in the first X 8611 // iterations of this loop, where X is the SCEV expression found by the 8612 // algorithm below. 8613 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 8614 PredicatedIV = true; 8615 } 8616 8617 // Avoid weird loops 8618 if (!IV || IV->getLoop() != L || !IV->isAffine()) 8619 return getCouldNotCompute(); 8620 8621 bool NoWrap = ControlsExit && 8622 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 8623 8624 const SCEV *Stride = IV->getStepRecurrence(*this); 8625 8626 bool PositiveStride = isKnownPositive(Stride); 8627 8628 // Avoid negative or zero stride values. 8629 if (!PositiveStride) { 8630 // We can compute the correct backedge taken count for loops with unknown 8631 // strides if we can prove that the loop is not an infinite loop with side 8632 // effects. Here's the loop structure we are trying to handle - 8633 // 8634 // i = start 8635 // do { 8636 // A[i] = i; 8637 // i += s; 8638 // } while (i < end); 8639 // 8640 // The backedge taken count for such loops is evaluated as - 8641 // (max(end, start + stride) - start - 1) /u stride 8642 // 8643 // The additional preconditions that we need to check to prove correctness 8644 // of the above formula is as follows - 8645 // 8646 // a) IV is either nuw or nsw depending upon signedness (indicated by the 8647 // NoWrap flag). 8648 // b) loop is single exit with no side effects. 8649 // 8650 // 8651 // Precondition a) implies that if the stride is negative, this is a single 8652 // trip loop. The backedge taken count formula reduces to zero in this case. 8653 // 8654 // Precondition b) implies that the unknown stride cannot be zero otherwise 8655 // we have UB. 8656 // 8657 // The positive stride case is the same as isKnownPositive(Stride) returning 8658 // true (original behavior of the function). 8659 // 8660 // We want to make sure that the stride is truly unknown as there are edge 8661 // cases where ScalarEvolution propagates no wrap flags to the 8662 // post-increment/decrement IV even though the increment/decrement operation 8663 // itself is wrapping. The computed backedge taken count may be wrong in 8664 // such cases. This is prevented by checking that the stride is not known to 8665 // be either positive or non-positive. For example, no wrap flags are 8666 // propagated to the post-increment IV of this loop with a trip count of 2 - 8667 // 8668 // unsigned char i; 8669 // for(i=127; i<128; i+=129) 8670 // A[i] = i; 8671 // 8672 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) || 8673 !loopHasNoSideEffects(L)) 8674 return getCouldNotCompute(); 8675 8676 } else if (!Stride->isOne() && 8677 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap)) 8678 // Avoid proven overflow cases: this will ensure that the backedge taken 8679 // count will not generate any unsigned overflow. Relaxed no-overflow 8680 // conditions exploit NoWrapFlags, allowing to optimize in presence of 8681 // undefined behaviors like the case of C language. 8682 return getCouldNotCompute(); 8683 8684 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT 8685 : ICmpInst::ICMP_ULT; 8686 const SCEV *Start = IV->getStart(); 8687 const SCEV *End = RHS; 8688 // If the backedge is taken at least once, then it will be taken 8689 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start 8690 // is the LHS value of the less-than comparison the first time it is evaluated 8691 // and End is the RHS. 8692 const SCEV *BECountIfBackedgeTaken = 8693 computeBECount(getMinusSCEV(End, Start), Stride, false); 8694 // If the loop entry is guarded by the result of the backedge test of the 8695 // first loop iteration, then we know the backedge will be taken at least 8696 // once and so the backedge taken count is as above. If not then we use the 8697 // expression (max(End,Start)-Start)/Stride to describe the backedge count, 8698 // as if the backedge is taken at least once max(End,Start) is End and so the 8699 // result is as above, and if not max(End,Start) is Start so we get a backedge 8700 // count of zero. 8701 const SCEV *BECount; 8702 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) 8703 BECount = BECountIfBackedgeTaken; 8704 else { 8705 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 8706 BECount = computeBECount(getMinusSCEV(End, Start), Stride, false); 8707 } 8708 8709 const SCEV *MaxBECount; 8710 bool MaxOrZero = false; 8711 if (isa<SCEVConstant>(BECount)) 8712 MaxBECount = BECount; 8713 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) { 8714 // If we know exactly how many times the backedge will be taken if it's 8715 // taken at least once, then the backedge count will either be that or 8716 // zero. 8717 MaxBECount = BECountIfBackedgeTaken; 8718 MaxOrZero = true; 8719 } else { 8720 // Calculate the maximum backedge count based on the range of values 8721 // permitted by Start, End, and Stride. 8722 APInt MinStart = IsSigned ? getSignedRange(Start).getSignedMin() 8723 : getUnsignedRange(Start).getUnsignedMin(); 8724 8725 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 8726 8727 APInt StrideForMaxBECount; 8728 8729 if (PositiveStride) 8730 StrideForMaxBECount = 8731 IsSigned ? getSignedRange(Stride).getSignedMin() 8732 : getUnsignedRange(Stride).getUnsignedMin(); 8733 else 8734 // Using a stride of 1 is safe when computing max backedge taken count for 8735 // a loop with unknown stride. 8736 StrideForMaxBECount = APInt(BitWidth, 1, IsSigned); 8737 8738 APInt Limit = 8739 IsSigned ? APInt::getSignedMaxValue(BitWidth) - (StrideForMaxBECount - 1) 8740 : APInt::getMaxValue(BitWidth) - (StrideForMaxBECount - 1); 8741 8742 // Although End can be a MAX expression we estimate MaxEnd considering only 8743 // the case End = RHS. This is safe because in the other case (End - Start) 8744 // is zero, leading to a zero maximum backedge taken count. 8745 APInt MaxEnd = 8746 IsSigned ? APIntOps::smin(getSignedRange(RHS).getSignedMax(), Limit) 8747 : APIntOps::umin(getUnsignedRange(RHS).getUnsignedMax(), Limit); 8748 8749 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart), 8750 getConstant(StrideForMaxBECount), false); 8751 } 8752 8753 if (isa<SCEVCouldNotCompute>(MaxBECount)) 8754 MaxBECount = BECount; 8755 8756 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 8757 } 8758 8759 ScalarEvolution::ExitLimit 8760 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 8761 const Loop *L, bool IsSigned, 8762 bool ControlsExit, bool AllowPredicates) { 8763 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 8764 // We handle only IV > Invariant 8765 if (!isLoopInvariant(RHS, L)) 8766 return getCouldNotCompute(); 8767 8768 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 8769 if (!IV && AllowPredicates) 8770 // Try to make this an AddRec using runtime tests, in the first X 8771 // iterations of this loop, where X is the SCEV expression found by the 8772 // algorithm below. 8773 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 8774 8775 // Avoid weird loops 8776 if (!IV || IV->getLoop() != L || !IV->isAffine()) 8777 return getCouldNotCompute(); 8778 8779 bool NoWrap = ControlsExit && 8780 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 8781 8782 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 8783 8784 // Avoid negative or zero stride values 8785 if (!isKnownPositive(Stride)) 8786 return getCouldNotCompute(); 8787 8788 // Avoid proven overflow cases: this will ensure that the backedge taken count 8789 // will not generate any unsigned overflow. Relaxed no-overflow conditions 8790 // exploit NoWrapFlags, allowing to optimize in presence of undefined 8791 // behaviors like the case of C language. 8792 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap)) 8793 return getCouldNotCompute(); 8794 8795 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT 8796 : ICmpInst::ICMP_UGT; 8797 8798 const SCEV *Start = IV->getStart(); 8799 const SCEV *End = RHS; 8800 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) 8801 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 8802 8803 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false); 8804 8805 APInt MaxStart = IsSigned ? getSignedRange(Start).getSignedMax() 8806 : getUnsignedRange(Start).getUnsignedMax(); 8807 8808 APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin() 8809 : getUnsignedRange(Stride).getUnsignedMin(); 8810 8811 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 8812 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 8813 : APInt::getMinValue(BitWidth) + (MinStride - 1); 8814 8815 // Although End can be a MIN expression we estimate MinEnd considering only 8816 // the case End = RHS. This is safe because in the other case (Start - End) 8817 // is zero, leading to a zero maximum backedge taken count. 8818 APInt MinEnd = 8819 IsSigned ? APIntOps::smax(getSignedRange(RHS).getSignedMin(), Limit) 8820 : APIntOps::umax(getUnsignedRange(RHS).getUnsignedMin(), Limit); 8821 8822 8823 const SCEV *MaxBECount = getCouldNotCompute(); 8824 if (isa<SCEVConstant>(BECount)) 8825 MaxBECount = BECount; 8826 else 8827 MaxBECount = computeBECount(getConstant(MaxStart - MinEnd), 8828 getConstant(MinStride), false); 8829 8830 if (isa<SCEVCouldNotCompute>(MaxBECount)) 8831 MaxBECount = BECount; 8832 8833 return ExitLimit(BECount, MaxBECount, false, Predicates); 8834 } 8835 8836 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 8837 ScalarEvolution &SE) const { 8838 if (Range.isFullSet()) // Infinite loop. 8839 return SE.getCouldNotCompute(); 8840 8841 // If the start is a non-zero constant, shift the range to simplify things. 8842 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 8843 if (!SC->getValue()->isZero()) { 8844 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end()); 8845 Operands[0] = SE.getZero(SC->getType()); 8846 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 8847 getNoWrapFlags(FlagNW)); 8848 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 8849 return ShiftedAddRec->getNumIterationsInRange( 8850 Range.subtract(SC->getAPInt()), SE); 8851 // This is strange and shouldn't happen. 8852 return SE.getCouldNotCompute(); 8853 } 8854 8855 // The only time we can solve this is when we have all constant indices. 8856 // Otherwise, we cannot determine the overflow conditions. 8857 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 8858 return SE.getCouldNotCompute(); 8859 8860 // Okay at this point we know that all elements of the chrec are constants and 8861 // that the start element is zero. 8862 8863 // First check to see if the range contains zero. If not, the first 8864 // iteration exits. 8865 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 8866 if (!Range.contains(APInt(BitWidth, 0))) 8867 return SE.getZero(getType()); 8868 8869 if (isAffine()) { 8870 // If this is an affine expression then we have this situation: 8871 // Solve {0,+,A} in Range === Ax in Range 8872 8873 // We know that zero is in the range. If A is positive then we know that 8874 // the upper value of the range must be the first possible exit value. 8875 // If A is negative then the lower of the range is the last possible loop 8876 // value. Also note that we already checked for a full range. 8877 APInt One(BitWidth,1); 8878 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 8879 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower(); 8880 8881 // The exit value should be (End+A)/A. 8882 APInt ExitVal = (End + A).udiv(A); 8883 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 8884 8885 // Evaluate at the exit value. If we really did fall out of the valid 8886 // range, then we computed our trip count, otherwise wrap around or other 8887 // things must have happened. 8888 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 8889 if (Range.contains(Val->getValue())) 8890 return SE.getCouldNotCompute(); // Something strange happened 8891 8892 // Ensure that the previous value is in the range. This is a sanity check. 8893 assert(Range.contains( 8894 EvaluateConstantChrecAtConstant(this, 8895 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) && 8896 "Linear scev computation is off in a bad way!"); 8897 return SE.getConstant(ExitValue); 8898 } else if (isQuadratic()) { 8899 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the 8900 // quadratic equation to solve it. To do this, we must frame our problem in 8901 // terms of figuring out when zero is crossed, instead of when 8902 // Range.getUpper() is crossed. 8903 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end()); 8904 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper())); 8905 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), FlagAnyWrap); 8906 8907 // Next, solve the constructed addrec 8908 if (auto Roots = 8909 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE)) { 8910 const SCEVConstant *R1 = Roots->first; 8911 const SCEVConstant *R2 = Roots->second; 8912 // Pick the smallest positive root value. 8913 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp( 8914 ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) { 8915 if (!CB->getZExtValue()) 8916 std::swap(R1, R2); // R1 is the minimum root now. 8917 8918 // Make sure the root is not off by one. The returned iteration should 8919 // not be in the range, but the previous one should be. When solving 8920 // for "X*X < 5", for example, we should not return a root of 2. 8921 ConstantInt *R1Val = 8922 EvaluateConstantChrecAtConstant(this, R1->getValue(), SE); 8923 if (Range.contains(R1Val->getValue())) { 8924 // The next iteration must be out of the range... 8925 ConstantInt *NextVal = 8926 ConstantInt::get(SE.getContext(), R1->getAPInt() + 1); 8927 8928 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); 8929 if (!Range.contains(R1Val->getValue())) 8930 return SE.getConstant(NextVal); 8931 return SE.getCouldNotCompute(); // Something strange happened 8932 } 8933 8934 // If R1 was not in the range, then it is a good return value. Make 8935 // sure that R1-1 WAS in the range though, just in case. 8936 ConstantInt *NextVal = 8937 ConstantInt::get(SE.getContext(), R1->getAPInt() - 1); 8938 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); 8939 if (Range.contains(R1Val->getValue())) 8940 return R1; 8941 return SE.getCouldNotCompute(); // Something strange happened 8942 } 8943 } 8944 } 8945 8946 return SE.getCouldNotCompute(); 8947 } 8948 8949 // Return true when S contains at least an undef value. 8950 static inline bool containsUndefs(const SCEV *S) { 8951 return SCEVExprContains(S, [](const SCEV *S) { 8952 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 8953 return isa<UndefValue>(SU->getValue()); 8954 else if (const auto *SC = dyn_cast<SCEVConstant>(S)) 8955 return isa<UndefValue>(SC->getValue()); 8956 return false; 8957 }); 8958 } 8959 8960 namespace { 8961 // Collect all steps of SCEV expressions. 8962 struct SCEVCollectStrides { 8963 ScalarEvolution &SE; 8964 SmallVectorImpl<const SCEV *> &Strides; 8965 8966 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) 8967 : SE(SE), Strides(S) {} 8968 8969 bool follow(const SCEV *S) { 8970 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 8971 Strides.push_back(AR->getStepRecurrence(SE)); 8972 return true; 8973 } 8974 bool isDone() const { return false; } 8975 }; 8976 8977 // Collect all SCEVUnknown and SCEVMulExpr expressions. 8978 struct SCEVCollectTerms { 8979 SmallVectorImpl<const SCEV *> &Terms; 8980 8981 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) 8982 : Terms(T) {} 8983 8984 bool follow(const SCEV *S) { 8985 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) || 8986 isa<SCEVSignExtendExpr>(S)) { 8987 if (!containsUndefs(S)) 8988 Terms.push_back(S); 8989 8990 // Stop recursion: once we collected a term, do not walk its operands. 8991 return false; 8992 } 8993 8994 // Keep looking. 8995 return true; 8996 } 8997 bool isDone() const { return false; } 8998 }; 8999 9000 // Check if a SCEV contains an AddRecExpr. 9001 struct SCEVHasAddRec { 9002 bool &ContainsAddRec; 9003 9004 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) { 9005 ContainsAddRec = false; 9006 } 9007 9008 bool follow(const SCEV *S) { 9009 if (isa<SCEVAddRecExpr>(S)) { 9010 ContainsAddRec = true; 9011 9012 // Stop recursion: once we collected a term, do not walk its operands. 9013 return false; 9014 } 9015 9016 // Keep looking. 9017 return true; 9018 } 9019 bool isDone() const { return false; } 9020 }; 9021 9022 // Find factors that are multiplied with an expression that (possibly as a 9023 // subexpression) contains an AddRecExpr. In the expression: 9024 // 9025 // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop)) 9026 // 9027 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)" 9028 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size 9029 // parameters as they form a product with an induction variable. 9030 // 9031 // This collector expects all array size parameters to be in the same MulExpr. 9032 // It might be necessary to later add support for collecting parameters that are 9033 // spread over different nested MulExpr. 9034 struct SCEVCollectAddRecMultiplies { 9035 SmallVectorImpl<const SCEV *> &Terms; 9036 ScalarEvolution &SE; 9037 9038 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE) 9039 : Terms(T), SE(SE) {} 9040 9041 bool follow(const SCEV *S) { 9042 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) { 9043 bool HasAddRec = false; 9044 SmallVector<const SCEV *, 0> Operands; 9045 for (auto Op : Mul->operands()) { 9046 if (isa<SCEVUnknown>(Op)) { 9047 Operands.push_back(Op); 9048 } else { 9049 bool ContainsAddRec; 9050 SCEVHasAddRec ContiansAddRec(ContainsAddRec); 9051 visitAll(Op, ContiansAddRec); 9052 HasAddRec |= ContainsAddRec; 9053 } 9054 } 9055 if (Operands.size() == 0) 9056 return true; 9057 9058 if (!HasAddRec) 9059 return false; 9060 9061 Terms.push_back(SE.getMulExpr(Operands)); 9062 // Stop recursion: once we collected a term, do not walk its operands. 9063 return false; 9064 } 9065 9066 // Keep looking. 9067 return true; 9068 } 9069 bool isDone() const { return false; } 9070 }; 9071 } 9072 9073 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in 9074 /// two places: 9075 /// 1) The strides of AddRec expressions. 9076 /// 2) Unknowns that are multiplied with AddRec expressions. 9077 void ScalarEvolution::collectParametricTerms(const SCEV *Expr, 9078 SmallVectorImpl<const SCEV *> &Terms) { 9079 SmallVector<const SCEV *, 4> Strides; 9080 SCEVCollectStrides StrideCollector(*this, Strides); 9081 visitAll(Expr, StrideCollector); 9082 9083 DEBUG({ 9084 dbgs() << "Strides:\n"; 9085 for (const SCEV *S : Strides) 9086 dbgs() << *S << "\n"; 9087 }); 9088 9089 for (const SCEV *S : Strides) { 9090 SCEVCollectTerms TermCollector(Terms); 9091 visitAll(S, TermCollector); 9092 } 9093 9094 DEBUG({ 9095 dbgs() << "Terms:\n"; 9096 for (const SCEV *T : Terms) 9097 dbgs() << *T << "\n"; 9098 }); 9099 9100 SCEVCollectAddRecMultiplies MulCollector(Terms, *this); 9101 visitAll(Expr, MulCollector); 9102 } 9103 9104 static bool findArrayDimensionsRec(ScalarEvolution &SE, 9105 SmallVectorImpl<const SCEV *> &Terms, 9106 SmallVectorImpl<const SCEV *> &Sizes) { 9107 int Last = Terms.size() - 1; 9108 const SCEV *Step = Terms[Last]; 9109 9110 // End of recursion. 9111 if (Last == 0) { 9112 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { 9113 SmallVector<const SCEV *, 2> Qs; 9114 for (const SCEV *Op : M->operands()) 9115 if (!isa<SCEVConstant>(Op)) 9116 Qs.push_back(Op); 9117 9118 Step = SE.getMulExpr(Qs); 9119 } 9120 9121 Sizes.push_back(Step); 9122 return true; 9123 } 9124 9125 for (const SCEV *&Term : Terms) { 9126 // Normalize the terms before the next call to findArrayDimensionsRec. 9127 const SCEV *Q, *R; 9128 SCEVDivision::divide(SE, Term, Step, &Q, &R); 9129 9130 // Bail out when GCD does not evenly divide one of the terms. 9131 if (!R->isZero()) 9132 return false; 9133 9134 Term = Q; 9135 } 9136 9137 // Remove all SCEVConstants. 9138 Terms.erase( 9139 remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }), 9140 Terms.end()); 9141 9142 if (Terms.size() > 0) 9143 if (!findArrayDimensionsRec(SE, Terms, Sizes)) 9144 return false; 9145 9146 Sizes.push_back(Step); 9147 return true; 9148 } 9149 9150 9151 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. 9152 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) { 9153 for (const SCEV *T : Terms) 9154 if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>)) 9155 return true; 9156 return false; 9157 } 9158 9159 // Return the number of product terms in S. 9160 static inline int numberOfTerms(const SCEV *S) { 9161 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) 9162 return Expr->getNumOperands(); 9163 return 1; 9164 } 9165 9166 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { 9167 if (isa<SCEVConstant>(T)) 9168 return nullptr; 9169 9170 if (isa<SCEVUnknown>(T)) 9171 return T; 9172 9173 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { 9174 SmallVector<const SCEV *, 2> Factors; 9175 for (const SCEV *Op : M->operands()) 9176 if (!isa<SCEVConstant>(Op)) 9177 Factors.push_back(Op); 9178 9179 return SE.getMulExpr(Factors); 9180 } 9181 9182 return T; 9183 } 9184 9185 /// Return the size of an element read or written by Inst. 9186 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 9187 Type *Ty; 9188 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 9189 Ty = Store->getValueOperand()->getType(); 9190 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 9191 Ty = Load->getType(); 9192 else 9193 return nullptr; 9194 9195 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 9196 return getSizeOfExpr(ETy, Ty); 9197 } 9198 9199 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, 9200 SmallVectorImpl<const SCEV *> &Sizes, 9201 const SCEV *ElementSize) const { 9202 if (Terms.size() < 1 || !ElementSize) 9203 return; 9204 9205 // Early return when Terms do not contain parameters: we do not delinearize 9206 // non parametric SCEVs. 9207 if (!containsParameters(Terms)) 9208 return; 9209 9210 DEBUG({ 9211 dbgs() << "Terms:\n"; 9212 for (const SCEV *T : Terms) 9213 dbgs() << *T << "\n"; 9214 }); 9215 9216 // Remove duplicates. 9217 std::sort(Terms.begin(), Terms.end()); 9218 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); 9219 9220 // Put larger terms first. 9221 std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) { 9222 return numberOfTerms(LHS) > numberOfTerms(RHS); 9223 }); 9224 9225 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 9226 9227 // Try to divide all terms by the element size. If term is not divisible by 9228 // element size, proceed with the original term. 9229 for (const SCEV *&Term : Terms) { 9230 const SCEV *Q, *R; 9231 SCEVDivision::divide(SE, Term, ElementSize, &Q, &R); 9232 if (!Q->isZero()) 9233 Term = Q; 9234 } 9235 9236 SmallVector<const SCEV *, 4> NewTerms; 9237 9238 // Remove constant factors. 9239 for (const SCEV *T : Terms) 9240 if (const SCEV *NewT = removeConstantFactors(SE, T)) 9241 NewTerms.push_back(NewT); 9242 9243 DEBUG({ 9244 dbgs() << "Terms after sorting:\n"; 9245 for (const SCEV *T : NewTerms) 9246 dbgs() << *T << "\n"; 9247 }); 9248 9249 if (NewTerms.empty() || 9250 !findArrayDimensionsRec(SE, NewTerms, Sizes)) { 9251 Sizes.clear(); 9252 return; 9253 } 9254 9255 // The last element to be pushed into Sizes is the size of an element. 9256 Sizes.push_back(ElementSize); 9257 9258 DEBUG({ 9259 dbgs() << "Sizes:\n"; 9260 for (const SCEV *S : Sizes) 9261 dbgs() << *S << "\n"; 9262 }); 9263 } 9264 9265 void ScalarEvolution::computeAccessFunctions( 9266 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, 9267 SmallVectorImpl<const SCEV *> &Sizes) { 9268 9269 // Early exit in case this SCEV is not an affine multivariate function. 9270 if (Sizes.empty()) 9271 return; 9272 9273 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr)) 9274 if (!AR->isAffine()) 9275 return; 9276 9277 const SCEV *Res = Expr; 9278 int Last = Sizes.size() - 1; 9279 for (int i = Last; i >= 0; i--) { 9280 const SCEV *Q, *R; 9281 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); 9282 9283 DEBUG({ 9284 dbgs() << "Res: " << *Res << "\n"; 9285 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; 9286 dbgs() << "Res divided by Sizes[i]:\n"; 9287 dbgs() << "Quotient: " << *Q << "\n"; 9288 dbgs() << "Remainder: " << *R << "\n"; 9289 }); 9290 9291 Res = Q; 9292 9293 // Do not record the last subscript corresponding to the size of elements in 9294 // the array. 9295 if (i == Last) { 9296 9297 // Bail out if the remainder is too complex. 9298 if (isa<SCEVAddRecExpr>(R)) { 9299 Subscripts.clear(); 9300 Sizes.clear(); 9301 return; 9302 } 9303 9304 continue; 9305 } 9306 9307 // Record the access function for the current subscript. 9308 Subscripts.push_back(R); 9309 } 9310 9311 // Also push in last position the remainder of the last division: it will be 9312 // the access function of the innermost dimension. 9313 Subscripts.push_back(Res); 9314 9315 std::reverse(Subscripts.begin(), Subscripts.end()); 9316 9317 DEBUG({ 9318 dbgs() << "Subscripts:\n"; 9319 for (const SCEV *S : Subscripts) 9320 dbgs() << *S << "\n"; 9321 }); 9322 } 9323 9324 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and 9325 /// sizes of an array access. Returns the remainder of the delinearization that 9326 /// is the offset start of the array. The SCEV->delinearize algorithm computes 9327 /// the multiples of SCEV coefficients: that is a pattern matching of sub 9328 /// expressions in the stride and base of a SCEV corresponding to the 9329 /// computation of a GCD (greatest common divisor) of base and stride. When 9330 /// SCEV->delinearize fails, it returns the SCEV unchanged. 9331 /// 9332 /// For example: when analyzing the memory access A[i][j][k] in this loop nest 9333 /// 9334 /// void foo(long n, long m, long o, double A[n][m][o]) { 9335 /// 9336 /// for (long i = 0; i < n; i++) 9337 /// for (long j = 0; j < m; j++) 9338 /// for (long k = 0; k < o; k++) 9339 /// A[i][j][k] = 1.0; 9340 /// } 9341 /// 9342 /// the delinearization input is the following AddRec SCEV: 9343 /// 9344 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> 9345 /// 9346 /// From this SCEV, we are able to say that the base offset of the access is %A 9347 /// because it appears as an offset that does not divide any of the strides in 9348 /// the loops: 9349 /// 9350 /// CHECK: Base offset: %A 9351 /// 9352 /// and then SCEV->delinearize determines the size of some of the dimensions of 9353 /// the array as these are the multiples by which the strides are happening: 9354 /// 9355 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. 9356 /// 9357 /// Note that the outermost dimension remains of UnknownSize because there are 9358 /// no strides that would help identifying the size of the last dimension: when 9359 /// the array has been statically allocated, one could compute the size of that 9360 /// dimension by dividing the overall size of the array by the size of the known 9361 /// dimensions: %m * %o * 8. 9362 /// 9363 /// Finally delinearize provides the access functions for the array reference 9364 /// that does correspond to A[i][j][k] of the above C testcase: 9365 /// 9366 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] 9367 /// 9368 /// The testcases are checking the output of a function pass: 9369 /// DelinearizationPass that walks through all loads and stores of a function 9370 /// asking for the SCEV of the memory access with respect to all enclosing 9371 /// loops, calling SCEV->delinearize on that and printing the results. 9372 9373 void ScalarEvolution::delinearize(const SCEV *Expr, 9374 SmallVectorImpl<const SCEV *> &Subscripts, 9375 SmallVectorImpl<const SCEV *> &Sizes, 9376 const SCEV *ElementSize) { 9377 // First step: collect parametric terms. 9378 SmallVector<const SCEV *, 4> Terms; 9379 collectParametricTerms(Expr, Terms); 9380 9381 if (Terms.empty()) 9382 return; 9383 9384 // Second step: find subscript sizes. 9385 findArrayDimensions(Terms, Sizes, ElementSize); 9386 9387 if (Sizes.empty()) 9388 return; 9389 9390 // Third step: compute the access functions for each subscript. 9391 computeAccessFunctions(Expr, Subscripts, Sizes); 9392 9393 if (Subscripts.empty()) 9394 return; 9395 9396 DEBUG({ 9397 dbgs() << "succeeded to delinearize " << *Expr << "\n"; 9398 dbgs() << "ArrayDecl[UnknownSize]"; 9399 for (const SCEV *S : Sizes) 9400 dbgs() << "[" << *S << "]"; 9401 9402 dbgs() << "\nArrayRef"; 9403 for (const SCEV *S : Subscripts) 9404 dbgs() << "[" << *S << "]"; 9405 dbgs() << "\n"; 9406 }); 9407 } 9408 9409 //===----------------------------------------------------------------------===// 9410 // SCEVCallbackVH Class Implementation 9411 //===----------------------------------------------------------------------===// 9412 9413 void ScalarEvolution::SCEVCallbackVH::deleted() { 9414 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 9415 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 9416 SE->ConstantEvolutionLoopExitValue.erase(PN); 9417 SE->eraseValueFromMap(getValPtr()); 9418 // this now dangles! 9419 } 9420 9421 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 9422 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 9423 9424 // Forget all the expressions associated with users of the old value, 9425 // so that future queries will recompute the expressions using the new 9426 // value. 9427 Value *Old = getValPtr(); 9428 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end()); 9429 SmallPtrSet<User *, 8> Visited; 9430 while (!Worklist.empty()) { 9431 User *U = Worklist.pop_back_val(); 9432 // Deleting the Old value will cause this to dangle. Postpone 9433 // that until everything else is done. 9434 if (U == Old) 9435 continue; 9436 if (!Visited.insert(U).second) 9437 continue; 9438 if (PHINode *PN = dyn_cast<PHINode>(U)) 9439 SE->ConstantEvolutionLoopExitValue.erase(PN); 9440 SE->eraseValueFromMap(U); 9441 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end()); 9442 } 9443 // Delete the Old value. 9444 if (PHINode *PN = dyn_cast<PHINode>(Old)) 9445 SE->ConstantEvolutionLoopExitValue.erase(PN); 9446 SE->eraseValueFromMap(Old); 9447 // this now dangles! 9448 } 9449 9450 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 9451 : CallbackVH(V), SE(se) {} 9452 9453 //===----------------------------------------------------------------------===// 9454 // ScalarEvolution Class Implementation 9455 //===----------------------------------------------------------------------===// 9456 9457 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 9458 AssumptionCache &AC, DominatorTree &DT, 9459 LoopInfo &LI) 9460 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 9461 CouldNotCompute(new SCEVCouldNotCompute()), 9462 WalkingBEDominatingConds(false), ProvingSplitPredicate(false), 9463 ValuesAtScopes(64), LoopDispositions(64), BlockDispositions(64), 9464 FirstUnknown(nullptr) { 9465 9466 // To use guards for proving predicates, we need to scan every instruction in 9467 // relevant basic blocks, and not just terminators. Doing this is a waste of 9468 // time if the IR does not actually contain any calls to 9469 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 9470 // 9471 // This pessimizes the case where a pass that preserves ScalarEvolution wants 9472 // to _add_ guards to the module when there weren't any before, and wants 9473 // ScalarEvolution to optimize based on those guards. For now we prefer to be 9474 // efficient in lieu of being smart in that rather obscure case. 9475 9476 auto *GuardDecl = F.getParent()->getFunction( 9477 Intrinsic::getName(Intrinsic::experimental_guard)); 9478 HasGuards = GuardDecl && !GuardDecl->use_empty(); 9479 } 9480 9481 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 9482 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 9483 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 9484 ValueExprMap(std::move(Arg.ValueExprMap)), 9485 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 9486 WalkingBEDominatingConds(false), ProvingSplitPredicate(false), 9487 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 9488 PredicatedBackedgeTakenCounts( 9489 std::move(Arg.PredicatedBackedgeTakenCounts)), 9490 ConstantEvolutionLoopExitValue( 9491 std::move(Arg.ConstantEvolutionLoopExitValue)), 9492 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 9493 LoopDispositions(std::move(Arg.LoopDispositions)), 9494 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 9495 BlockDispositions(std::move(Arg.BlockDispositions)), 9496 UnsignedRanges(std::move(Arg.UnsignedRanges)), 9497 SignedRanges(std::move(Arg.SignedRanges)), 9498 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 9499 UniquePreds(std::move(Arg.UniquePreds)), 9500 SCEVAllocator(std::move(Arg.SCEVAllocator)), 9501 FirstUnknown(Arg.FirstUnknown) { 9502 Arg.FirstUnknown = nullptr; 9503 } 9504 9505 ScalarEvolution::~ScalarEvolution() { 9506 // Iterate through all the SCEVUnknown instances and call their 9507 // destructors, so that they release their references to their values. 9508 for (SCEVUnknown *U = FirstUnknown; U;) { 9509 SCEVUnknown *Tmp = U; 9510 U = U->Next; 9511 Tmp->~SCEVUnknown(); 9512 } 9513 FirstUnknown = nullptr; 9514 9515 ExprValueMap.clear(); 9516 ValueExprMap.clear(); 9517 HasRecMap.clear(); 9518 9519 // Free any extra memory created for ExitNotTakenInfo in the unlikely event 9520 // that a loop had multiple computable exits. 9521 for (auto &BTCI : BackedgeTakenCounts) 9522 BTCI.second.clear(); 9523 for (auto &BTCI : PredicatedBackedgeTakenCounts) 9524 BTCI.second.clear(); 9525 9526 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 9527 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 9528 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 9529 } 9530 9531 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 9532 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 9533 } 9534 9535 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 9536 const Loop *L) { 9537 // Print all inner loops first 9538 for (Loop *I : *L) 9539 PrintLoopInfo(OS, SE, I); 9540 9541 OS << "Loop "; 9542 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 9543 OS << ": "; 9544 9545 SmallVector<BasicBlock *, 8> ExitBlocks; 9546 L->getExitBlocks(ExitBlocks); 9547 if (ExitBlocks.size() != 1) 9548 OS << "<multiple exits> "; 9549 9550 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 9551 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L); 9552 } else { 9553 OS << "Unpredictable backedge-taken count. "; 9554 } 9555 9556 OS << "\n" 9557 "Loop "; 9558 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 9559 OS << ": "; 9560 9561 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) { 9562 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L); 9563 if (SE->isBackedgeTakenCountMaxOrZero(L)) 9564 OS << ", actual taken count either this or zero."; 9565 } else { 9566 OS << "Unpredictable max backedge-taken count. "; 9567 } 9568 9569 OS << "\n" 9570 "Loop "; 9571 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 9572 OS << ": "; 9573 9574 SCEVUnionPredicate Pred; 9575 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); 9576 if (!isa<SCEVCouldNotCompute>(PBT)) { 9577 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 9578 OS << " Predicates:\n"; 9579 Pred.print(OS, 4); 9580 } else { 9581 OS << "Unpredictable predicated backedge-taken count. "; 9582 } 9583 OS << "\n"; 9584 } 9585 9586 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 9587 switch (LD) { 9588 case ScalarEvolution::LoopVariant: 9589 return "Variant"; 9590 case ScalarEvolution::LoopInvariant: 9591 return "Invariant"; 9592 case ScalarEvolution::LoopComputable: 9593 return "Computable"; 9594 } 9595 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 9596 } 9597 9598 void ScalarEvolution::print(raw_ostream &OS) const { 9599 // ScalarEvolution's implementation of the print method is to print 9600 // out SCEV values of all instructions that are interesting. Doing 9601 // this potentially causes it to create new SCEV objects though, 9602 // which technically conflicts with the const qualifier. This isn't 9603 // observable from outside the class though, so casting away the 9604 // const isn't dangerous. 9605 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 9606 9607 OS << "Classifying expressions for: "; 9608 F.printAsOperand(OS, /*PrintType=*/false); 9609 OS << "\n"; 9610 for (Instruction &I : instructions(F)) 9611 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 9612 OS << I << '\n'; 9613 OS << " --> "; 9614 const SCEV *SV = SE.getSCEV(&I); 9615 SV->print(OS); 9616 if (!isa<SCEVCouldNotCompute>(SV)) { 9617 OS << " U: "; 9618 SE.getUnsignedRange(SV).print(OS); 9619 OS << " S: "; 9620 SE.getSignedRange(SV).print(OS); 9621 } 9622 9623 const Loop *L = LI.getLoopFor(I.getParent()); 9624 9625 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 9626 if (AtUse != SV) { 9627 OS << " --> "; 9628 AtUse->print(OS); 9629 if (!isa<SCEVCouldNotCompute>(AtUse)) { 9630 OS << " U: "; 9631 SE.getUnsignedRange(AtUse).print(OS); 9632 OS << " S: "; 9633 SE.getSignedRange(AtUse).print(OS); 9634 } 9635 } 9636 9637 if (L) { 9638 OS << "\t\t" "Exits: "; 9639 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 9640 if (!SE.isLoopInvariant(ExitValue, L)) { 9641 OS << "<<Unknown>>"; 9642 } else { 9643 OS << *ExitValue; 9644 } 9645 9646 bool First = true; 9647 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 9648 if (First) { 9649 OS << "\t\t" "LoopDispositions: { "; 9650 First = false; 9651 } else { 9652 OS << ", "; 9653 } 9654 9655 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 9656 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 9657 } 9658 9659 for (auto *InnerL : depth_first(L)) { 9660 if (InnerL == L) 9661 continue; 9662 if (First) { 9663 OS << "\t\t" "LoopDispositions: { "; 9664 First = false; 9665 } else { 9666 OS << ", "; 9667 } 9668 9669 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 9670 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 9671 } 9672 9673 OS << " }"; 9674 } 9675 9676 OS << "\n"; 9677 } 9678 9679 OS << "Determining loop execution counts for: "; 9680 F.printAsOperand(OS, /*PrintType=*/false); 9681 OS << "\n"; 9682 for (Loop *I : LI) 9683 PrintLoopInfo(OS, &SE, I); 9684 } 9685 9686 ScalarEvolution::LoopDisposition 9687 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 9688 auto &Values = LoopDispositions[S]; 9689 for (auto &V : Values) { 9690 if (V.getPointer() == L) 9691 return V.getInt(); 9692 } 9693 Values.emplace_back(L, LoopVariant); 9694 LoopDisposition D = computeLoopDisposition(S, L); 9695 auto &Values2 = LoopDispositions[S]; 9696 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 9697 if (V.getPointer() == L) { 9698 V.setInt(D); 9699 break; 9700 } 9701 } 9702 return D; 9703 } 9704 9705 ScalarEvolution::LoopDisposition 9706 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 9707 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 9708 case scConstant: 9709 return LoopInvariant; 9710 case scTruncate: 9711 case scZeroExtend: 9712 case scSignExtend: 9713 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 9714 case scAddRecExpr: { 9715 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 9716 9717 // If L is the addrec's loop, it's computable. 9718 if (AR->getLoop() == L) 9719 return LoopComputable; 9720 9721 // Add recurrences are never invariant in the function-body (null loop). 9722 if (!L) 9723 return LoopVariant; 9724 9725 // This recurrence is variant w.r.t. L if L contains AR's loop. 9726 if (L->contains(AR->getLoop())) 9727 return LoopVariant; 9728 9729 // This recurrence is invariant w.r.t. L if AR's loop contains L. 9730 if (AR->getLoop()->contains(L)) 9731 return LoopInvariant; 9732 9733 // This recurrence is variant w.r.t. L if any of its operands 9734 // are variant. 9735 for (auto *Op : AR->operands()) 9736 if (!isLoopInvariant(Op, L)) 9737 return LoopVariant; 9738 9739 // Otherwise it's loop-invariant. 9740 return LoopInvariant; 9741 } 9742 case scAddExpr: 9743 case scMulExpr: 9744 case scUMaxExpr: 9745 case scSMaxExpr: { 9746 bool HasVarying = false; 9747 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 9748 LoopDisposition D = getLoopDisposition(Op, L); 9749 if (D == LoopVariant) 9750 return LoopVariant; 9751 if (D == LoopComputable) 9752 HasVarying = true; 9753 } 9754 return HasVarying ? LoopComputable : LoopInvariant; 9755 } 9756 case scUDivExpr: { 9757 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 9758 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 9759 if (LD == LoopVariant) 9760 return LoopVariant; 9761 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 9762 if (RD == LoopVariant) 9763 return LoopVariant; 9764 return (LD == LoopInvariant && RD == LoopInvariant) ? 9765 LoopInvariant : LoopComputable; 9766 } 9767 case scUnknown: 9768 // All non-instruction values are loop invariant. All instructions are loop 9769 // invariant if they are not contained in the specified loop. 9770 // Instructions are never considered invariant in the function body 9771 // (null loop) because they are defined within the "loop". 9772 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 9773 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 9774 return LoopInvariant; 9775 case scCouldNotCompute: 9776 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 9777 } 9778 llvm_unreachable("Unknown SCEV kind!"); 9779 } 9780 9781 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 9782 return getLoopDisposition(S, L) == LoopInvariant; 9783 } 9784 9785 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 9786 return getLoopDisposition(S, L) == LoopComputable; 9787 } 9788 9789 ScalarEvolution::BlockDisposition 9790 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 9791 auto &Values = BlockDispositions[S]; 9792 for (auto &V : Values) { 9793 if (V.getPointer() == BB) 9794 return V.getInt(); 9795 } 9796 Values.emplace_back(BB, DoesNotDominateBlock); 9797 BlockDisposition D = computeBlockDisposition(S, BB); 9798 auto &Values2 = BlockDispositions[S]; 9799 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 9800 if (V.getPointer() == BB) { 9801 V.setInt(D); 9802 break; 9803 } 9804 } 9805 return D; 9806 } 9807 9808 ScalarEvolution::BlockDisposition 9809 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 9810 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 9811 case scConstant: 9812 return ProperlyDominatesBlock; 9813 case scTruncate: 9814 case scZeroExtend: 9815 case scSignExtend: 9816 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 9817 case scAddRecExpr: { 9818 // This uses a "dominates" query instead of "properly dominates" query 9819 // to test for proper dominance too, because the instruction which 9820 // produces the addrec's value is a PHI, and a PHI effectively properly 9821 // dominates its entire containing block. 9822 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 9823 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 9824 return DoesNotDominateBlock; 9825 9826 // Fall through into SCEVNAryExpr handling. 9827 LLVM_FALLTHROUGH; 9828 } 9829 case scAddExpr: 9830 case scMulExpr: 9831 case scUMaxExpr: 9832 case scSMaxExpr: { 9833 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 9834 bool Proper = true; 9835 for (const SCEV *NAryOp : NAry->operands()) { 9836 BlockDisposition D = getBlockDisposition(NAryOp, BB); 9837 if (D == DoesNotDominateBlock) 9838 return DoesNotDominateBlock; 9839 if (D == DominatesBlock) 9840 Proper = false; 9841 } 9842 return Proper ? ProperlyDominatesBlock : DominatesBlock; 9843 } 9844 case scUDivExpr: { 9845 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 9846 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 9847 BlockDisposition LD = getBlockDisposition(LHS, BB); 9848 if (LD == DoesNotDominateBlock) 9849 return DoesNotDominateBlock; 9850 BlockDisposition RD = getBlockDisposition(RHS, BB); 9851 if (RD == DoesNotDominateBlock) 9852 return DoesNotDominateBlock; 9853 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 9854 ProperlyDominatesBlock : DominatesBlock; 9855 } 9856 case scUnknown: 9857 if (Instruction *I = 9858 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 9859 if (I->getParent() == BB) 9860 return DominatesBlock; 9861 if (DT.properlyDominates(I->getParent(), BB)) 9862 return ProperlyDominatesBlock; 9863 return DoesNotDominateBlock; 9864 } 9865 return ProperlyDominatesBlock; 9866 case scCouldNotCompute: 9867 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 9868 } 9869 llvm_unreachable("Unknown SCEV kind!"); 9870 } 9871 9872 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 9873 return getBlockDisposition(S, BB) >= DominatesBlock; 9874 } 9875 9876 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 9877 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 9878 } 9879 9880 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 9881 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); 9882 } 9883 9884 void ScalarEvolution::forgetMemoizedResults(const SCEV *S) { 9885 ValuesAtScopes.erase(S); 9886 LoopDispositions.erase(S); 9887 BlockDispositions.erase(S); 9888 UnsignedRanges.erase(S); 9889 SignedRanges.erase(S); 9890 ExprValueMap.erase(S); 9891 HasRecMap.erase(S); 9892 9893 auto RemoveSCEVFromBackedgeMap = 9894 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 9895 for (auto I = Map.begin(), E = Map.end(); I != E;) { 9896 BackedgeTakenInfo &BEInfo = I->second; 9897 if (BEInfo.hasOperand(S, this)) { 9898 BEInfo.clear(); 9899 Map.erase(I++); 9900 } else 9901 ++I; 9902 } 9903 }; 9904 9905 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); 9906 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); 9907 } 9908 9909 typedef DenseMap<const Loop *, std::string> VerifyMap; 9910 9911 /// replaceSubString - Replaces all occurrences of From in Str with To. 9912 static void replaceSubString(std::string &Str, StringRef From, StringRef To) { 9913 size_t Pos = 0; 9914 while ((Pos = Str.find(From, Pos)) != std::string::npos) { 9915 Str.replace(Pos, From.size(), To.data(), To.size()); 9916 Pos += To.size(); 9917 } 9918 } 9919 9920 /// getLoopBackedgeTakenCounts - Helper method for verifyAnalysis. 9921 static void 9922 getLoopBackedgeTakenCounts(Loop *L, VerifyMap &Map, ScalarEvolution &SE) { 9923 std::string &S = Map[L]; 9924 if (S.empty()) { 9925 raw_string_ostream OS(S); 9926 SE.getBackedgeTakenCount(L)->print(OS); 9927 9928 // false and 0 are semantically equivalent. This can happen in dead loops. 9929 replaceSubString(OS.str(), "false", "0"); 9930 // Remove wrap flags, their use in SCEV is highly fragile. 9931 // FIXME: Remove this when SCEV gets smarter about them. 9932 replaceSubString(OS.str(), "<nw>", ""); 9933 replaceSubString(OS.str(), "<nsw>", ""); 9934 replaceSubString(OS.str(), "<nuw>", ""); 9935 } 9936 9937 for (auto *R : reverse(*L)) 9938 getLoopBackedgeTakenCounts(R, Map, SE); // recurse. 9939 } 9940 9941 void ScalarEvolution::verify() const { 9942 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 9943 9944 // Gather stringified backedge taken counts for all loops using SCEV's caches. 9945 // FIXME: It would be much better to store actual values instead of strings, 9946 // but SCEV pointers will change if we drop the caches. 9947 VerifyMap BackedgeDumpsOld, BackedgeDumpsNew; 9948 for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I) 9949 getLoopBackedgeTakenCounts(*I, BackedgeDumpsOld, SE); 9950 9951 // Gather stringified backedge taken counts for all loops using a fresh 9952 // ScalarEvolution object. 9953 ScalarEvolution SE2(F, TLI, AC, DT, LI); 9954 for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I) 9955 getLoopBackedgeTakenCounts(*I, BackedgeDumpsNew, SE2); 9956 9957 // Now compare whether they're the same with and without caches. This allows 9958 // verifying that no pass changed the cache. 9959 assert(BackedgeDumpsOld.size() == BackedgeDumpsNew.size() && 9960 "New loops suddenly appeared!"); 9961 9962 for (VerifyMap::iterator OldI = BackedgeDumpsOld.begin(), 9963 OldE = BackedgeDumpsOld.end(), 9964 NewI = BackedgeDumpsNew.begin(); 9965 OldI != OldE; ++OldI, ++NewI) { 9966 assert(OldI->first == NewI->first && "Loop order changed!"); 9967 9968 // Compare the stringified SCEVs. We don't care if undef backedgetaken count 9969 // changes. 9970 // FIXME: We currently ignore SCEV changes from/to CouldNotCompute. This 9971 // means that a pass is buggy or SCEV has to learn a new pattern but is 9972 // usually not harmful. 9973 if (OldI->second != NewI->second && 9974 OldI->second.find("undef") == std::string::npos && 9975 NewI->second.find("undef") == std::string::npos && 9976 OldI->second != "***COULDNOTCOMPUTE***" && 9977 NewI->second != "***COULDNOTCOMPUTE***") { 9978 dbgs() << "SCEVValidator: SCEV for loop '" 9979 << OldI->first->getHeader()->getName() 9980 << "' changed from '" << OldI->second 9981 << "' to '" << NewI->second << "'!\n"; 9982 std::abort(); 9983 } 9984 } 9985 9986 // TODO: Verify more things. 9987 } 9988 9989 char ScalarEvolutionAnalysis::PassID; 9990 9991 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 9992 FunctionAnalysisManager &AM) { 9993 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 9994 AM.getResult<AssumptionAnalysis>(F), 9995 AM.getResult<DominatorTreeAnalysis>(F), 9996 AM.getResult<LoopAnalysis>(F)); 9997 } 9998 9999 PreservedAnalyses 10000 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 10001 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 10002 return PreservedAnalyses::all(); 10003 } 10004 10005 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 10006 "Scalar Evolution Analysis", false, true) 10007 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 10008 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 10009 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 10010 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 10011 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 10012 "Scalar Evolution Analysis", false, true) 10013 char ScalarEvolutionWrapperPass::ID = 0; 10014 10015 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 10016 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 10017 } 10018 10019 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 10020 SE.reset(new ScalarEvolution( 10021 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(), 10022 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 10023 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 10024 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 10025 return false; 10026 } 10027 10028 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 10029 10030 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 10031 SE->print(OS); 10032 } 10033 10034 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 10035 if (!VerifySCEV) 10036 return; 10037 10038 SE->verify(); 10039 } 10040 10041 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 10042 AU.setPreservesAll(); 10043 AU.addRequiredTransitive<AssumptionCacheTracker>(); 10044 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 10045 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 10046 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 10047 } 10048 10049 const SCEVPredicate * 10050 ScalarEvolution::getEqualPredicate(const SCEVUnknown *LHS, 10051 const SCEVConstant *RHS) { 10052 FoldingSetNodeID ID; 10053 // Unique this node based on the arguments 10054 ID.AddInteger(SCEVPredicate::P_Equal); 10055 ID.AddPointer(LHS); 10056 ID.AddPointer(RHS); 10057 void *IP = nullptr; 10058 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 10059 return S; 10060 SCEVEqualPredicate *Eq = new (SCEVAllocator) 10061 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 10062 UniquePreds.InsertNode(Eq, IP); 10063 return Eq; 10064 } 10065 10066 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 10067 const SCEVAddRecExpr *AR, 10068 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 10069 FoldingSetNodeID ID; 10070 // Unique this node based on the arguments 10071 ID.AddInteger(SCEVPredicate::P_Wrap); 10072 ID.AddPointer(AR); 10073 ID.AddInteger(AddedFlags); 10074 void *IP = nullptr; 10075 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 10076 return S; 10077 auto *OF = new (SCEVAllocator) 10078 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 10079 UniquePreds.InsertNode(OF, IP); 10080 return OF; 10081 } 10082 10083 namespace { 10084 10085 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 10086 public: 10087 /// Rewrites \p S in the context of a loop L and the SCEV predication 10088 /// infrastructure. 10089 /// 10090 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 10091 /// equivalences present in \p Pred. 10092 /// 10093 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 10094 /// \p NewPreds such that the result will be an AddRecExpr. 10095 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 10096 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 10097 SCEVUnionPredicate *Pred) { 10098 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 10099 return Rewriter.visit(S); 10100 } 10101 10102 SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 10103 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 10104 SCEVUnionPredicate *Pred) 10105 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 10106 10107 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 10108 if (Pred) { 10109 auto ExprPreds = Pred->getPredicatesForExpr(Expr); 10110 for (auto *Pred : ExprPreds) 10111 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) 10112 if (IPred->getLHS() == Expr) 10113 return IPred->getRHS(); 10114 } 10115 10116 return Expr; 10117 } 10118 10119 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 10120 const SCEV *Operand = visit(Expr->getOperand()); 10121 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 10122 if (AR && AR->getLoop() == L && AR->isAffine()) { 10123 // This couldn't be folded because the operand didn't have the nuw 10124 // flag. Add the nusw flag as an assumption that we could make. 10125 const SCEV *Step = AR->getStepRecurrence(SE); 10126 Type *Ty = Expr->getType(); 10127 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 10128 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 10129 SE.getSignExtendExpr(Step, Ty), L, 10130 AR->getNoWrapFlags()); 10131 } 10132 return SE.getZeroExtendExpr(Operand, Expr->getType()); 10133 } 10134 10135 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 10136 const SCEV *Operand = visit(Expr->getOperand()); 10137 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 10138 if (AR && AR->getLoop() == L && AR->isAffine()) { 10139 // This couldn't be folded because the operand didn't have the nsw 10140 // flag. Add the nssw flag as an assumption that we could make. 10141 const SCEV *Step = AR->getStepRecurrence(SE); 10142 Type *Ty = Expr->getType(); 10143 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 10144 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 10145 SE.getSignExtendExpr(Step, Ty), L, 10146 AR->getNoWrapFlags()); 10147 } 10148 return SE.getSignExtendExpr(Operand, Expr->getType()); 10149 } 10150 10151 private: 10152 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 10153 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 10154 auto *A = SE.getWrapPredicate(AR, AddedFlags); 10155 if (!NewPreds) { 10156 // Check if we've already made this assumption. 10157 return Pred && Pred->implies(A); 10158 } 10159 NewPreds->insert(A); 10160 return true; 10161 } 10162 10163 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 10164 SCEVUnionPredicate *Pred; 10165 const Loop *L; 10166 }; 10167 } // end anonymous namespace 10168 10169 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 10170 SCEVUnionPredicate &Preds) { 10171 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 10172 } 10173 10174 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 10175 const SCEV *S, const Loop *L, 10176 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 10177 10178 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 10179 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 10180 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 10181 10182 if (!AddRec) 10183 return nullptr; 10184 10185 // Since the transformation was successful, we can now transfer the SCEV 10186 // predicates. 10187 for (auto *P : TransformPreds) 10188 Preds.insert(P); 10189 10190 return AddRec; 10191 } 10192 10193 /// SCEV predicates 10194 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 10195 SCEVPredicateKind Kind) 10196 : FastID(ID), Kind(Kind) {} 10197 10198 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 10199 const SCEVUnknown *LHS, 10200 const SCEVConstant *RHS) 10201 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {} 10202 10203 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 10204 const auto *Op = dyn_cast<SCEVEqualPredicate>(N); 10205 10206 if (!Op) 10207 return false; 10208 10209 return Op->LHS == LHS && Op->RHS == RHS; 10210 } 10211 10212 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 10213 10214 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 10215 10216 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 10217 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 10218 } 10219 10220 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 10221 const SCEVAddRecExpr *AR, 10222 IncrementWrapFlags Flags) 10223 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 10224 10225 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 10226 10227 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 10228 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 10229 10230 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 10231 } 10232 10233 bool SCEVWrapPredicate::isAlwaysTrue() const { 10234 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 10235 IncrementWrapFlags IFlags = Flags; 10236 10237 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 10238 IFlags = clearFlags(IFlags, IncrementNSSW); 10239 10240 return IFlags == IncrementAnyWrap; 10241 } 10242 10243 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 10244 OS.indent(Depth) << *getExpr() << " Added Flags: "; 10245 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 10246 OS << "<nusw>"; 10247 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 10248 OS << "<nssw>"; 10249 OS << "\n"; 10250 } 10251 10252 SCEVWrapPredicate::IncrementWrapFlags 10253 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 10254 ScalarEvolution &SE) { 10255 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 10256 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 10257 10258 // We can safely transfer the NSW flag as NSSW. 10259 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 10260 ImpliedFlags = IncrementNSSW; 10261 10262 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 10263 // If the increment is positive, the SCEV NUW flag will also imply the 10264 // WrapPredicate NUSW flag. 10265 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 10266 if (Step->getValue()->getValue().isNonNegative()) 10267 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 10268 } 10269 10270 return ImpliedFlags; 10271 } 10272 10273 /// Union predicates don't get cached so create a dummy set ID for it. 10274 SCEVUnionPredicate::SCEVUnionPredicate() 10275 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 10276 10277 bool SCEVUnionPredicate::isAlwaysTrue() const { 10278 return all_of(Preds, 10279 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 10280 } 10281 10282 ArrayRef<const SCEVPredicate *> 10283 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 10284 auto I = SCEVToPreds.find(Expr); 10285 if (I == SCEVToPreds.end()) 10286 return ArrayRef<const SCEVPredicate *>(); 10287 return I->second; 10288 } 10289 10290 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 10291 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 10292 return all_of(Set->Preds, 10293 [this](const SCEVPredicate *I) { return this->implies(I); }); 10294 10295 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 10296 if (ScevPredsIt == SCEVToPreds.end()) 10297 return false; 10298 auto &SCEVPreds = ScevPredsIt->second; 10299 10300 return any_of(SCEVPreds, 10301 [N](const SCEVPredicate *I) { return I->implies(N); }); 10302 } 10303 10304 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 10305 10306 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 10307 for (auto Pred : Preds) 10308 Pred->print(OS, Depth); 10309 } 10310 10311 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 10312 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 10313 for (auto Pred : Set->Preds) 10314 add(Pred); 10315 return; 10316 } 10317 10318 if (implies(N)) 10319 return; 10320 10321 const SCEV *Key = N->getExpr(); 10322 assert(Key && "Only SCEVUnionPredicate doesn't have an " 10323 " associated expression!"); 10324 10325 SCEVToPreds[Key].push_back(N); 10326 Preds.push_back(N); 10327 } 10328 10329 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 10330 Loop &L) 10331 : SE(SE), L(L), Generation(0), BackedgeCount(nullptr) {} 10332 10333 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 10334 const SCEV *Expr = SE.getSCEV(V); 10335 RewriteEntry &Entry = RewriteMap[Expr]; 10336 10337 // If we already have an entry and the version matches, return it. 10338 if (Entry.second && Generation == Entry.first) 10339 return Entry.second; 10340 10341 // We found an entry but it's stale. Rewrite the stale entry 10342 // acording to the current predicate. 10343 if (Entry.second) 10344 Expr = Entry.second; 10345 10346 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 10347 Entry = {Generation, NewSCEV}; 10348 10349 return NewSCEV; 10350 } 10351 10352 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 10353 if (!BackedgeCount) { 10354 SCEVUnionPredicate BackedgePred; 10355 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); 10356 addPredicate(BackedgePred); 10357 } 10358 return BackedgeCount; 10359 } 10360 10361 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 10362 if (Preds.implies(&Pred)) 10363 return; 10364 Preds.add(&Pred); 10365 updateGeneration(); 10366 } 10367 10368 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 10369 return Preds; 10370 } 10371 10372 void PredicatedScalarEvolution::updateGeneration() { 10373 // If the generation number wrapped recompute everything. 10374 if (++Generation == 0) { 10375 for (auto &II : RewriteMap) { 10376 const SCEV *Rewritten = II.second.second; 10377 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 10378 } 10379 } 10380 } 10381 10382 void PredicatedScalarEvolution::setNoOverflow( 10383 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 10384 const SCEV *Expr = getSCEV(V); 10385 const auto *AR = cast<SCEVAddRecExpr>(Expr); 10386 10387 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 10388 10389 // Clear the statically implied flags. 10390 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 10391 addPredicate(*SE.getWrapPredicate(AR, Flags)); 10392 10393 auto II = FlagsMap.insert({V, Flags}); 10394 if (!II.second) 10395 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 10396 } 10397 10398 bool PredicatedScalarEvolution::hasNoOverflow( 10399 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 10400 const SCEV *Expr = getSCEV(V); 10401 const auto *AR = cast<SCEVAddRecExpr>(Expr); 10402 10403 Flags = SCEVWrapPredicate::clearFlags( 10404 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 10405 10406 auto II = FlagsMap.find(V); 10407 10408 if (II != FlagsMap.end()) 10409 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 10410 10411 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 10412 } 10413 10414 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 10415 const SCEV *Expr = this->getSCEV(V); 10416 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 10417 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 10418 10419 if (!New) 10420 return nullptr; 10421 10422 for (auto *P : NewPreds) 10423 Preds.add(P); 10424 10425 updateGeneration(); 10426 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 10427 return New; 10428 } 10429 10430 PredicatedScalarEvolution::PredicatedScalarEvolution( 10431 const PredicatedScalarEvolution &Init) 10432 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 10433 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 10434 for (const auto &I : Init.FlagsMap) 10435 FlagsMap.insert(I); 10436 } 10437 10438 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 10439 // For each block. 10440 for (auto *BB : L.getBlocks()) 10441 for (auto &I : *BB) { 10442 if (!SE.isSCEVable(I.getType())) 10443 continue; 10444 10445 auto *Expr = SE.getSCEV(&I); 10446 auto II = RewriteMap.find(Expr); 10447 10448 if (II == RewriteMap.end()) 10449 continue; 10450 10451 // Don't print things that are not interesting. 10452 if (II->second.second == Expr) 10453 continue; 10454 10455 OS.indent(Depth) << "[PSE]" << I << ":\n"; 10456 OS.indent(Depth + 2) << *Expr << "\n"; 10457 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 10458 } 10459 } 10460