1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file contains the implementation of the scalar evolution analysis 11 // engine, which is used primarily to analyze expressions involving induction 12 // variables in loops. 13 // 14 // There are several aspects to this library. First is the representation of 15 // scalar expressions, which are represented as subclasses of the SCEV class. 16 // These classes are used to represent certain types of subexpressions that we 17 // can handle. We only create one SCEV of a particular shape, so 18 // pointer-comparisons for equality are legal. 19 // 20 // One important aspect of the SCEV objects is that they are never cyclic, even 21 // if there is a cycle in the dataflow for an expression (ie, a PHI node). If 22 // the PHI node is one of the idioms that we can represent (e.g., a polynomial 23 // recurrence) then we represent it directly as a recurrence node, otherwise we 24 // represent it as a SCEVUnknown node. 25 // 26 // In addition to being able to represent expressions of various types, we also 27 // have folders that are used to build the *canonical* representation for a 28 // particular expression. These folders are capable of using a variety of 29 // rewrite rules to simplify the expressions. 30 // 31 // Once the folders are defined, we can implement the more interesting 32 // higher-level code, such as the code that recognizes PHI nodes of various 33 // types, computes the execution count of a loop, etc. 34 // 35 // TODO: We should use these routines and value representations to implement 36 // dependence analysis! 37 // 38 //===----------------------------------------------------------------------===// 39 // 40 // There are several good references for the techniques used in this analysis. 41 // 42 // Chains of recurrences -- a method to expedite the evaluation 43 // of closed-form functions 44 // Olaf Bachmann, Paul S. Wang, Eugene V. Zima 45 // 46 // On computational properties of chains of recurrences 47 // Eugene V. Zima 48 // 49 // Symbolic Evaluation of Chains of Recurrences for Loop Optimization 50 // Robert A. van Engelen 51 // 52 // Efficient Symbolic Analysis for Optimizing Compilers 53 // Robert A. van Engelen 54 // 55 // Using the chains of recurrences algebra for data dependence testing and 56 // induction variable substitution 57 // MS Thesis, Johnie Birch 58 // 59 //===----------------------------------------------------------------------===// 60 61 #include "llvm/Analysis/ScalarEvolution.h" 62 #include "llvm/ADT/Optional.h" 63 #include "llvm/ADT/STLExtras.h" 64 #include "llvm/ADT/ScopeExit.h" 65 #include "llvm/ADT/Sequence.h" 66 #include "llvm/ADT/SmallPtrSet.h" 67 #include "llvm/ADT/Statistic.h" 68 #include "llvm/Analysis/AssumptionCache.h" 69 #include "llvm/Analysis/ConstantFolding.h" 70 #include "llvm/Analysis/InstructionSimplify.h" 71 #include "llvm/Analysis/LoopInfo.h" 72 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 73 #include "llvm/Analysis/TargetLibraryInfo.h" 74 #include "llvm/Analysis/ValueTracking.h" 75 #include "llvm/IR/ConstantRange.h" 76 #include "llvm/IR/Constants.h" 77 #include "llvm/IR/DataLayout.h" 78 #include "llvm/IR/DerivedTypes.h" 79 #include "llvm/IR/Dominators.h" 80 #include "llvm/IR/GetElementPtrTypeIterator.h" 81 #include "llvm/IR/GlobalAlias.h" 82 #include "llvm/IR/GlobalVariable.h" 83 #include "llvm/IR/InstIterator.h" 84 #include "llvm/IR/Instructions.h" 85 #include "llvm/IR/LLVMContext.h" 86 #include "llvm/IR/Metadata.h" 87 #include "llvm/IR/Operator.h" 88 #include "llvm/IR/PatternMatch.h" 89 #include "llvm/Support/CommandLine.h" 90 #include "llvm/Support/Debug.h" 91 #include "llvm/Support/ErrorHandling.h" 92 #include "llvm/Support/MathExtras.h" 93 #include "llvm/Support/raw_ostream.h" 94 #include "llvm/Support/SaveAndRestore.h" 95 #include <algorithm> 96 using namespace llvm; 97 98 #define DEBUG_TYPE "scalar-evolution" 99 100 STATISTIC(NumArrayLenItCounts, 101 "Number of trip counts computed with array length"); 102 STATISTIC(NumTripCountsComputed, 103 "Number of loops with predictable loop counts"); 104 STATISTIC(NumTripCountsNotComputed, 105 "Number of loops without predictable loop counts"); 106 STATISTIC(NumBruteForceTripCountsComputed, 107 "Number of loops with trip counts computed by force"); 108 109 static cl::opt<unsigned> 110 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, 111 cl::desc("Maximum number of iterations SCEV will " 112 "symbolically execute a constant " 113 "derived loop"), 114 cl::init(100)); 115 116 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean. 117 static cl::opt<bool> 118 VerifySCEV("verify-scev", 119 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)")); 120 static cl::opt<bool> 121 VerifySCEVMap("verify-scev-maps", 122 cl::desc("Verify no dangling value in ScalarEvolution's " 123 "ExprValueMap (slow)")); 124 125 static cl::opt<unsigned> MulOpsInlineThreshold( 126 "scev-mulops-inline-threshold", cl::Hidden, 127 cl::desc("Threshold for inlining multiplication operands into a SCEV"), 128 cl::init(1000)); 129 130 //===----------------------------------------------------------------------===// 131 // SCEV class definitions 132 //===----------------------------------------------------------------------===// 133 134 //===----------------------------------------------------------------------===// 135 // Implementation of the SCEV class. 136 // 137 138 LLVM_DUMP_METHOD 139 void SCEV::dump() const { 140 print(dbgs()); 141 dbgs() << '\n'; 142 } 143 144 void SCEV::print(raw_ostream &OS) const { 145 switch (static_cast<SCEVTypes>(getSCEVType())) { 146 case scConstant: 147 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false); 148 return; 149 case scTruncate: { 150 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this); 151 const SCEV *Op = Trunc->getOperand(); 152 OS << "(trunc " << *Op->getType() << " " << *Op << " to " 153 << *Trunc->getType() << ")"; 154 return; 155 } 156 case scZeroExtend: { 157 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this); 158 const SCEV *Op = ZExt->getOperand(); 159 OS << "(zext " << *Op->getType() << " " << *Op << " to " 160 << *ZExt->getType() << ")"; 161 return; 162 } 163 case scSignExtend: { 164 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this); 165 const SCEV *Op = SExt->getOperand(); 166 OS << "(sext " << *Op->getType() << " " << *Op << " to " 167 << *SExt->getType() << ")"; 168 return; 169 } 170 case scAddRecExpr: { 171 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this); 172 OS << "{" << *AR->getOperand(0); 173 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i) 174 OS << ",+," << *AR->getOperand(i); 175 OS << "}<"; 176 if (AR->hasNoUnsignedWrap()) 177 OS << "nuw><"; 178 if (AR->hasNoSignedWrap()) 179 OS << "nsw><"; 180 if (AR->hasNoSelfWrap() && 181 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW))) 182 OS << "nw><"; 183 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false); 184 OS << ">"; 185 return; 186 } 187 case scAddExpr: 188 case scMulExpr: 189 case scUMaxExpr: 190 case scSMaxExpr: { 191 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this); 192 const char *OpStr = nullptr; 193 switch (NAry->getSCEVType()) { 194 case scAddExpr: OpStr = " + "; break; 195 case scMulExpr: OpStr = " * "; break; 196 case scUMaxExpr: OpStr = " umax "; break; 197 case scSMaxExpr: OpStr = " smax "; break; 198 } 199 OS << "("; 200 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end(); 201 I != E; ++I) { 202 OS << **I; 203 if (std::next(I) != E) 204 OS << OpStr; 205 } 206 OS << ")"; 207 switch (NAry->getSCEVType()) { 208 case scAddExpr: 209 case scMulExpr: 210 if (NAry->hasNoUnsignedWrap()) 211 OS << "<nuw>"; 212 if (NAry->hasNoSignedWrap()) 213 OS << "<nsw>"; 214 } 215 return; 216 } 217 case scUDivExpr: { 218 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this); 219 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")"; 220 return; 221 } 222 case scUnknown: { 223 const SCEVUnknown *U = cast<SCEVUnknown>(this); 224 Type *AllocTy; 225 if (U->isSizeOf(AllocTy)) { 226 OS << "sizeof(" << *AllocTy << ")"; 227 return; 228 } 229 if (U->isAlignOf(AllocTy)) { 230 OS << "alignof(" << *AllocTy << ")"; 231 return; 232 } 233 234 Type *CTy; 235 Constant *FieldNo; 236 if (U->isOffsetOf(CTy, FieldNo)) { 237 OS << "offsetof(" << *CTy << ", "; 238 FieldNo->printAsOperand(OS, false); 239 OS << ")"; 240 return; 241 } 242 243 // Otherwise just print it normally. 244 U->getValue()->printAsOperand(OS, false); 245 return; 246 } 247 case scCouldNotCompute: 248 OS << "***COULDNOTCOMPUTE***"; 249 return; 250 } 251 llvm_unreachable("Unknown SCEV kind!"); 252 } 253 254 Type *SCEV::getType() const { 255 switch (static_cast<SCEVTypes>(getSCEVType())) { 256 case scConstant: 257 return cast<SCEVConstant>(this)->getType(); 258 case scTruncate: 259 case scZeroExtend: 260 case scSignExtend: 261 return cast<SCEVCastExpr>(this)->getType(); 262 case scAddRecExpr: 263 case scMulExpr: 264 case scUMaxExpr: 265 case scSMaxExpr: 266 return cast<SCEVNAryExpr>(this)->getType(); 267 case scAddExpr: 268 return cast<SCEVAddExpr>(this)->getType(); 269 case scUDivExpr: 270 return cast<SCEVUDivExpr>(this)->getType(); 271 case scUnknown: 272 return cast<SCEVUnknown>(this)->getType(); 273 case scCouldNotCompute: 274 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 275 } 276 llvm_unreachable("Unknown SCEV kind!"); 277 } 278 279 bool SCEV::isZero() const { 280 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 281 return SC->getValue()->isZero(); 282 return false; 283 } 284 285 bool SCEV::isOne() const { 286 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 287 return SC->getValue()->isOne(); 288 return false; 289 } 290 291 bool SCEV::isAllOnesValue() const { 292 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 293 return SC->getValue()->isAllOnesValue(); 294 return false; 295 } 296 297 bool SCEV::isNonConstantNegative() const { 298 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this); 299 if (!Mul) return false; 300 301 // If there is a constant factor, it will be first. 302 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); 303 if (!SC) return false; 304 305 // Return true if the value is negative, this matches things like (-42 * V). 306 return SC->getAPInt().isNegative(); 307 } 308 309 SCEVCouldNotCompute::SCEVCouldNotCompute() : 310 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {} 311 312 bool SCEVCouldNotCompute::classof(const SCEV *S) { 313 return S->getSCEVType() == scCouldNotCompute; 314 } 315 316 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) { 317 FoldingSetNodeID ID; 318 ID.AddInteger(scConstant); 319 ID.AddPointer(V); 320 void *IP = nullptr; 321 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 322 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V); 323 UniqueSCEVs.InsertNode(S, IP); 324 return S; 325 } 326 327 const SCEV *ScalarEvolution::getConstant(const APInt &Val) { 328 return getConstant(ConstantInt::get(getContext(), Val)); 329 } 330 331 const SCEV * 332 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) { 333 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty)); 334 return getConstant(ConstantInt::get(ITy, V, isSigned)); 335 } 336 337 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, 338 unsigned SCEVTy, const SCEV *op, Type *ty) 339 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {} 340 341 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, 342 const SCEV *op, Type *ty) 343 : SCEVCastExpr(ID, scTruncate, op, ty) { 344 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && 345 (Ty->isIntegerTy() || Ty->isPointerTy()) && 346 "Cannot truncate non-integer value!"); 347 } 348 349 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, 350 const SCEV *op, Type *ty) 351 : SCEVCastExpr(ID, scZeroExtend, op, ty) { 352 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && 353 (Ty->isIntegerTy() || Ty->isPointerTy()) && 354 "Cannot zero extend non-integer value!"); 355 } 356 357 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, 358 const SCEV *op, Type *ty) 359 : SCEVCastExpr(ID, scSignExtend, op, ty) { 360 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && 361 (Ty->isIntegerTy() || Ty->isPointerTy()) && 362 "Cannot sign extend non-integer value!"); 363 } 364 365 void SCEVUnknown::deleted() { 366 // Clear this SCEVUnknown from various maps. 367 SE->forgetMemoizedResults(this); 368 369 // Remove this SCEVUnknown from the uniquing map. 370 SE->UniqueSCEVs.RemoveNode(this); 371 372 // Release the value. 373 setValPtr(nullptr); 374 } 375 376 void SCEVUnknown::allUsesReplacedWith(Value *New) { 377 // Clear this SCEVUnknown from various maps. 378 SE->forgetMemoizedResults(this); 379 380 // Remove this SCEVUnknown from the uniquing map. 381 SE->UniqueSCEVs.RemoveNode(this); 382 383 // Update this SCEVUnknown to point to the new value. This is needed 384 // because there may still be outstanding SCEVs which still point to 385 // this SCEVUnknown. 386 setValPtr(New); 387 } 388 389 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const { 390 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 391 if (VCE->getOpcode() == Instruction::PtrToInt) 392 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 393 if (CE->getOpcode() == Instruction::GetElementPtr && 394 CE->getOperand(0)->isNullValue() && 395 CE->getNumOperands() == 2) 396 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1))) 397 if (CI->isOne()) { 398 AllocTy = cast<PointerType>(CE->getOperand(0)->getType()) 399 ->getElementType(); 400 return true; 401 } 402 403 return false; 404 } 405 406 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const { 407 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 408 if (VCE->getOpcode() == Instruction::PtrToInt) 409 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 410 if (CE->getOpcode() == Instruction::GetElementPtr && 411 CE->getOperand(0)->isNullValue()) { 412 Type *Ty = 413 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 414 if (StructType *STy = dyn_cast<StructType>(Ty)) 415 if (!STy->isPacked() && 416 CE->getNumOperands() == 3 && 417 CE->getOperand(1)->isNullValue()) { 418 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2))) 419 if (CI->isOne() && 420 STy->getNumElements() == 2 && 421 STy->getElementType(0)->isIntegerTy(1)) { 422 AllocTy = STy->getElementType(1); 423 return true; 424 } 425 } 426 } 427 428 return false; 429 } 430 431 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const { 432 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 433 if (VCE->getOpcode() == Instruction::PtrToInt) 434 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 435 if (CE->getOpcode() == Instruction::GetElementPtr && 436 CE->getNumOperands() == 3 && 437 CE->getOperand(0)->isNullValue() && 438 CE->getOperand(1)->isNullValue()) { 439 Type *Ty = 440 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 441 // Ignore vector types here so that ScalarEvolutionExpander doesn't 442 // emit getelementptrs that index into vectors. 443 if (Ty->isStructTy() || Ty->isArrayTy()) { 444 CTy = Ty; 445 FieldNo = CE->getOperand(2); 446 return true; 447 } 448 } 449 450 return false; 451 } 452 453 //===----------------------------------------------------------------------===// 454 // SCEV Utilities 455 //===----------------------------------------------------------------------===// 456 457 /// Compare the two values \p LV and \p RV in terms of their "complexity" where 458 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order 459 /// operands in SCEV expressions. \p EqCache is a set of pairs of values that 460 /// have been previously deemed to be "equally complex" by this routine. It is 461 /// intended to avoid exponential time complexity in cases like: 462 /// 463 /// %a = f(%x, %y) 464 /// %b = f(%a, %a) 465 /// %c = f(%b, %b) 466 /// 467 /// %d = f(%x, %y) 468 /// %e = f(%d, %d) 469 /// %f = f(%e, %e) 470 /// 471 /// CompareValueComplexity(%f, %c) 472 /// 473 /// Since we do not continue running this routine on expression trees once we 474 /// have seen unequal values, there is no need to track them in the cache. 475 static int 476 CompareValueComplexity(SmallSet<std::pair<Value *, Value *>, 8> &EqCache, 477 const LoopInfo *const LI, Value *LV, Value *RV, 478 unsigned DepthLeft = 2) { 479 if (DepthLeft == 0 || EqCache.count({LV, RV})) 480 return 0; 481 482 // Order pointer values after integer values. This helps SCEVExpander form 483 // GEPs. 484 bool LIsPointer = LV->getType()->isPointerTy(), 485 RIsPointer = RV->getType()->isPointerTy(); 486 if (LIsPointer != RIsPointer) 487 return (int)LIsPointer - (int)RIsPointer; 488 489 // Compare getValueID values. 490 unsigned LID = LV->getValueID(), RID = RV->getValueID(); 491 if (LID != RID) 492 return (int)LID - (int)RID; 493 494 // Sort arguments by their position. 495 if (const auto *LA = dyn_cast<Argument>(LV)) { 496 const auto *RA = cast<Argument>(RV); 497 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo(); 498 return (int)LArgNo - (int)RArgNo; 499 } 500 501 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) { 502 const auto *RGV = cast<GlobalValue>(RV); 503 504 const auto IsGVNameSemantic = [&](const GlobalValue *GV) { 505 auto LT = GV->getLinkage(); 506 return !(GlobalValue::isPrivateLinkage(LT) || 507 GlobalValue::isInternalLinkage(LT)); 508 }; 509 510 // Use the names to distinguish the two values, but only if the 511 // names are semantically important. 512 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV)) 513 return LGV->getName().compare(RGV->getName()); 514 } 515 516 // For instructions, compare their loop depth, and their operand count. This 517 // is pretty loose. 518 if (const auto *LInst = dyn_cast<Instruction>(LV)) { 519 const auto *RInst = cast<Instruction>(RV); 520 521 // Compare loop depths. 522 const BasicBlock *LParent = LInst->getParent(), 523 *RParent = RInst->getParent(); 524 if (LParent != RParent) { 525 unsigned LDepth = LI->getLoopDepth(LParent), 526 RDepth = LI->getLoopDepth(RParent); 527 if (LDepth != RDepth) 528 return (int)LDepth - (int)RDepth; 529 } 530 531 // Compare the number of operands. 532 unsigned LNumOps = LInst->getNumOperands(), 533 RNumOps = RInst->getNumOperands(); 534 if (LNumOps != RNumOps) 535 return (int)LNumOps - (int)RNumOps; 536 537 for (unsigned Idx : seq(0u, LNumOps)) { 538 int Result = 539 CompareValueComplexity(EqCache, LI, LInst->getOperand(Idx), 540 RInst->getOperand(Idx), DepthLeft - 1); 541 if (Result != 0) 542 return Result; 543 EqCache.insert({LV, RV}); 544 } 545 } 546 547 return 0; 548 } 549 550 // Return negative, zero, or positive, if LHS is less than, equal to, or greater 551 // than RHS, respectively. A three-way result allows recursive comparisons to be 552 // more efficient. 553 static int CompareSCEVComplexity(const LoopInfo *const LI, const SCEV *LHS, 554 const SCEV *RHS) { 555 // Fast-path: SCEVs are uniqued so we can do a quick equality check. 556 if (LHS == RHS) 557 return 0; 558 559 // Primarily, sort the SCEVs by their getSCEVType(). 560 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType(); 561 if (LType != RType) 562 return (int)LType - (int)RType; 563 564 // Aside from the getSCEVType() ordering, the particular ordering 565 // isn't very important except that it's beneficial to be consistent, 566 // so that (a + b) and (b + a) don't end up as different expressions. 567 switch (static_cast<SCEVTypes>(LType)) { 568 case scUnknown: { 569 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS); 570 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); 571 572 SmallSet<std::pair<Value *, Value *>, 8> EqCache; 573 return CompareValueComplexity(EqCache, LI, LU->getValue(), RU->getValue()); 574 } 575 576 case scConstant: { 577 const SCEVConstant *LC = cast<SCEVConstant>(LHS); 578 const SCEVConstant *RC = cast<SCEVConstant>(RHS); 579 580 // Compare constant values. 581 const APInt &LA = LC->getAPInt(); 582 const APInt &RA = RC->getAPInt(); 583 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth(); 584 if (LBitWidth != RBitWidth) 585 return (int)LBitWidth - (int)RBitWidth; 586 return LA.ult(RA) ? -1 : 1; 587 } 588 589 case scAddRecExpr: { 590 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); 591 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); 592 593 // Compare addrec loop depths. 594 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); 595 if (LLoop != RLoop) { 596 unsigned LDepth = LLoop->getLoopDepth(), RDepth = RLoop->getLoopDepth(); 597 if (LDepth != RDepth) 598 return (int)LDepth - (int)RDepth; 599 } 600 601 // Addrec complexity grows with operand count. 602 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands(); 603 if (LNumOps != RNumOps) 604 return (int)LNumOps - (int)RNumOps; 605 606 // Lexicographically compare. 607 for (unsigned i = 0; i != LNumOps; ++i) { 608 long X = CompareSCEVComplexity(LI, LA->getOperand(i), RA->getOperand(i)); 609 if (X != 0) 610 return X; 611 } 612 613 return 0; 614 } 615 616 case scAddExpr: 617 case scMulExpr: 618 case scSMaxExpr: 619 case scUMaxExpr: { 620 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); 621 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); 622 623 // Lexicographically compare n-ary expressions. 624 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); 625 if (LNumOps != RNumOps) 626 return (int)LNumOps - (int)RNumOps; 627 628 for (unsigned i = 0; i != LNumOps; ++i) { 629 if (i >= RNumOps) 630 return 1; 631 long X = CompareSCEVComplexity(LI, LC->getOperand(i), RC->getOperand(i)); 632 if (X != 0) 633 return X; 634 } 635 return (int)LNumOps - (int)RNumOps; 636 } 637 638 case scUDivExpr: { 639 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); 640 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); 641 642 // Lexicographically compare udiv expressions. 643 long X = CompareSCEVComplexity(LI, LC->getLHS(), RC->getLHS()); 644 if (X != 0) 645 return X; 646 return CompareSCEVComplexity(LI, LC->getRHS(), RC->getRHS()); 647 } 648 649 case scTruncate: 650 case scZeroExtend: 651 case scSignExtend: { 652 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS); 653 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS); 654 655 // Compare cast expressions by operand. 656 return CompareSCEVComplexity(LI, LC->getOperand(), RC->getOperand()); 657 } 658 659 case scCouldNotCompute: 660 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 661 } 662 llvm_unreachable("Unknown SCEV kind!"); 663 } 664 665 /// Given a list of SCEV objects, order them by their complexity, and group 666 /// objects of the same complexity together by value. When this routine is 667 /// finished, we know that any duplicates in the vector are consecutive and that 668 /// complexity is monotonically increasing. 669 /// 670 /// Note that we go take special precautions to ensure that we get deterministic 671 /// results from this routine. In other words, we don't want the results of 672 /// this to depend on where the addresses of various SCEV objects happened to 673 /// land in memory. 674 /// 675 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, 676 LoopInfo *LI) { 677 if (Ops.size() < 2) return; // Noop 678 if (Ops.size() == 2) { 679 // This is the common case, which also happens to be trivially simple. 680 // Special case it. 681 const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; 682 if (CompareSCEVComplexity(LI, RHS, LHS) < 0) 683 std::swap(LHS, RHS); 684 return; 685 } 686 687 // Do the rough sort by complexity. 688 std::stable_sort(Ops.begin(), Ops.end(), 689 [LI](const SCEV *LHS, const SCEV *RHS) { 690 return CompareSCEVComplexity(LI, LHS, RHS) < 0; 691 }); 692 693 // Now that we are sorted by complexity, group elements of the same 694 // complexity. Note that this is, at worst, N^2, but the vector is likely to 695 // be extremely short in practice. Note that we take this approach because we 696 // do not want to depend on the addresses of the objects we are grouping. 697 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { 698 const SCEV *S = Ops[i]; 699 unsigned Complexity = S->getSCEVType(); 700 701 // If there are any objects of the same complexity and same value as this 702 // one, group them. 703 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { 704 if (Ops[j] == S) { // Found a duplicate. 705 // Move it to immediately after i'th element. 706 std::swap(Ops[i+1], Ops[j]); 707 ++i; // no need to rescan it. 708 if (i == e-2) return; // Done! 709 } 710 } 711 } 712 } 713 714 // Returns the size of the SCEV S. 715 static inline int sizeOfSCEV(const SCEV *S) { 716 struct FindSCEVSize { 717 int Size; 718 FindSCEVSize() : Size(0) {} 719 720 bool follow(const SCEV *S) { 721 ++Size; 722 // Keep looking at all operands of S. 723 return true; 724 } 725 bool isDone() const { 726 return false; 727 } 728 }; 729 730 FindSCEVSize F; 731 SCEVTraversal<FindSCEVSize> ST(F); 732 ST.visitAll(S); 733 return F.Size; 734 } 735 736 namespace { 737 738 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> { 739 public: 740 // Computes the Quotient and Remainder of the division of Numerator by 741 // Denominator. 742 static void divide(ScalarEvolution &SE, const SCEV *Numerator, 743 const SCEV *Denominator, const SCEV **Quotient, 744 const SCEV **Remainder) { 745 assert(Numerator && Denominator && "Uninitialized SCEV"); 746 747 SCEVDivision D(SE, Numerator, Denominator); 748 749 // Check for the trivial case here to avoid having to check for it in the 750 // rest of the code. 751 if (Numerator == Denominator) { 752 *Quotient = D.One; 753 *Remainder = D.Zero; 754 return; 755 } 756 757 if (Numerator->isZero()) { 758 *Quotient = D.Zero; 759 *Remainder = D.Zero; 760 return; 761 } 762 763 // A simple case when N/1. The quotient is N. 764 if (Denominator->isOne()) { 765 *Quotient = Numerator; 766 *Remainder = D.Zero; 767 return; 768 } 769 770 // Split the Denominator when it is a product. 771 if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) { 772 const SCEV *Q, *R; 773 *Quotient = Numerator; 774 for (const SCEV *Op : T->operands()) { 775 divide(SE, *Quotient, Op, &Q, &R); 776 *Quotient = Q; 777 778 // Bail out when the Numerator is not divisible by one of the terms of 779 // the Denominator. 780 if (!R->isZero()) { 781 *Quotient = D.Zero; 782 *Remainder = Numerator; 783 return; 784 } 785 } 786 *Remainder = D.Zero; 787 return; 788 } 789 790 D.visit(Numerator); 791 *Quotient = D.Quotient; 792 *Remainder = D.Remainder; 793 } 794 795 // Except in the trivial case described above, we do not know how to divide 796 // Expr by Denominator for the following functions with empty implementation. 797 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {} 798 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {} 799 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {} 800 void visitUDivExpr(const SCEVUDivExpr *Numerator) {} 801 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {} 802 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {} 803 void visitUnknown(const SCEVUnknown *Numerator) {} 804 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {} 805 806 void visitConstant(const SCEVConstant *Numerator) { 807 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) { 808 APInt NumeratorVal = Numerator->getAPInt(); 809 APInt DenominatorVal = D->getAPInt(); 810 uint32_t NumeratorBW = NumeratorVal.getBitWidth(); 811 uint32_t DenominatorBW = DenominatorVal.getBitWidth(); 812 813 if (NumeratorBW > DenominatorBW) 814 DenominatorVal = DenominatorVal.sext(NumeratorBW); 815 else if (NumeratorBW < DenominatorBW) 816 NumeratorVal = NumeratorVal.sext(DenominatorBW); 817 818 APInt QuotientVal(NumeratorVal.getBitWidth(), 0); 819 APInt RemainderVal(NumeratorVal.getBitWidth(), 0); 820 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal); 821 Quotient = SE.getConstant(QuotientVal); 822 Remainder = SE.getConstant(RemainderVal); 823 return; 824 } 825 } 826 827 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) { 828 const SCEV *StartQ, *StartR, *StepQ, *StepR; 829 if (!Numerator->isAffine()) 830 return cannotDivide(Numerator); 831 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR); 832 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR); 833 // Bail out if the types do not match. 834 Type *Ty = Denominator->getType(); 835 if (Ty != StartQ->getType() || Ty != StartR->getType() || 836 Ty != StepQ->getType() || Ty != StepR->getType()) 837 return cannotDivide(Numerator); 838 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(), 839 Numerator->getNoWrapFlags()); 840 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(), 841 Numerator->getNoWrapFlags()); 842 } 843 844 void visitAddExpr(const SCEVAddExpr *Numerator) { 845 SmallVector<const SCEV *, 2> Qs, Rs; 846 Type *Ty = Denominator->getType(); 847 848 for (const SCEV *Op : Numerator->operands()) { 849 const SCEV *Q, *R; 850 divide(SE, Op, Denominator, &Q, &R); 851 852 // Bail out if types do not match. 853 if (Ty != Q->getType() || Ty != R->getType()) 854 return cannotDivide(Numerator); 855 856 Qs.push_back(Q); 857 Rs.push_back(R); 858 } 859 860 if (Qs.size() == 1) { 861 Quotient = Qs[0]; 862 Remainder = Rs[0]; 863 return; 864 } 865 866 Quotient = SE.getAddExpr(Qs); 867 Remainder = SE.getAddExpr(Rs); 868 } 869 870 void visitMulExpr(const SCEVMulExpr *Numerator) { 871 SmallVector<const SCEV *, 2> Qs; 872 Type *Ty = Denominator->getType(); 873 874 bool FoundDenominatorTerm = false; 875 for (const SCEV *Op : Numerator->operands()) { 876 // Bail out if types do not match. 877 if (Ty != Op->getType()) 878 return cannotDivide(Numerator); 879 880 if (FoundDenominatorTerm) { 881 Qs.push_back(Op); 882 continue; 883 } 884 885 // Check whether Denominator divides one of the product operands. 886 const SCEV *Q, *R; 887 divide(SE, Op, Denominator, &Q, &R); 888 if (!R->isZero()) { 889 Qs.push_back(Op); 890 continue; 891 } 892 893 // Bail out if types do not match. 894 if (Ty != Q->getType()) 895 return cannotDivide(Numerator); 896 897 FoundDenominatorTerm = true; 898 Qs.push_back(Q); 899 } 900 901 if (FoundDenominatorTerm) { 902 Remainder = Zero; 903 if (Qs.size() == 1) 904 Quotient = Qs[0]; 905 else 906 Quotient = SE.getMulExpr(Qs); 907 return; 908 } 909 910 if (!isa<SCEVUnknown>(Denominator)) 911 return cannotDivide(Numerator); 912 913 // The Remainder is obtained by replacing Denominator by 0 in Numerator. 914 ValueToValueMap RewriteMap; 915 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 916 cast<SCEVConstant>(Zero)->getValue(); 917 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 918 919 if (Remainder->isZero()) { 920 // The Quotient is obtained by replacing Denominator by 1 in Numerator. 921 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 922 cast<SCEVConstant>(One)->getValue(); 923 Quotient = 924 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 925 return; 926 } 927 928 // Quotient is (Numerator - Remainder) divided by Denominator. 929 const SCEV *Q, *R; 930 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder); 931 // This SCEV does not seem to simplify: fail the division here. 932 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator)) 933 return cannotDivide(Numerator); 934 divide(SE, Diff, Denominator, &Q, &R); 935 if (R != Zero) 936 return cannotDivide(Numerator); 937 Quotient = Q; 938 } 939 940 private: 941 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator, 942 const SCEV *Denominator) 943 : SE(S), Denominator(Denominator) { 944 Zero = SE.getZero(Denominator->getType()); 945 One = SE.getOne(Denominator->getType()); 946 947 // We generally do not know how to divide Expr by Denominator. We 948 // initialize the division to a "cannot divide" state to simplify the rest 949 // of the code. 950 cannotDivide(Numerator); 951 } 952 953 // Convenience function for giving up on the division. We set the quotient to 954 // be equal to zero and the remainder to be equal to the numerator. 955 void cannotDivide(const SCEV *Numerator) { 956 Quotient = Zero; 957 Remainder = Numerator; 958 } 959 960 ScalarEvolution &SE; 961 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One; 962 }; 963 964 } 965 966 //===----------------------------------------------------------------------===// 967 // Simple SCEV method implementations 968 //===----------------------------------------------------------------------===// 969 970 /// Compute BC(It, K). The result has width W. Assume, K > 0. 971 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, 972 ScalarEvolution &SE, 973 Type *ResultTy) { 974 // Handle the simplest case efficiently. 975 if (K == 1) 976 return SE.getTruncateOrZeroExtend(It, ResultTy); 977 978 // We are using the following formula for BC(It, K): 979 // 980 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! 981 // 982 // Suppose, W is the bitwidth of the return value. We must be prepared for 983 // overflow. Hence, we must assure that the result of our computation is 984 // equal to the accurate one modulo 2^W. Unfortunately, division isn't 985 // safe in modular arithmetic. 986 // 987 // However, this code doesn't use exactly that formula; the formula it uses 988 // is something like the following, where T is the number of factors of 2 in 989 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is 990 // exponentiation: 991 // 992 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) 993 // 994 // This formula is trivially equivalent to the previous formula. However, 995 // this formula can be implemented much more efficiently. The trick is that 996 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular 997 // arithmetic. To do exact division in modular arithmetic, all we have 998 // to do is multiply by the inverse. Therefore, this step can be done at 999 // width W. 1000 // 1001 // The next issue is how to safely do the division by 2^T. The way this 1002 // is done is by doing the multiplication step at a width of at least W + T 1003 // bits. This way, the bottom W+T bits of the product are accurate. Then, 1004 // when we perform the division by 2^T (which is equivalent to a right shift 1005 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get 1006 // truncated out after the division by 2^T. 1007 // 1008 // In comparison to just directly using the first formula, this technique 1009 // is much more efficient; using the first formula requires W * K bits, 1010 // but this formula less than W + K bits. Also, the first formula requires 1011 // a division step, whereas this formula only requires multiplies and shifts. 1012 // 1013 // It doesn't matter whether the subtraction step is done in the calculation 1014 // width or the input iteration count's width; if the subtraction overflows, 1015 // the result must be zero anyway. We prefer here to do it in the width of 1016 // the induction variable because it helps a lot for certain cases; CodeGen 1017 // isn't smart enough to ignore the overflow, which leads to much less 1018 // efficient code if the width of the subtraction is wider than the native 1019 // register width. 1020 // 1021 // (It's possible to not widen at all by pulling out factors of 2 before 1022 // the multiplication; for example, K=2 can be calculated as 1023 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires 1024 // extra arithmetic, so it's not an obvious win, and it gets 1025 // much more complicated for K > 3.) 1026 1027 // Protection from insane SCEVs; this bound is conservative, 1028 // but it probably doesn't matter. 1029 if (K > 1000) 1030 return SE.getCouldNotCompute(); 1031 1032 unsigned W = SE.getTypeSizeInBits(ResultTy); 1033 1034 // Calculate K! / 2^T and T; we divide out the factors of two before 1035 // multiplying for calculating K! / 2^T to avoid overflow. 1036 // Other overflow doesn't matter because we only care about the bottom 1037 // W bits of the result. 1038 APInt OddFactorial(W, 1); 1039 unsigned T = 1; 1040 for (unsigned i = 3; i <= K; ++i) { 1041 APInt Mult(W, i); 1042 unsigned TwoFactors = Mult.countTrailingZeros(); 1043 T += TwoFactors; 1044 Mult = Mult.lshr(TwoFactors); 1045 OddFactorial *= Mult; 1046 } 1047 1048 // We need at least W + T bits for the multiplication step 1049 unsigned CalculationBits = W + T; 1050 1051 // Calculate 2^T, at width T+W. 1052 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T); 1053 1054 // Calculate the multiplicative inverse of K! / 2^T; 1055 // this multiplication factor will perform the exact division by 1056 // K! / 2^T. 1057 APInt Mod = APInt::getSignedMinValue(W+1); 1058 APInt MultiplyFactor = OddFactorial.zext(W+1); 1059 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); 1060 MultiplyFactor = MultiplyFactor.trunc(W); 1061 1062 // Calculate the product, at width T+W 1063 IntegerType *CalculationTy = IntegerType::get(SE.getContext(), 1064 CalculationBits); 1065 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); 1066 for (unsigned i = 1; i != K; ++i) { 1067 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); 1068 Dividend = SE.getMulExpr(Dividend, 1069 SE.getTruncateOrZeroExtend(S, CalculationTy)); 1070 } 1071 1072 // Divide by 2^T 1073 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); 1074 1075 // Truncate the result, and divide by K! / 2^T. 1076 1077 return SE.getMulExpr(SE.getConstant(MultiplyFactor), 1078 SE.getTruncateOrZeroExtend(DivResult, ResultTy)); 1079 } 1080 1081 /// Return the value of this chain of recurrences at the specified iteration 1082 /// number. We can evaluate this recurrence by multiplying each element in the 1083 /// chain by the binomial coefficient corresponding to it. In other words, we 1084 /// can evaluate {A,+,B,+,C,+,D} as: 1085 /// 1086 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) 1087 /// 1088 /// where BC(It, k) stands for binomial coefficient. 1089 /// 1090 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, 1091 ScalarEvolution &SE) const { 1092 const SCEV *Result = getStart(); 1093 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 1094 // The computation is correct in the face of overflow provided that the 1095 // multiplication is performed _after_ the evaluation of the binomial 1096 // coefficient. 1097 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType()); 1098 if (isa<SCEVCouldNotCompute>(Coeff)) 1099 return Coeff; 1100 1101 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff)); 1102 } 1103 return Result; 1104 } 1105 1106 //===----------------------------------------------------------------------===// 1107 // SCEV Expression folder implementations 1108 //===----------------------------------------------------------------------===// 1109 1110 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, 1111 Type *Ty) { 1112 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && 1113 "This is not a truncating conversion!"); 1114 assert(isSCEVable(Ty) && 1115 "This is not a conversion to a SCEVable type!"); 1116 Ty = getEffectiveSCEVType(Ty); 1117 1118 FoldingSetNodeID ID; 1119 ID.AddInteger(scTruncate); 1120 ID.AddPointer(Op); 1121 ID.AddPointer(Ty); 1122 void *IP = nullptr; 1123 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1124 1125 // Fold if the operand is constant. 1126 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1127 return getConstant( 1128 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); 1129 1130 // trunc(trunc(x)) --> trunc(x) 1131 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) 1132 return getTruncateExpr(ST->getOperand(), Ty); 1133 1134 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing 1135 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1136 return getTruncateOrSignExtend(SS->getOperand(), Ty); 1137 1138 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing 1139 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1140 return getTruncateOrZeroExtend(SZ->getOperand(), Ty); 1141 1142 // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can 1143 // eliminate all the truncates, or we replace other casts with truncates. 1144 if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) { 1145 SmallVector<const SCEV *, 4> Operands; 1146 bool hasTrunc = false; 1147 for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) { 1148 const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty); 1149 if (!isa<SCEVCastExpr>(SA->getOperand(i))) 1150 hasTrunc = isa<SCEVTruncateExpr>(S); 1151 Operands.push_back(S); 1152 } 1153 if (!hasTrunc) 1154 return getAddExpr(Operands); 1155 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL. 1156 } 1157 1158 // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can 1159 // eliminate all the truncates, or we replace other casts with truncates. 1160 if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) { 1161 SmallVector<const SCEV *, 4> Operands; 1162 bool hasTrunc = false; 1163 for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) { 1164 const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty); 1165 if (!isa<SCEVCastExpr>(SM->getOperand(i))) 1166 hasTrunc = isa<SCEVTruncateExpr>(S); 1167 Operands.push_back(S); 1168 } 1169 if (!hasTrunc) 1170 return getMulExpr(Operands); 1171 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL. 1172 } 1173 1174 // If the input value is a chrec scev, truncate the chrec's operands. 1175 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 1176 SmallVector<const SCEV *, 4> Operands; 1177 for (const SCEV *Op : AddRec->operands()) 1178 Operands.push_back(getTruncateExpr(Op, Ty)); 1179 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap); 1180 } 1181 1182 // The cast wasn't folded; create an explicit cast node. We can reuse 1183 // the existing insert position since if we get here, we won't have 1184 // made any changes which would invalidate it. 1185 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), 1186 Op, Ty); 1187 UniqueSCEVs.InsertNode(S, IP); 1188 return S; 1189 } 1190 1191 // Get the limit of a recurrence such that incrementing by Step cannot cause 1192 // signed overflow as long as the value of the recurrence within the 1193 // loop does not exceed this limit before incrementing. 1194 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step, 1195 ICmpInst::Predicate *Pred, 1196 ScalarEvolution *SE) { 1197 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1198 if (SE->isKnownPositive(Step)) { 1199 *Pred = ICmpInst::ICMP_SLT; 1200 return SE->getConstant(APInt::getSignedMinValue(BitWidth) - 1201 SE->getSignedRange(Step).getSignedMax()); 1202 } 1203 if (SE->isKnownNegative(Step)) { 1204 *Pred = ICmpInst::ICMP_SGT; 1205 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - 1206 SE->getSignedRange(Step).getSignedMin()); 1207 } 1208 return nullptr; 1209 } 1210 1211 // Get the limit of a recurrence such that incrementing by Step cannot cause 1212 // unsigned overflow as long as the value of the recurrence within the loop does 1213 // not exceed this limit before incrementing. 1214 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step, 1215 ICmpInst::Predicate *Pred, 1216 ScalarEvolution *SE) { 1217 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1218 *Pred = ICmpInst::ICMP_ULT; 1219 1220 return SE->getConstant(APInt::getMinValue(BitWidth) - 1221 SE->getUnsignedRange(Step).getUnsignedMax()); 1222 } 1223 1224 namespace { 1225 1226 struct ExtendOpTraitsBase { 1227 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *); 1228 }; 1229 1230 // Used to make code generic over signed and unsigned overflow. 1231 template <typename ExtendOp> struct ExtendOpTraits { 1232 // Members present: 1233 // 1234 // static const SCEV::NoWrapFlags WrapType; 1235 // 1236 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr; 1237 // 1238 // static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1239 // ICmpInst::Predicate *Pred, 1240 // ScalarEvolution *SE); 1241 }; 1242 1243 template <> 1244 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase { 1245 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW; 1246 1247 static const GetExtendExprTy GetExtendExpr; 1248 1249 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1250 ICmpInst::Predicate *Pred, 1251 ScalarEvolution *SE) { 1252 return getSignedOverflowLimitForStep(Step, Pred, SE); 1253 } 1254 }; 1255 1256 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1257 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr; 1258 1259 template <> 1260 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase { 1261 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW; 1262 1263 static const GetExtendExprTy GetExtendExpr; 1264 1265 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1266 ICmpInst::Predicate *Pred, 1267 ScalarEvolution *SE) { 1268 return getUnsignedOverflowLimitForStep(Step, Pred, SE); 1269 } 1270 }; 1271 1272 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1273 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr; 1274 } 1275 1276 // The recurrence AR has been shown to have no signed/unsigned wrap or something 1277 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as 1278 // easily prove NSW/NUW for its preincrement or postincrement sibling. This 1279 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step + 1280 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the 1281 // expression "Step + sext/zext(PreIncAR)" is congruent with 1282 // "sext/zext(PostIncAR)" 1283 template <typename ExtendOpTy> 1284 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, 1285 ScalarEvolution *SE) { 1286 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1287 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1288 1289 const Loop *L = AR->getLoop(); 1290 const SCEV *Start = AR->getStart(); 1291 const SCEV *Step = AR->getStepRecurrence(*SE); 1292 1293 // Check for a simple looking step prior to loop entry. 1294 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); 1295 if (!SA) 1296 return nullptr; 1297 1298 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV 1299 // subtraction is expensive. For this purpose, perform a quick and dirty 1300 // difference, by checking for Step in the operand list. 1301 SmallVector<const SCEV *, 4> DiffOps; 1302 for (const SCEV *Op : SA->operands()) 1303 if (Op != Step) 1304 DiffOps.push_back(Op); 1305 1306 if (DiffOps.size() == SA->getNumOperands()) 1307 return nullptr; 1308 1309 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` + 1310 // `Step`: 1311 1312 // 1. NSW/NUW flags on the step increment. 1313 auto PreStartFlags = 1314 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW); 1315 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags); 1316 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( 1317 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); 1318 1319 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies 1320 // "S+X does not sign/unsign-overflow". 1321 // 1322 1323 const SCEV *BECount = SE->getBackedgeTakenCount(L); 1324 if (PreAR && PreAR->getNoWrapFlags(WrapType) && 1325 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) 1326 return PreStart; 1327 1328 // 2. Direct overflow check on the step operation's expression. 1329 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); 1330 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); 1331 const SCEV *OperandExtendedStart = 1332 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy), 1333 (SE->*GetExtendExpr)(Step, WideTy)); 1334 if ((SE->*GetExtendExpr)(Start, WideTy) == OperandExtendedStart) { 1335 if (PreAR && AR->getNoWrapFlags(WrapType)) { 1336 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW 1337 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then 1338 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. 1339 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType); 1340 } 1341 return PreStart; 1342 } 1343 1344 // 3. Loop precondition. 1345 ICmpInst::Predicate Pred; 1346 const SCEV *OverflowLimit = 1347 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); 1348 1349 if (OverflowLimit && 1350 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) 1351 return PreStart; 1352 1353 return nullptr; 1354 } 1355 1356 // Get the normalized zero or sign extended expression for this AddRec's Start. 1357 template <typename ExtendOpTy> 1358 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, 1359 ScalarEvolution *SE) { 1360 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1361 1362 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE); 1363 if (!PreStart) 1364 return (SE->*GetExtendExpr)(AR->getStart(), Ty); 1365 1366 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty), 1367 (SE->*GetExtendExpr)(PreStart, Ty)); 1368 } 1369 1370 // Try to prove away overflow by looking at "nearby" add recurrences. A 1371 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it 1372 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. 1373 // 1374 // Formally: 1375 // 1376 // {S,+,X} == {S-T,+,X} + T 1377 // => Ext({S,+,X}) == Ext({S-T,+,X} + T) 1378 // 1379 // If ({S-T,+,X} + T) does not overflow ... (1) 1380 // 1381 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) 1382 // 1383 // If {S-T,+,X} does not overflow ... (2) 1384 // 1385 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) 1386 // == {Ext(S-T)+Ext(T),+,Ext(X)} 1387 // 1388 // If (S-T)+T does not overflow ... (3) 1389 // 1390 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} 1391 // == {Ext(S),+,Ext(X)} == LHS 1392 // 1393 // Thus, if (1), (2) and (3) are true for some T, then 1394 // Ext({S,+,X}) == {Ext(S),+,Ext(X)} 1395 // 1396 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) 1397 // does not overflow" restricted to the 0th iteration. Therefore we only need 1398 // to check for (1) and (2). 1399 // 1400 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T 1401 // is `Delta` (defined below). 1402 // 1403 template <typename ExtendOpTy> 1404 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, 1405 const SCEV *Step, 1406 const Loop *L) { 1407 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1408 1409 // We restrict `Start` to a constant to prevent SCEV from spending too much 1410 // time here. It is correct (but more expensive) to continue with a 1411 // non-constant `Start` and do a general SCEV subtraction to compute 1412 // `PreStart` below. 1413 // 1414 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); 1415 if (!StartC) 1416 return false; 1417 1418 APInt StartAI = StartC->getAPInt(); 1419 1420 for (unsigned Delta : {-2, -1, 1, 2}) { 1421 const SCEV *PreStart = getConstant(StartAI - Delta); 1422 1423 FoldingSetNodeID ID; 1424 ID.AddInteger(scAddRecExpr); 1425 ID.AddPointer(PreStart); 1426 ID.AddPointer(Step); 1427 ID.AddPointer(L); 1428 void *IP = nullptr; 1429 const auto *PreAR = 1430 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 1431 1432 // Give up if we don't already have the add recurrence we need because 1433 // actually constructing an add recurrence is relatively expensive. 1434 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2) 1435 const SCEV *DeltaS = getConstant(StartC->getType(), Delta); 1436 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; 1437 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep( 1438 DeltaS, &Pred, this); 1439 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1) 1440 return true; 1441 } 1442 } 1443 1444 return false; 1445 } 1446 1447 const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op, 1448 Type *Ty) { 1449 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1450 "This is not an extending conversion!"); 1451 assert(isSCEVable(Ty) && 1452 "This is not a conversion to a SCEVable type!"); 1453 Ty = getEffectiveSCEVType(Ty); 1454 1455 // Fold if the operand is constant. 1456 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1457 return getConstant( 1458 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty))); 1459 1460 // zext(zext(x)) --> zext(x) 1461 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1462 return getZeroExtendExpr(SZ->getOperand(), Ty); 1463 1464 // Before doing any expensive analysis, check to see if we've already 1465 // computed a SCEV for this Op and Ty. 1466 FoldingSetNodeID ID; 1467 ID.AddInteger(scZeroExtend); 1468 ID.AddPointer(Op); 1469 ID.AddPointer(Ty); 1470 void *IP = nullptr; 1471 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1472 1473 // zext(trunc(x)) --> zext(x) or x or trunc(x) 1474 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1475 // It's possible the bits taken off by the truncate were all zero bits. If 1476 // so, we should be able to simplify this further. 1477 const SCEV *X = ST->getOperand(); 1478 ConstantRange CR = getUnsignedRange(X); 1479 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1480 unsigned NewBits = getTypeSizeInBits(Ty); 1481 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( 1482 CR.zextOrTrunc(NewBits))) 1483 return getTruncateOrZeroExtend(X, Ty); 1484 } 1485 1486 // If the input value is a chrec scev, and we can prove that the value 1487 // did not overflow the old, smaller, value, we can zero extend all of the 1488 // operands (often constants). This allows analysis of something like 1489 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } 1490 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1491 if (AR->isAffine()) { 1492 const SCEV *Start = AR->getStart(); 1493 const SCEV *Step = AR->getStepRecurrence(*this); 1494 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1495 const Loop *L = AR->getLoop(); 1496 1497 if (!AR->hasNoUnsignedWrap()) { 1498 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1499 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1500 } 1501 1502 // If we have special knowledge that this addrec won't overflow, 1503 // we don't need to do any further analysis. 1504 if (AR->hasNoUnsignedWrap()) 1505 return getAddRecExpr( 1506 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), 1507 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1508 1509 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1510 // Note that this serves two purposes: It filters out loops that are 1511 // simply not analyzable, and it covers the case where this code is 1512 // being called from within backedge-taken count analysis, such that 1513 // attempting to ask for the backedge-taken count would likely result 1514 // in infinite recursion. In the later case, the analysis code will 1515 // cope with a conservative value, and it will take care to purge 1516 // that value once it has finished. 1517 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); 1518 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1519 // Manually compute the final value for AR, checking for 1520 // overflow. 1521 1522 // Check whether the backedge-taken count can be losslessly casted to 1523 // the addrec's type. The count is always unsigned. 1524 const SCEV *CastedMaxBECount = 1525 getTruncateOrZeroExtend(MaxBECount, Start->getType()); 1526 const SCEV *RecastedMaxBECount = 1527 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); 1528 if (MaxBECount == RecastedMaxBECount) { 1529 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1530 // Check whether Start+Step*MaxBECount has no unsigned overflow. 1531 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step); 1532 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul), WideTy); 1533 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy); 1534 const SCEV *WideMaxBECount = 1535 getZeroExtendExpr(CastedMaxBECount, WideTy); 1536 const SCEV *OperandExtendedAdd = 1537 getAddExpr(WideStart, 1538 getMulExpr(WideMaxBECount, 1539 getZeroExtendExpr(Step, WideTy))); 1540 if (ZAdd == OperandExtendedAdd) { 1541 // Cache knowledge of AR NUW, which is propagated to this AddRec. 1542 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1543 // Return the expression with the addrec on the outside. 1544 return getAddRecExpr( 1545 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), 1546 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1547 } 1548 // Similar to above, only this time treat the step value as signed. 1549 // This covers loops that count down. 1550 OperandExtendedAdd = 1551 getAddExpr(WideStart, 1552 getMulExpr(WideMaxBECount, 1553 getSignExtendExpr(Step, WideTy))); 1554 if (ZAdd == OperandExtendedAdd) { 1555 // Cache knowledge of AR NW, which is propagated to this AddRec. 1556 // Negative step causes unsigned wrap, but it still can't self-wrap. 1557 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1558 // Return the expression with the addrec on the outside. 1559 return getAddRecExpr( 1560 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), 1561 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1562 } 1563 } 1564 } 1565 1566 // Normally, in the cases we can prove no-overflow via a 1567 // backedge guarding condition, we can also compute a backedge 1568 // taken count for the loop. The exceptions are assumptions and 1569 // guards present in the loop -- SCEV is not great at exploiting 1570 // these to compute max backedge taken counts, but can still use 1571 // these to prove lack of overflow. Use this fact to avoid 1572 // doing extra work that may not pay off. 1573 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1574 !AC.assumptions().empty()) { 1575 // If the backedge is guarded by a comparison with the pre-inc 1576 // value the addrec is safe. Also, if the entry is guarded by 1577 // a comparison with the start value and the backedge is 1578 // guarded by a comparison with the post-inc value, the addrec 1579 // is safe. 1580 if (isKnownPositive(Step)) { 1581 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 1582 getUnsignedRange(Step).getUnsignedMax()); 1583 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 1584 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) && 1585 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, 1586 AR->getPostIncExpr(*this), N))) { 1587 // Cache knowledge of AR NUW, which is propagated to this 1588 // AddRec. 1589 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1590 // Return the expression with the addrec on the outside. 1591 return getAddRecExpr( 1592 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), 1593 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1594 } 1595 } else if (isKnownNegative(Step)) { 1596 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - 1597 getSignedRange(Step).getSignedMin()); 1598 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || 1599 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) && 1600 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, 1601 AR->getPostIncExpr(*this), N))) { 1602 // Cache knowledge of AR NW, which is propagated to this 1603 // AddRec. Negative step causes unsigned wrap, but it 1604 // still can't self-wrap. 1605 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1606 // Return the expression with the addrec on the outside. 1607 return getAddRecExpr( 1608 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), 1609 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1610 } 1611 } 1612 } 1613 1614 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { 1615 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1616 return getAddRecExpr( 1617 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), 1618 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1619 } 1620 } 1621 1622 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1623 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> 1624 if (SA->hasNoUnsignedWrap()) { 1625 // If the addition does not unsign overflow then we can, by definition, 1626 // commute the zero extension with the addition operation. 1627 SmallVector<const SCEV *, 4> Ops; 1628 for (const auto *Op : SA->operands()) 1629 Ops.push_back(getZeroExtendExpr(Op, Ty)); 1630 return getAddExpr(Ops, SCEV::FlagNUW); 1631 } 1632 } 1633 1634 // The cast wasn't folded; create an explicit cast node. 1635 // Recompute the insert position, as it may have been invalidated. 1636 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1637 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1638 Op, Ty); 1639 UniqueSCEVs.InsertNode(S, IP); 1640 return S; 1641 } 1642 1643 const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op, 1644 Type *Ty) { 1645 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1646 "This is not an extending conversion!"); 1647 assert(isSCEVable(Ty) && 1648 "This is not a conversion to a SCEVable type!"); 1649 Ty = getEffectiveSCEVType(Ty); 1650 1651 // Fold if the operand is constant. 1652 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1653 return getConstant( 1654 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); 1655 1656 // sext(sext(x)) --> sext(x) 1657 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1658 return getSignExtendExpr(SS->getOperand(), Ty); 1659 1660 // sext(zext(x)) --> zext(x) 1661 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1662 return getZeroExtendExpr(SZ->getOperand(), Ty); 1663 1664 // Before doing any expensive analysis, check to see if we've already 1665 // computed a SCEV for this Op and Ty. 1666 FoldingSetNodeID ID; 1667 ID.AddInteger(scSignExtend); 1668 ID.AddPointer(Op); 1669 ID.AddPointer(Ty); 1670 void *IP = nullptr; 1671 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1672 1673 // sext(trunc(x)) --> sext(x) or x or trunc(x) 1674 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1675 // It's possible the bits taken off by the truncate were all sign bits. If 1676 // so, we should be able to simplify this further. 1677 const SCEV *X = ST->getOperand(); 1678 ConstantRange CR = getSignedRange(X); 1679 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1680 unsigned NewBits = getTypeSizeInBits(Ty); 1681 if (CR.truncate(TruncBits).signExtend(NewBits).contains( 1682 CR.sextOrTrunc(NewBits))) 1683 return getTruncateOrSignExtend(X, Ty); 1684 } 1685 1686 // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2 1687 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1688 if (SA->getNumOperands() == 2) { 1689 auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0)); 1690 auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1)); 1691 if (SMul && SC1) { 1692 if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) { 1693 const APInt &C1 = SC1->getAPInt(); 1694 const APInt &C2 = SC2->getAPInt(); 1695 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && 1696 C2.ugt(C1) && C2.isPowerOf2()) 1697 return getAddExpr(getSignExtendExpr(SC1, Ty), 1698 getSignExtendExpr(SMul, Ty)); 1699 } 1700 } 1701 } 1702 1703 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 1704 if (SA->hasNoSignedWrap()) { 1705 // If the addition does not sign overflow then we can, by definition, 1706 // commute the sign extension with the addition operation. 1707 SmallVector<const SCEV *, 4> Ops; 1708 for (const auto *Op : SA->operands()) 1709 Ops.push_back(getSignExtendExpr(Op, Ty)); 1710 return getAddExpr(Ops, SCEV::FlagNSW); 1711 } 1712 } 1713 // If the input value is a chrec scev, and we can prove that the value 1714 // did not overflow the old, smaller, value, we can sign extend all of the 1715 // operands (often constants). This allows analysis of something like 1716 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 1717 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1718 if (AR->isAffine()) { 1719 const SCEV *Start = AR->getStart(); 1720 const SCEV *Step = AR->getStepRecurrence(*this); 1721 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1722 const Loop *L = AR->getLoop(); 1723 1724 if (!AR->hasNoSignedWrap()) { 1725 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1726 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1727 } 1728 1729 // If we have special knowledge that this addrec won't overflow, 1730 // we don't need to do any further analysis. 1731 if (AR->hasNoSignedWrap()) 1732 return getAddRecExpr( 1733 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), 1734 getSignExtendExpr(Step, Ty), L, SCEV::FlagNSW); 1735 1736 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1737 // Note that this serves two purposes: It filters out loops that are 1738 // simply not analyzable, and it covers the case where this code is 1739 // being called from within backedge-taken count analysis, such that 1740 // attempting to ask for the backedge-taken count would likely result 1741 // in infinite recursion. In the later case, the analysis code will 1742 // cope with a conservative value, and it will take care to purge 1743 // that value once it has finished. 1744 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); 1745 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1746 // Manually compute the final value for AR, checking for 1747 // overflow. 1748 1749 // Check whether the backedge-taken count can be losslessly casted to 1750 // the addrec's type. The count is always unsigned. 1751 const SCEV *CastedMaxBECount = 1752 getTruncateOrZeroExtend(MaxBECount, Start->getType()); 1753 const SCEV *RecastedMaxBECount = 1754 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); 1755 if (MaxBECount == RecastedMaxBECount) { 1756 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1757 // Check whether Start+Step*MaxBECount has no signed overflow. 1758 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step); 1759 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul), WideTy); 1760 const SCEV *WideStart = getSignExtendExpr(Start, WideTy); 1761 const SCEV *WideMaxBECount = 1762 getZeroExtendExpr(CastedMaxBECount, WideTy); 1763 const SCEV *OperandExtendedAdd = 1764 getAddExpr(WideStart, 1765 getMulExpr(WideMaxBECount, 1766 getSignExtendExpr(Step, WideTy))); 1767 if (SAdd == OperandExtendedAdd) { 1768 // Cache knowledge of AR NSW, which is propagated to this AddRec. 1769 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1770 // Return the expression with the addrec on the outside. 1771 return getAddRecExpr( 1772 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), 1773 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1774 } 1775 // Similar to above, only this time treat the step value as unsigned. 1776 // This covers loops that count up with an unsigned step. 1777 OperandExtendedAdd = 1778 getAddExpr(WideStart, 1779 getMulExpr(WideMaxBECount, 1780 getZeroExtendExpr(Step, WideTy))); 1781 if (SAdd == OperandExtendedAdd) { 1782 // If AR wraps around then 1783 // 1784 // abs(Step) * MaxBECount > unsigned-max(AR->getType()) 1785 // => SAdd != OperandExtendedAdd 1786 // 1787 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> 1788 // (SAdd == OperandExtendedAdd => AR is NW) 1789 1790 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1791 1792 // Return the expression with the addrec on the outside. 1793 return getAddRecExpr( 1794 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), 1795 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1796 } 1797 } 1798 } 1799 1800 // Normally, in the cases we can prove no-overflow via a 1801 // backedge guarding condition, we can also compute a backedge 1802 // taken count for the loop. The exceptions are assumptions and 1803 // guards present in the loop -- SCEV is not great at exploiting 1804 // these to compute max backedge taken counts, but can still use 1805 // these to prove lack of overflow. Use this fact to avoid 1806 // doing extra work that may not pay off. 1807 1808 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1809 !AC.assumptions().empty()) { 1810 // If the backedge is guarded by a comparison with the pre-inc 1811 // value the addrec is safe. Also, if the entry is guarded by 1812 // a comparison with the start value and the backedge is 1813 // guarded by a comparison with the post-inc value, the addrec 1814 // is safe. 1815 ICmpInst::Predicate Pred; 1816 const SCEV *OverflowLimit = 1817 getSignedOverflowLimitForStep(Step, &Pred, this); 1818 if (OverflowLimit && 1819 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 1820 (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) && 1821 isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this), 1822 OverflowLimit)))) { 1823 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec. 1824 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1825 return getAddRecExpr( 1826 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), 1827 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1828 } 1829 } 1830 1831 // If Start and Step are constants, check if we can apply this 1832 // transformation: 1833 // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2 1834 auto *SC1 = dyn_cast<SCEVConstant>(Start); 1835 auto *SC2 = dyn_cast<SCEVConstant>(Step); 1836 if (SC1 && SC2) { 1837 const APInt &C1 = SC1->getAPInt(); 1838 const APInt &C2 = SC2->getAPInt(); 1839 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) && 1840 C2.isPowerOf2()) { 1841 Start = getSignExtendExpr(Start, Ty); 1842 const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L, 1843 AR->getNoWrapFlags()); 1844 return getAddExpr(Start, getSignExtendExpr(NewAR, Ty)); 1845 } 1846 } 1847 1848 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { 1849 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1850 return getAddRecExpr( 1851 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), 1852 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1853 } 1854 } 1855 1856 // If the input value is provably positive and we could not simplify 1857 // away the sext build a zext instead. 1858 if (isKnownNonNegative(Op)) 1859 return getZeroExtendExpr(Op, Ty); 1860 1861 // The cast wasn't folded; create an explicit cast node. 1862 // Recompute the insert position, as it may have been invalidated. 1863 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1864 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1865 Op, Ty); 1866 UniqueSCEVs.InsertNode(S, IP); 1867 return S; 1868 } 1869 1870 /// getAnyExtendExpr - Return a SCEV for the given operand extended with 1871 /// unspecified bits out to the given type. 1872 /// 1873 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, 1874 Type *Ty) { 1875 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1876 "This is not an extending conversion!"); 1877 assert(isSCEVable(Ty) && 1878 "This is not a conversion to a SCEVable type!"); 1879 Ty = getEffectiveSCEVType(Ty); 1880 1881 // Sign-extend negative constants. 1882 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1883 if (SC->getAPInt().isNegative()) 1884 return getSignExtendExpr(Op, Ty); 1885 1886 // Peel off a truncate cast. 1887 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { 1888 const SCEV *NewOp = T->getOperand(); 1889 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) 1890 return getAnyExtendExpr(NewOp, Ty); 1891 return getTruncateOrNoop(NewOp, Ty); 1892 } 1893 1894 // Next try a zext cast. If the cast is folded, use it. 1895 const SCEV *ZExt = getZeroExtendExpr(Op, Ty); 1896 if (!isa<SCEVZeroExtendExpr>(ZExt)) 1897 return ZExt; 1898 1899 // Next try a sext cast. If the cast is folded, use it. 1900 const SCEV *SExt = getSignExtendExpr(Op, Ty); 1901 if (!isa<SCEVSignExtendExpr>(SExt)) 1902 return SExt; 1903 1904 // Force the cast to be folded into the operands of an addrec. 1905 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { 1906 SmallVector<const SCEV *, 4> Ops; 1907 for (const SCEV *Op : AR->operands()) 1908 Ops.push_back(getAnyExtendExpr(Op, Ty)); 1909 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); 1910 } 1911 1912 // If the expression is obviously signed, use the sext cast value. 1913 if (isa<SCEVSMaxExpr>(Op)) 1914 return SExt; 1915 1916 // Absent any other information, use the zext cast value. 1917 return ZExt; 1918 } 1919 1920 /// Process the given Ops list, which is a list of operands to be added under 1921 /// the given scale, update the given map. This is a helper function for 1922 /// getAddRecExpr. As an example of what it does, given a sequence of operands 1923 /// that would form an add expression like this: 1924 /// 1925 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r) 1926 /// 1927 /// where A and B are constants, update the map with these values: 1928 /// 1929 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) 1930 /// 1931 /// and add 13 + A*B*29 to AccumulatedConstant. 1932 /// This will allow getAddRecExpr to produce this: 1933 /// 1934 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) 1935 /// 1936 /// This form often exposes folding opportunities that are hidden in 1937 /// the original operand list. 1938 /// 1939 /// Return true iff it appears that any interesting folding opportunities 1940 /// may be exposed. This helps getAddRecExpr short-circuit extra work in 1941 /// the common case where no interesting opportunities are present, and 1942 /// is also used as a check to avoid infinite recursion. 1943 /// 1944 static bool 1945 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, 1946 SmallVectorImpl<const SCEV *> &NewOps, 1947 APInt &AccumulatedConstant, 1948 const SCEV *const *Ops, size_t NumOperands, 1949 const APInt &Scale, 1950 ScalarEvolution &SE) { 1951 bool Interesting = false; 1952 1953 // Iterate over the add operands. They are sorted, with constants first. 1954 unsigned i = 0; 1955 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 1956 ++i; 1957 // Pull a buried constant out to the outside. 1958 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) 1959 Interesting = true; 1960 AccumulatedConstant += Scale * C->getAPInt(); 1961 } 1962 1963 // Next comes everything else. We're especially interested in multiplies 1964 // here, but they're in the middle, so just visit the rest with one loop. 1965 for (; i != NumOperands; ++i) { 1966 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); 1967 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { 1968 APInt NewScale = 1969 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); 1970 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { 1971 // A multiplication of a constant with another add; recurse. 1972 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); 1973 Interesting |= 1974 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 1975 Add->op_begin(), Add->getNumOperands(), 1976 NewScale, SE); 1977 } else { 1978 // A multiplication of a constant with some other value. Update 1979 // the map. 1980 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end()); 1981 const SCEV *Key = SE.getMulExpr(MulOps); 1982 auto Pair = M.insert({Key, NewScale}); 1983 if (Pair.second) { 1984 NewOps.push_back(Pair.first->first); 1985 } else { 1986 Pair.first->second += NewScale; 1987 // The map already had an entry for this value, which may indicate 1988 // a folding opportunity. 1989 Interesting = true; 1990 } 1991 } 1992 } else { 1993 // An ordinary operand. Update the map. 1994 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = 1995 M.insert({Ops[i], Scale}); 1996 if (Pair.second) { 1997 NewOps.push_back(Pair.first->first); 1998 } else { 1999 Pair.first->second += Scale; 2000 // The map already had an entry for this value, which may indicate 2001 // a folding opportunity. 2002 Interesting = true; 2003 } 2004 } 2005 } 2006 2007 return Interesting; 2008 } 2009 2010 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and 2011 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of 2012 // can't-overflow flags for the operation if possible. 2013 static SCEV::NoWrapFlags 2014 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, 2015 const SmallVectorImpl<const SCEV *> &Ops, 2016 SCEV::NoWrapFlags Flags) { 2017 using namespace std::placeholders; 2018 typedef OverflowingBinaryOperator OBO; 2019 2020 bool CanAnalyze = 2021 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; 2022 (void)CanAnalyze; 2023 assert(CanAnalyze && "don't call from other places!"); 2024 2025 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 2026 SCEV::NoWrapFlags SignOrUnsignWrap = 2027 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2028 2029 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 2030 auto IsKnownNonNegative = [&](const SCEV *S) { 2031 return SE->isKnownNonNegative(S); 2032 }; 2033 2034 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) 2035 Flags = 2036 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); 2037 2038 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2039 2040 if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr && 2041 Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) { 2042 2043 // (A + C) --> (A + C)<nsw> if the addition does not sign overflow 2044 // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow 2045 2046 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); 2047 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { 2048 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2049 Instruction::Add, C, OBO::NoSignedWrap); 2050 if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) 2051 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2052 } 2053 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { 2054 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2055 Instruction::Add, C, OBO::NoUnsignedWrap); 2056 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) 2057 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2058 } 2059 } 2060 2061 return Flags; 2062 } 2063 2064 /// Get a canonical add expression, or something simpler if possible. 2065 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2066 SCEV::NoWrapFlags Flags) { 2067 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && 2068 "only nuw or nsw allowed"); 2069 assert(!Ops.empty() && "Cannot get empty add!"); 2070 if (Ops.size() == 1) return Ops[0]; 2071 #ifndef NDEBUG 2072 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2073 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2074 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2075 "SCEVAddExpr operand types don't match!"); 2076 #endif 2077 2078 // Sort by complexity, this groups all similar expression types together. 2079 GroupByComplexity(Ops, &LI); 2080 2081 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags); 2082 2083 // If there are any constants, fold them together. 2084 unsigned Idx = 0; 2085 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2086 ++Idx; 2087 assert(Idx < Ops.size()); 2088 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2089 // We found two constants, fold them together! 2090 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); 2091 if (Ops.size() == 2) return Ops[0]; 2092 Ops.erase(Ops.begin()+1); // Erase the folded element 2093 LHSC = cast<SCEVConstant>(Ops[0]); 2094 } 2095 2096 // If we are left with a constant zero being added, strip it off. 2097 if (LHSC->getValue()->isZero()) { 2098 Ops.erase(Ops.begin()); 2099 --Idx; 2100 } 2101 2102 if (Ops.size() == 1) return Ops[0]; 2103 } 2104 2105 // Okay, check to see if the same value occurs in the operand list more than 2106 // once. If so, merge them together into an multiply expression. Since we 2107 // sorted the list, these values are required to be adjacent. 2108 Type *Ty = Ops[0]->getType(); 2109 bool FoundMatch = false; 2110 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 2111 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 2112 // Scan ahead to count how many equal operands there are. 2113 unsigned Count = 2; 2114 while (i+Count != e && Ops[i+Count] == Ops[i]) 2115 ++Count; 2116 // Merge the values into a multiply. 2117 const SCEV *Scale = getConstant(Ty, Count); 2118 const SCEV *Mul = getMulExpr(Scale, Ops[i]); 2119 if (Ops.size() == Count) 2120 return Mul; 2121 Ops[i] = Mul; 2122 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 2123 --i; e -= Count - 1; 2124 FoundMatch = true; 2125 } 2126 if (FoundMatch) 2127 return getAddExpr(Ops, Flags); 2128 2129 // Check for truncates. If all the operands are truncated from the same 2130 // type, see if factoring out the truncate would permit the result to be 2131 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n) 2132 // if the contents of the resulting outer trunc fold to something simple. 2133 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) { 2134 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]); 2135 Type *DstType = Trunc->getType(); 2136 Type *SrcType = Trunc->getOperand()->getType(); 2137 SmallVector<const SCEV *, 8> LargeOps; 2138 bool Ok = true; 2139 // Check all the operands to see if they can be represented in the 2140 // source type of the truncate. 2141 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 2142 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 2143 if (T->getOperand()->getType() != SrcType) { 2144 Ok = false; 2145 break; 2146 } 2147 LargeOps.push_back(T->getOperand()); 2148 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2149 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 2150 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 2151 SmallVector<const SCEV *, 8> LargeMulOps; 2152 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 2153 if (const SCEVTruncateExpr *T = 2154 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 2155 if (T->getOperand()->getType() != SrcType) { 2156 Ok = false; 2157 break; 2158 } 2159 LargeMulOps.push_back(T->getOperand()); 2160 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { 2161 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 2162 } else { 2163 Ok = false; 2164 break; 2165 } 2166 } 2167 if (Ok) 2168 LargeOps.push_back(getMulExpr(LargeMulOps)); 2169 } else { 2170 Ok = false; 2171 break; 2172 } 2173 } 2174 if (Ok) { 2175 // Evaluate the expression in the larger type. 2176 const SCEV *Fold = getAddExpr(LargeOps, Flags); 2177 // If it folds to something simple, use it. Otherwise, don't. 2178 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 2179 return getTruncateExpr(Fold, DstType); 2180 } 2181 } 2182 2183 // Skip past any other cast SCEVs. 2184 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 2185 ++Idx; 2186 2187 // If there are add operands they would be next. 2188 if (Idx < Ops.size()) { 2189 bool DeletedAdd = false; 2190 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2191 // If we have an add, expand the add operands onto the end of the operands 2192 // list. 2193 Ops.erase(Ops.begin()+Idx); 2194 Ops.append(Add->op_begin(), Add->op_end()); 2195 DeletedAdd = true; 2196 } 2197 2198 // If we deleted at least one add, we added operands to the end of the list, 2199 // and they are not necessarily sorted. Recurse to resort and resimplify 2200 // any operands we just acquired. 2201 if (DeletedAdd) 2202 return getAddExpr(Ops); 2203 } 2204 2205 // Skip over the add expression until we get to a multiply. 2206 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2207 ++Idx; 2208 2209 // Check to see if there are any folding opportunities present with 2210 // operands multiplied by constant values. 2211 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2212 uint64_t BitWidth = getTypeSizeInBits(Ty); 2213 DenseMap<const SCEV *, APInt> M; 2214 SmallVector<const SCEV *, 8> NewOps; 2215 APInt AccumulatedConstant(BitWidth, 0); 2216 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2217 Ops.data(), Ops.size(), 2218 APInt(BitWidth, 1), *this)) { 2219 struct APIntCompare { 2220 bool operator()(const APInt &LHS, const APInt &RHS) const { 2221 return LHS.ult(RHS); 2222 } 2223 }; 2224 2225 // Some interesting folding opportunity is present, so its worthwhile to 2226 // re-generate the operands list. Group the operands by constant scale, 2227 // to avoid multiplying by the same constant scale multiple times. 2228 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2229 for (const SCEV *NewOp : NewOps) 2230 MulOpLists[M.find(NewOp)->second].push_back(NewOp); 2231 // Re-generate the operands list. 2232 Ops.clear(); 2233 if (AccumulatedConstant != 0) 2234 Ops.push_back(getConstant(AccumulatedConstant)); 2235 for (auto &MulOp : MulOpLists) 2236 if (MulOp.first != 0) 2237 Ops.push_back(getMulExpr(getConstant(MulOp.first), 2238 getAddExpr(MulOp.second))); 2239 if (Ops.empty()) 2240 return getZero(Ty); 2241 if (Ops.size() == 1) 2242 return Ops[0]; 2243 return getAddExpr(Ops); 2244 } 2245 } 2246 2247 // If we are adding something to a multiply expression, make sure the 2248 // something is not already an operand of the multiply. If so, merge it into 2249 // the multiply. 2250 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2251 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2252 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2253 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2254 if (isa<SCEVConstant>(MulOpSCEV)) 2255 continue; 2256 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2257 if (MulOpSCEV == Ops[AddOp]) { 2258 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2259 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2260 if (Mul->getNumOperands() != 2) { 2261 // If the multiply has more than two operands, we must get the 2262 // Y*Z term. 2263 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2264 Mul->op_begin()+MulOp); 2265 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2266 InnerMul = getMulExpr(MulOps); 2267 } 2268 const SCEV *One = getOne(Ty); 2269 const SCEV *AddOne = getAddExpr(One, InnerMul); 2270 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV); 2271 if (Ops.size() == 2) return OuterMul; 2272 if (AddOp < Idx) { 2273 Ops.erase(Ops.begin()+AddOp); 2274 Ops.erase(Ops.begin()+Idx-1); 2275 } else { 2276 Ops.erase(Ops.begin()+Idx); 2277 Ops.erase(Ops.begin()+AddOp-1); 2278 } 2279 Ops.push_back(OuterMul); 2280 return getAddExpr(Ops); 2281 } 2282 2283 // Check this multiply against other multiplies being added together. 2284 for (unsigned OtherMulIdx = Idx+1; 2285 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2286 ++OtherMulIdx) { 2287 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2288 // If MulOp occurs in OtherMul, we can fold the two multiplies 2289 // together. 2290 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2291 OMulOp != e; ++OMulOp) 2292 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2293 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2294 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2295 if (Mul->getNumOperands() != 2) { 2296 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2297 Mul->op_begin()+MulOp); 2298 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2299 InnerMul1 = getMulExpr(MulOps); 2300 } 2301 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2302 if (OtherMul->getNumOperands() != 2) { 2303 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2304 OtherMul->op_begin()+OMulOp); 2305 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2306 InnerMul2 = getMulExpr(MulOps); 2307 } 2308 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2); 2309 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum); 2310 if (Ops.size() == 2) return OuterMul; 2311 Ops.erase(Ops.begin()+Idx); 2312 Ops.erase(Ops.begin()+OtherMulIdx-1); 2313 Ops.push_back(OuterMul); 2314 return getAddExpr(Ops); 2315 } 2316 } 2317 } 2318 } 2319 2320 // If there are any add recurrences in the operands list, see if any other 2321 // added values are loop invariant. If so, we can fold them into the 2322 // recurrence. 2323 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2324 ++Idx; 2325 2326 // Scan over all recurrences, trying to fold loop invariants into them. 2327 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2328 // Scan all of the other operands to this add and add them to the vector if 2329 // they are loop invariant w.r.t. the recurrence. 2330 SmallVector<const SCEV *, 8> LIOps; 2331 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2332 const Loop *AddRecLoop = AddRec->getLoop(); 2333 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2334 if (isLoopInvariant(Ops[i], AddRecLoop)) { 2335 LIOps.push_back(Ops[i]); 2336 Ops.erase(Ops.begin()+i); 2337 --i; --e; 2338 } 2339 2340 // If we found some loop invariants, fold them into the recurrence. 2341 if (!LIOps.empty()) { 2342 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2343 LIOps.push_back(AddRec->getStart()); 2344 2345 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2346 AddRec->op_end()); 2347 // This follows from the fact that the no-wrap flags on the outer add 2348 // expression are applicable on the 0th iteration, when the add recurrence 2349 // will be equal to its start value. 2350 AddRecOps[0] = getAddExpr(LIOps, Flags); 2351 2352 // Build the new addrec. Propagate the NUW and NSW flags if both the 2353 // outer add and the inner addrec are guaranteed to have no overflow. 2354 // Always propagate NW. 2355 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2356 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2357 2358 // If all of the other operands were loop invariant, we are done. 2359 if (Ops.size() == 1) return NewRec; 2360 2361 // Otherwise, add the folded AddRec by the non-invariant parts. 2362 for (unsigned i = 0;; ++i) 2363 if (Ops[i] == AddRec) { 2364 Ops[i] = NewRec; 2365 break; 2366 } 2367 return getAddExpr(Ops); 2368 } 2369 2370 // Okay, if there weren't any loop invariants to be folded, check to see if 2371 // there are multiple AddRec's with the same loop induction variable being 2372 // added together. If so, we can fold them. 2373 for (unsigned OtherIdx = Idx+1; 2374 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2375 ++OtherIdx) 2376 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2377 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2378 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2379 AddRec->op_end()); 2380 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2381 ++OtherIdx) 2382 if (const auto *OtherAddRec = dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx])) 2383 if (OtherAddRec->getLoop() == AddRecLoop) { 2384 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2385 i != e; ++i) { 2386 if (i >= AddRecOps.size()) { 2387 AddRecOps.append(OtherAddRec->op_begin()+i, 2388 OtherAddRec->op_end()); 2389 break; 2390 } 2391 AddRecOps[i] = getAddExpr(AddRecOps[i], 2392 OtherAddRec->getOperand(i)); 2393 } 2394 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2395 } 2396 // Step size has changed, so we cannot guarantee no self-wraparound. 2397 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2398 return getAddExpr(Ops); 2399 } 2400 2401 // Otherwise couldn't fold anything into this recurrence. Move onto the 2402 // next one. 2403 } 2404 2405 // Okay, it looks like we really DO need an add expr. Check to see if we 2406 // already have one, otherwise create a new one. 2407 FoldingSetNodeID ID; 2408 ID.AddInteger(scAddExpr); 2409 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2410 ID.AddPointer(Ops[i]); 2411 void *IP = nullptr; 2412 SCEVAddExpr *S = 2413 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2414 if (!S) { 2415 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2416 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2417 S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator), 2418 O, Ops.size()); 2419 UniqueSCEVs.InsertNode(S, IP); 2420 } 2421 S->setNoWrapFlags(Flags); 2422 return S; 2423 } 2424 2425 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2426 uint64_t k = i*j; 2427 if (j > 1 && k / j != i) Overflow = true; 2428 return k; 2429 } 2430 2431 /// Compute the result of "n choose k", the binomial coefficient. If an 2432 /// intermediate computation overflows, Overflow will be set and the return will 2433 /// be garbage. Overflow is not cleared on absence of overflow. 2434 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 2435 // We use the multiplicative formula: 2436 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 2437 // At each iteration, we take the n-th term of the numeral and divide by the 2438 // (k-n)th term of the denominator. This division will always produce an 2439 // integral result, and helps reduce the chance of overflow in the 2440 // intermediate computations. However, we can still overflow even when the 2441 // final result would fit. 2442 2443 if (n == 0 || n == k) return 1; 2444 if (k > n) return 0; 2445 2446 if (k > n/2) 2447 k = n-k; 2448 2449 uint64_t r = 1; 2450 for (uint64_t i = 1; i <= k; ++i) { 2451 r = umul_ov(r, n-(i-1), Overflow); 2452 r /= i; 2453 } 2454 return r; 2455 } 2456 2457 /// Determine if any of the operands in this SCEV are a constant or if 2458 /// any of the add or multiply expressions in this SCEV contain a constant. 2459 static bool containsConstantSomewhere(const SCEV *StartExpr) { 2460 SmallVector<const SCEV *, 4> Ops; 2461 Ops.push_back(StartExpr); 2462 while (!Ops.empty()) { 2463 const SCEV *CurrentExpr = Ops.pop_back_val(); 2464 if (isa<SCEVConstant>(*CurrentExpr)) 2465 return true; 2466 2467 if (isa<SCEVAddExpr>(*CurrentExpr) || isa<SCEVMulExpr>(*CurrentExpr)) { 2468 const auto *CurrentNAry = cast<SCEVNAryExpr>(CurrentExpr); 2469 Ops.append(CurrentNAry->op_begin(), CurrentNAry->op_end()); 2470 } 2471 } 2472 return false; 2473 } 2474 2475 /// Get a canonical multiply expression, or something simpler if possible. 2476 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2477 SCEV::NoWrapFlags Flags) { 2478 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && 2479 "only nuw or nsw allowed"); 2480 assert(!Ops.empty() && "Cannot get empty mul!"); 2481 if (Ops.size() == 1) return Ops[0]; 2482 #ifndef NDEBUG 2483 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2484 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2485 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2486 "SCEVMulExpr operand types don't match!"); 2487 #endif 2488 2489 // Sort by complexity, this groups all similar expression types together. 2490 GroupByComplexity(Ops, &LI); 2491 2492 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags); 2493 2494 // If there are any constants, fold them together. 2495 unsigned Idx = 0; 2496 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2497 2498 // C1*(C2+V) -> C1*C2 + C1*V 2499 if (Ops.size() == 2) 2500 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 2501 // If any of Add's ops are Adds or Muls with a constant, 2502 // apply this transformation as well. 2503 if (Add->getNumOperands() == 2) 2504 if (containsConstantSomewhere(Add)) 2505 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)), 2506 getMulExpr(LHSC, Add->getOperand(1))); 2507 2508 ++Idx; 2509 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2510 // We found two constants, fold them together! 2511 ConstantInt *Fold = 2512 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt()); 2513 Ops[0] = getConstant(Fold); 2514 Ops.erase(Ops.begin()+1); // Erase the folded element 2515 if (Ops.size() == 1) return Ops[0]; 2516 LHSC = cast<SCEVConstant>(Ops[0]); 2517 } 2518 2519 // If we are left with a constant one being multiplied, strip it off. 2520 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) { 2521 Ops.erase(Ops.begin()); 2522 --Idx; 2523 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) { 2524 // If we have a multiply of zero, it will always be zero. 2525 return Ops[0]; 2526 } else if (Ops[0]->isAllOnesValue()) { 2527 // If we have a mul by -1 of an add, try distributing the -1 among the 2528 // add operands. 2529 if (Ops.size() == 2) { 2530 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 2531 SmallVector<const SCEV *, 4> NewOps; 2532 bool AnyFolded = false; 2533 for (const SCEV *AddOp : Add->operands()) { 2534 const SCEV *Mul = getMulExpr(Ops[0], AddOp); 2535 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 2536 NewOps.push_back(Mul); 2537 } 2538 if (AnyFolded) 2539 return getAddExpr(NewOps); 2540 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 2541 // Negation preserves a recurrence's no self-wrap property. 2542 SmallVector<const SCEV *, 4> Operands; 2543 for (const SCEV *AddRecOp : AddRec->operands()) 2544 Operands.push_back(getMulExpr(Ops[0], AddRecOp)); 2545 2546 return getAddRecExpr(Operands, AddRec->getLoop(), 2547 AddRec->getNoWrapFlags(SCEV::FlagNW)); 2548 } 2549 } 2550 } 2551 2552 if (Ops.size() == 1) 2553 return Ops[0]; 2554 } 2555 2556 // Skip over the add expression until we get to a multiply. 2557 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2558 ++Idx; 2559 2560 // If there are mul operands inline them all into this expression. 2561 if (Idx < Ops.size()) { 2562 bool DeletedMul = false; 2563 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2564 if (Ops.size() > MulOpsInlineThreshold) 2565 break; 2566 // If we have an mul, expand the mul operands onto the end of the operands 2567 // list. 2568 Ops.erase(Ops.begin()+Idx); 2569 Ops.append(Mul->op_begin(), Mul->op_end()); 2570 DeletedMul = true; 2571 } 2572 2573 // If we deleted at least one mul, we added operands to the end of the list, 2574 // and they are not necessarily sorted. Recurse to resort and resimplify 2575 // any operands we just acquired. 2576 if (DeletedMul) 2577 return getMulExpr(Ops); 2578 } 2579 2580 // If there are any add recurrences in the operands list, see if any other 2581 // added values are loop invariant. If so, we can fold them into the 2582 // recurrence. 2583 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2584 ++Idx; 2585 2586 // Scan over all recurrences, trying to fold loop invariants into them. 2587 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2588 // Scan all of the other operands to this mul and add them to the vector if 2589 // they are loop invariant w.r.t. the recurrence. 2590 SmallVector<const SCEV *, 8> LIOps; 2591 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2592 const Loop *AddRecLoop = AddRec->getLoop(); 2593 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2594 if (isLoopInvariant(Ops[i], AddRecLoop)) { 2595 LIOps.push_back(Ops[i]); 2596 Ops.erase(Ops.begin()+i); 2597 --i; --e; 2598 } 2599 2600 // If we found some loop invariants, fold them into the recurrence. 2601 if (!LIOps.empty()) { 2602 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 2603 SmallVector<const SCEV *, 4> NewOps; 2604 NewOps.reserve(AddRec->getNumOperands()); 2605 const SCEV *Scale = getMulExpr(LIOps); 2606 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 2607 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i))); 2608 2609 // Build the new addrec. Propagate the NUW and NSW flags if both the 2610 // outer mul and the inner addrec are guaranteed to have no overflow. 2611 // 2612 // No self-wrap cannot be guaranteed after changing the step size, but 2613 // will be inferred if either NUW or NSW is true. 2614 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW)); 2615 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags); 2616 2617 // If all of the other operands were loop invariant, we are done. 2618 if (Ops.size() == 1) return NewRec; 2619 2620 // Otherwise, multiply the folded AddRec by the non-invariant parts. 2621 for (unsigned i = 0;; ++i) 2622 if (Ops[i] == AddRec) { 2623 Ops[i] = NewRec; 2624 break; 2625 } 2626 return getMulExpr(Ops); 2627 } 2628 2629 // Okay, if there weren't any loop invariants to be folded, check to see if 2630 // there are multiple AddRec's with the same loop induction variable being 2631 // multiplied together. If so, we can fold them. 2632 2633 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 2634 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 2635 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 2636 // ]]],+,...up to x=2n}. 2637 // Note that the arguments to choose() are always integers with values 2638 // known at compile time, never SCEV objects. 2639 // 2640 // The implementation avoids pointless extra computations when the two 2641 // addrec's are of different length (mathematically, it's equivalent to 2642 // an infinite stream of zeros on the right). 2643 bool OpsModified = false; 2644 for (unsigned OtherIdx = Idx+1; 2645 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2646 ++OtherIdx) { 2647 const SCEVAddRecExpr *OtherAddRec = 2648 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2649 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 2650 continue; 2651 2652 bool Overflow = false; 2653 Type *Ty = AddRec->getType(); 2654 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 2655 SmallVector<const SCEV*, 7> AddRecOps; 2656 for (int x = 0, xe = AddRec->getNumOperands() + 2657 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 2658 const SCEV *Term = getZero(Ty); 2659 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 2660 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 2661 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 2662 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 2663 z < ze && !Overflow; ++z) { 2664 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 2665 uint64_t Coeff; 2666 if (LargerThan64Bits) 2667 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 2668 else 2669 Coeff = Coeff1*Coeff2; 2670 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 2671 const SCEV *Term1 = AddRec->getOperand(y-z); 2672 const SCEV *Term2 = OtherAddRec->getOperand(z); 2673 Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1,Term2)); 2674 } 2675 } 2676 AddRecOps.push_back(Term); 2677 } 2678 if (!Overflow) { 2679 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(), 2680 SCEV::FlagAnyWrap); 2681 if (Ops.size() == 2) return NewAddRec; 2682 Ops[Idx] = NewAddRec; 2683 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2684 OpsModified = true; 2685 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 2686 if (!AddRec) 2687 break; 2688 } 2689 } 2690 if (OpsModified) 2691 return getMulExpr(Ops); 2692 2693 // Otherwise couldn't fold anything into this recurrence. Move onto the 2694 // next one. 2695 } 2696 2697 // Okay, it looks like we really DO need an mul expr. Check to see if we 2698 // already have one, otherwise create a new one. 2699 FoldingSetNodeID ID; 2700 ID.AddInteger(scMulExpr); 2701 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2702 ID.AddPointer(Ops[i]); 2703 void *IP = nullptr; 2704 SCEVMulExpr *S = 2705 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2706 if (!S) { 2707 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2708 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2709 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2710 O, Ops.size()); 2711 UniqueSCEVs.InsertNode(S, IP); 2712 } 2713 S->setNoWrapFlags(Flags); 2714 return S; 2715 } 2716 2717 /// Get a canonical unsigned division expression, or something simpler if 2718 /// possible. 2719 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 2720 const SCEV *RHS) { 2721 assert(getEffectiveSCEVType(LHS->getType()) == 2722 getEffectiveSCEVType(RHS->getType()) && 2723 "SCEVUDivExpr operand types don't match!"); 2724 2725 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 2726 if (RHSC->getValue()->equalsInt(1)) 2727 return LHS; // X udiv 1 --> x 2728 // If the denominator is zero, the result of the udiv is undefined. Don't 2729 // try to analyze it, because the resolution chosen here may differ from 2730 // the resolution chosen in other parts of the compiler. 2731 if (!RHSC->getValue()->isZero()) { 2732 // Determine if the division can be folded into the operands of 2733 // its operands. 2734 // TODO: Generalize this to non-constants by using known-bits information. 2735 Type *Ty = LHS->getType(); 2736 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 2737 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 2738 // For non-power-of-two values, effectively round the value up to the 2739 // nearest power of two. 2740 if (!RHSC->getAPInt().isPowerOf2()) 2741 ++MaxShiftAmt; 2742 IntegerType *ExtTy = 2743 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 2744 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 2745 if (const SCEVConstant *Step = 2746 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 2747 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 2748 const APInt &StepInt = Step->getAPInt(); 2749 const APInt &DivInt = RHSC->getAPInt(); 2750 if (!StepInt.urem(DivInt) && 2751 getZeroExtendExpr(AR, ExtTy) == 2752 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 2753 getZeroExtendExpr(Step, ExtTy), 2754 AR->getLoop(), SCEV::FlagAnyWrap)) { 2755 SmallVector<const SCEV *, 4> Operands; 2756 for (const SCEV *Op : AR->operands()) 2757 Operands.push_back(getUDivExpr(Op, RHS)); 2758 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 2759 } 2760 /// Get a canonical UDivExpr for a recurrence. 2761 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 2762 // We can currently only fold X%N if X is constant. 2763 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 2764 if (StartC && !DivInt.urem(StepInt) && 2765 getZeroExtendExpr(AR, ExtTy) == 2766 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 2767 getZeroExtendExpr(Step, ExtTy), 2768 AR->getLoop(), SCEV::FlagAnyWrap)) { 2769 const APInt &StartInt = StartC->getAPInt(); 2770 const APInt &StartRem = StartInt.urem(StepInt); 2771 if (StartRem != 0) 2772 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step, 2773 AR->getLoop(), SCEV::FlagNW); 2774 } 2775 } 2776 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 2777 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 2778 SmallVector<const SCEV *, 4> Operands; 2779 for (const SCEV *Op : M->operands()) 2780 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 2781 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 2782 // Find an operand that's safely divisible. 2783 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 2784 const SCEV *Op = M->getOperand(i); 2785 const SCEV *Div = getUDivExpr(Op, RHSC); 2786 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 2787 Operands = SmallVector<const SCEV *, 4>(M->op_begin(), 2788 M->op_end()); 2789 Operands[i] = Div; 2790 return getMulExpr(Operands); 2791 } 2792 } 2793 } 2794 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 2795 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 2796 SmallVector<const SCEV *, 4> Operands; 2797 for (const SCEV *Op : A->operands()) 2798 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 2799 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 2800 Operands.clear(); 2801 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 2802 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 2803 if (isa<SCEVUDivExpr>(Op) || 2804 getMulExpr(Op, RHS) != A->getOperand(i)) 2805 break; 2806 Operands.push_back(Op); 2807 } 2808 if (Operands.size() == A->getNumOperands()) 2809 return getAddExpr(Operands); 2810 } 2811 } 2812 2813 // Fold if both operands are constant. 2814 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 2815 Constant *LHSCV = LHSC->getValue(); 2816 Constant *RHSCV = RHSC->getValue(); 2817 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 2818 RHSCV))); 2819 } 2820 } 2821 } 2822 2823 FoldingSetNodeID ID; 2824 ID.AddInteger(scUDivExpr); 2825 ID.AddPointer(LHS); 2826 ID.AddPointer(RHS); 2827 void *IP = nullptr; 2828 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 2829 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 2830 LHS, RHS); 2831 UniqueSCEVs.InsertNode(S, IP); 2832 return S; 2833 } 2834 2835 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 2836 APInt A = C1->getAPInt().abs(); 2837 APInt B = C2->getAPInt().abs(); 2838 uint32_t ABW = A.getBitWidth(); 2839 uint32_t BBW = B.getBitWidth(); 2840 2841 if (ABW > BBW) 2842 B = B.zext(ABW); 2843 else if (ABW < BBW) 2844 A = A.zext(BBW); 2845 2846 return APIntOps::GreatestCommonDivisor(A, B); 2847 } 2848 2849 /// Get a canonical unsigned division expression, or something simpler if 2850 /// possible. There is no representation for an exact udiv in SCEV IR, but we 2851 /// can attempt to remove factors from the LHS and RHS. We can't do this when 2852 /// it's not exact because the udiv may be clearing bits. 2853 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 2854 const SCEV *RHS) { 2855 // TODO: we could try to find factors in all sorts of things, but for now we 2856 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 2857 // end of this file for inspiration. 2858 2859 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 2860 if (!Mul) 2861 return getUDivExpr(LHS, RHS); 2862 2863 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 2864 // If the mulexpr multiplies by a constant, then that constant must be the 2865 // first element of the mulexpr. 2866 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 2867 if (LHSCst == RHSCst) { 2868 SmallVector<const SCEV *, 2> Operands; 2869 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 2870 return getMulExpr(Operands); 2871 } 2872 2873 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 2874 // that there's a factor provided by one of the other terms. We need to 2875 // check. 2876 APInt Factor = gcd(LHSCst, RHSCst); 2877 if (!Factor.isIntN(1)) { 2878 LHSCst = 2879 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 2880 RHSCst = 2881 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 2882 SmallVector<const SCEV *, 2> Operands; 2883 Operands.push_back(LHSCst); 2884 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 2885 LHS = getMulExpr(Operands); 2886 RHS = RHSCst; 2887 Mul = dyn_cast<SCEVMulExpr>(LHS); 2888 if (!Mul) 2889 return getUDivExactExpr(LHS, RHS); 2890 } 2891 } 2892 } 2893 2894 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 2895 if (Mul->getOperand(i) == RHS) { 2896 SmallVector<const SCEV *, 2> Operands; 2897 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 2898 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 2899 return getMulExpr(Operands); 2900 } 2901 } 2902 2903 return getUDivExpr(LHS, RHS); 2904 } 2905 2906 /// Get an add recurrence expression for the specified loop. Simplify the 2907 /// expression as much as possible. 2908 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 2909 const Loop *L, 2910 SCEV::NoWrapFlags Flags) { 2911 SmallVector<const SCEV *, 4> Operands; 2912 Operands.push_back(Start); 2913 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 2914 if (StepChrec->getLoop() == L) { 2915 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 2916 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 2917 } 2918 2919 Operands.push_back(Step); 2920 return getAddRecExpr(Operands, L, Flags); 2921 } 2922 2923 /// Get an add recurrence expression for the specified loop. Simplify the 2924 /// expression as much as possible. 2925 const SCEV * 2926 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 2927 const Loop *L, SCEV::NoWrapFlags Flags) { 2928 if (Operands.size() == 1) return Operands[0]; 2929 #ifndef NDEBUG 2930 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 2931 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 2932 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 2933 "SCEVAddRecExpr operand types don't match!"); 2934 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 2935 assert(isLoopInvariant(Operands[i], L) && 2936 "SCEVAddRecExpr operand is not loop-invariant!"); 2937 #endif 2938 2939 if (Operands.back()->isZero()) { 2940 Operands.pop_back(); 2941 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 2942 } 2943 2944 // It's tempting to want to call getMaxBackedgeTakenCount count here and 2945 // use that information to infer NUW and NSW flags. However, computing a 2946 // BE count requires calling getAddRecExpr, so we may not yet have a 2947 // meaningful BE count at this point (and if we don't, we'd be stuck 2948 // with a SCEVCouldNotCompute as the cached BE count). 2949 2950 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 2951 2952 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 2953 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 2954 const Loop *NestedLoop = NestedAR->getLoop(); 2955 if (L->contains(NestedLoop) 2956 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 2957 : (!NestedLoop->contains(L) && 2958 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 2959 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(), 2960 NestedAR->op_end()); 2961 Operands[0] = NestedAR->getStart(); 2962 // AddRecs require their operands be loop-invariant with respect to their 2963 // loops. Don't perform this transformation if it would break this 2964 // requirement. 2965 bool AllInvariant = all_of( 2966 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 2967 2968 if (AllInvariant) { 2969 // Create a recurrence for the outer loop with the same step size. 2970 // 2971 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 2972 // inner recurrence has the same property. 2973 SCEV::NoWrapFlags OuterFlags = 2974 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 2975 2976 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 2977 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 2978 return isLoopInvariant(Op, NestedLoop); 2979 }); 2980 2981 if (AllInvariant) { 2982 // Ok, both add recurrences are valid after the transformation. 2983 // 2984 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 2985 // the outer recurrence has the same property. 2986 SCEV::NoWrapFlags InnerFlags = 2987 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 2988 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 2989 } 2990 } 2991 // Reset Operands to its original state. 2992 Operands[0] = NestedAR; 2993 } 2994 } 2995 2996 // Okay, it looks like we really DO need an addrec expr. Check to see if we 2997 // already have one, otherwise create a new one. 2998 FoldingSetNodeID ID; 2999 ID.AddInteger(scAddRecExpr); 3000 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3001 ID.AddPointer(Operands[i]); 3002 ID.AddPointer(L); 3003 void *IP = nullptr; 3004 SCEVAddRecExpr *S = 3005 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 3006 if (!S) { 3007 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size()); 3008 std::uninitialized_copy(Operands.begin(), Operands.end(), O); 3009 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator), 3010 O, Operands.size(), L); 3011 UniqueSCEVs.InsertNode(S, IP); 3012 } 3013 S->setNoWrapFlags(Flags); 3014 return S; 3015 } 3016 3017 const SCEV * 3018 ScalarEvolution::getGEPExpr(Type *PointeeType, const SCEV *BaseExpr, 3019 const SmallVectorImpl<const SCEV *> &IndexExprs, 3020 bool InBounds) { 3021 // getSCEV(Base)->getType() has the same address space as Base->getType() 3022 // because SCEV::getType() preserves the address space. 3023 Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType()); 3024 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP 3025 // instruction to its SCEV, because the Instruction may be guarded by control 3026 // flow and the no-overflow bits may not be valid for the expression in any 3027 // context. This can be fixed similarly to how these flags are handled for 3028 // adds. 3029 SCEV::NoWrapFlags Wrap = InBounds ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3030 3031 const SCEV *TotalOffset = getZero(IntPtrTy); 3032 // The address space is unimportant. The first thing we do on CurTy is getting 3033 // its element type. 3034 Type *CurTy = PointerType::getUnqual(PointeeType); 3035 for (const SCEV *IndexExpr : IndexExprs) { 3036 // Compute the (potentially symbolic) offset in bytes for this index. 3037 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 3038 // For a struct, add the member offset. 3039 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 3040 unsigned FieldNo = Index->getZExtValue(); 3041 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo); 3042 3043 // Add the field offset to the running total offset. 3044 TotalOffset = getAddExpr(TotalOffset, FieldOffset); 3045 3046 // Update CurTy to the type of the field at Index. 3047 CurTy = STy->getTypeAtIndex(Index); 3048 } else { 3049 // Update CurTy to its element type. 3050 CurTy = cast<SequentialType>(CurTy)->getElementType(); 3051 // For an array, add the element offset, explicitly scaled. 3052 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy); 3053 // Getelementptr indices are signed. 3054 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy); 3055 3056 // Multiply the index by the element size to compute the element offset. 3057 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap); 3058 3059 // Add the element offset to the running total offset. 3060 TotalOffset = getAddExpr(TotalOffset, LocalOffset); 3061 } 3062 } 3063 3064 // Add the total offset from all the GEP indices to the base. 3065 return getAddExpr(BaseExpr, TotalOffset, Wrap); 3066 } 3067 3068 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, 3069 const SCEV *RHS) { 3070 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3071 return getSMaxExpr(Ops); 3072 } 3073 3074 const SCEV * 3075 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3076 assert(!Ops.empty() && "Cannot get empty smax!"); 3077 if (Ops.size() == 1) return Ops[0]; 3078 #ifndef NDEBUG 3079 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3080 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3081 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3082 "SCEVSMaxExpr operand types don't match!"); 3083 #endif 3084 3085 // Sort by complexity, this groups all similar expression types together. 3086 GroupByComplexity(Ops, &LI); 3087 3088 // If there are any constants, fold them together. 3089 unsigned Idx = 0; 3090 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3091 ++Idx; 3092 assert(Idx < Ops.size()); 3093 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3094 // We found two constants, fold them together! 3095 ConstantInt *Fold = ConstantInt::get( 3096 getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt())); 3097 Ops[0] = getConstant(Fold); 3098 Ops.erase(Ops.begin()+1); // Erase the folded element 3099 if (Ops.size() == 1) return Ops[0]; 3100 LHSC = cast<SCEVConstant>(Ops[0]); 3101 } 3102 3103 // If we are left with a constant minimum-int, strip it off. 3104 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) { 3105 Ops.erase(Ops.begin()); 3106 --Idx; 3107 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) { 3108 // If we have an smax with a constant maximum-int, it will always be 3109 // maximum-int. 3110 return Ops[0]; 3111 } 3112 3113 if (Ops.size() == 1) return Ops[0]; 3114 } 3115 3116 // Find the first SMax 3117 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr) 3118 ++Idx; 3119 3120 // Check to see if one of the operands is an SMax. If so, expand its operands 3121 // onto our operand list, and recurse to simplify. 3122 if (Idx < Ops.size()) { 3123 bool DeletedSMax = false; 3124 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) { 3125 Ops.erase(Ops.begin()+Idx); 3126 Ops.append(SMax->op_begin(), SMax->op_end()); 3127 DeletedSMax = true; 3128 } 3129 3130 if (DeletedSMax) 3131 return getSMaxExpr(Ops); 3132 } 3133 3134 // Okay, check to see if the same value occurs in the operand list twice. If 3135 // so, delete one. Since we sorted the list, these values are required to 3136 // be adjacent. 3137 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 3138 // X smax Y smax Y --> X smax Y 3139 // X smax Y --> X, if X is always greater than Y 3140 if (Ops[i] == Ops[i+1] || 3141 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) { 3142 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); 3143 --i; --e; 3144 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) { 3145 Ops.erase(Ops.begin()+i, Ops.begin()+i+1); 3146 --i; --e; 3147 } 3148 3149 if (Ops.size() == 1) return Ops[0]; 3150 3151 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3152 3153 // Okay, it looks like we really DO need an smax expr. Check to see if we 3154 // already have one, otherwise create a new one. 3155 FoldingSetNodeID ID; 3156 ID.AddInteger(scSMaxExpr); 3157 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3158 ID.AddPointer(Ops[i]); 3159 void *IP = nullptr; 3160 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3161 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3162 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3163 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator), 3164 O, Ops.size()); 3165 UniqueSCEVs.InsertNode(S, IP); 3166 return S; 3167 } 3168 3169 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, 3170 const SCEV *RHS) { 3171 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3172 return getUMaxExpr(Ops); 3173 } 3174 3175 const SCEV * 3176 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3177 assert(!Ops.empty() && "Cannot get empty umax!"); 3178 if (Ops.size() == 1) return Ops[0]; 3179 #ifndef NDEBUG 3180 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3181 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3182 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3183 "SCEVUMaxExpr operand types don't match!"); 3184 #endif 3185 3186 // Sort by complexity, this groups all similar expression types together. 3187 GroupByComplexity(Ops, &LI); 3188 3189 // If there are any constants, fold them together. 3190 unsigned Idx = 0; 3191 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3192 ++Idx; 3193 assert(Idx < Ops.size()); 3194 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3195 // We found two constants, fold them together! 3196 ConstantInt *Fold = ConstantInt::get( 3197 getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt())); 3198 Ops[0] = getConstant(Fold); 3199 Ops.erase(Ops.begin()+1); // Erase the folded element 3200 if (Ops.size() == 1) return Ops[0]; 3201 LHSC = cast<SCEVConstant>(Ops[0]); 3202 } 3203 3204 // If we are left with a constant minimum-int, strip it off. 3205 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) { 3206 Ops.erase(Ops.begin()); 3207 --Idx; 3208 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) { 3209 // If we have an umax with a constant maximum-int, it will always be 3210 // maximum-int. 3211 return Ops[0]; 3212 } 3213 3214 if (Ops.size() == 1) return Ops[0]; 3215 } 3216 3217 // Find the first UMax 3218 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr) 3219 ++Idx; 3220 3221 // Check to see if one of the operands is a UMax. If so, expand its operands 3222 // onto our operand list, and recurse to simplify. 3223 if (Idx < Ops.size()) { 3224 bool DeletedUMax = false; 3225 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) { 3226 Ops.erase(Ops.begin()+Idx); 3227 Ops.append(UMax->op_begin(), UMax->op_end()); 3228 DeletedUMax = true; 3229 } 3230 3231 if (DeletedUMax) 3232 return getUMaxExpr(Ops); 3233 } 3234 3235 // Okay, check to see if the same value occurs in the operand list twice. If 3236 // so, delete one. Since we sorted the list, these values are required to 3237 // be adjacent. 3238 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 3239 // X umax Y umax Y --> X umax Y 3240 // X umax Y --> X, if X is always greater than Y 3241 if (Ops[i] == Ops[i+1] || 3242 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) { 3243 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); 3244 --i; --e; 3245 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) { 3246 Ops.erase(Ops.begin()+i, Ops.begin()+i+1); 3247 --i; --e; 3248 } 3249 3250 if (Ops.size() == 1) return Ops[0]; 3251 3252 assert(!Ops.empty() && "Reduced umax down to nothing!"); 3253 3254 // Okay, it looks like we really DO need a umax expr. Check to see if we 3255 // already have one, otherwise create a new one. 3256 FoldingSetNodeID ID; 3257 ID.AddInteger(scUMaxExpr); 3258 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3259 ID.AddPointer(Ops[i]); 3260 void *IP = nullptr; 3261 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3262 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3263 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3264 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator), 3265 O, Ops.size()); 3266 UniqueSCEVs.InsertNode(S, IP); 3267 return S; 3268 } 3269 3270 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 3271 const SCEV *RHS) { 3272 // ~smax(~x, ~y) == smin(x, y). 3273 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS))); 3274 } 3275 3276 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, 3277 const SCEV *RHS) { 3278 // ~umax(~x, ~y) == umin(x, y) 3279 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS))); 3280 } 3281 3282 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 3283 // We can bypass creating a target-independent 3284 // constant expression and then folding it back into a ConstantInt. 3285 // This is just a compile-time optimization. 3286 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 3287 } 3288 3289 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 3290 StructType *STy, 3291 unsigned FieldNo) { 3292 // We can bypass creating a target-independent 3293 // constant expression and then folding it back into a ConstantInt. 3294 // This is just a compile-time optimization. 3295 return getConstant( 3296 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 3297 } 3298 3299 const SCEV *ScalarEvolution::getUnknown(Value *V) { 3300 // Don't attempt to do anything other than create a SCEVUnknown object 3301 // here. createSCEV only calls getUnknown after checking for all other 3302 // interesting possibilities, and any other code that calls getUnknown 3303 // is doing so in order to hide a value from SCEV canonicalization. 3304 3305 FoldingSetNodeID ID; 3306 ID.AddInteger(scUnknown); 3307 ID.AddPointer(V); 3308 void *IP = nullptr; 3309 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 3310 assert(cast<SCEVUnknown>(S)->getValue() == V && 3311 "Stale SCEVUnknown in uniquing map!"); 3312 return S; 3313 } 3314 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 3315 FirstUnknown); 3316 FirstUnknown = cast<SCEVUnknown>(S); 3317 UniqueSCEVs.InsertNode(S, IP); 3318 return S; 3319 } 3320 3321 //===----------------------------------------------------------------------===// 3322 // Basic SCEV Analysis and PHI Idiom Recognition Code 3323 // 3324 3325 /// Test if values of the given type are analyzable within the SCEV 3326 /// framework. This primarily includes integer types, and it can optionally 3327 /// include pointer types if the ScalarEvolution class has access to 3328 /// target-specific information. 3329 bool ScalarEvolution::isSCEVable(Type *Ty) const { 3330 // Integers and pointers are always SCEVable. 3331 return Ty->isIntegerTy() || Ty->isPointerTy(); 3332 } 3333 3334 /// Return the size in bits of the specified type, for which isSCEVable must 3335 /// return true. 3336 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 3337 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3338 return getDataLayout().getTypeSizeInBits(Ty); 3339 } 3340 3341 /// Return a type with the same bitwidth as the given type and which represents 3342 /// how SCEV will treat the given type, for which isSCEVable must return 3343 /// true. For pointer types, this is the pointer-sized integer type. 3344 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 3345 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3346 3347 if (Ty->isIntegerTy()) 3348 return Ty; 3349 3350 // The only other support type is pointer. 3351 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 3352 return getDataLayout().getIntPtrType(Ty); 3353 } 3354 3355 const SCEV *ScalarEvolution::getCouldNotCompute() { 3356 return CouldNotCompute.get(); 3357 } 3358 3359 3360 bool ScalarEvolution::checkValidity(const SCEV *S) const { 3361 // Helper class working with SCEVTraversal to figure out if a SCEV contains 3362 // a SCEVUnknown with null value-pointer. FindInvalidSCEVUnknown::FindOne 3363 // is set iff if find such SCEVUnknown. 3364 // 3365 struct FindInvalidSCEVUnknown { 3366 bool FindOne; 3367 FindInvalidSCEVUnknown() { FindOne = false; } 3368 bool follow(const SCEV *S) { 3369 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 3370 case scConstant: 3371 return false; 3372 case scUnknown: 3373 if (!cast<SCEVUnknown>(S)->getValue()) 3374 FindOne = true; 3375 return false; 3376 default: 3377 return true; 3378 } 3379 } 3380 bool isDone() const { return FindOne; } 3381 }; 3382 3383 FindInvalidSCEVUnknown F; 3384 SCEVTraversal<FindInvalidSCEVUnknown> ST(F); 3385 ST.visitAll(S); 3386 3387 return !F.FindOne; 3388 } 3389 3390 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 3391 // Helper class working with SCEVTraversal to figure out if a SCEV contains a 3392 // sub SCEV of scAddRecExpr type. FindInvalidSCEVUnknown::FoundOne is set iff 3393 // if such sub scAddRecExpr type SCEV is found. 3394 struct FindAddRecurrence { 3395 bool FoundOne; 3396 FindAddRecurrence() : FoundOne(false) {} 3397 3398 bool follow(const SCEV *S) { 3399 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 3400 case scAddRecExpr: 3401 FoundOne = true; 3402 case scConstant: 3403 case scUnknown: 3404 case scCouldNotCompute: 3405 return false; 3406 default: 3407 return true; 3408 } 3409 } 3410 bool isDone() const { return FoundOne; } 3411 }; 3412 3413 HasRecMapType::iterator I = HasRecMap.find(S); 3414 if (I != HasRecMap.end()) 3415 return I->second; 3416 3417 FindAddRecurrence F; 3418 SCEVTraversal<FindAddRecurrence> ST(F); 3419 ST.visitAll(S); 3420 HasRecMap.insert({S, F.FoundOne}); 3421 return F.FoundOne; 3422 } 3423 3424 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. 3425 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an 3426 /// offset I, then return {S', I}, else return {\p S, nullptr}. 3427 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { 3428 const auto *Add = dyn_cast<SCEVAddExpr>(S); 3429 if (!Add) 3430 return {S, nullptr}; 3431 3432 if (Add->getNumOperands() != 2) 3433 return {S, nullptr}; 3434 3435 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); 3436 if (!ConstOp) 3437 return {S, nullptr}; 3438 3439 return {Add->getOperand(1), ConstOp->getValue()}; 3440 } 3441 3442 /// Return the ValueOffsetPair set for \p S. \p S can be represented 3443 /// by the value and offset from any ValueOffsetPair in the set. 3444 SetVector<ScalarEvolution::ValueOffsetPair> * 3445 ScalarEvolution::getSCEVValues(const SCEV *S) { 3446 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 3447 if (SI == ExprValueMap.end()) 3448 return nullptr; 3449 #ifndef NDEBUG 3450 if (VerifySCEVMap) { 3451 // Check there is no dangling Value in the set returned. 3452 for (const auto &VE : SI->second) 3453 assert(ValueExprMap.count(VE.first)); 3454 } 3455 #endif 3456 return &SI->second; 3457 } 3458 3459 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) 3460 /// cannot be used separately. eraseValueFromMap should be used to remove 3461 /// V from ValueExprMap and ExprValueMap at the same time. 3462 void ScalarEvolution::eraseValueFromMap(Value *V) { 3463 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3464 if (I != ValueExprMap.end()) { 3465 const SCEV *S = I->second; 3466 // Remove {V, 0} from the set of ExprValueMap[S] 3467 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S)) 3468 SV->remove({V, nullptr}); 3469 3470 // Remove {V, Offset} from the set of ExprValueMap[Stripped] 3471 const SCEV *Stripped; 3472 ConstantInt *Offset; 3473 std::tie(Stripped, Offset) = splitAddExpr(S); 3474 if (Offset != nullptr) { 3475 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped)) 3476 SV->remove({V, Offset}); 3477 } 3478 ValueExprMap.erase(V); 3479 } 3480 } 3481 3482 /// Return an existing SCEV if it exists, otherwise analyze the expression and 3483 /// create a new one. 3484 const SCEV *ScalarEvolution::getSCEV(Value *V) { 3485 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3486 3487 const SCEV *S = getExistingSCEV(V); 3488 if (S == nullptr) { 3489 S = createSCEV(V); 3490 // During PHI resolution, it is possible to create two SCEVs for the same 3491 // V, so it is needed to double check whether V->S is inserted into 3492 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 3493 std::pair<ValueExprMapType::iterator, bool> Pair = 3494 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 3495 if (Pair.second) { 3496 ExprValueMap[S].insert({V, nullptr}); 3497 3498 // If S == Stripped + Offset, add Stripped -> {V, Offset} into 3499 // ExprValueMap. 3500 const SCEV *Stripped = S; 3501 ConstantInt *Offset = nullptr; 3502 std::tie(Stripped, Offset) = splitAddExpr(S); 3503 // If stripped is SCEVUnknown, don't bother to save 3504 // Stripped -> {V, offset}. It doesn't simplify and sometimes even 3505 // increase the complexity of the expansion code. 3506 // If V is GetElementPtrInst, don't save Stripped -> {V, offset} 3507 // because it may generate add/sub instead of GEP in SCEV expansion. 3508 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && 3509 !isa<GetElementPtrInst>(V)) 3510 ExprValueMap[Stripped].insert({V, Offset}); 3511 } 3512 } 3513 return S; 3514 } 3515 3516 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 3517 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3518 3519 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3520 if (I != ValueExprMap.end()) { 3521 const SCEV *S = I->second; 3522 if (checkValidity(S)) 3523 return S; 3524 eraseValueFromMap(V); 3525 forgetMemoizedResults(S); 3526 } 3527 return nullptr; 3528 } 3529 3530 /// Return a SCEV corresponding to -V = -1*V 3531 /// 3532 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 3533 SCEV::NoWrapFlags Flags) { 3534 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3535 return getConstant( 3536 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 3537 3538 Type *Ty = V->getType(); 3539 Ty = getEffectiveSCEVType(Ty); 3540 return getMulExpr( 3541 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags); 3542 } 3543 3544 /// Return a SCEV corresponding to ~V = -1-V 3545 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 3546 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3547 return getConstant( 3548 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 3549 3550 Type *Ty = V->getType(); 3551 Ty = getEffectiveSCEVType(Ty); 3552 const SCEV *AllOnes = 3553 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))); 3554 return getMinusSCEV(AllOnes, V); 3555 } 3556 3557 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 3558 SCEV::NoWrapFlags Flags) { 3559 // Fast path: X - X --> 0. 3560 if (LHS == RHS) 3561 return getZero(LHS->getType()); 3562 3563 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 3564 // makes it so that we cannot make much use of NUW. 3565 auto AddFlags = SCEV::FlagAnyWrap; 3566 const bool RHSIsNotMinSigned = 3567 !getSignedRange(RHS).getSignedMin().isMinSignedValue(); 3568 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) { 3569 // Let M be the minimum representable signed value. Then (-1)*RHS 3570 // signed-wraps if and only if RHS is M. That can happen even for 3571 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 3572 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 3573 // (-1)*RHS, we need to prove that RHS != M. 3574 // 3575 // If LHS is non-negative and we know that LHS - RHS does not 3576 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 3577 // either by proving that RHS > M or that LHS >= 0. 3578 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 3579 AddFlags = SCEV::FlagNSW; 3580 } 3581 } 3582 3583 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 3584 // RHS is NSW and LHS >= 0. 3585 // 3586 // The difficulty here is that the NSW flag may have been proven 3587 // relative to a loop that is to be found in a recurrence in LHS and 3588 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 3589 // larger scope than intended. 3590 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3591 3592 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags); 3593 } 3594 3595 const SCEV * 3596 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) { 3597 Type *SrcTy = V->getType(); 3598 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3599 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3600 "Cannot truncate or zero extend with non-integer arguments!"); 3601 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3602 return V; // No conversion 3603 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 3604 return getTruncateExpr(V, Ty); 3605 return getZeroExtendExpr(V, Ty); 3606 } 3607 3608 const SCEV * 3609 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, 3610 Type *Ty) { 3611 Type *SrcTy = V->getType(); 3612 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3613 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3614 "Cannot truncate or zero extend with non-integer arguments!"); 3615 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3616 return V; // No conversion 3617 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 3618 return getTruncateExpr(V, Ty); 3619 return getSignExtendExpr(V, Ty); 3620 } 3621 3622 const SCEV * 3623 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 3624 Type *SrcTy = V->getType(); 3625 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3626 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3627 "Cannot noop or zero extend with non-integer arguments!"); 3628 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3629 "getNoopOrZeroExtend cannot truncate!"); 3630 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3631 return V; // No conversion 3632 return getZeroExtendExpr(V, Ty); 3633 } 3634 3635 const SCEV * 3636 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 3637 Type *SrcTy = V->getType(); 3638 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3639 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3640 "Cannot noop or sign extend with non-integer arguments!"); 3641 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3642 "getNoopOrSignExtend cannot truncate!"); 3643 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3644 return V; // No conversion 3645 return getSignExtendExpr(V, Ty); 3646 } 3647 3648 const SCEV * 3649 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 3650 Type *SrcTy = V->getType(); 3651 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3652 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3653 "Cannot noop or any extend with non-integer arguments!"); 3654 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3655 "getNoopOrAnyExtend cannot truncate!"); 3656 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3657 return V; // No conversion 3658 return getAnyExtendExpr(V, Ty); 3659 } 3660 3661 const SCEV * 3662 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 3663 Type *SrcTy = V->getType(); 3664 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3665 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3666 "Cannot truncate or noop with non-integer arguments!"); 3667 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 3668 "getTruncateOrNoop cannot extend!"); 3669 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3670 return V; // No conversion 3671 return getTruncateExpr(V, Ty); 3672 } 3673 3674 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 3675 const SCEV *RHS) { 3676 const SCEV *PromotedLHS = LHS; 3677 const SCEV *PromotedRHS = RHS; 3678 3679 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 3680 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 3681 else 3682 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 3683 3684 return getUMaxExpr(PromotedLHS, PromotedRHS); 3685 } 3686 3687 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 3688 const SCEV *RHS) { 3689 const SCEV *PromotedLHS = LHS; 3690 const SCEV *PromotedRHS = RHS; 3691 3692 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 3693 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 3694 else 3695 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 3696 3697 return getUMinExpr(PromotedLHS, PromotedRHS); 3698 } 3699 3700 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 3701 // A pointer operand may evaluate to a nonpointer expression, such as null. 3702 if (!V->getType()->isPointerTy()) 3703 return V; 3704 3705 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) { 3706 return getPointerBase(Cast->getOperand()); 3707 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) { 3708 const SCEV *PtrOp = nullptr; 3709 for (const SCEV *NAryOp : NAry->operands()) { 3710 if (NAryOp->getType()->isPointerTy()) { 3711 // Cannot find the base of an expression with multiple pointer operands. 3712 if (PtrOp) 3713 return V; 3714 PtrOp = NAryOp; 3715 } 3716 } 3717 if (!PtrOp) 3718 return V; 3719 return getPointerBase(PtrOp); 3720 } 3721 return V; 3722 } 3723 3724 /// Push users of the given Instruction onto the given Worklist. 3725 static void 3726 PushDefUseChildren(Instruction *I, 3727 SmallVectorImpl<Instruction *> &Worklist) { 3728 // Push the def-use children onto the Worklist stack. 3729 for (User *U : I->users()) 3730 Worklist.push_back(cast<Instruction>(U)); 3731 } 3732 3733 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { 3734 SmallVector<Instruction *, 16> Worklist; 3735 PushDefUseChildren(PN, Worklist); 3736 3737 SmallPtrSet<Instruction *, 8> Visited; 3738 Visited.insert(PN); 3739 while (!Worklist.empty()) { 3740 Instruction *I = Worklist.pop_back_val(); 3741 if (!Visited.insert(I).second) 3742 continue; 3743 3744 auto It = ValueExprMap.find_as(static_cast<Value *>(I)); 3745 if (It != ValueExprMap.end()) { 3746 const SCEV *Old = It->second; 3747 3748 // Short-circuit the def-use traversal if the symbolic name 3749 // ceases to appear in expressions. 3750 if (Old != SymName && !hasOperand(Old, SymName)) 3751 continue; 3752 3753 // SCEVUnknown for a PHI either means that it has an unrecognized 3754 // structure, it's a PHI that's in the progress of being computed 3755 // by createNodeForPHI, or it's a single-value PHI. In the first case, 3756 // additional loop trip count information isn't going to change anything. 3757 // In the second case, createNodeForPHI will perform the necessary 3758 // updates on its own when it gets to that point. In the third, we do 3759 // want to forget the SCEVUnknown. 3760 if (!isa<PHINode>(I) || 3761 !isa<SCEVUnknown>(Old) || 3762 (I != PN && Old == SymName)) { 3763 eraseValueFromMap(It->first); 3764 forgetMemoizedResults(Old); 3765 } 3766 } 3767 3768 PushDefUseChildren(I, Worklist); 3769 } 3770 } 3771 3772 namespace { 3773 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 3774 public: 3775 static const SCEV *rewrite(const SCEV *S, const Loop *L, 3776 ScalarEvolution &SE) { 3777 SCEVInitRewriter Rewriter(L, SE); 3778 const SCEV *Result = Rewriter.visit(S); 3779 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 3780 } 3781 3782 SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 3783 : SCEVRewriteVisitor(SE), L(L), Valid(true) {} 3784 3785 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 3786 if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant)) 3787 Valid = false; 3788 return Expr; 3789 } 3790 3791 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 3792 // Only allow AddRecExprs for this loop. 3793 if (Expr->getLoop() == L) 3794 return Expr->getStart(); 3795 Valid = false; 3796 return Expr; 3797 } 3798 3799 bool isValid() { return Valid; } 3800 3801 private: 3802 const Loop *L; 3803 bool Valid; 3804 }; 3805 3806 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 3807 public: 3808 static const SCEV *rewrite(const SCEV *S, const Loop *L, 3809 ScalarEvolution &SE) { 3810 SCEVShiftRewriter Rewriter(L, SE); 3811 const SCEV *Result = Rewriter.visit(S); 3812 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 3813 } 3814 3815 SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 3816 : SCEVRewriteVisitor(SE), L(L), Valid(true) {} 3817 3818 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 3819 // Only allow AddRecExprs for this loop. 3820 if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant)) 3821 Valid = false; 3822 return Expr; 3823 } 3824 3825 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 3826 if (Expr->getLoop() == L && Expr->isAffine()) 3827 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 3828 Valid = false; 3829 return Expr; 3830 } 3831 bool isValid() { return Valid; } 3832 3833 private: 3834 const Loop *L; 3835 bool Valid; 3836 }; 3837 } // end anonymous namespace 3838 3839 SCEV::NoWrapFlags 3840 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 3841 if (!AR->isAffine()) 3842 return SCEV::FlagAnyWrap; 3843 3844 typedef OverflowingBinaryOperator OBO; 3845 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 3846 3847 if (!AR->hasNoSignedWrap()) { 3848 ConstantRange AddRecRange = getSignedRange(AR); 3849 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 3850 3851 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 3852 Instruction::Add, IncRange, OBO::NoSignedWrap); 3853 if (NSWRegion.contains(AddRecRange)) 3854 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 3855 } 3856 3857 if (!AR->hasNoUnsignedWrap()) { 3858 ConstantRange AddRecRange = getUnsignedRange(AR); 3859 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 3860 3861 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 3862 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 3863 if (NUWRegion.contains(AddRecRange)) 3864 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 3865 } 3866 3867 return Result; 3868 } 3869 3870 namespace { 3871 /// Represents an abstract binary operation. This may exist as a 3872 /// normal instruction or constant expression, or may have been 3873 /// derived from an expression tree. 3874 struct BinaryOp { 3875 unsigned Opcode; 3876 Value *LHS; 3877 Value *RHS; 3878 bool IsNSW; 3879 bool IsNUW; 3880 3881 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 3882 /// constant expression. 3883 Operator *Op; 3884 3885 explicit BinaryOp(Operator *Op) 3886 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 3887 IsNSW(false), IsNUW(false), Op(Op) { 3888 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 3889 IsNSW = OBO->hasNoSignedWrap(); 3890 IsNUW = OBO->hasNoUnsignedWrap(); 3891 } 3892 } 3893 3894 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 3895 bool IsNUW = false) 3896 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW), 3897 Op(nullptr) {} 3898 }; 3899 } 3900 3901 3902 /// Try to map \p V into a BinaryOp, and return \c None on failure. 3903 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 3904 auto *Op = dyn_cast<Operator>(V); 3905 if (!Op) 3906 return None; 3907 3908 // Implementation detail: all the cleverness here should happen without 3909 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 3910 // SCEV expressions when possible, and we should not break that. 3911 3912 switch (Op->getOpcode()) { 3913 case Instruction::Add: 3914 case Instruction::Sub: 3915 case Instruction::Mul: 3916 case Instruction::UDiv: 3917 case Instruction::And: 3918 case Instruction::Or: 3919 case Instruction::AShr: 3920 case Instruction::Shl: 3921 return BinaryOp(Op); 3922 3923 case Instruction::Xor: 3924 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 3925 // If the RHS of the xor is a signbit, then this is just an add. 3926 // Instcombine turns add of signbit into xor as a strength reduction step. 3927 if (RHSC->getValue().isSignBit()) 3928 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 3929 return BinaryOp(Op); 3930 3931 case Instruction::LShr: 3932 // Turn logical shift right of a constant into a unsigned divide. 3933 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 3934 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 3935 3936 // If the shift count is not less than the bitwidth, the result of 3937 // the shift is undefined. Don't try to analyze it, because the 3938 // resolution chosen here may differ from the resolution chosen in 3939 // other parts of the compiler. 3940 if (SA->getValue().ult(BitWidth)) { 3941 Constant *X = 3942 ConstantInt::get(SA->getContext(), 3943 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 3944 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 3945 } 3946 } 3947 return BinaryOp(Op); 3948 3949 case Instruction::ExtractValue: { 3950 auto *EVI = cast<ExtractValueInst>(Op); 3951 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 3952 break; 3953 3954 auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand()); 3955 if (!CI) 3956 break; 3957 3958 if (auto *F = CI->getCalledFunction()) 3959 switch (F->getIntrinsicID()) { 3960 case Intrinsic::sadd_with_overflow: 3961 case Intrinsic::uadd_with_overflow: { 3962 if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT)) 3963 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 3964 CI->getArgOperand(1)); 3965 3966 // Now that we know that all uses of the arithmetic-result component of 3967 // CI are guarded by the overflow check, we can go ahead and pretend 3968 // that the arithmetic is non-overflowing. 3969 if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow) 3970 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 3971 CI->getArgOperand(1), /* IsNSW = */ true, 3972 /* IsNUW = */ false); 3973 else 3974 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 3975 CI->getArgOperand(1), /* IsNSW = */ false, 3976 /* IsNUW*/ true); 3977 } 3978 3979 case Intrinsic::ssub_with_overflow: 3980 case Intrinsic::usub_with_overflow: 3981 return BinaryOp(Instruction::Sub, CI->getArgOperand(0), 3982 CI->getArgOperand(1)); 3983 3984 case Intrinsic::smul_with_overflow: 3985 case Intrinsic::umul_with_overflow: 3986 return BinaryOp(Instruction::Mul, CI->getArgOperand(0), 3987 CI->getArgOperand(1)); 3988 default: 3989 break; 3990 } 3991 } 3992 3993 default: 3994 break; 3995 } 3996 3997 return None; 3998 } 3999 4000 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 4001 const Loop *L = LI.getLoopFor(PN->getParent()); 4002 if (!L || L->getHeader() != PN->getParent()) 4003 return nullptr; 4004 4005 // The loop may have multiple entrances or multiple exits; we can analyze 4006 // this phi as an addrec if it has a unique entry value and a unique 4007 // backedge value. 4008 Value *BEValueV = nullptr, *StartValueV = nullptr; 4009 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 4010 Value *V = PN->getIncomingValue(i); 4011 if (L->contains(PN->getIncomingBlock(i))) { 4012 if (!BEValueV) { 4013 BEValueV = V; 4014 } else if (BEValueV != V) { 4015 BEValueV = nullptr; 4016 break; 4017 } 4018 } else if (!StartValueV) { 4019 StartValueV = V; 4020 } else if (StartValueV != V) { 4021 StartValueV = nullptr; 4022 break; 4023 } 4024 } 4025 if (BEValueV && StartValueV) { 4026 // While we are analyzing this PHI node, handle its value symbolically. 4027 const SCEV *SymbolicName = getUnknown(PN); 4028 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 4029 "PHI node already processed?"); 4030 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); 4031 4032 // Using this symbolic name for the PHI, analyze the value coming around 4033 // the back-edge. 4034 const SCEV *BEValue = getSCEV(BEValueV); 4035 4036 // NOTE: If BEValue is loop invariant, we know that the PHI node just 4037 // has a special value for the first iteration of the loop. 4038 4039 // If the value coming around the backedge is an add with the symbolic 4040 // value we just inserted, then we found a simple induction variable! 4041 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 4042 // If there is a single occurrence of the symbolic value, replace it 4043 // with a recurrence. 4044 unsigned FoundIndex = Add->getNumOperands(); 4045 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4046 if (Add->getOperand(i) == SymbolicName) 4047 if (FoundIndex == e) { 4048 FoundIndex = i; 4049 break; 4050 } 4051 4052 if (FoundIndex != Add->getNumOperands()) { 4053 // Create an add with everything but the specified operand. 4054 SmallVector<const SCEV *, 8> Ops; 4055 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4056 if (i != FoundIndex) 4057 Ops.push_back(Add->getOperand(i)); 4058 const SCEV *Accum = getAddExpr(Ops); 4059 4060 // This is not a valid addrec if the step amount is varying each 4061 // loop iteration, but is not itself an addrec in this loop. 4062 if (isLoopInvariant(Accum, L) || 4063 (isa<SCEVAddRecExpr>(Accum) && 4064 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 4065 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 4066 4067 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 4068 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 4069 if (BO->IsNUW) 4070 Flags = setFlags(Flags, SCEV::FlagNUW); 4071 if (BO->IsNSW) 4072 Flags = setFlags(Flags, SCEV::FlagNSW); 4073 } 4074 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 4075 // If the increment is an inbounds GEP, then we know the address 4076 // space cannot be wrapped around. We cannot make any guarantee 4077 // about signed or unsigned overflow because pointers are 4078 // unsigned but we may have a negative index from the base 4079 // pointer. We can guarantee that no unsigned wrap occurs if the 4080 // indices form a positive value. 4081 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 4082 Flags = setFlags(Flags, SCEV::FlagNW); 4083 4084 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 4085 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 4086 Flags = setFlags(Flags, SCEV::FlagNUW); 4087 } 4088 4089 // We cannot transfer nuw and nsw flags from subtraction 4090 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 4091 // for instance. 4092 } 4093 4094 const SCEV *StartVal = getSCEV(StartValueV); 4095 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 4096 4097 // Okay, for the entire analysis of this edge we assumed the PHI 4098 // to be symbolic. We now need to go back and purge all of the 4099 // entries for the scalars that use the symbolic expression. 4100 forgetSymbolicName(PN, SymbolicName); 4101 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 4102 4103 // We can add Flags to the post-inc expression only if we 4104 // know that it us *undefined behavior* for BEValueV to 4105 // overflow. 4106 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 4107 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 4108 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 4109 4110 return PHISCEV; 4111 } 4112 } 4113 } else { 4114 // Otherwise, this could be a loop like this: 4115 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 4116 // In this case, j = {1,+,1} and BEValue is j. 4117 // Because the other in-value of i (0) fits the evolution of BEValue 4118 // i really is an addrec evolution. 4119 // 4120 // We can generalize this saying that i is the shifted value of BEValue 4121 // by one iteration: 4122 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 4123 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 4124 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this); 4125 if (Shifted != getCouldNotCompute() && 4126 Start != getCouldNotCompute()) { 4127 const SCEV *StartVal = getSCEV(StartValueV); 4128 if (Start == StartVal) { 4129 // Okay, for the entire analysis of this edge we assumed the PHI 4130 // to be symbolic. We now need to go back and purge all of the 4131 // entries for the scalars that use the symbolic expression. 4132 forgetSymbolicName(PN, SymbolicName); 4133 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; 4134 return Shifted; 4135 } 4136 } 4137 } 4138 4139 // Remove the temporary PHI node SCEV that has been inserted while intending 4140 // to create an AddRecExpr for this PHI node. We can not keep this temporary 4141 // as it will prevent later (possibly simpler) SCEV expressions to be added 4142 // to the ValueExprMap. 4143 eraseValueFromMap(PN); 4144 } 4145 4146 return nullptr; 4147 } 4148 4149 // Checks if the SCEV S is available at BB. S is considered available at BB 4150 // if S can be materialized at BB without introducing a fault. 4151 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 4152 BasicBlock *BB) { 4153 struct CheckAvailable { 4154 bool TraversalDone = false; 4155 bool Available = true; 4156 4157 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 4158 BasicBlock *BB = nullptr; 4159 DominatorTree &DT; 4160 4161 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 4162 : L(L), BB(BB), DT(DT) {} 4163 4164 bool setUnavailable() { 4165 TraversalDone = true; 4166 Available = false; 4167 return false; 4168 } 4169 4170 bool follow(const SCEV *S) { 4171 switch (S->getSCEVType()) { 4172 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend: 4173 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr: 4174 // These expressions are available if their operand(s) is/are. 4175 return true; 4176 4177 case scAddRecExpr: { 4178 // We allow add recurrences that are on the loop BB is in, or some 4179 // outer loop. This guarantees availability because the value of the 4180 // add recurrence at BB is simply the "current" value of the induction 4181 // variable. We can relax this in the future; for instance an add 4182 // recurrence on a sibling dominating loop is also available at BB. 4183 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 4184 if (L && (ARLoop == L || ARLoop->contains(L))) 4185 return true; 4186 4187 return setUnavailable(); 4188 } 4189 4190 case scUnknown: { 4191 // For SCEVUnknown, we check for simple dominance. 4192 const auto *SU = cast<SCEVUnknown>(S); 4193 Value *V = SU->getValue(); 4194 4195 if (isa<Argument>(V)) 4196 return false; 4197 4198 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 4199 return false; 4200 4201 return setUnavailable(); 4202 } 4203 4204 case scUDivExpr: 4205 case scCouldNotCompute: 4206 // We do not try to smart about these at all. 4207 return setUnavailable(); 4208 } 4209 llvm_unreachable("switch should be fully covered!"); 4210 } 4211 4212 bool isDone() { return TraversalDone; } 4213 }; 4214 4215 CheckAvailable CA(L, BB, DT); 4216 SCEVTraversal<CheckAvailable> ST(CA); 4217 4218 ST.visitAll(S); 4219 return CA.Available; 4220 } 4221 4222 // Try to match a control flow sequence that branches out at BI and merges back 4223 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 4224 // match. 4225 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 4226 Value *&C, Value *&LHS, Value *&RHS) { 4227 C = BI->getCondition(); 4228 4229 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 4230 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 4231 4232 if (!LeftEdge.isSingleEdge()) 4233 return false; 4234 4235 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 4236 4237 Use &LeftUse = Merge->getOperandUse(0); 4238 Use &RightUse = Merge->getOperandUse(1); 4239 4240 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 4241 LHS = LeftUse; 4242 RHS = RightUse; 4243 return true; 4244 } 4245 4246 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 4247 LHS = RightUse; 4248 RHS = LeftUse; 4249 return true; 4250 } 4251 4252 return false; 4253 } 4254 4255 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 4256 auto IsReachable = 4257 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 4258 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 4259 const Loop *L = LI.getLoopFor(PN->getParent()); 4260 4261 // We don't want to break LCSSA, even in a SCEV expression tree. 4262 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 4263 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 4264 return nullptr; 4265 4266 // Try to match 4267 // 4268 // br %cond, label %left, label %right 4269 // left: 4270 // br label %merge 4271 // right: 4272 // br label %merge 4273 // merge: 4274 // V = phi [ %x, %left ], [ %y, %right ] 4275 // 4276 // as "select %cond, %x, %y" 4277 4278 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 4279 assert(IDom && "At least the entry block should dominate PN"); 4280 4281 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 4282 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 4283 4284 if (BI && BI->isConditional() && 4285 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 4286 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 4287 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 4288 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 4289 } 4290 4291 return nullptr; 4292 } 4293 4294 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 4295 if (const SCEV *S = createAddRecFromPHI(PN)) 4296 return S; 4297 4298 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 4299 return S; 4300 4301 // If the PHI has a single incoming value, follow that value, unless the 4302 // PHI's incoming blocks are in a different loop, in which case doing so 4303 // risks breaking LCSSA form. Instcombine would normally zap these, but 4304 // it doesn't have DominatorTree information, so it may miss cases. 4305 if (Value *V = SimplifyInstruction(PN, getDataLayout(), &TLI, &DT, &AC)) 4306 if (LI.replacementPreservesLCSSAForm(PN, V)) 4307 return getSCEV(V); 4308 4309 // If it's not a loop phi, we can't handle it yet. 4310 return getUnknown(PN); 4311 } 4312 4313 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, 4314 Value *Cond, 4315 Value *TrueVal, 4316 Value *FalseVal) { 4317 // Handle "constant" branch or select. This can occur for instance when a 4318 // loop pass transforms an inner loop and moves on to process the outer loop. 4319 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 4320 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 4321 4322 // Try to match some simple smax or umax patterns. 4323 auto *ICI = dyn_cast<ICmpInst>(Cond); 4324 if (!ICI) 4325 return getUnknown(I); 4326 4327 Value *LHS = ICI->getOperand(0); 4328 Value *RHS = ICI->getOperand(1); 4329 4330 switch (ICI->getPredicate()) { 4331 case ICmpInst::ICMP_SLT: 4332 case ICmpInst::ICMP_SLE: 4333 std::swap(LHS, RHS); 4334 LLVM_FALLTHROUGH; 4335 case ICmpInst::ICMP_SGT: 4336 case ICmpInst::ICMP_SGE: 4337 // a >s b ? a+x : b+x -> smax(a, b)+x 4338 // a >s b ? b+x : a+x -> smin(a, b)+x 4339 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 4340 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType()); 4341 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType()); 4342 const SCEV *LA = getSCEV(TrueVal); 4343 const SCEV *RA = getSCEV(FalseVal); 4344 const SCEV *LDiff = getMinusSCEV(LA, LS); 4345 const SCEV *RDiff = getMinusSCEV(RA, RS); 4346 if (LDiff == RDiff) 4347 return getAddExpr(getSMaxExpr(LS, RS), LDiff); 4348 LDiff = getMinusSCEV(LA, RS); 4349 RDiff = getMinusSCEV(RA, LS); 4350 if (LDiff == RDiff) 4351 return getAddExpr(getSMinExpr(LS, RS), LDiff); 4352 } 4353 break; 4354 case ICmpInst::ICMP_ULT: 4355 case ICmpInst::ICMP_ULE: 4356 std::swap(LHS, RHS); 4357 LLVM_FALLTHROUGH; 4358 case ICmpInst::ICMP_UGT: 4359 case ICmpInst::ICMP_UGE: 4360 // a >u b ? a+x : b+x -> umax(a, b)+x 4361 // a >u b ? b+x : a+x -> umin(a, b)+x 4362 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 4363 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 4364 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType()); 4365 const SCEV *LA = getSCEV(TrueVal); 4366 const SCEV *RA = getSCEV(FalseVal); 4367 const SCEV *LDiff = getMinusSCEV(LA, LS); 4368 const SCEV *RDiff = getMinusSCEV(RA, RS); 4369 if (LDiff == RDiff) 4370 return getAddExpr(getUMaxExpr(LS, RS), LDiff); 4371 LDiff = getMinusSCEV(LA, RS); 4372 RDiff = getMinusSCEV(RA, LS); 4373 if (LDiff == RDiff) 4374 return getAddExpr(getUMinExpr(LS, RS), LDiff); 4375 } 4376 break; 4377 case ICmpInst::ICMP_NE: 4378 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 4379 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 4380 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 4381 const SCEV *One = getOne(I->getType()); 4382 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 4383 const SCEV *LA = getSCEV(TrueVal); 4384 const SCEV *RA = getSCEV(FalseVal); 4385 const SCEV *LDiff = getMinusSCEV(LA, LS); 4386 const SCEV *RDiff = getMinusSCEV(RA, One); 4387 if (LDiff == RDiff) 4388 return getAddExpr(getUMaxExpr(One, LS), LDiff); 4389 } 4390 break; 4391 case ICmpInst::ICMP_EQ: 4392 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 4393 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 4394 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 4395 const SCEV *One = getOne(I->getType()); 4396 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 4397 const SCEV *LA = getSCEV(TrueVal); 4398 const SCEV *RA = getSCEV(FalseVal); 4399 const SCEV *LDiff = getMinusSCEV(LA, One); 4400 const SCEV *RDiff = getMinusSCEV(RA, LS); 4401 if (LDiff == RDiff) 4402 return getAddExpr(getUMaxExpr(One, LS), LDiff); 4403 } 4404 break; 4405 default: 4406 break; 4407 } 4408 4409 return getUnknown(I); 4410 } 4411 4412 /// Expand GEP instructions into add and multiply operations. This allows them 4413 /// to be analyzed by regular SCEV code. 4414 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 4415 // Don't attempt to analyze GEPs over unsized objects. 4416 if (!GEP->getSourceElementType()->isSized()) 4417 return getUnknown(GEP); 4418 4419 SmallVector<const SCEV *, 4> IndexExprs; 4420 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) 4421 IndexExprs.push_back(getSCEV(*Index)); 4422 return getGEPExpr(GEP->getSourceElementType(), 4423 getSCEV(GEP->getPointerOperand()), 4424 IndexExprs, GEP->isInBounds()); 4425 } 4426 4427 uint32_t 4428 ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 4429 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 4430 return C->getAPInt().countTrailingZeros(); 4431 4432 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 4433 return std::min(GetMinTrailingZeros(T->getOperand()), 4434 (uint32_t)getTypeSizeInBits(T->getType())); 4435 4436 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 4437 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 4438 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ? 4439 getTypeSizeInBits(E->getType()) : OpRes; 4440 } 4441 4442 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 4443 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 4444 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ? 4445 getTypeSizeInBits(E->getType()) : OpRes; 4446 } 4447 4448 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 4449 // The result is the min of all operands results. 4450 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 4451 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 4452 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 4453 return MinOpRes; 4454 } 4455 4456 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 4457 // The result is the sum of all operands results. 4458 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 4459 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 4460 for (unsigned i = 1, e = M->getNumOperands(); 4461 SumOpRes != BitWidth && i != e; ++i) 4462 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), 4463 BitWidth); 4464 return SumOpRes; 4465 } 4466 4467 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 4468 // The result is the min of all operands results. 4469 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 4470 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 4471 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 4472 return MinOpRes; 4473 } 4474 4475 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 4476 // The result is the min of all operands results. 4477 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 4478 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 4479 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 4480 return MinOpRes; 4481 } 4482 4483 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 4484 // The result is the min of all operands results. 4485 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 4486 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 4487 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 4488 return MinOpRes; 4489 } 4490 4491 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 4492 // For a SCEVUnknown, ask ValueTracking. 4493 unsigned BitWidth = getTypeSizeInBits(U->getType()); 4494 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0); 4495 computeKnownBits(U->getValue(), Zeros, Ones, getDataLayout(), 0, &AC, 4496 nullptr, &DT); 4497 return Zeros.countTrailingOnes(); 4498 } 4499 4500 // SCEVUDivExpr 4501 return 0; 4502 } 4503 4504 /// Helper method to assign a range to V from metadata present in the IR. 4505 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 4506 if (Instruction *I = dyn_cast<Instruction>(V)) 4507 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 4508 return getConstantRangeFromMetadata(*MD); 4509 4510 return None; 4511 } 4512 4513 /// Determine the range for a particular SCEV. If SignHint is 4514 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 4515 /// with a "cleaner" unsigned (resp. signed) representation. 4516 ConstantRange 4517 ScalarEvolution::getRange(const SCEV *S, 4518 ScalarEvolution::RangeSignHint SignHint) { 4519 DenseMap<const SCEV *, ConstantRange> &Cache = 4520 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 4521 : SignedRanges; 4522 4523 // See if we've computed this range already. 4524 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 4525 if (I != Cache.end()) 4526 return I->second; 4527 4528 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 4529 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 4530 4531 unsigned BitWidth = getTypeSizeInBits(S->getType()); 4532 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 4533 4534 // If the value has known zeros, the maximum value will have those known zeros 4535 // as well. 4536 uint32_t TZ = GetMinTrailingZeros(S); 4537 if (TZ != 0) { 4538 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 4539 ConservativeResult = 4540 ConstantRange(APInt::getMinValue(BitWidth), 4541 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 4542 else 4543 ConservativeResult = ConstantRange( 4544 APInt::getSignedMinValue(BitWidth), 4545 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 4546 } 4547 4548 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 4549 ConstantRange X = getRange(Add->getOperand(0), SignHint); 4550 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 4551 X = X.add(getRange(Add->getOperand(i), SignHint)); 4552 return setRange(Add, SignHint, ConservativeResult.intersectWith(X)); 4553 } 4554 4555 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 4556 ConstantRange X = getRange(Mul->getOperand(0), SignHint); 4557 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 4558 X = X.multiply(getRange(Mul->getOperand(i), SignHint)); 4559 return setRange(Mul, SignHint, ConservativeResult.intersectWith(X)); 4560 } 4561 4562 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 4563 ConstantRange X = getRange(SMax->getOperand(0), SignHint); 4564 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 4565 X = X.smax(getRange(SMax->getOperand(i), SignHint)); 4566 return setRange(SMax, SignHint, ConservativeResult.intersectWith(X)); 4567 } 4568 4569 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 4570 ConstantRange X = getRange(UMax->getOperand(0), SignHint); 4571 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 4572 X = X.umax(getRange(UMax->getOperand(i), SignHint)); 4573 return setRange(UMax, SignHint, ConservativeResult.intersectWith(X)); 4574 } 4575 4576 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 4577 ConstantRange X = getRange(UDiv->getLHS(), SignHint); 4578 ConstantRange Y = getRange(UDiv->getRHS(), SignHint); 4579 return setRange(UDiv, SignHint, 4580 ConservativeResult.intersectWith(X.udiv(Y))); 4581 } 4582 4583 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 4584 ConstantRange X = getRange(ZExt->getOperand(), SignHint); 4585 return setRange(ZExt, SignHint, 4586 ConservativeResult.intersectWith(X.zeroExtend(BitWidth))); 4587 } 4588 4589 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 4590 ConstantRange X = getRange(SExt->getOperand(), SignHint); 4591 return setRange(SExt, SignHint, 4592 ConservativeResult.intersectWith(X.signExtend(BitWidth))); 4593 } 4594 4595 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 4596 ConstantRange X = getRange(Trunc->getOperand(), SignHint); 4597 return setRange(Trunc, SignHint, 4598 ConservativeResult.intersectWith(X.truncate(BitWidth))); 4599 } 4600 4601 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 4602 // If there's no unsigned wrap, the value will never be less than its 4603 // initial value. 4604 if (AddRec->hasNoUnsignedWrap()) 4605 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart())) 4606 if (!C->getValue()->isZero()) 4607 ConservativeResult = ConservativeResult.intersectWith( 4608 ConstantRange(C->getAPInt(), APInt(BitWidth, 0))); 4609 4610 // If there's no signed wrap, and all the operands have the same sign or 4611 // zero, the value won't ever change sign. 4612 if (AddRec->hasNoSignedWrap()) { 4613 bool AllNonNeg = true; 4614 bool AllNonPos = true; 4615 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 4616 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false; 4617 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false; 4618 } 4619 if (AllNonNeg) 4620 ConservativeResult = ConservativeResult.intersectWith( 4621 ConstantRange(APInt(BitWidth, 0), 4622 APInt::getSignedMinValue(BitWidth))); 4623 else if (AllNonPos) 4624 ConservativeResult = ConservativeResult.intersectWith( 4625 ConstantRange(APInt::getSignedMinValue(BitWidth), 4626 APInt(BitWidth, 1))); 4627 } 4628 4629 // TODO: non-affine addrec 4630 if (AddRec->isAffine()) { 4631 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop()); 4632 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 4633 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 4634 auto RangeFromAffine = getRangeForAffineAR( 4635 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 4636 BitWidth); 4637 if (!RangeFromAffine.isFullSet()) 4638 ConservativeResult = 4639 ConservativeResult.intersectWith(RangeFromAffine); 4640 4641 auto RangeFromFactoring = getRangeViaFactoring( 4642 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 4643 BitWidth); 4644 if (!RangeFromFactoring.isFullSet()) 4645 ConservativeResult = 4646 ConservativeResult.intersectWith(RangeFromFactoring); 4647 } 4648 } 4649 4650 return setRange(AddRec, SignHint, ConservativeResult); 4651 } 4652 4653 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 4654 // Check if the IR explicitly contains !range metadata. 4655 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 4656 if (MDRange.hasValue()) 4657 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue()); 4658 4659 // Split here to avoid paying the compile-time cost of calling both 4660 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted 4661 // if needed. 4662 const DataLayout &DL = getDataLayout(); 4663 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) { 4664 // For a SCEVUnknown, ask ValueTracking. 4665 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0); 4666 computeKnownBits(U->getValue(), Zeros, Ones, DL, 0, &AC, nullptr, &DT); 4667 if (Ones != ~Zeros + 1) 4668 ConservativeResult = 4669 ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1)); 4670 } else { 4671 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED && 4672 "generalize as needed!"); 4673 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 4674 if (NS > 1) 4675 ConservativeResult = ConservativeResult.intersectWith( 4676 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 4677 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1)); 4678 } 4679 4680 return setRange(U, SignHint, ConservativeResult); 4681 } 4682 4683 return setRange(S, SignHint, ConservativeResult); 4684 } 4685 4686 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 4687 const SCEV *Step, 4688 const SCEV *MaxBECount, 4689 unsigned BitWidth) { 4690 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 4691 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 4692 "Precondition!"); 4693 4694 ConstantRange Result(BitWidth, /* isFullSet = */ true); 4695 4696 // Check for overflow. This must be done with ConstantRange arithmetic 4697 // because we could be called from within the ScalarEvolution overflow 4698 // checking code. 4699 4700 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 4701 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount); 4702 ConstantRange ZExtMaxBECountRange = 4703 MaxBECountRange.zextOrTrunc(BitWidth * 2 + 1); 4704 4705 ConstantRange StepSRange = getSignedRange(Step); 4706 ConstantRange SExtStepSRange = StepSRange.sextOrTrunc(BitWidth * 2 + 1); 4707 4708 ConstantRange StartURange = getUnsignedRange(Start); 4709 ConstantRange EndURange = 4710 StartURange.add(MaxBECountRange.multiply(StepSRange)); 4711 4712 // Check for unsigned overflow. 4713 ConstantRange ZExtStartURange = StartURange.zextOrTrunc(BitWidth * 2 + 1); 4714 ConstantRange ZExtEndURange = EndURange.zextOrTrunc(BitWidth * 2 + 1); 4715 if (ZExtStartURange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) == 4716 ZExtEndURange) { 4717 APInt Min = APIntOps::umin(StartURange.getUnsignedMin(), 4718 EndURange.getUnsignedMin()); 4719 APInt Max = APIntOps::umax(StartURange.getUnsignedMax(), 4720 EndURange.getUnsignedMax()); 4721 bool IsFullRange = Min.isMinValue() && Max.isMaxValue(); 4722 if (!IsFullRange) 4723 Result = 4724 Result.intersectWith(ConstantRange(Min, Max + 1)); 4725 } 4726 4727 ConstantRange StartSRange = getSignedRange(Start); 4728 ConstantRange EndSRange = 4729 StartSRange.add(MaxBECountRange.multiply(StepSRange)); 4730 4731 // Check for signed overflow. This must be done with ConstantRange 4732 // arithmetic because we could be called from within the ScalarEvolution 4733 // overflow checking code. 4734 ConstantRange SExtStartSRange = StartSRange.sextOrTrunc(BitWidth * 2 + 1); 4735 ConstantRange SExtEndSRange = EndSRange.sextOrTrunc(BitWidth * 2 + 1); 4736 if (SExtStartSRange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) == 4737 SExtEndSRange) { 4738 APInt Min = 4739 APIntOps::smin(StartSRange.getSignedMin(), EndSRange.getSignedMin()); 4740 APInt Max = 4741 APIntOps::smax(StartSRange.getSignedMax(), EndSRange.getSignedMax()); 4742 bool IsFullRange = Min.isMinSignedValue() && Max.isMaxSignedValue(); 4743 if (!IsFullRange) 4744 Result = 4745 Result.intersectWith(ConstantRange(Min, Max + 1)); 4746 } 4747 4748 return Result; 4749 } 4750 4751 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 4752 const SCEV *Step, 4753 const SCEV *MaxBECount, 4754 unsigned BitWidth) { 4755 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 4756 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 4757 4758 struct SelectPattern { 4759 Value *Condition = nullptr; 4760 APInt TrueValue; 4761 APInt FalseValue; 4762 4763 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 4764 const SCEV *S) { 4765 Optional<unsigned> CastOp; 4766 APInt Offset(BitWidth, 0); 4767 4768 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 4769 "Should be!"); 4770 4771 // Peel off a constant offset: 4772 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 4773 // In the future we could consider being smarter here and handle 4774 // {Start+Step,+,Step} too. 4775 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 4776 return; 4777 4778 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 4779 S = SA->getOperand(1); 4780 } 4781 4782 // Peel off a cast operation 4783 if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) { 4784 CastOp = SCast->getSCEVType(); 4785 S = SCast->getOperand(); 4786 } 4787 4788 using namespace llvm::PatternMatch; 4789 4790 auto *SU = dyn_cast<SCEVUnknown>(S); 4791 const APInt *TrueVal, *FalseVal; 4792 if (!SU || 4793 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 4794 m_APInt(FalseVal)))) { 4795 Condition = nullptr; 4796 return; 4797 } 4798 4799 TrueValue = *TrueVal; 4800 FalseValue = *FalseVal; 4801 4802 // Re-apply the cast we peeled off earlier 4803 if (CastOp.hasValue()) 4804 switch (*CastOp) { 4805 default: 4806 llvm_unreachable("Unknown SCEV cast type!"); 4807 4808 case scTruncate: 4809 TrueValue = TrueValue.trunc(BitWidth); 4810 FalseValue = FalseValue.trunc(BitWidth); 4811 break; 4812 case scZeroExtend: 4813 TrueValue = TrueValue.zext(BitWidth); 4814 FalseValue = FalseValue.zext(BitWidth); 4815 break; 4816 case scSignExtend: 4817 TrueValue = TrueValue.sext(BitWidth); 4818 FalseValue = FalseValue.sext(BitWidth); 4819 break; 4820 } 4821 4822 // Re-apply the constant offset we peeled off earlier 4823 TrueValue += Offset; 4824 FalseValue += Offset; 4825 } 4826 4827 bool isRecognized() { return Condition != nullptr; } 4828 }; 4829 4830 SelectPattern StartPattern(*this, BitWidth, Start); 4831 if (!StartPattern.isRecognized()) 4832 return ConstantRange(BitWidth, /* isFullSet = */ true); 4833 4834 SelectPattern StepPattern(*this, BitWidth, Step); 4835 if (!StepPattern.isRecognized()) 4836 return ConstantRange(BitWidth, /* isFullSet = */ true); 4837 4838 if (StartPattern.Condition != StepPattern.Condition) { 4839 // We don't handle this case today; but we could, by considering four 4840 // possibilities below instead of two. I'm not sure if there are cases where 4841 // that will help over what getRange already does, though. 4842 return ConstantRange(BitWidth, /* isFullSet = */ true); 4843 } 4844 4845 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 4846 // construct arbitrary general SCEV expressions here. This function is called 4847 // from deep in the call stack, and calling getSCEV (on a sext instruction, 4848 // say) can end up caching a suboptimal value. 4849 4850 // FIXME: without the explicit `this` receiver below, MSVC errors out with 4851 // C2352 and C2512 (otherwise it isn't needed). 4852 4853 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 4854 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 4855 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 4856 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 4857 4858 ConstantRange TrueRange = 4859 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 4860 ConstantRange FalseRange = 4861 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 4862 4863 return TrueRange.unionWith(FalseRange); 4864 } 4865 4866 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 4867 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 4868 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 4869 4870 // Return early if there are no flags to propagate to the SCEV. 4871 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 4872 if (BinOp->hasNoUnsignedWrap()) 4873 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 4874 if (BinOp->hasNoSignedWrap()) 4875 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 4876 if (Flags == SCEV::FlagAnyWrap) 4877 return SCEV::FlagAnyWrap; 4878 4879 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 4880 } 4881 4882 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 4883 // Here we check that I is in the header of the innermost loop containing I, 4884 // since we only deal with instructions in the loop header. The actual loop we 4885 // need to check later will come from an add recurrence, but getting that 4886 // requires computing the SCEV of the operands, which can be expensive. This 4887 // check we can do cheaply to rule out some cases early. 4888 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent()); 4889 if (InnermostContainingLoop == nullptr || 4890 InnermostContainingLoop->getHeader() != I->getParent()) 4891 return false; 4892 4893 // Only proceed if we can prove that I does not yield poison. 4894 if (!isKnownNotFullPoison(I)) return false; 4895 4896 // At this point we know that if I is executed, then it does not wrap 4897 // according to at least one of NSW or NUW. If I is not executed, then we do 4898 // not know if the calculation that I represents would wrap. Multiple 4899 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 4900 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 4901 // derived from other instructions that map to the same SCEV. We cannot make 4902 // that guarantee for cases where I is not executed. So we need to find the 4903 // loop that I is considered in relation to and prove that I is executed for 4904 // every iteration of that loop. That implies that the value that I 4905 // calculates does not wrap anywhere in the loop, so then we can apply the 4906 // flags to the SCEV. 4907 // 4908 // We check isLoopInvariant to disambiguate in case we are adding recurrences 4909 // from different loops, so that we know which loop to prove that I is 4910 // executed in. 4911 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) { 4912 // I could be an extractvalue from a call to an overflow intrinsic. 4913 // TODO: We can do better here in some cases. 4914 if (!isSCEVable(I->getOperand(OpIndex)->getType())) 4915 return false; 4916 const SCEV *Op = getSCEV(I->getOperand(OpIndex)); 4917 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 4918 bool AllOtherOpsLoopInvariant = true; 4919 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands(); 4920 ++OtherOpIndex) { 4921 if (OtherOpIndex != OpIndex) { 4922 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex)); 4923 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) { 4924 AllOtherOpsLoopInvariant = false; 4925 break; 4926 } 4927 } 4928 } 4929 if (AllOtherOpsLoopInvariant && 4930 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop())) 4931 return true; 4932 } 4933 } 4934 return false; 4935 } 4936 4937 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 4938 // If we know that \c I can never be poison period, then that's enough. 4939 if (isSCEVExprNeverPoison(I)) 4940 return true; 4941 4942 // For an add recurrence specifically, we assume that infinite loops without 4943 // side effects are undefined behavior, and then reason as follows: 4944 // 4945 // If the add recurrence is poison in any iteration, it is poison on all 4946 // future iterations (since incrementing poison yields poison). If the result 4947 // of the add recurrence is fed into the loop latch condition and the loop 4948 // does not contain any throws or exiting blocks other than the latch, we now 4949 // have the ability to "choose" whether the backedge is taken or not (by 4950 // choosing a sufficiently evil value for the poison feeding into the branch) 4951 // for every iteration including and after the one in which \p I first became 4952 // poison. There are two possibilities (let's call the iteration in which \p 4953 // I first became poison as K): 4954 // 4955 // 1. In the set of iterations including and after K, the loop body executes 4956 // no side effects. In this case executing the backege an infinte number 4957 // of times will yield undefined behavior. 4958 // 4959 // 2. In the set of iterations including and after K, the loop body executes 4960 // at least one side effect. In this case, that specific instance of side 4961 // effect is control dependent on poison, which also yields undefined 4962 // behavior. 4963 4964 auto *ExitingBB = L->getExitingBlock(); 4965 auto *LatchBB = L->getLoopLatch(); 4966 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 4967 return false; 4968 4969 SmallPtrSet<const Instruction *, 16> Pushed; 4970 SmallVector<const Instruction *, 8> PoisonStack; 4971 4972 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 4973 // things that are known to be fully poison under that assumption go on the 4974 // PoisonStack. 4975 Pushed.insert(I); 4976 PoisonStack.push_back(I); 4977 4978 bool LatchControlDependentOnPoison = false; 4979 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 4980 const Instruction *Poison = PoisonStack.pop_back_val(); 4981 4982 for (auto *PoisonUser : Poison->users()) { 4983 if (propagatesFullPoison(cast<Instruction>(PoisonUser))) { 4984 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 4985 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 4986 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 4987 assert(BI->isConditional() && "Only possibility!"); 4988 if (BI->getParent() == LatchBB) { 4989 LatchControlDependentOnPoison = true; 4990 break; 4991 } 4992 } 4993 } 4994 } 4995 4996 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 4997 } 4998 4999 ScalarEvolution::LoopProperties 5000 ScalarEvolution::getLoopProperties(const Loop *L) { 5001 typedef ScalarEvolution::LoopProperties LoopProperties; 5002 5003 auto Itr = LoopPropertiesCache.find(L); 5004 if (Itr == LoopPropertiesCache.end()) { 5005 auto HasSideEffects = [](Instruction *I) { 5006 if (auto *SI = dyn_cast<StoreInst>(I)) 5007 return !SI->isSimple(); 5008 5009 return I->mayHaveSideEffects(); 5010 }; 5011 5012 LoopProperties LP = {/* HasNoAbnormalExits */ true, 5013 /*HasNoSideEffects*/ true}; 5014 5015 for (auto *BB : L->getBlocks()) 5016 for (auto &I : *BB) { 5017 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 5018 LP.HasNoAbnormalExits = false; 5019 if (HasSideEffects(&I)) 5020 LP.HasNoSideEffects = false; 5021 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 5022 break; // We're already as pessimistic as we can get. 5023 } 5024 5025 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 5026 assert(InsertPair.second && "We just checked!"); 5027 Itr = InsertPair.first; 5028 } 5029 5030 return Itr->second; 5031 } 5032 5033 const SCEV *ScalarEvolution::createSCEV(Value *V) { 5034 if (!isSCEVable(V->getType())) 5035 return getUnknown(V); 5036 5037 if (Instruction *I = dyn_cast<Instruction>(V)) { 5038 // Don't attempt to analyze instructions in blocks that aren't 5039 // reachable. Such instructions don't matter, and they aren't required 5040 // to obey basic rules for definitions dominating uses which this 5041 // analysis depends on. 5042 if (!DT.isReachableFromEntry(I->getParent())) 5043 return getUnknown(V); 5044 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 5045 return getConstant(CI); 5046 else if (isa<ConstantPointerNull>(V)) 5047 return getZero(V->getType()); 5048 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 5049 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 5050 else if (!isa<ConstantExpr>(V)) 5051 return getUnknown(V); 5052 5053 Operator *U = cast<Operator>(V); 5054 if (auto BO = MatchBinaryOp(U, DT)) { 5055 switch (BO->Opcode) { 5056 case Instruction::Add: { 5057 // The simple thing to do would be to just call getSCEV on both operands 5058 // and call getAddExpr with the result. However if we're looking at a 5059 // bunch of things all added together, this can be quite inefficient, 5060 // because it leads to N-1 getAddExpr calls for N ultimate operands. 5061 // Instead, gather up all the operands and make a single getAddExpr call. 5062 // LLVM IR canonical form means we need only traverse the left operands. 5063 SmallVector<const SCEV *, 4> AddOps; 5064 do { 5065 if (BO->Op) { 5066 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 5067 AddOps.push_back(OpSCEV); 5068 break; 5069 } 5070 5071 // If a NUW or NSW flag can be applied to the SCEV for this 5072 // addition, then compute the SCEV for this addition by itself 5073 // with a separate call to getAddExpr. We need to do that 5074 // instead of pushing the operands of the addition onto AddOps, 5075 // since the flags are only known to apply to this particular 5076 // addition - they may not apply to other additions that can be 5077 // formed with operands from AddOps. 5078 const SCEV *RHS = getSCEV(BO->RHS); 5079 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 5080 if (Flags != SCEV::FlagAnyWrap) { 5081 const SCEV *LHS = getSCEV(BO->LHS); 5082 if (BO->Opcode == Instruction::Sub) 5083 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 5084 else 5085 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 5086 break; 5087 } 5088 } 5089 5090 if (BO->Opcode == Instruction::Sub) 5091 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 5092 else 5093 AddOps.push_back(getSCEV(BO->RHS)); 5094 5095 auto NewBO = MatchBinaryOp(BO->LHS, DT); 5096 if (!NewBO || (NewBO->Opcode != Instruction::Add && 5097 NewBO->Opcode != Instruction::Sub)) { 5098 AddOps.push_back(getSCEV(BO->LHS)); 5099 break; 5100 } 5101 BO = NewBO; 5102 } while (true); 5103 5104 return getAddExpr(AddOps); 5105 } 5106 5107 case Instruction::Mul: { 5108 SmallVector<const SCEV *, 4> MulOps; 5109 do { 5110 if (BO->Op) { 5111 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 5112 MulOps.push_back(OpSCEV); 5113 break; 5114 } 5115 5116 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 5117 if (Flags != SCEV::FlagAnyWrap) { 5118 MulOps.push_back( 5119 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 5120 break; 5121 } 5122 } 5123 5124 MulOps.push_back(getSCEV(BO->RHS)); 5125 auto NewBO = MatchBinaryOp(BO->LHS, DT); 5126 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 5127 MulOps.push_back(getSCEV(BO->LHS)); 5128 break; 5129 } 5130 BO = NewBO; 5131 } while (true); 5132 5133 return getMulExpr(MulOps); 5134 } 5135 case Instruction::UDiv: 5136 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 5137 case Instruction::Sub: { 5138 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5139 if (BO->Op) 5140 Flags = getNoWrapFlagsFromUB(BO->Op); 5141 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 5142 } 5143 case Instruction::And: 5144 // For an expression like x&255 that merely masks off the high bits, 5145 // use zext(trunc(x)) as the SCEV expression. 5146 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 5147 if (CI->isNullValue()) 5148 return getSCEV(BO->RHS); 5149 if (CI->isAllOnesValue()) 5150 return getSCEV(BO->LHS); 5151 const APInt &A = CI->getValue(); 5152 5153 // Instcombine's ShrinkDemandedConstant may strip bits out of 5154 // constants, obscuring what would otherwise be a low-bits mask. 5155 // Use computeKnownBits to compute what ShrinkDemandedConstant 5156 // knew about to reconstruct a low-bits mask value. 5157 unsigned LZ = A.countLeadingZeros(); 5158 unsigned TZ = A.countTrailingZeros(); 5159 unsigned BitWidth = A.getBitWidth(); 5160 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0); 5161 computeKnownBits(BO->LHS, KnownZero, KnownOne, getDataLayout(), 5162 0, &AC, nullptr, &DT); 5163 5164 APInt EffectiveMask = 5165 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 5166 if ((LZ != 0 || TZ != 0) && !((~A & ~KnownZero) & EffectiveMask)) { 5167 const SCEV *MulCount = getConstant(ConstantInt::get( 5168 getContext(), APInt::getOneBitSet(BitWidth, TZ))); 5169 return getMulExpr( 5170 getZeroExtendExpr( 5171 getTruncateExpr( 5172 getUDivExactExpr(getSCEV(BO->LHS), MulCount), 5173 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 5174 BO->LHS->getType()), 5175 MulCount); 5176 } 5177 } 5178 break; 5179 5180 case Instruction::Or: 5181 // If the RHS of the Or is a constant, we may have something like: 5182 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 5183 // optimizations will transparently handle this case. 5184 // 5185 // In order for this transformation to be safe, the LHS must be of the 5186 // form X*(2^n) and the Or constant must be less than 2^n. 5187 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 5188 const SCEV *LHS = getSCEV(BO->LHS); 5189 const APInt &CIVal = CI->getValue(); 5190 if (GetMinTrailingZeros(LHS) >= 5191 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 5192 // Build a plain add SCEV. 5193 const SCEV *S = getAddExpr(LHS, getSCEV(CI)); 5194 // If the LHS of the add was an addrec and it has no-wrap flags, 5195 // transfer the no-wrap flags, since an or won't introduce a wrap. 5196 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) { 5197 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS); 5198 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags( 5199 OldAR->getNoWrapFlags()); 5200 } 5201 return S; 5202 } 5203 } 5204 break; 5205 5206 case Instruction::Xor: 5207 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 5208 // If the RHS of xor is -1, then this is a not operation. 5209 if (CI->isAllOnesValue()) 5210 return getNotSCEV(getSCEV(BO->LHS)); 5211 5212 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 5213 // This is a variant of the check for xor with -1, and it handles 5214 // the case where instcombine has trimmed non-demanded bits out 5215 // of an xor with -1. 5216 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 5217 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 5218 if (LBO->getOpcode() == Instruction::And && 5219 LCI->getValue() == CI->getValue()) 5220 if (const SCEVZeroExtendExpr *Z = 5221 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 5222 Type *UTy = BO->LHS->getType(); 5223 const SCEV *Z0 = Z->getOperand(); 5224 Type *Z0Ty = Z0->getType(); 5225 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 5226 5227 // If C is a low-bits mask, the zero extend is serving to 5228 // mask off the high bits. Complement the operand and 5229 // re-apply the zext. 5230 if (APIntOps::isMask(Z0TySize, CI->getValue())) 5231 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 5232 5233 // If C is a single bit, it may be in the sign-bit position 5234 // before the zero-extend. In this case, represent the xor 5235 // using an add, which is equivalent, and re-apply the zext. 5236 APInt Trunc = CI->getValue().trunc(Z0TySize); 5237 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 5238 Trunc.isSignBit()) 5239 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 5240 UTy); 5241 } 5242 } 5243 break; 5244 5245 case Instruction::Shl: 5246 // Turn shift left of a constant amount into a multiply. 5247 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 5248 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 5249 5250 // If the shift count is not less than the bitwidth, the result of 5251 // the shift is undefined. Don't try to analyze it, because the 5252 // resolution chosen here may differ from the resolution chosen in 5253 // other parts of the compiler. 5254 if (SA->getValue().uge(BitWidth)) 5255 break; 5256 5257 // It is currently not resolved how to interpret NSW for left 5258 // shift by BitWidth - 1, so we avoid applying flags in that 5259 // case. Remove this check (or this comment) once the situation 5260 // is resolved. See 5261 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html 5262 // and http://reviews.llvm.org/D8890 . 5263 auto Flags = SCEV::FlagAnyWrap; 5264 if (BO->Op && SA->getValue().ult(BitWidth - 1)) 5265 Flags = getNoWrapFlagsFromUB(BO->Op); 5266 5267 Constant *X = ConstantInt::get(getContext(), 5268 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 5269 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 5270 } 5271 break; 5272 5273 case Instruction::AShr: 5274 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression. 5275 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) 5276 if (Operator *L = dyn_cast<Operator>(BO->LHS)) 5277 if (L->getOpcode() == Instruction::Shl && 5278 L->getOperand(1) == BO->RHS) { 5279 uint64_t BitWidth = getTypeSizeInBits(BO->LHS->getType()); 5280 5281 // If the shift count is not less than the bitwidth, the result of 5282 // the shift is undefined. Don't try to analyze it, because the 5283 // resolution chosen here may differ from the resolution chosen in 5284 // other parts of the compiler. 5285 if (CI->getValue().uge(BitWidth)) 5286 break; 5287 5288 uint64_t Amt = BitWidth - CI->getZExtValue(); 5289 if (Amt == BitWidth) 5290 return getSCEV(L->getOperand(0)); // shift by zero --> noop 5291 return getSignExtendExpr( 5292 getTruncateExpr(getSCEV(L->getOperand(0)), 5293 IntegerType::get(getContext(), Amt)), 5294 BO->LHS->getType()); 5295 } 5296 break; 5297 } 5298 } 5299 5300 switch (U->getOpcode()) { 5301 case Instruction::Trunc: 5302 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 5303 5304 case Instruction::ZExt: 5305 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 5306 5307 case Instruction::SExt: 5308 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 5309 5310 case Instruction::BitCast: 5311 // BitCasts are no-op casts so we just eliminate the cast. 5312 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 5313 return getSCEV(U->getOperand(0)); 5314 break; 5315 5316 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can 5317 // lead to pointer expressions which cannot safely be expanded to GEPs, 5318 // because ScalarEvolution doesn't respect the GEP aliasing rules when 5319 // simplifying integer expressions. 5320 5321 case Instruction::GetElementPtr: 5322 return createNodeForGEP(cast<GEPOperator>(U)); 5323 5324 case Instruction::PHI: 5325 return createNodeForPHI(cast<PHINode>(U)); 5326 5327 case Instruction::Select: 5328 // U can also be a select constant expr, which let fall through. Since 5329 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 5330 // constant expressions cannot have instructions as operands, we'd have 5331 // returned getUnknown for a select constant expressions anyway. 5332 if (isa<Instruction>(U)) 5333 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 5334 U->getOperand(1), U->getOperand(2)); 5335 break; 5336 5337 case Instruction::Call: 5338 case Instruction::Invoke: 5339 if (Value *RV = CallSite(U).getReturnedArgOperand()) 5340 return getSCEV(RV); 5341 break; 5342 } 5343 5344 return getUnknown(V); 5345 } 5346 5347 5348 5349 //===----------------------------------------------------------------------===// 5350 // Iteration Count Computation Code 5351 // 5352 5353 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 5354 if (!ExitCount) 5355 return 0; 5356 5357 ConstantInt *ExitConst = ExitCount->getValue(); 5358 5359 // Guard against huge trip counts. 5360 if (ExitConst->getValue().getActiveBits() > 32) 5361 return 0; 5362 5363 // In case of integer overflow, this returns 0, which is correct. 5364 return ((unsigned)ExitConst->getZExtValue()) + 1; 5365 } 5366 5367 unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L) { 5368 if (BasicBlock *ExitingBB = L->getExitingBlock()) 5369 return getSmallConstantTripCount(L, ExitingBB); 5370 5371 // No trip count information for multiple exits. 5372 return 0; 5373 } 5374 5375 unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L, 5376 BasicBlock *ExitingBlock) { 5377 assert(ExitingBlock && "Must pass a non-null exiting block!"); 5378 assert(L->isLoopExiting(ExitingBlock) && 5379 "Exiting block must actually branch out of the loop!"); 5380 const SCEVConstant *ExitCount = 5381 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 5382 return getConstantTripCount(ExitCount); 5383 } 5384 5385 unsigned ScalarEvolution::getSmallConstantMaxTripCount(Loop *L) { 5386 const auto *MaxExitCount = 5387 dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L)); 5388 return getConstantTripCount(MaxExitCount); 5389 } 5390 5391 unsigned ScalarEvolution::getSmallConstantTripMultiple(Loop *L) { 5392 if (BasicBlock *ExitingBB = L->getExitingBlock()) 5393 return getSmallConstantTripMultiple(L, ExitingBB); 5394 5395 // No trip multiple information for multiple exits. 5396 return 0; 5397 } 5398 5399 /// Returns the largest constant divisor of the trip count of this loop as a 5400 /// normal unsigned value, if possible. This means that the actual trip count is 5401 /// always a multiple of the returned value (don't forget the trip count could 5402 /// very well be zero as well!). 5403 /// 5404 /// Returns 1 if the trip count is unknown or not guaranteed to be the 5405 /// multiple of a constant (which is also the case if the trip count is simply 5406 /// constant, use getSmallConstantTripCount for that case), Will also return 1 5407 /// if the trip count is very large (>= 2^32). 5408 /// 5409 /// As explained in the comments for getSmallConstantTripCount, this assumes 5410 /// that control exits the loop via ExitingBlock. 5411 unsigned 5412 ScalarEvolution::getSmallConstantTripMultiple(Loop *L, 5413 BasicBlock *ExitingBlock) { 5414 assert(ExitingBlock && "Must pass a non-null exiting block!"); 5415 assert(L->isLoopExiting(ExitingBlock) && 5416 "Exiting block must actually branch out of the loop!"); 5417 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 5418 if (ExitCount == getCouldNotCompute()) 5419 return 1; 5420 5421 // Get the trip count from the BE count by adding 1. 5422 const SCEV *TCMul = getAddExpr(ExitCount, getOne(ExitCount->getType())); 5423 // FIXME: SCEV distributes multiplication as V1*C1 + V2*C1. We could attempt 5424 // to factor simple cases. 5425 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(TCMul)) 5426 TCMul = Mul->getOperand(0); 5427 5428 const SCEVConstant *MulC = dyn_cast<SCEVConstant>(TCMul); 5429 if (!MulC) 5430 return 1; 5431 5432 ConstantInt *Result = MulC->getValue(); 5433 5434 // Guard against huge trip counts (this requires checking 5435 // for zero to handle the case where the trip count == -1 and the 5436 // addition wraps). 5437 if (!Result || Result->getValue().getActiveBits() > 32 || 5438 Result->getValue().getActiveBits() == 0) 5439 return 1; 5440 5441 return (unsigned)Result->getZExtValue(); 5442 } 5443 5444 /// Get the expression for the number of loop iterations for which this loop is 5445 /// guaranteed not to exit via ExitingBlock. Otherwise return 5446 /// SCEVCouldNotCompute. 5447 const SCEV *ScalarEvolution::getExitCount(Loop *L, BasicBlock *ExitingBlock) { 5448 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 5449 } 5450 5451 const SCEV * 5452 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 5453 SCEVUnionPredicate &Preds) { 5454 return getPredicatedBackedgeTakenInfo(L).getExact(this, &Preds); 5455 } 5456 5457 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) { 5458 return getBackedgeTakenInfo(L).getExact(this); 5459 } 5460 5461 /// Similar to getBackedgeTakenCount, except return the least SCEV value that is 5462 /// known never to be less than the actual backedge taken count. 5463 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) { 5464 return getBackedgeTakenInfo(L).getMax(this); 5465 } 5466 5467 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 5468 return getBackedgeTakenInfo(L).isMaxOrZero(this); 5469 } 5470 5471 /// Push PHI nodes in the header of the given loop onto the given Worklist. 5472 static void 5473 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { 5474 BasicBlock *Header = L->getHeader(); 5475 5476 // Push all Loop-header PHIs onto the Worklist stack. 5477 for (BasicBlock::iterator I = Header->begin(); 5478 PHINode *PN = dyn_cast<PHINode>(I); ++I) 5479 Worklist.push_back(PN); 5480 } 5481 5482 const ScalarEvolution::BackedgeTakenInfo & 5483 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 5484 auto &BTI = getBackedgeTakenInfo(L); 5485 if (BTI.hasFullInfo()) 5486 return BTI; 5487 5488 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 5489 5490 if (!Pair.second) 5491 return Pair.first->second; 5492 5493 BackedgeTakenInfo Result = 5494 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 5495 5496 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 5497 } 5498 5499 const ScalarEvolution::BackedgeTakenInfo & 5500 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 5501 // Initially insert an invalid entry for this loop. If the insertion 5502 // succeeds, proceed to actually compute a backedge-taken count and 5503 // update the value. The temporary CouldNotCompute value tells SCEV 5504 // code elsewhere that it shouldn't attempt to request a new 5505 // backedge-taken count, which could result in infinite recursion. 5506 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 5507 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 5508 if (!Pair.second) 5509 return Pair.first->second; 5510 5511 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 5512 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 5513 // must be cleared in this scope. 5514 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 5515 5516 if (Result.getExact(this) != getCouldNotCompute()) { 5517 assert(isLoopInvariant(Result.getExact(this), L) && 5518 isLoopInvariant(Result.getMax(this), L) && 5519 "Computed backedge-taken count isn't loop invariant for loop!"); 5520 ++NumTripCountsComputed; 5521 } 5522 else if (Result.getMax(this) == getCouldNotCompute() && 5523 isa<PHINode>(L->getHeader()->begin())) { 5524 // Only count loops that have phi nodes as not being computable. 5525 ++NumTripCountsNotComputed; 5526 } 5527 5528 // Now that we know more about the trip count for this loop, forget any 5529 // existing SCEV values for PHI nodes in this loop since they are only 5530 // conservative estimates made without the benefit of trip count 5531 // information. This is similar to the code in forgetLoop, except that 5532 // it handles SCEVUnknown PHI nodes specially. 5533 if (Result.hasAnyInfo()) { 5534 SmallVector<Instruction *, 16> Worklist; 5535 PushLoopPHIs(L, Worklist); 5536 5537 SmallPtrSet<Instruction *, 8> Visited; 5538 while (!Worklist.empty()) { 5539 Instruction *I = Worklist.pop_back_val(); 5540 if (!Visited.insert(I).second) 5541 continue; 5542 5543 ValueExprMapType::iterator It = 5544 ValueExprMap.find_as(static_cast<Value *>(I)); 5545 if (It != ValueExprMap.end()) { 5546 const SCEV *Old = It->second; 5547 5548 // SCEVUnknown for a PHI either means that it has an unrecognized 5549 // structure, or it's a PHI that's in the progress of being computed 5550 // by createNodeForPHI. In the former case, additional loop trip 5551 // count information isn't going to change anything. In the later 5552 // case, createNodeForPHI will perform the necessary updates on its 5553 // own when it gets to that point. 5554 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 5555 eraseValueFromMap(It->first); 5556 forgetMemoizedResults(Old); 5557 } 5558 if (PHINode *PN = dyn_cast<PHINode>(I)) 5559 ConstantEvolutionLoopExitValue.erase(PN); 5560 } 5561 5562 PushDefUseChildren(I, Worklist); 5563 } 5564 } 5565 5566 // Re-lookup the insert position, since the call to 5567 // computeBackedgeTakenCount above could result in a 5568 // recusive call to getBackedgeTakenInfo (on a different 5569 // loop), which would invalidate the iterator computed 5570 // earlier. 5571 return BackedgeTakenCounts.find(L)->second = std::move(Result); 5572 } 5573 5574 void ScalarEvolution::forgetLoop(const Loop *L) { 5575 // Drop any stored trip count value. 5576 auto RemoveLoopFromBackedgeMap = 5577 [L](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 5578 auto BTCPos = Map.find(L); 5579 if (BTCPos != Map.end()) { 5580 BTCPos->second.clear(); 5581 Map.erase(BTCPos); 5582 } 5583 }; 5584 5585 RemoveLoopFromBackedgeMap(BackedgeTakenCounts); 5586 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts); 5587 5588 // Drop information about expressions based on loop-header PHIs. 5589 SmallVector<Instruction *, 16> Worklist; 5590 PushLoopPHIs(L, Worklist); 5591 5592 SmallPtrSet<Instruction *, 8> Visited; 5593 while (!Worklist.empty()) { 5594 Instruction *I = Worklist.pop_back_val(); 5595 if (!Visited.insert(I).second) 5596 continue; 5597 5598 ValueExprMapType::iterator It = 5599 ValueExprMap.find_as(static_cast<Value *>(I)); 5600 if (It != ValueExprMap.end()) { 5601 eraseValueFromMap(It->first); 5602 forgetMemoizedResults(It->second); 5603 if (PHINode *PN = dyn_cast<PHINode>(I)) 5604 ConstantEvolutionLoopExitValue.erase(PN); 5605 } 5606 5607 PushDefUseChildren(I, Worklist); 5608 } 5609 5610 // Forget all contained loops too, to avoid dangling entries in the 5611 // ValuesAtScopes map. 5612 for (Loop *I : *L) 5613 forgetLoop(I); 5614 5615 LoopPropertiesCache.erase(L); 5616 } 5617 5618 void ScalarEvolution::forgetValue(Value *V) { 5619 Instruction *I = dyn_cast<Instruction>(V); 5620 if (!I) return; 5621 5622 // Drop information about expressions based on loop-header PHIs. 5623 SmallVector<Instruction *, 16> Worklist; 5624 Worklist.push_back(I); 5625 5626 SmallPtrSet<Instruction *, 8> Visited; 5627 while (!Worklist.empty()) { 5628 I = Worklist.pop_back_val(); 5629 if (!Visited.insert(I).second) 5630 continue; 5631 5632 ValueExprMapType::iterator It = 5633 ValueExprMap.find_as(static_cast<Value *>(I)); 5634 if (It != ValueExprMap.end()) { 5635 eraseValueFromMap(It->first); 5636 forgetMemoizedResults(It->second); 5637 if (PHINode *PN = dyn_cast<PHINode>(I)) 5638 ConstantEvolutionLoopExitValue.erase(PN); 5639 } 5640 5641 PushDefUseChildren(I, Worklist); 5642 } 5643 } 5644 5645 /// Get the exact loop backedge taken count considering all loop exits. A 5646 /// computable result can only be returned for loops with a single exit. 5647 /// Returning the minimum taken count among all exits is incorrect because one 5648 /// of the loop's exit limit's may have been skipped. howFarToZero assumes that 5649 /// the limit of each loop test is never skipped. This is a valid assumption as 5650 /// long as the loop exits via that test. For precise results, it is the 5651 /// caller's responsibility to specify the relevant loop exit using 5652 /// getExact(ExitingBlock, SE). 5653 const SCEV * 5654 ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE, 5655 SCEVUnionPredicate *Preds) const { 5656 // If any exits were not computable, the loop is not computable. 5657 if (!isComplete() || ExitNotTaken.empty()) 5658 return SE->getCouldNotCompute(); 5659 5660 const SCEV *BECount = nullptr; 5661 for (auto &ENT : ExitNotTaken) { 5662 assert(ENT.ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV"); 5663 5664 if (!BECount) 5665 BECount = ENT.ExactNotTaken; 5666 else if (BECount != ENT.ExactNotTaken) 5667 return SE->getCouldNotCompute(); 5668 if (Preds && !ENT.hasAlwaysTruePredicate()) 5669 Preds->add(ENT.Predicate.get()); 5670 5671 assert((Preds || ENT.hasAlwaysTruePredicate()) && 5672 "Predicate should be always true!"); 5673 } 5674 5675 assert(BECount && "Invalid not taken count for loop exit"); 5676 return BECount; 5677 } 5678 5679 /// Get the exact not taken count for this loop exit. 5680 const SCEV * 5681 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock, 5682 ScalarEvolution *SE) const { 5683 for (auto &ENT : ExitNotTaken) 5684 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 5685 return ENT.ExactNotTaken; 5686 5687 return SE->getCouldNotCompute(); 5688 } 5689 5690 /// getMax - Get the max backedge taken count for the loop. 5691 const SCEV * 5692 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const { 5693 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 5694 return !ENT.hasAlwaysTruePredicate(); 5695 }; 5696 5697 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax()) 5698 return SE->getCouldNotCompute(); 5699 5700 return getMax(); 5701 } 5702 5703 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const { 5704 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 5705 return !ENT.hasAlwaysTruePredicate(); 5706 }; 5707 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 5708 } 5709 5710 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S, 5711 ScalarEvolution *SE) const { 5712 if (getMax() && getMax() != SE->getCouldNotCompute() && 5713 SE->hasOperand(getMax(), S)) 5714 return true; 5715 5716 for (auto &ENT : ExitNotTaken) 5717 if (ENT.ExactNotTaken != SE->getCouldNotCompute() && 5718 SE->hasOperand(ENT.ExactNotTaken, S)) 5719 return true; 5720 5721 return false; 5722 } 5723 5724 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 5725 /// computable exit into a persistent ExitNotTakenInfo array. 5726 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 5727 SmallVectorImpl<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> 5728 &&ExitCounts, 5729 bool Complete, const SCEV *MaxCount, bool MaxOrZero) 5730 : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) { 5731 typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo; 5732 ExitNotTaken.reserve(ExitCounts.size()); 5733 std::transform( 5734 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 5735 [&](const EdgeExitInfo &EEI) { 5736 BasicBlock *ExitBB = EEI.first; 5737 const ExitLimit &EL = EEI.second; 5738 if (EL.Predicates.empty()) 5739 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr); 5740 5741 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); 5742 for (auto *Pred : EL.Predicates) 5743 Predicate->add(Pred); 5744 5745 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate)); 5746 }); 5747 } 5748 5749 /// Invalidate this result and free the ExitNotTakenInfo array. 5750 void ScalarEvolution::BackedgeTakenInfo::clear() { 5751 ExitNotTaken.clear(); 5752 } 5753 5754 /// Compute the number of times the backedge of the specified loop will execute. 5755 ScalarEvolution::BackedgeTakenInfo 5756 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 5757 bool AllowPredicates) { 5758 SmallVector<BasicBlock *, 8> ExitingBlocks; 5759 L->getExitingBlocks(ExitingBlocks); 5760 5761 typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo; 5762 5763 SmallVector<EdgeExitInfo, 4> ExitCounts; 5764 bool CouldComputeBECount = true; 5765 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 5766 const SCEV *MustExitMaxBECount = nullptr; 5767 const SCEV *MayExitMaxBECount = nullptr; 5768 bool MustExitMaxOrZero = false; 5769 5770 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 5771 // and compute maxBECount. 5772 // Do a union of all the predicates here. 5773 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 5774 BasicBlock *ExitBB = ExitingBlocks[i]; 5775 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 5776 5777 assert((AllowPredicates || EL.Predicates.empty()) && 5778 "Predicated exit limit when predicates are not allowed!"); 5779 5780 // 1. For each exit that can be computed, add an entry to ExitCounts. 5781 // CouldComputeBECount is true only if all exits can be computed. 5782 if (EL.ExactNotTaken == getCouldNotCompute()) 5783 // We couldn't compute an exact value for this exit, so 5784 // we won't be able to compute an exact value for the loop. 5785 CouldComputeBECount = false; 5786 else 5787 ExitCounts.emplace_back(ExitBB, EL); 5788 5789 // 2. Derive the loop's MaxBECount from each exit's max number of 5790 // non-exiting iterations. Partition the loop exits into two kinds: 5791 // LoopMustExits and LoopMayExits. 5792 // 5793 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 5794 // is a LoopMayExit. If any computable LoopMustExit is found, then 5795 // MaxBECount is the minimum EL.MaxNotTaken of computable 5796 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 5797 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 5798 // computable EL.MaxNotTaken. 5799 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 5800 DT.dominates(ExitBB, Latch)) { 5801 if (!MustExitMaxBECount) { 5802 MustExitMaxBECount = EL.MaxNotTaken; 5803 MustExitMaxOrZero = EL.MaxOrZero; 5804 } else { 5805 MustExitMaxBECount = 5806 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 5807 } 5808 } else if (MayExitMaxBECount != getCouldNotCompute()) { 5809 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 5810 MayExitMaxBECount = EL.MaxNotTaken; 5811 else { 5812 MayExitMaxBECount = 5813 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 5814 } 5815 } 5816 } 5817 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 5818 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 5819 // The loop backedge will be taken the maximum or zero times if there's 5820 // a single exit that must be taken the maximum or zero times. 5821 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 5822 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 5823 MaxBECount, MaxOrZero); 5824 } 5825 5826 ScalarEvolution::ExitLimit 5827 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 5828 bool AllowPredicates) { 5829 5830 // Okay, we've chosen an exiting block. See what condition causes us to exit 5831 // at this block and remember the exit block and whether all other targets 5832 // lead to the loop header. 5833 bool MustExecuteLoopHeader = true; 5834 BasicBlock *Exit = nullptr; 5835 for (auto *SBB : successors(ExitingBlock)) 5836 if (!L->contains(SBB)) { 5837 if (Exit) // Multiple exit successors. 5838 return getCouldNotCompute(); 5839 Exit = SBB; 5840 } else if (SBB != L->getHeader()) { 5841 MustExecuteLoopHeader = false; 5842 } 5843 5844 // At this point, we know we have a conditional branch that determines whether 5845 // the loop is exited. However, we don't know if the branch is executed each 5846 // time through the loop. If not, then the execution count of the branch will 5847 // not be equal to the trip count of the loop. 5848 // 5849 // Currently we check for this by checking to see if the Exit branch goes to 5850 // the loop header. If so, we know it will always execute the same number of 5851 // times as the loop. We also handle the case where the exit block *is* the 5852 // loop header. This is common for un-rotated loops. 5853 // 5854 // If both of those tests fail, walk up the unique predecessor chain to the 5855 // header, stopping if there is an edge that doesn't exit the loop. If the 5856 // header is reached, the execution count of the branch will be equal to the 5857 // trip count of the loop. 5858 // 5859 // More extensive analysis could be done to handle more cases here. 5860 // 5861 if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) { 5862 // The simple checks failed, try climbing the unique predecessor chain 5863 // up to the header. 5864 bool Ok = false; 5865 for (BasicBlock *BB = ExitingBlock; BB; ) { 5866 BasicBlock *Pred = BB->getUniquePredecessor(); 5867 if (!Pred) 5868 return getCouldNotCompute(); 5869 TerminatorInst *PredTerm = Pred->getTerminator(); 5870 for (const BasicBlock *PredSucc : PredTerm->successors()) { 5871 if (PredSucc == BB) 5872 continue; 5873 // If the predecessor has a successor that isn't BB and isn't 5874 // outside the loop, assume the worst. 5875 if (L->contains(PredSucc)) 5876 return getCouldNotCompute(); 5877 } 5878 if (Pred == L->getHeader()) { 5879 Ok = true; 5880 break; 5881 } 5882 BB = Pred; 5883 } 5884 if (!Ok) 5885 return getCouldNotCompute(); 5886 } 5887 5888 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 5889 TerminatorInst *Term = ExitingBlock->getTerminator(); 5890 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 5891 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 5892 // Proceed to the next level to examine the exit condition expression. 5893 return computeExitLimitFromCond( 5894 L, BI->getCondition(), BI->getSuccessor(0), BI->getSuccessor(1), 5895 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 5896 } 5897 5898 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) 5899 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 5900 /*ControlsExit=*/IsOnlyExit); 5901 5902 return getCouldNotCompute(); 5903 } 5904 5905 ScalarEvolution::ExitLimit 5906 ScalarEvolution::computeExitLimitFromCond(const Loop *L, 5907 Value *ExitCond, 5908 BasicBlock *TBB, 5909 BasicBlock *FBB, 5910 bool ControlsExit, 5911 bool AllowPredicates) { 5912 // Check if the controlling expression for this loop is an And or Or. 5913 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) { 5914 if (BO->getOpcode() == Instruction::And) { 5915 // Recurse on the operands of the and. 5916 bool EitherMayExit = L->contains(TBB); 5917 ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB, 5918 ControlsExit && !EitherMayExit, 5919 AllowPredicates); 5920 ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB, 5921 ControlsExit && !EitherMayExit, 5922 AllowPredicates); 5923 const SCEV *BECount = getCouldNotCompute(); 5924 const SCEV *MaxBECount = getCouldNotCompute(); 5925 if (EitherMayExit) { 5926 // Both conditions must be true for the loop to continue executing. 5927 // Choose the less conservative count. 5928 if (EL0.ExactNotTaken == getCouldNotCompute() || 5929 EL1.ExactNotTaken == getCouldNotCompute()) 5930 BECount = getCouldNotCompute(); 5931 else 5932 BECount = 5933 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 5934 if (EL0.MaxNotTaken == getCouldNotCompute()) 5935 MaxBECount = EL1.MaxNotTaken; 5936 else if (EL1.MaxNotTaken == getCouldNotCompute()) 5937 MaxBECount = EL0.MaxNotTaken; 5938 else 5939 MaxBECount = 5940 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 5941 } else { 5942 // Both conditions must be true at the same time for the loop to exit. 5943 // For now, be conservative. 5944 assert(L->contains(FBB) && "Loop block has no successor in loop!"); 5945 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 5946 MaxBECount = EL0.MaxNotTaken; 5947 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 5948 BECount = EL0.ExactNotTaken; 5949 } 5950 5951 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 5952 // to be more aggressive when computing BECount than when computing 5953 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 5954 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 5955 // to not. 5956 if (isa<SCEVCouldNotCompute>(MaxBECount) && 5957 !isa<SCEVCouldNotCompute>(BECount)) 5958 MaxBECount = BECount; 5959 5960 return ExitLimit(BECount, MaxBECount, false, 5961 {&EL0.Predicates, &EL1.Predicates}); 5962 } 5963 if (BO->getOpcode() == Instruction::Or) { 5964 // Recurse on the operands of the or. 5965 bool EitherMayExit = L->contains(FBB); 5966 ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB, 5967 ControlsExit && !EitherMayExit, 5968 AllowPredicates); 5969 ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB, 5970 ControlsExit && !EitherMayExit, 5971 AllowPredicates); 5972 const SCEV *BECount = getCouldNotCompute(); 5973 const SCEV *MaxBECount = getCouldNotCompute(); 5974 if (EitherMayExit) { 5975 // Both conditions must be false for the loop to continue executing. 5976 // Choose the less conservative count. 5977 if (EL0.ExactNotTaken == getCouldNotCompute() || 5978 EL1.ExactNotTaken == getCouldNotCompute()) 5979 BECount = getCouldNotCompute(); 5980 else 5981 BECount = 5982 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 5983 if (EL0.MaxNotTaken == getCouldNotCompute()) 5984 MaxBECount = EL1.MaxNotTaken; 5985 else if (EL1.MaxNotTaken == getCouldNotCompute()) 5986 MaxBECount = EL0.MaxNotTaken; 5987 else 5988 MaxBECount = 5989 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 5990 } else { 5991 // Both conditions must be false at the same time for the loop to exit. 5992 // For now, be conservative. 5993 assert(L->contains(TBB) && "Loop block has no successor in loop!"); 5994 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 5995 MaxBECount = EL0.MaxNotTaken; 5996 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 5997 BECount = EL0.ExactNotTaken; 5998 } 5999 6000 return ExitLimit(BECount, MaxBECount, false, 6001 {&EL0.Predicates, &EL1.Predicates}); 6002 } 6003 } 6004 6005 // With an icmp, it may be feasible to compute an exact backedge-taken count. 6006 // Proceed to the next level to examine the icmp. 6007 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 6008 ExitLimit EL = 6009 computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit); 6010 if (EL.hasFullInfo() || !AllowPredicates) 6011 return EL; 6012 6013 // Try again, but use SCEV predicates this time. 6014 return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit, 6015 /*AllowPredicates=*/true); 6016 } 6017 6018 // Check for a constant condition. These are normally stripped out by 6019 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 6020 // preserve the CFG and is temporarily leaving constant conditions 6021 // in place. 6022 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 6023 if (L->contains(FBB) == !CI->getZExtValue()) 6024 // The backedge is always taken. 6025 return getCouldNotCompute(); 6026 else 6027 // The backedge is never taken. 6028 return getZero(CI->getType()); 6029 } 6030 6031 // If it's not an integer or pointer comparison then compute it the hard way. 6032 return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB)); 6033 } 6034 6035 ScalarEvolution::ExitLimit 6036 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 6037 ICmpInst *ExitCond, 6038 BasicBlock *TBB, 6039 BasicBlock *FBB, 6040 bool ControlsExit, 6041 bool AllowPredicates) { 6042 6043 // If the condition was exit on true, convert the condition to exit on false 6044 ICmpInst::Predicate Cond; 6045 if (!L->contains(FBB)) 6046 Cond = ExitCond->getPredicate(); 6047 else 6048 Cond = ExitCond->getInversePredicate(); 6049 6050 // Handle common loops like: for (X = "string"; *X; ++X) 6051 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 6052 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 6053 ExitLimit ItCnt = 6054 computeLoadConstantCompareExitLimit(LI, RHS, L, Cond); 6055 if (ItCnt.hasAnyInfo()) 6056 return ItCnt; 6057 } 6058 6059 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 6060 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 6061 6062 // Try to evaluate any dependencies out of the loop. 6063 LHS = getSCEVAtScope(LHS, L); 6064 RHS = getSCEVAtScope(RHS, L); 6065 6066 // At this point, we would like to compute how many iterations of the 6067 // loop the predicate will return true for these inputs. 6068 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 6069 // If there is a loop-invariant, force it into the RHS. 6070 std::swap(LHS, RHS); 6071 Cond = ICmpInst::getSwappedPredicate(Cond); 6072 } 6073 6074 // Simplify the operands before analyzing them. 6075 (void)SimplifyICmpOperands(Cond, LHS, RHS); 6076 6077 // If we have a comparison of a chrec against a constant, try to use value 6078 // ranges to answer this query. 6079 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 6080 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 6081 if (AddRec->getLoop() == L) { 6082 // Form the constant range. 6083 ConstantRange CompRange = 6084 ConstantRange::makeExactICmpRegion(Cond, RHSC->getAPInt()); 6085 6086 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 6087 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 6088 } 6089 6090 switch (Cond) { 6091 case ICmpInst::ICMP_NE: { // while (X != Y) 6092 // Convert to: while (X-Y != 0) 6093 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 6094 AllowPredicates); 6095 if (EL.hasAnyInfo()) return EL; 6096 break; 6097 } 6098 case ICmpInst::ICMP_EQ: { // while (X == Y) 6099 // Convert to: while (X-Y == 0) 6100 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 6101 if (EL.hasAnyInfo()) return EL; 6102 break; 6103 } 6104 case ICmpInst::ICMP_SLT: 6105 case ICmpInst::ICMP_ULT: { // while (X < Y) 6106 bool IsSigned = Cond == ICmpInst::ICMP_SLT; 6107 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 6108 AllowPredicates); 6109 if (EL.hasAnyInfo()) return EL; 6110 break; 6111 } 6112 case ICmpInst::ICMP_SGT: 6113 case ICmpInst::ICMP_UGT: { // while (X > Y) 6114 bool IsSigned = Cond == ICmpInst::ICMP_SGT; 6115 ExitLimit EL = 6116 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 6117 AllowPredicates); 6118 if (EL.hasAnyInfo()) return EL; 6119 break; 6120 } 6121 default: 6122 break; 6123 } 6124 6125 auto *ExhaustiveCount = 6126 computeExitCountExhaustively(L, ExitCond, !L->contains(TBB)); 6127 6128 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 6129 return ExhaustiveCount; 6130 6131 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 6132 ExitCond->getOperand(1), L, Cond); 6133 } 6134 6135 ScalarEvolution::ExitLimit 6136 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 6137 SwitchInst *Switch, 6138 BasicBlock *ExitingBlock, 6139 bool ControlsExit) { 6140 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 6141 6142 // Give up if the exit is the default dest of a switch. 6143 if (Switch->getDefaultDest() == ExitingBlock) 6144 return getCouldNotCompute(); 6145 6146 assert(L->contains(Switch->getDefaultDest()) && 6147 "Default case must not exit the loop!"); 6148 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 6149 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 6150 6151 // while (X != Y) --> while (X-Y != 0) 6152 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 6153 if (EL.hasAnyInfo()) 6154 return EL; 6155 6156 return getCouldNotCompute(); 6157 } 6158 6159 static ConstantInt * 6160 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 6161 ScalarEvolution &SE) { 6162 const SCEV *InVal = SE.getConstant(C); 6163 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 6164 assert(isa<SCEVConstant>(Val) && 6165 "Evaluation of SCEV at constant didn't fold correctly?"); 6166 return cast<SCEVConstant>(Val)->getValue(); 6167 } 6168 6169 /// Given an exit condition of 'icmp op load X, cst', try to see if we can 6170 /// compute the backedge execution count. 6171 ScalarEvolution::ExitLimit 6172 ScalarEvolution::computeLoadConstantCompareExitLimit( 6173 LoadInst *LI, 6174 Constant *RHS, 6175 const Loop *L, 6176 ICmpInst::Predicate predicate) { 6177 6178 if (LI->isVolatile()) return getCouldNotCompute(); 6179 6180 // Check to see if the loaded pointer is a getelementptr of a global. 6181 // TODO: Use SCEV instead of manually grubbing with GEPs. 6182 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 6183 if (!GEP) return getCouldNotCompute(); 6184 6185 // Make sure that it is really a constant global we are gepping, with an 6186 // initializer, and make sure the first IDX is really 0. 6187 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 6188 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || 6189 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 6190 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 6191 return getCouldNotCompute(); 6192 6193 // Okay, we allow one non-constant index into the GEP instruction. 6194 Value *VarIdx = nullptr; 6195 std::vector<Constant*> Indexes; 6196 unsigned VarIdxNum = 0; 6197 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 6198 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 6199 Indexes.push_back(CI); 6200 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 6201 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. 6202 VarIdx = GEP->getOperand(i); 6203 VarIdxNum = i-2; 6204 Indexes.push_back(nullptr); 6205 } 6206 6207 // Loop-invariant loads may be a byproduct of loop optimization. Skip them. 6208 if (!VarIdx) 6209 return getCouldNotCompute(); 6210 6211 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 6212 // Check to see if X is a loop variant variable value now. 6213 const SCEV *Idx = getSCEV(VarIdx); 6214 Idx = getSCEVAtScope(Idx, L); 6215 6216 // We can only recognize very limited forms of loop index expressions, in 6217 // particular, only affine AddRec's like {C1,+,C2}. 6218 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 6219 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) || 6220 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 6221 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 6222 return getCouldNotCompute(); 6223 6224 unsigned MaxSteps = MaxBruteForceIterations; 6225 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 6226 ConstantInt *ItCst = ConstantInt::get( 6227 cast<IntegerType>(IdxExpr->getType()), IterationNum); 6228 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 6229 6230 // Form the GEP offset. 6231 Indexes[VarIdxNum] = Val; 6232 6233 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), 6234 Indexes); 6235 if (!Result) break; // Cannot compute! 6236 6237 // Evaluate the condition for this iteration. 6238 Result = ConstantExpr::getICmp(predicate, Result, RHS); 6239 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 6240 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 6241 ++NumArrayLenItCounts; 6242 return getConstant(ItCst); // Found terminating iteration! 6243 } 6244 } 6245 return getCouldNotCompute(); 6246 } 6247 6248 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 6249 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 6250 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 6251 if (!RHS) 6252 return getCouldNotCompute(); 6253 6254 const BasicBlock *Latch = L->getLoopLatch(); 6255 if (!Latch) 6256 return getCouldNotCompute(); 6257 6258 const BasicBlock *Predecessor = L->getLoopPredecessor(); 6259 if (!Predecessor) 6260 return getCouldNotCompute(); 6261 6262 // Return true if V is of the form "LHS `shift_op` <positive constant>". 6263 // Return LHS in OutLHS and shift_opt in OutOpCode. 6264 auto MatchPositiveShift = 6265 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 6266 6267 using namespace PatternMatch; 6268 6269 ConstantInt *ShiftAmt; 6270 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 6271 OutOpCode = Instruction::LShr; 6272 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 6273 OutOpCode = Instruction::AShr; 6274 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 6275 OutOpCode = Instruction::Shl; 6276 else 6277 return false; 6278 6279 return ShiftAmt->getValue().isStrictlyPositive(); 6280 }; 6281 6282 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 6283 // 6284 // loop: 6285 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 6286 // %iv.shifted = lshr i32 %iv, <positive constant> 6287 // 6288 // Return true on a succesful match. Return the corresponding PHI node (%iv 6289 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 6290 auto MatchShiftRecurrence = 6291 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 6292 Optional<Instruction::BinaryOps> PostShiftOpCode; 6293 6294 { 6295 Instruction::BinaryOps OpC; 6296 Value *V; 6297 6298 // If we encounter a shift instruction, "peel off" the shift operation, 6299 // and remember that we did so. Later when we inspect %iv's backedge 6300 // value, we will make sure that the backedge value uses the same 6301 // operation. 6302 // 6303 // Note: the peeled shift operation does not have to be the same 6304 // instruction as the one feeding into the PHI's backedge value. We only 6305 // really care about it being the same *kind* of shift instruction -- 6306 // that's all that is required for our later inferences to hold. 6307 if (MatchPositiveShift(LHS, V, OpC)) { 6308 PostShiftOpCode = OpC; 6309 LHS = V; 6310 } 6311 } 6312 6313 PNOut = dyn_cast<PHINode>(LHS); 6314 if (!PNOut || PNOut->getParent() != L->getHeader()) 6315 return false; 6316 6317 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 6318 Value *OpLHS; 6319 6320 return 6321 // The backedge value for the PHI node must be a shift by a positive 6322 // amount 6323 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 6324 6325 // of the PHI node itself 6326 OpLHS == PNOut && 6327 6328 // and the kind of shift should be match the kind of shift we peeled 6329 // off, if any. 6330 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 6331 }; 6332 6333 PHINode *PN; 6334 Instruction::BinaryOps OpCode; 6335 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 6336 return getCouldNotCompute(); 6337 6338 const DataLayout &DL = getDataLayout(); 6339 6340 // The key rationale for this optimization is that for some kinds of shift 6341 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 6342 // within a finite number of iterations. If the condition guarding the 6343 // backedge (in the sense that the backedge is taken if the condition is true) 6344 // is false for the value the shift recurrence stabilizes to, then we know 6345 // that the backedge is taken only a finite number of times. 6346 6347 ConstantInt *StableValue = nullptr; 6348 switch (OpCode) { 6349 default: 6350 llvm_unreachable("Impossible case!"); 6351 6352 case Instruction::AShr: { 6353 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 6354 // bitwidth(K) iterations. 6355 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 6356 bool KnownZero, KnownOne; 6357 ComputeSignBit(FirstValue, KnownZero, KnownOne, DL, 0, nullptr, 6358 Predecessor->getTerminator(), &DT); 6359 auto *Ty = cast<IntegerType>(RHS->getType()); 6360 if (KnownZero) 6361 StableValue = ConstantInt::get(Ty, 0); 6362 else if (KnownOne) 6363 StableValue = ConstantInt::get(Ty, -1, true); 6364 else 6365 return getCouldNotCompute(); 6366 6367 break; 6368 } 6369 case Instruction::LShr: 6370 case Instruction::Shl: 6371 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 6372 // stabilize to 0 in at most bitwidth(K) iterations. 6373 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 6374 break; 6375 } 6376 6377 auto *Result = 6378 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 6379 assert(Result->getType()->isIntegerTy(1) && 6380 "Otherwise cannot be an operand to a branch instruction"); 6381 6382 if (Result->isZeroValue()) { 6383 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 6384 const SCEV *UpperBound = 6385 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 6386 return ExitLimit(getCouldNotCompute(), UpperBound, false); 6387 } 6388 6389 return getCouldNotCompute(); 6390 } 6391 6392 /// Return true if we can constant fold an instruction of the specified type, 6393 /// assuming that all operands were constants. 6394 static bool CanConstantFold(const Instruction *I) { 6395 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 6396 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 6397 isa<LoadInst>(I)) 6398 return true; 6399 6400 if (const CallInst *CI = dyn_cast<CallInst>(I)) 6401 if (const Function *F = CI->getCalledFunction()) 6402 return canConstantFoldCallTo(F); 6403 return false; 6404 } 6405 6406 /// Determine whether this instruction can constant evolve within this loop 6407 /// assuming its operands can all constant evolve. 6408 static bool canConstantEvolve(Instruction *I, const Loop *L) { 6409 // An instruction outside of the loop can't be derived from a loop PHI. 6410 if (!L->contains(I)) return false; 6411 6412 if (isa<PHINode>(I)) { 6413 // We don't currently keep track of the control flow needed to evaluate 6414 // PHIs, so we cannot handle PHIs inside of loops. 6415 return L->getHeader() == I->getParent(); 6416 } 6417 6418 // If we won't be able to constant fold this expression even if the operands 6419 // are constants, bail early. 6420 return CanConstantFold(I); 6421 } 6422 6423 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 6424 /// recursing through each instruction operand until reaching a loop header phi. 6425 static PHINode * 6426 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 6427 DenseMap<Instruction *, PHINode *> &PHIMap) { 6428 6429 // Otherwise, we can evaluate this instruction if all of its operands are 6430 // constant or derived from a PHI node themselves. 6431 PHINode *PHI = nullptr; 6432 for (Value *Op : UseInst->operands()) { 6433 if (isa<Constant>(Op)) continue; 6434 6435 Instruction *OpInst = dyn_cast<Instruction>(Op); 6436 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 6437 6438 PHINode *P = dyn_cast<PHINode>(OpInst); 6439 if (!P) 6440 // If this operand is already visited, reuse the prior result. 6441 // We may have P != PHI if this is the deepest point at which the 6442 // inconsistent paths meet. 6443 P = PHIMap.lookup(OpInst); 6444 if (!P) { 6445 // Recurse and memoize the results, whether a phi is found or not. 6446 // This recursive call invalidates pointers into PHIMap. 6447 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap); 6448 PHIMap[OpInst] = P; 6449 } 6450 if (!P) 6451 return nullptr; // Not evolving from PHI 6452 if (PHI && PHI != P) 6453 return nullptr; // Evolving from multiple different PHIs. 6454 PHI = P; 6455 } 6456 // This is a expression evolving from a constant PHI! 6457 return PHI; 6458 } 6459 6460 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 6461 /// in the loop that V is derived from. We allow arbitrary operations along the 6462 /// way, but the operands of an operation must either be constants or a value 6463 /// derived from a constant PHI. If this expression does not fit with these 6464 /// constraints, return null. 6465 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 6466 Instruction *I = dyn_cast<Instruction>(V); 6467 if (!I || !canConstantEvolve(I, L)) return nullptr; 6468 6469 if (PHINode *PN = dyn_cast<PHINode>(I)) 6470 return PN; 6471 6472 // Record non-constant instructions contained by the loop. 6473 DenseMap<Instruction *, PHINode *> PHIMap; 6474 return getConstantEvolvingPHIOperands(I, L, PHIMap); 6475 } 6476 6477 /// EvaluateExpression - Given an expression that passes the 6478 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 6479 /// in the loop has the value PHIVal. If we can't fold this expression for some 6480 /// reason, return null. 6481 static Constant *EvaluateExpression(Value *V, const Loop *L, 6482 DenseMap<Instruction *, Constant *> &Vals, 6483 const DataLayout &DL, 6484 const TargetLibraryInfo *TLI) { 6485 // Convenient constant check, but redundant for recursive calls. 6486 if (Constant *C = dyn_cast<Constant>(V)) return C; 6487 Instruction *I = dyn_cast<Instruction>(V); 6488 if (!I) return nullptr; 6489 6490 if (Constant *C = Vals.lookup(I)) return C; 6491 6492 // An instruction inside the loop depends on a value outside the loop that we 6493 // weren't given a mapping for, or a value such as a call inside the loop. 6494 if (!canConstantEvolve(I, L)) return nullptr; 6495 6496 // An unmapped PHI can be due to a branch or another loop inside this loop, 6497 // or due to this not being the initial iteration through a loop where we 6498 // couldn't compute the evolution of this particular PHI last time. 6499 if (isa<PHINode>(I)) return nullptr; 6500 6501 std::vector<Constant*> Operands(I->getNumOperands()); 6502 6503 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 6504 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 6505 if (!Operand) { 6506 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 6507 if (!Operands[i]) return nullptr; 6508 continue; 6509 } 6510 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 6511 Vals[Operand] = C; 6512 if (!C) return nullptr; 6513 Operands[i] = C; 6514 } 6515 6516 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 6517 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 6518 Operands[1], DL, TLI); 6519 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 6520 if (!LI->isVolatile()) 6521 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 6522 } 6523 return ConstantFoldInstOperands(I, Operands, DL, TLI); 6524 } 6525 6526 6527 // If every incoming value to PN except the one for BB is a specific Constant, 6528 // return that, else return nullptr. 6529 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 6530 Constant *IncomingVal = nullptr; 6531 6532 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 6533 if (PN->getIncomingBlock(i) == BB) 6534 continue; 6535 6536 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 6537 if (!CurrentVal) 6538 return nullptr; 6539 6540 if (IncomingVal != CurrentVal) { 6541 if (IncomingVal) 6542 return nullptr; 6543 IncomingVal = CurrentVal; 6544 } 6545 } 6546 6547 return IncomingVal; 6548 } 6549 6550 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 6551 /// in the header of its containing loop, we know the loop executes a 6552 /// constant number of times, and the PHI node is just a recurrence 6553 /// involving constants, fold it. 6554 Constant * 6555 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 6556 const APInt &BEs, 6557 const Loop *L) { 6558 auto I = ConstantEvolutionLoopExitValue.find(PN); 6559 if (I != ConstantEvolutionLoopExitValue.end()) 6560 return I->second; 6561 6562 if (BEs.ugt(MaxBruteForceIterations)) 6563 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 6564 6565 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 6566 6567 DenseMap<Instruction *, Constant *> CurrentIterVals; 6568 BasicBlock *Header = L->getHeader(); 6569 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 6570 6571 BasicBlock *Latch = L->getLoopLatch(); 6572 if (!Latch) 6573 return nullptr; 6574 6575 for (auto &I : *Header) { 6576 PHINode *PHI = dyn_cast<PHINode>(&I); 6577 if (!PHI) break; 6578 auto *StartCST = getOtherIncomingValue(PHI, Latch); 6579 if (!StartCST) continue; 6580 CurrentIterVals[PHI] = StartCST; 6581 } 6582 if (!CurrentIterVals.count(PN)) 6583 return RetVal = nullptr; 6584 6585 Value *BEValue = PN->getIncomingValueForBlock(Latch); 6586 6587 // Execute the loop symbolically to determine the exit value. 6588 if (BEs.getActiveBits() >= 32) 6589 return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it! 6590 6591 unsigned NumIterations = BEs.getZExtValue(); // must be in range 6592 unsigned IterationNum = 0; 6593 const DataLayout &DL = getDataLayout(); 6594 for (; ; ++IterationNum) { 6595 if (IterationNum == NumIterations) 6596 return RetVal = CurrentIterVals[PN]; // Got exit value! 6597 6598 // Compute the value of the PHIs for the next iteration. 6599 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 6600 DenseMap<Instruction *, Constant *> NextIterVals; 6601 Constant *NextPHI = 6602 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 6603 if (!NextPHI) 6604 return nullptr; // Couldn't evaluate! 6605 NextIterVals[PN] = NextPHI; 6606 6607 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 6608 6609 // Also evaluate the other PHI nodes. However, we don't get to stop if we 6610 // cease to be able to evaluate one of them or if they stop evolving, 6611 // because that doesn't necessarily prevent us from computing PN. 6612 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 6613 for (const auto &I : CurrentIterVals) { 6614 PHINode *PHI = dyn_cast<PHINode>(I.first); 6615 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 6616 PHIsToCompute.emplace_back(PHI, I.second); 6617 } 6618 // We use two distinct loops because EvaluateExpression may invalidate any 6619 // iterators into CurrentIterVals. 6620 for (const auto &I : PHIsToCompute) { 6621 PHINode *PHI = I.first; 6622 Constant *&NextPHI = NextIterVals[PHI]; 6623 if (!NextPHI) { // Not already computed. 6624 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 6625 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 6626 } 6627 if (NextPHI != I.second) 6628 StoppedEvolving = false; 6629 } 6630 6631 // If all entries in CurrentIterVals == NextIterVals then we can stop 6632 // iterating, the loop can't continue to change. 6633 if (StoppedEvolving) 6634 return RetVal = CurrentIterVals[PN]; 6635 6636 CurrentIterVals.swap(NextIterVals); 6637 } 6638 } 6639 6640 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 6641 Value *Cond, 6642 bool ExitWhen) { 6643 PHINode *PN = getConstantEvolvingPHI(Cond, L); 6644 if (!PN) return getCouldNotCompute(); 6645 6646 // If the loop is canonicalized, the PHI will have exactly two entries. 6647 // That's the only form we support here. 6648 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 6649 6650 DenseMap<Instruction *, Constant *> CurrentIterVals; 6651 BasicBlock *Header = L->getHeader(); 6652 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 6653 6654 BasicBlock *Latch = L->getLoopLatch(); 6655 assert(Latch && "Should follow from NumIncomingValues == 2!"); 6656 6657 for (auto &I : *Header) { 6658 PHINode *PHI = dyn_cast<PHINode>(&I); 6659 if (!PHI) 6660 break; 6661 auto *StartCST = getOtherIncomingValue(PHI, Latch); 6662 if (!StartCST) continue; 6663 CurrentIterVals[PHI] = StartCST; 6664 } 6665 if (!CurrentIterVals.count(PN)) 6666 return getCouldNotCompute(); 6667 6668 // Okay, we find a PHI node that defines the trip count of this loop. Execute 6669 // the loop symbolically to determine when the condition gets a value of 6670 // "ExitWhen". 6671 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 6672 const DataLayout &DL = getDataLayout(); 6673 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 6674 auto *CondVal = dyn_cast_or_null<ConstantInt>( 6675 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 6676 6677 // Couldn't symbolically evaluate. 6678 if (!CondVal) return getCouldNotCompute(); 6679 6680 if (CondVal->getValue() == uint64_t(ExitWhen)) { 6681 ++NumBruteForceTripCountsComputed; 6682 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 6683 } 6684 6685 // Update all the PHI nodes for the next iteration. 6686 DenseMap<Instruction *, Constant *> NextIterVals; 6687 6688 // Create a list of which PHIs we need to compute. We want to do this before 6689 // calling EvaluateExpression on them because that may invalidate iterators 6690 // into CurrentIterVals. 6691 SmallVector<PHINode *, 8> PHIsToCompute; 6692 for (const auto &I : CurrentIterVals) { 6693 PHINode *PHI = dyn_cast<PHINode>(I.first); 6694 if (!PHI || PHI->getParent() != Header) continue; 6695 PHIsToCompute.push_back(PHI); 6696 } 6697 for (PHINode *PHI : PHIsToCompute) { 6698 Constant *&NextPHI = NextIterVals[PHI]; 6699 if (NextPHI) continue; // Already computed! 6700 6701 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 6702 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 6703 } 6704 CurrentIterVals.swap(NextIterVals); 6705 } 6706 6707 // Too many iterations were needed to evaluate. 6708 return getCouldNotCompute(); 6709 } 6710 6711 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 6712 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 6713 ValuesAtScopes[V]; 6714 // Check to see if we've folded this expression at this loop before. 6715 for (auto &LS : Values) 6716 if (LS.first == L) 6717 return LS.second ? LS.second : V; 6718 6719 Values.emplace_back(L, nullptr); 6720 6721 // Otherwise compute it. 6722 const SCEV *C = computeSCEVAtScope(V, L); 6723 for (auto &LS : reverse(ValuesAtScopes[V])) 6724 if (LS.first == L) { 6725 LS.second = C; 6726 break; 6727 } 6728 return C; 6729 } 6730 6731 /// This builds up a Constant using the ConstantExpr interface. That way, we 6732 /// will return Constants for objects which aren't represented by a 6733 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 6734 /// Returns NULL if the SCEV isn't representable as a Constant. 6735 static Constant *BuildConstantFromSCEV(const SCEV *V) { 6736 switch (static_cast<SCEVTypes>(V->getSCEVType())) { 6737 case scCouldNotCompute: 6738 case scAddRecExpr: 6739 break; 6740 case scConstant: 6741 return cast<SCEVConstant>(V)->getValue(); 6742 case scUnknown: 6743 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 6744 case scSignExtend: { 6745 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 6746 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 6747 return ConstantExpr::getSExt(CastOp, SS->getType()); 6748 break; 6749 } 6750 case scZeroExtend: { 6751 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 6752 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 6753 return ConstantExpr::getZExt(CastOp, SZ->getType()); 6754 break; 6755 } 6756 case scTruncate: { 6757 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 6758 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 6759 return ConstantExpr::getTrunc(CastOp, ST->getType()); 6760 break; 6761 } 6762 case scAddExpr: { 6763 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 6764 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 6765 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 6766 unsigned AS = PTy->getAddressSpace(); 6767 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 6768 C = ConstantExpr::getBitCast(C, DestPtrTy); 6769 } 6770 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 6771 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 6772 if (!C2) return nullptr; 6773 6774 // First pointer! 6775 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 6776 unsigned AS = C2->getType()->getPointerAddressSpace(); 6777 std::swap(C, C2); 6778 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 6779 // The offsets have been converted to bytes. We can add bytes to an 6780 // i8* by GEP with the byte count in the first index. 6781 C = ConstantExpr::getBitCast(C, DestPtrTy); 6782 } 6783 6784 // Don't bother trying to sum two pointers. We probably can't 6785 // statically compute a load that results from it anyway. 6786 if (C2->getType()->isPointerTy()) 6787 return nullptr; 6788 6789 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 6790 if (PTy->getElementType()->isStructTy()) 6791 C2 = ConstantExpr::getIntegerCast( 6792 C2, Type::getInt32Ty(C->getContext()), true); 6793 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); 6794 } else 6795 C = ConstantExpr::getAdd(C, C2); 6796 } 6797 return C; 6798 } 6799 break; 6800 } 6801 case scMulExpr: { 6802 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 6803 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 6804 // Don't bother with pointers at all. 6805 if (C->getType()->isPointerTy()) return nullptr; 6806 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 6807 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 6808 if (!C2 || C2->getType()->isPointerTy()) return nullptr; 6809 C = ConstantExpr::getMul(C, C2); 6810 } 6811 return C; 6812 } 6813 break; 6814 } 6815 case scUDivExpr: { 6816 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 6817 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 6818 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 6819 if (LHS->getType() == RHS->getType()) 6820 return ConstantExpr::getUDiv(LHS, RHS); 6821 break; 6822 } 6823 case scSMaxExpr: 6824 case scUMaxExpr: 6825 break; // TODO: smax, umax. 6826 } 6827 return nullptr; 6828 } 6829 6830 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 6831 if (isa<SCEVConstant>(V)) return V; 6832 6833 // If this instruction is evolved from a constant-evolving PHI, compute the 6834 // exit value from the loop without using SCEVs. 6835 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 6836 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 6837 const Loop *LI = this->LI[I->getParent()]; 6838 if (LI && LI->getParentLoop() == L) // Looking for loop exit value. 6839 if (PHINode *PN = dyn_cast<PHINode>(I)) 6840 if (PN->getParent() == LI->getHeader()) { 6841 // Okay, there is no closed form solution for the PHI node. Check 6842 // to see if the loop that contains it has a known backedge-taken 6843 // count. If so, we may be able to force computation of the exit 6844 // value. 6845 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI); 6846 if (const SCEVConstant *BTCC = 6847 dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 6848 // Okay, we know how many times the containing loop executes. If 6849 // this is a constant evolving PHI node, get the final value at 6850 // the specified iteration number. 6851 Constant *RV = 6852 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI); 6853 if (RV) return getSCEV(RV); 6854 } 6855 } 6856 6857 // Okay, this is an expression that we cannot symbolically evaluate 6858 // into a SCEV. Check to see if it's possible to symbolically evaluate 6859 // the arguments into constants, and if so, try to constant propagate the 6860 // result. This is particularly useful for computing loop exit values. 6861 if (CanConstantFold(I)) { 6862 SmallVector<Constant *, 4> Operands; 6863 bool MadeImprovement = false; 6864 for (Value *Op : I->operands()) { 6865 if (Constant *C = dyn_cast<Constant>(Op)) { 6866 Operands.push_back(C); 6867 continue; 6868 } 6869 6870 // If any of the operands is non-constant and if they are 6871 // non-integer and non-pointer, don't even try to analyze them 6872 // with scev techniques. 6873 if (!isSCEVable(Op->getType())) 6874 return V; 6875 6876 const SCEV *OrigV = getSCEV(Op); 6877 const SCEV *OpV = getSCEVAtScope(OrigV, L); 6878 MadeImprovement |= OrigV != OpV; 6879 6880 Constant *C = BuildConstantFromSCEV(OpV); 6881 if (!C) return V; 6882 if (C->getType() != Op->getType()) 6883 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 6884 Op->getType(), 6885 false), 6886 C, Op->getType()); 6887 Operands.push_back(C); 6888 } 6889 6890 // Check to see if getSCEVAtScope actually made an improvement. 6891 if (MadeImprovement) { 6892 Constant *C = nullptr; 6893 const DataLayout &DL = getDataLayout(); 6894 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 6895 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 6896 Operands[1], DL, &TLI); 6897 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) { 6898 if (!LI->isVolatile()) 6899 C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 6900 } else 6901 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 6902 if (!C) return V; 6903 return getSCEV(C); 6904 } 6905 } 6906 } 6907 6908 // This is some other type of SCEVUnknown, just return it. 6909 return V; 6910 } 6911 6912 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 6913 // Avoid performing the look-up in the common case where the specified 6914 // expression has no loop-variant portions. 6915 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 6916 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 6917 if (OpAtScope != Comm->getOperand(i)) { 6918 // Okay, at least one of these operands is loop variant but might be 6919 // foldable. Build a new instance of the folded commutative expression. 6920 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 6921 Comm->op_begin()+i); 6922 NewOps.push_back(OpAtScope); 6923 6924 for (++i; i != e; ++i) { 6925 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 6926 NewOps.push_back(OpAtScope); 6927 } 6928 if (isa<SCEVAddExpr>(Comm)) 6929 return getAddExpr(NewOps); 6930 if (isa<SCEVMulExpr>(Comm)) 6931 return getMulExpr(NewOps); 6932 if (isa<SCEVSMaxExpr>(Comm)) 6933 return getSMaxExpr(NewOps); 6934 if (isa<SCEVUMaxExpr>(Comm)) 6935 return getUMaxExpr(NewOps); 6936 llvm_unreachable("Unknown commutative SCEV type!"); 6937 } 6938 } 6939 // If we got here, all operands are loop invariant. 6940 return Comm; 6941 } 6942 6943 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 6944 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 6945 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 6946 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 6947 return Div; // must be loop invariant 6948 return getUDivExpr(LHS, RHS); 6949 } 6950 6951 // If this is a loop recurrence for a loop that does not contain L, then we 6952 // are dealing with the final value computed by the loop. 6953 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 6954 // First, attempt to evaluate each operand. 6955 // Avoid performing the look-up in the common case where the specified 6956 // expression has no loop-variant portions. 6957 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 6958 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 6959 if (OpAtScope == AddRec->getOperand(i)) 6960 continue; 6961 6962 // Okay, at least one of these operands is loop variant but might be 6963 // foldable. Build a new instance of the folded commutative expression. 6964 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 6965 AddRec->op_begin()+i); 6966 NewOps.push_back(OpAtScope); 6967 for (++i; i != e; ++i) 6968 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 6969 6970 const SCEV *FoldedRec = 6971 getAddRecExpr(NewOps, AddRec->getLoop(), 6972 AddRec->getNoWrapFlags(SCEV::FlagNW)); 6973 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 6974 // The addrec may be folded to a nonrecurrence, for example, if the 6975 // induction variable is multiplied by zero after constant folding. Go 6976 // ahead and return the folded value. 6977 if (!AddRec) 6978 return FoldedRec; 6979 break; 6980 } 6981 6982 // If the scope is outside the addrec's loop, evaluate it by using the 6983 // loop exit value of the addrec. 6984 if (!AddRec->getLoop()->contains(L)) { 6985 // To evaluate this recurrence, we need to know how many times the AddRec 6986 // loop iterates. Compute this now. 6987 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 6988 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 6989 6990 // Then, evaluate the AddRec. 6991 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 6992 } 6993 6994 return AddRec; 6995 } 6996 6997 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 6998 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 6999 if (Op == Cast->getOperand()) 7000 return Cast; // must be loop invariant 7001 return getZeroExtendExpr(Op, Cast->getType()); 7002 } 7003 7004 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 7005 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 7006 if (Op == Cast->getOperand()) 7007 return Cast; // must be loop invariant 7008 return getSignExtendExpr(Op, Cast->getType()); 7009 } 7010 7011 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 7012 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 7013 if (Op == Cast->getOperand()) 7014 return Cast; // must be loop invariant 7015 return getTruncateExpr(Op, Cast->getType()); 7016 } 7017 7018 llvm_unreachable("Unknown SCEV type!"); 7019 } 7020 7021 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 7022 return getSCEVAtScope(getSCEV(V), L); 7023 } 7024 7025 /// Finds the minimum unsigned root of the following equation: 7026 /// 7027 /// A * X = B (mod N) 7028 /// 7029 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 7030 /// A and B isn't important. 7031 /// 7032 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 7033 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B, 7034 ScalarEvolution &SE) { 7035 uint32_t BW = A.getBitWidth(); 7036 assert(BW == B.getBitWidth() && "Bit widths must be the same."); 7037 assert(A != 0 && "A must be non-zero."); 7038 7039 // 1. D = gcd(A, N) 7040 // 7041 // The gcd of A and N may have only one prime factor: 2. The number of 7042 // trailing zeros in A is its multiplicity 7043 uint32_t Mult2 = A.countTrailingZeros(); 7044 // D = 2^Mult2 7045 7046 // 2. Check if B is divisible by D. 7047 // 7048 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 7049 // is not less than multiplicity of this prime factor for D. 7050 if (B.countTrailingZeros() < Mult2) 7051 return SE.getCouldNotCompute(); 7052 7053 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 7054 // modulo (N / D). 7055 // 7056 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this 7057 // bit width during computations. 7058 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 7059 APInt Mod(BW + 1, 0); 7060 Mod.setBit(BW - Mult2); // Mod = N / D 7061 APInt I = AD.multiplicativeInverse(Mod); 7062 7063 // 4. Compute the minimum unsigned root of the equation: 7064 // I * (B / D) mod (N / D) 7065 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod); 7066 7067 // The result is guaranteed to be less than 2^BW so we may truncate it to BW 7068 // bits. 7069 return SE.getConstant(Result.trunc(BW)); 7070 } 7071 7072 /// Find the roots of the quadratic equation for the given quadratic chrec 7073 /// {L,+,M,+,N}. This returns either the two roots (which might be the same) or 7074 /// two SCEVCouldNotCompute objects. 7075 /// 7076 static Optional<std::pair<const SCEVConstant *,const SCEVConstant *>> 7077 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 7078 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 7079 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 7080 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 7081 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 7082 7083 // We currently can only solve this if the coefficients are constants. 7084 if (!LC || !MC || !NC) 7085 return None; 7086 7087 uint32_t BitWidth = LC->getAPInt().getBitWidth(); 7088 const APInt &L = LC->getAPInt(); 7089 const APInt &M = MC->getAPInt(); 7090 const APInt &N = NC->getAPInt(); 7091 APInt Two(BitWidth, 2); 7092 APInt Four(BitWidth, 4); 7093 7094 { 7095 using namespace APIntOps; 7096 const APInt& C = L; 7097 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C 7098 // The B coefficient is M-N/2 7099 APInt B(M); 7100 B -= sdiv(N,Two); 7101 7102 // The A coefficient is N/2 7103 APInt A(N.sdiv(Two)); 7104 7105 // Compute the B^2-4ac term. 7106 APInt SqrtTerm(B); 7107 SqrtTerm *= B; 7108 SqrtTerm -= Four * (A * C); 7109 7110 if (SqrtTerm.isNegative()) { 7111 // The loop is provably infinite. 7112 return None; 7113 } 7114 7115 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest 7116 // integer value or else APInt::sqrt() will assert. 7117 APInt SqrtVal(SqrtTerm.sqrt()); 7118 7119 // Compute the two solutions for the quadratic formula. 7120 // The divisions must be performed as signed divisions. 7121 APInt NegB(-B); 7122 APInt TwoA(A << 1); 7123 if (TwoA.isMinValue()) 7124 return None; 7125 7126 LLVMContext &Context = SE.getContext(); 7127 7128 ConstantInt *Solution1 = 7129 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA)); 7130 ConstantInt *Solution2 = 7131 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA)); 7132 7133 return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)), 7134 cast<SCEVConstant>(SE.getConstant(Solution2))); 7135 } // end APIntOps namespace 7136 } 7137 7138 ScalarEvolution::ExitLimit 7139 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 7140 bool AllowPredicates) { 7141 7142 // This is only used for loops with a "x != y" exit test. The exit condition 7143 // is now expressed as a single expression, V = x-y. So the exit test is 7144 // effectively V != 0. We know and take advantage of the fact that this 7145 // expression only being used in a comparison by zero context. 7146 7147 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 7148 // If the value is a constant 7149 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 7150 // If the value is already zero, the branch will execute zero times. 7151 if (C->getValue()->isZero()) return C; 7152 return getCouldNotCompute(); // Otherwise it will loop infinitely. 7153 } 7154 7155 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V); 7156 if (!AddRec && AllowPredicates) 7157 // Try to make this an AddRec using runtime tests, in the first X 7158 // iterations of this loop, where X is the SCEV expression found by the 7159 // algorithm below. 7160 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 7161 7162 if (!AddRec || AddRec->getLoop() != L) 7163 return getCouldNotCompute(); 7164 7165 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 7166 // the quadratic equation to solve it. 7167 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 7168 if (auto Roots = SolveQuadraticEquation(AddRec, *this)) { 7169 const SCEVConstant *R1 = Roots->first; 7170 const SCEVConstant *R2 = Roots->second; 7171 // Pick the smallest positive root value. 7172 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp( 7173 CmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) { 7174 if (!CB->getZExtValue()) 7175 std::swap(R1, R2); // R1 is the minimum root now. 7176 7177 // We can only use this value if the chrec ends up with an exact zero 7178 // value at this index. When solving for "X*X != 5", for example, we 7179 // should not accept a root of 2. 7180 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this); 7181 if (Val->isZero()) 7182 // We found a quadratic root! 7183 return ExitLimit(R1, R1, false, Predicates); 7184 } 7185 } 7186 return getCouldNotCompute(); 7187 } 7188 7189 // Otherwise we can only handle this if it is affine. 7190 if (!AddRec->isAffine()) 7191 return getCouldNotCompute(); 7192 7193 // If this is an affine expression, the execution count of this branch is 7194 // the minimum unsigned root of the following equation: 7195 // 7196 // Start + Step*N = 0 (mod 2^BW) 7197 // 7198 // equivalent to: 7199 // 7200 // Step*N = -Start (mod 2^BW) 7201 // 7202 // where BW is the common bit width of Start and Step. 7203 7204 // Get the initial value for the loop. 7205 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 7206 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 7207 7208 // For now we handle only constant steps. 7209 // 7210 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 7211 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 7212 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 7213 // We have not yet seen any such cases. 7214 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 7215 if (!StepC || StepC->getValue()->equalsInt(0)) 7216 return getCouldNotCompute(); 7217 7218 // For positive steps (counting up until unsigned overflow): 7219 // N = -Start/Step (as unsigned) 7220 // For negative steps (counting down to zero): 7221 // N = Start/-Step 7222 // First compute the unsigned distance from zero in the direction of Step. 7223 bool CountDown = StepC->getAPInt().isNegative(); 7224 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 7225 7226 // Handle unitary steps, which cannot wraparound. 7227 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 7228 // N = Distance (as unsigned) 7229 if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) { 7230 ConstantRange CR = getUnsignedRange(Start); 7231 const SCEV *MaxBECount; 7232 if (!CountDown && CR.getUnsignedMin().isMinValue()) 7233 // When counting up, the worst starting value is 1, not 0. 7234 MaxBECount = CR.getUnsignedMax().isMinValue() 7235 ? getConstant(APInt::getMinValue(CR.getBitWidth())) 7236 : getConstant(APInt::getMaxValue(CR.getBitWidth())); 7237 else 7238 MaxBECount = getConstant(CountDown ? CR.getUnsignedMax() 7239 : -CR.getUnsignedMin()); 7240 return ExitLimit(Distance, MaxBECount, false, Predicates); 7241 } 7242 7243 // As a special case, handle the instance where Step is a positive power of 7244 // two. In this case, determining whether Step divides Distance evenly can be 7245 // done by counting and comparing the number of trailing zeros of Step and 7246 // Distance. 7247 if (!CountDown) { 7248 const APInt &StepV = StepC->getAPInt(); 7249 // StepV.isPowerOf2() returns true if StepV is an positive power of two. It 7250 // also returns true if StepV is maximally negative (eg, INT_MIN), but that 7251 // case is not handled as this code is guarded by !CountDown. 7252 if (StepV.isPowerOf2() && 7253 GetMinTrailingZeros(Distance) >= StepV.countTrailingZeros()) { 7254 // Here we've constrained the equation to be of the form 7255 // 7256 // 2^(N + k) * Distance' = (StepV == 2^N) * X (mod 2^W) ... (0) 7257 // 7258 // where we're operating on a W bit wide integer domain and k is 7259 // non-negative. The smallest unsigned solution for X is the trip count. 7260 // 7261 // (0) is equivalent to: 7262 // 7263 // 2^(N + k) * Distance' - 2^N * X = L * 2^W 7264 // <=> 2^N(2^k * Distance' - X) = L * 2^(W - N) * 2^N 7265 // <=> 2^k * Distance' - X = L * 2^(W - N) 7266 // <=> 2^k * Distance' = L * 2^(W - N) + X ... (1) 7267 // 7268 // The smallest X satisfying (1) is unsigned remainder of dividing the LHS 7269 // by 2^(W - N). 7270 // 7271 // <=> X = 2^k * Distance' URem 2^(W - N) ... (2) 7272 // 7273 // E.g. say we're solving 7274 // 7275 // 2 * Val = 2 * X (in i8) ... (3) 7276 // 7277 // then from (2), we get X = Val URem i8 128 (k = 0 in this case). 7278 // 7279 // Note: It is tempting to solve (3) by setting X = Val, but Val is not 7280 // necessarily the smallest unsigned value of X that satisfies (3). 7281 // E.g. if Val is i8 -127 then the smallest value of X that satisfies (3) 7282 // is i8 1, not i8 -127 7283 7284 const auto *ModuloResult = getUDivExactExpr(Distance, Step); 7285 7286 // Since SCEV does not have a URem node, we construct one using a truncate 7287 // and a zero extend. 7288 7289 unsigned NarrowWidth = StepV.getBitWidth() - StepV.countTrailingZeros(); 7290 auto *NarrowTy = IntegerType::get(getContext(), NarrowWidth); 7291 auto *WideTy = Distance->getType(); 7292 7293 const SCEV *Limit = 7294 getZeroExtendExpr(getTruncateExpr(ModuloResult, NarrowTy), WideTy); 7295 return ExitLimit(Limit, Limit, false, Predicates); 7296 } 7297 } 7298 7299 // If the condition controls loop exit (the loop exits only if the expression 7300 // is true) and the addition is no-wrap we can use unsigned divide to 7301 // compute the backedge count. In this case, the step may not divide the 7302 // distance, but we don't care because if the condition is "missed" the loop 7303 // will have undefined behavior due to wrapping. 7304 if (ControlsExit && AddRec->hasNoSelfWrap() && 7305 loopHasNoAbnormalExits(AddRec->getLoop())) { 7306 const SCEV *Exact = 7307 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 7308 return ExitLimit(Exact, Exact, false, Predicates); 7309 } 7310 7311 // Then, try to solve the above equation provided that Start is constant. 7312 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) { 7313 const SCEV *E = SolveLinEquationWithOverflow( 7314 StepC->getValue()->getValue(), -StartC->getValue()->getValue(), *this); 7315 return ExitLimit(E, E, false, Predicates); 7316 } 7317 return getCouldNotCompute(); 7318 } 7319 7320 ScalarEvolution::ExitLimit 7321 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 7322 // Loops that look like: while (X == 0) are very strange indeed. We don't 7323 // handle them yet except for the trivial case. This could be expanded in the 7324 // future as needed. 7325 7326 // If the value is a constant, check to see if it is known to be non-zero 7327 // already. If so, the backedge will execute zero times. 7328 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 7329 if (!C->getValue()->isNullValue()) 7330 return getZero(C->getType()); 7331 return getCouldNotCompute(); // Otherwise it will loop infinitely. 7332 } 7333 7334 // We could implement others, but I really doubt anyone writes loops like 7335 // this, and if they did, they would already be constant folded. 7336 return getCouldNotCompute(); 7337 } 7338 7339 std::pair<BasicBlock *, BasicBlock *> 7340 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) { 7341 // If the block has a unique predecessor, then there is no path from the 7342 // predecessor to the block that does not go through the direct edge 7343 // from the predecessor to the block. 7344 if (BasicBlock *Pred = BB->getSinglePredecessor()) 7345 return {Pred, BB}; 7346 7347 // A loop's header is defined to be a block that dominates the loop. 7348 // If the header has a unique predecessor outside the loop, it must be 7349 // a block that has exactly one successor that can reach the loop. 7350 if (Loop *L = LI.getLoopFor(BB)) 7351 return {L->getLoopPredecessor(), L->getHeader()}; 7352 7353 return {nullptr, nullptr}; 7354 } 7355 7356 /// SCEV structural equivalence is usually sufficient for testing whether two 7357 /// expressions are equal, however for the purposes of looking for a condition 7358 /// guarding a loop, it can be useful to be a little more general, since a 7359 /// front-end may have replicated the controlling expression. 7360 /// 7361 static bool HasSameValue(const SCEV *A, const SCEV *B) { 7362 // Quick check to see if they are the same SCEV. 7363 if (A == B) return true; 7364 7365 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 7366 // Not all instructions that are "identical" compute the same value. For 7367 // instance, two distinct alloca instructions allocating the same type are 7368 // identical and do not read memory; but compute distinct values. 7369 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 7370 }; 7371 7372 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 7373 // two different instructions with the same value. Check for this case. 7374 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 7375 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 7376 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 7377 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 7378 if (ComputesEqualValues(AI, BI)) 7379 return true; 7380 7381 // Otherwise assume they may have a different value. 7382 return false; 7383 } 7384 7385 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 7386 const SCEV *&LHS, const SCEV *&RHS, 7387 unsigned Depth) { 7388 bool Changed = false; 7389 7390 // If we hit the max recursion limit bail out. 7391 if (Depth >= 3) 7392 return false; 7393 7394 // Canonicalize a constant to the right side. 7395 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 7396 // Check for both operands constant. 7397 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 7398 if (ConstantExpr::getICmp(Pred, 7399 LHSC->getValue(), 7400 RHSC->getValue())->isNullValue()) 7401 goto trivially_false; 7402 else 7403 goto trivially_true; 7404 } 7405 // Otherwise swap the operands to put the constant on the right. 7406 std::swap(LHS, RHS); 7407 Pred = ICmpInst::getSwappedPredicate(Pred); 7408 Changed = true; 7409 } 7410 7411 // If we're comparing an addrec with a value which is loop-invariant in the 7412 // addrec's loop, put the addrec on the left. Also make a dominance check, 7413 // as both operands could be addrecs loop-invariant in each other's loop. 7414 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 7415 const Loop *L = AR->getLoop(); 7416 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 7417 std::swap(LHS, RHS); 7418 Pred = ICmpInst::getSwappedPredicate(Pred); 7419 Changed = true; 7420 } 7421 } 7422 7423 // If there's a constant operand, canonicalize comparisons with boundary 7424 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 7425 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 7426 const APInt &RA = RC->getAPInt(); 7427 7428 bool SimplifiedByConstantRange = false; 7429 7430 if (!ICmpInst::isEquality(Pred)) { 7431 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 7432 if (ExactCR.isFullSet()) 7433 goto trivially_true; 7434 else if (ExactCR.isEmptySet()) 7435 goto trivially_false; 7436 7437 APInt NewRHS; 7438 CmpInst::Predicate NewPred; 7439 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 7440 ICmpInst::isEquality(NewPred)) { 7441 // We were able to convert an inequality to an equality. 7442 Pred = NewPred; 7443 RHS = getConstant(NewRHS); 7444 Changed = SimplifiedByConstantRange = true; 7445 } 7446 } 7447 7448 if (!SimplifiedByConstantRange) { 7449 switch (Pred) { 7450 default: 7451 break; 7452 case ICmpInst::ICMP_EQ: 7453 case ICmpInst::ICMP_NE: 7454 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 7455 if (!RA) 7456 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 7457 if (const SCEVMulExpr *ME = 7458 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 7459 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 7460 ME->getOperand(0)->isAllOnesValue()) { 7461 RHS = AE->getOperand(1); 7462 LHS = ME->getOperand(1); 7463 Changed = true; 7464 } 7465 break; 7466 7467 7468 // The "Should have been caught earlier!" messages refer to the fact 7469 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 7470 // should have fired on the corresponding cases, and canonicalized the 7471 // check to trivially_true or trivially_false. 7472 7473 case ICmpInst::ICMP_UGE: 7474 assert(!RA.isMinValue() && "Should have been caught earlier!"); 7475 Pred = ICmpInst::ICMP_UGT; 7476 RHS = getConstant(RA - 1); 7477 Changed = true; 7478 break; 7479 case ICmpInst::ICMP_ULE: 7480 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 7481 Pred = ICmpInst::ICMP_ULT; 7482 RHS = getConstant(RA + 1); 7483 Changed = true; 7484 break; 7485 case ICmpInst::ICMP_SGE: 7486 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 7487 Pred = ICmpInst::ICMP_SGT; 7488 RHS = getConstant(RA - 1); 7489 Changed = true; 7490 break; 7491 case ICmpInst::ICMP_SLE: 7492 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 7493 Pred = ICmpInst::ICMP_SLT; 7494 RHS = getConstant(RA + 1); 7495 Changed = true; 7496 break; 7497 } 7498 } 7499 } 7500 7501 // Check for obvious equality. 7502 if (HasSameValue(LHS, RHS)) { 7503 if (ICmpInst::isTrueWhenEqual(Pred)) 7504 goto trivially_true; 7505 if (ICmpInst::isFalseWhenEqual(Pred)) 7506 goto trivially_false; 7507 } 7508 7509 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 7510 // adding or subtracting 1 from one of the operands. 7511 switch (Pred) { 7512 case ICmpInst::ICMP_SLE: 7513 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) { 7514 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 7515 SCEV::FlagNSW); 7516 Pred = ICmpInst::ICMP_SLT; 7517 Changed = true; 7518 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) { 7519 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 7520 SCEV::FlagNSW); 7521 Pred = ICmpInst::ICMP_SLT; 7522 Changed = true; 7523 } 7524 break; 7525 case ICmpInst::ICMP_SGE: 7526 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) { 7527 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 7528 SCEV::FlagNSW); 7529 Pred = ICmpInst::ICMP_SGT; 7530 Changed = true; 7531 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) { 7532 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 7533 SCEV::FlagNSW); 7534 Pred = ICmpInst::ICMP_SGT; 7535 Changed = true; 7536 } 7537 break; 7538 case ICmpInst::ICMP_ULE: 7539 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) { 7540 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 7541 SCEV::FlagNUW); 7542 Pred = ICmpInst::ICMP_ULT; 7543 Changed = true; 7544 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) { 7545 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 7546 Pred = ICmpInst::ICMP_ULT; 7547 Changed = true; 7548 } 7549 break; 7550 case ICmpInst::ICMP_UGE: 7551 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) { 7552 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 7553 Pred = ICmpInst::ICMP_UGT; 7554 Changed = true; 7555 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) { 7556 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 7557 SCEV::FlagNUW); 7558 Pred = ICmpInst::ICMP_UGT; 7559 Changed = true; 7560 } 7561 break; 7562 default: 7563 break; 7564 } 7565 7566 // TODO: More simplifications are possible here. 7567 7568 // Recursively simplify until we either hit a recursion limit or nothing 7569 // changes. 7570 if (Changed) 7571 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 7572 7573 return Changed; 7574 7575 trivially_true: 7576 // Return 0 == 0. 7577 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 7578 Pred = ICmpInst::ICMP_EQ; 7579 return true; 7580 7581 trivially_false: 7582 // Return 0 != 0. 7583 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 7584 Pred = ICmpInst::ICMP_NE; 7585 return true; 7586 } 7587 7588 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 7589 return getSignedRange(S).getSignedMax().isNegative(); 7590 } 7591 7592 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 7593 return getSignedRange(S).getSignedMin().isStrictlyPositive(); 7594 } 7595 7596 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 7597 return !getSignedRange(S).getSignedMin().isNegative(); 7598 } 7599 7600 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 7601 return !getSignedRange(S).getSignedMax().isStrictlyPositive(); 7602 } 7603 7604 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 7605 return isKnownNegative(S) || isKnownPositive(S); 7606 } 7607 7608 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 7609 const SCEV *LHS, const SCEV *RHS) { 7610 // Canonicalize the inputs first. 7611 (void)SimplifyICmpOperands(Pred, LHS, RHS); 7612 7613 // If LHS or RHS is an addrec, check to see if the condition is true in 7614 // every iteration of the loop. 7615 // If LHS and RHS are both addrec, both conditions must be true in 7616 // every iteration of the loop. 7617 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 7618 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 7619 bool LeftGuarded = false; 7620 bool RightGuarded = false; 7621 if (LAR) { 7622 const Loop *L = LAR->getLoop(); 7623 if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) && 7624 isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) { 7625 if (!RAR) return true; 7626 LeftGuarded = true; 7627 } 7628 } 7629 if (RAR) { 7630 const Loop *L = RAR->getLoop(); 7631 if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) && 7632 isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) { 7633 if (!LAR) return true; 7634 RightGuarded = true; 7635 } 7636 } 7637 if (LeftGuarded && RightGuarded) 7638 return true; 7639 7640 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 7641 return true; 7642 7643 // Otherwise see what can be done with known constant ranges. 7644 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS); 7645 } 7646 7647 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS, 7648 ICmpInst::Predicate Pred, 7649 bool &Increasing) { 7650 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing); 7651 7652 #ifndef NDEBUG 7653 // Verify an invariant: inverting the predicate should turn a monotonically 7654 // increasing change to a monotonically decreasing one, and vice versa. 7655 bool IncreasingSwapped; 7656 bool ResultSwapped = isMonotonicPredicateImpl( 7657 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped); 7658 7659 assert(Result == ResultSwapped && "should be able to analyze both!"); 7660 if (ResultSwapped) 7661 assert(Increasing == !IncreasingSwapped && 7662 "monotonicity should flip as we flip the predicate"); 7663 #endif 7664 7665 return Result; 7666 } 7667 7668 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS, 7669 ICmpInst::Predicate Pred, 7670 bool &Increasing) { 7671 7672 // A zero step value for LHS means the induction variable is essentially a 7673 // loop invariant value. We don't really depend on the predicate actually 7674 // flipping from false to true (for increasing predicates, and the other way 7675 // around for decreasing predicates), all we care about is that *if* the 7676 // predicate changes then it only changes from false to true. 7677 // 7678 // A zero step value in itself is not very useful, but there may be places 7679 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 7680 // as general as possible. 7681 7682 switch (Pred) { 7683 default: 7684 return false; // Conservative answer 7685 7686 case ICmpInst::ICMP_UGT: 7687 case ICmpInst::ICMP_UGE: 7688 case ICmpInst::ICMP_ULT: 7689 case ICmpInst::ICMP_ULE: 7690 if (!LHS->hasNoUnsignedWrap()) 7691 return false; 7692 7693 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE; 7694 return true; 7695 7696 case ICmpInst::ICMP_SGT: 7697 case ICmpInst::ICMP_SGE: 7698 case ICmpInst::ICMP_SLT: 7699 case ICmpInst::ICMP_SLE: { 7700 if (!LHS->hasNoSignedWrap()) 7701 return false; 7702 7703 const SCEV *Step = LHS->getStepRecurrence(*this); 7704 7705 if (isKnownNonNegative(Step)) { 7706 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE; 7707 return true; 7708 } 7709 7710 if (isKnownNonPositive(Step)) { 7711 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE; 7712 return true; 7713 } 7714 7715 return false; 7716 } 7717 7718 } 7719 7720 llvm_unreachable("switch has default clause!"); 7721 } 7722 7723 bool ScalarEvolution::isLoopInvariantPredicate( 7724 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 7725 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS, 7726 const SCEV *&InvariantRHS) { 7727 7728 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 7729 if (!isLoopInvariant(RHS, L)) { 7730 if (!isLoopInvariant(LHS, L)) 7731 return false; 7732 7733 std::swap(LHS, RHS); 7734 Pred = ICmpInst::getSwappedPredicate(Pred); 7735 } 7736 7737 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 7738 if (!ArLHS || ArLHS->getLoop() != L) 7739 return false; 7740 7741 bool Increasing; 7742 if (!isMonotonicPredicate(ArLHS, Pred, Increasing)) 7743 return false; 7744 7745 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 7746 // true as the loop iterates, and the backedge is control dependent on 7747 // "ArLHS `Pred` RHS" == true then we can reason as follows: 7748 // 7749 // * if the predicate was false in the first iteration then the predicate 7750 // is never evaluated again, since the loop exits without taking the 7751 // backedge. 7752 // * if the predicate was true in the first iteration then it will 7753 // continue to be true for all future iterations since it is 7754 // monotonically increasing. 7755 // 7756 // For both the above possibilities, we can replace the loop varying 7757 // predicate with its value on the first iteration of the loop (which is 7758 // loop invariant). 7759 // 7760 // A similar reasoning applies for a monotonically decreasing predicate, by 7761 // replacing true with false and false with true in the above two bullets. 7762 7763 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 7764 7765 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 7766 return false; 7767 7768 InvariantPred = Pred; 7769 InvariantLHS = ArLHS->getStart(); 7770 InvariantRHS = RHS; 7771 return true; 7772 } 7773 7774 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 7775 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 7776 if (HasSameValue(LHS, RHS)) 7777 return ICmpInst::isTrueWhenEqual(Pred); 7778 7779 // This code is split out from isKnownPredicate because it is called from 7780 // within isLoopEntryGuardedByCond. 7781 7782 auto CheckRanges = 7783 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) { 7784 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS) 7785 .contains(RangeLHS); 7786 }; 7787 7788 // The check at the top of the function catches the case where the values are 7789 // known to be equal. 7790 if (Pred == CmpInst::ICMP_EQ) 7791 return false; 7792 7793 if (Pred == CmpInst::ICMP_NE) 7794 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 7795 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) || 7796 isKnownNonZero(getMinusSCEV(LHS, RHS)); 7797 7798 if (CmpInst::isSigned(Pred)) 7799 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 7800 7801 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 7802 } 7803 7804 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 7805 const SCEV *LHS, 7806 const SCEV *RHS) { 7807 7808 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer. 7809 // Return Y via OutY. 7810 auto MatchBinaryAddToConst = 7811 [this](const SCEV *Result, const SCEV *X, APInt &OutY, 7812 SCEV::NoWrapFlags ExpectedFlags) { 7813 const SCEV *NonConstOp, *ConstOp; 7814 SCEV::NoWrapFlags FlagsPresent; 7815 7816 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) || 7817 !isa<SCEVConstant>(ConstOp) || NonConstOp != X) 7818 return false; 7819 7820 OutY = cast<SCEVConstant>(ConstOp)->getAPInt(); 7821 return (FlagsPresent & ExpectedFlags) == ExpectedFlags; 7822 }; 7823 7824 APInt C; 7825 7826 switch (Pred) { 7827 default: 7828 break; 7829 7830 case ICmpInst::ICMP_SGE: 7831 std::swap(LHS, RHS); 7832 case ICmpInst::ICMP_SLE: 7833 // X s<= (X + C)<nsw> if C >= 0 7834 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative()) 7835 return true; 7836 7837 // (X + C)<nsw> s<= X if C <= 0 7838 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && 7839 !C.isStrictlyPositive()) 7840 return true; 7841 break; 7842 7843 case ICmpInst::ICMP_SGT: 7844 std::swap(LHS, RHS); 7845 case ICmpInst::ICMP_SLT: 7846 // X s< (X + C)<nsw> if C > 0 7847 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && 7848 C.isStrictlyPositive()) 7849 return true; 7850 7851 // (X + C)<nsw> s< X if C < 0 7852 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative()) 7853 return true; 7854 break; 7855 } 7856 7857 return false; 7858 } 7859 7860 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 7861 const SCEV *LHS, 7862 const SCEV *RHS) { 7863 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 7864 return false; 7865 7866 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 7867 // the stack can result in exponential time complexity. 7868 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 7869 7870 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 7871 // 7872 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 7873 // isKnownPredicate. isKnownPredicate is more powerful, but also more 7874 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 7875 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 7876 // use isKnownPredicate later if needed. 7877 return isKnownNonNegative(RHS) && 7878 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 7879 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 7880 } 7881 7882 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB, 7883 ICmpInst::Predicate Pred, 7884 const SCEV *LHS, const SCEV *RHS) { 7885 // No need to even try if we know the module has no guards. 7886 if (!HasGuards) 7887 return false; 7888 7889 return any_of(*BB, [&](Instruction &I) { 7890 using namespace llvm::PatternMatch; 7891 7892 Value *Condition; 7893 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 7894 m_Value(Condition))) && 7895 isImpliedCond(Pred, LHS, RHS, Condition, false); 7896 }); 7897 } 7898 7899 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 7900 /// protected by a conditional between LHS and RHS. This is used to 7901 /// to eliminate casts. 7902 bool 7903 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 7904 ICmpInst::Predicate Pred, 7905 const SCEV *LHS, const SCEV *RHS) { 7906 // Interpret a null as meaning no loop, where there is obviously no guard 7907 // (interprocedural conditions notwithstanding). 7908 if (!L) return true; 7909 7910 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS)) 7911 return true; 7912 7913 BasicBlock *Latch = L->getLoopLatch(); 7914 if (!Latch) 7915 return false; 7916 7917 BranchInst *LoopContinuePredicate = 7918 dyn_cast<BranchInst>(Latch->getTerminator()); 7919 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 7920 isImpliedCond(Pred, LHS, RHS, 7921 LoopContinuePredicate->getCondition(), 7922 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 7923 return true; 7924 7925 // We don't want more than one activation of the following loops on the stack 7926 // -- that can lead to O(n!) time complexity. 7927 if (WalkingBEDominatingConds) 7928 return false; 7929 7930 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 7931 7932 // See if we can exploit a trip count to prove the predicate. 7933 const auto &BETakenInfo = getBackedgeTakenInfo(L); 7934 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 7935 if (LatchBECount != getCouldNotCompute()) { 7936 // We know that Latch branches back to the loop header exactly 7937 // LatchBECount times. This means the backdege condition at Latch is 7938 // equivalent to "{0,+,1} u< LatchBECount". 7939 Type *Ty = LatchBECount->getType(); 7940 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 7941 const SCEV *LoopCounter = 7942 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 7943 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 7944 LatchBECount)) 7945 return true; 7946 } 7947 7948 // Check conditions due to any @llvm.assume intrinsics. 7949 for (auto &AssumeVH : AC.assumptions()) { 7950 if (!AssumeVH) 7951 continue; 7952 auto *CI = cast<CallInst>(AssumeVH); 7953 if (!DT.dominates(CI, Latch->getTerminator())) 7954 continue; 7955 7956 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 7957 return true; 7958 } 7959 7960 // If the loop is not reachable from the entry block, we risk running into an 7961 // infinite loop as we walk up into the dom tree. These loops do not matter 7962 // anyway, so we just return a conservative answer when we see them. 7963 if (!DT.isReachableFromEntry(L->getHeader())) 7964 return false; 7965 7966 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 7967 return true; 7968 7969 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 7970 DTN != HeaderDTN; DTN = DTN->getIDom()) { 7971 7972 assert(DTN && "should reach the loop header before reaching the root!"); 7973 7974 BasicBlock *BB = DTN->getBlock(); 7975 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 7976 return true; 7977 7978 BasicBlock *PBB = BB->getSinglePredecessor(); 7979 if (!PBB) 7980 continue; 7981 7982 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 7983 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 7984 continue; 7985 7986 Value *Condition = ContinuePredicate->getCondition(); 7987 7988 // If we have an edge `E` within the loop body that dominates the only 7989 // latch, the condition guarding `E` also guards the backedge. This 7990 // reasoning works only for loops with a single latch. 7991 7992 BasicBlockEdge DominatingEdge(PBB, BB); 7993 if (DominatingEdge.isSingleEdge()) { 7994 // We're constructively (and conservatively) enumerating edges within the 7995 // loop body that dominate the latch. The dominator tree better agree 7996 // with us on this: 7997 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 7998 7999 if (isImpliedCond(Pred, LHS, RHS, Condition, 8000 BB != ContinuePredicate->getSuccessor(0))) 8001 return true; 8002 } 8003 } 8004 8005 return false; 8006 } 8007 8008 bool 8009 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 8010 ICmpInst::Predicate Pred, 8011 const SCEV *LHS, const SCEV *RHS) { 8012 // Interpret a null as meaning no loop, where there is obviously no guard 8013 // (interprocedural conditions notwithstanding). 8014 if (!L) return false; 8015 8016 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS)) 8017 return true; 8018 8019 // Starting at the loop predecessor, climb up the predecessor chain, as long 8020 // as there are predecessors that can be found that have unique successors 8021 // leading to the original header. 8022 for (std::pair<BasicBlock *, BasicBlock *> 8023 Pair(L->getLoopPredecessor(), L->getHeader()); 8024 Pair.first; 8025 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 8026 8027 if (isImpliedViaGuard(Pair.first, Pred, LHS, RHS)) 8028 return true; 8029 8030 BranchInst *LoopEntryPredicate = 8031 dyn_cast<BranchInst>(Pair.first->getTerminator()); 8032 if (!LoopEntryPredicate || 8033 LoopEntryPredicate->isUnconditional()) 8034 continue; 8035 8036 if (isImpliedCond(Pred, LHS, RHS, 8037 LoopEntryPredicate->getCondition(), 8038 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 8039 return true; 8040 } 8041 8042 // Check conditions due to any @llvm.assume intrinsics. 8043 for (auto &AssumeVH : AC.assumptions()) { 8044 if (!AssumeVH) 8045 continue; 8046 auto *CI = cast<CallInst>(AssumeVH); 8047 if (!DT.dominates(CI, L->getHeader())) 8048 continue; 8049 8050 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 8051 return true; 8052 } 8053 8054 return false; 8055 } 8056 8057 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, 8058 const SCEV *LHS, const SCEV *RHS, 8059 Value *FoundCondValue, 8060 bool Inverse) { 8061 if (!PendingLoopPredicates.insert(FoundCondValue).second) 8062 return false; 8063 8064 auto ClearOnExit = 8065 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 8066 8067 // Recursively handle And and Or conditions. 8068 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) { 8069 if (BO->getOpcode() == Instruction::And) { 8070 if (!Inverse) 8071 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 8072 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 8073 } else if (BO->getOpcode() == Instruction::Or) { 8074 if (Inverse) 8075 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 8076 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 8077 } 8078 } 8079 8080 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 8081 if (!ICI) return false; 8082 8083 // Now that we found a conditional branch that dominates the loop or controls 8084 // the loop latch. Check to see if it is the comparison we are looking for. 8085 ICmpInst::Predicate FoundPred; 8086 if (Inverse) 8087 FoundPred = ICI->getInversePredicate(); 8088 else 8089 FoundPred = ICI->getPredicate(); 8090 8091 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 8092 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 8093 8094 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS); 8095 } 8096 8097 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 8098 const SCEV *RHS, 8099 ICmpInst::Predicate FoundPred, 8100 const SCEV *FoundLHS, 8101 const SCEV *FoundRHS) { 8102 // Balance the types. 8103 if (getTypeSizeInBits(LHS->getType()) < 8104 getTypeSizeInBits(FoundLHS->getType())) { 8105 if (CmpInst::isSigned(Pred)) { 8106 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 8107 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 8108 } else { 8109 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 8110 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 8111 } 8112 } else if (getTypeSizeInBits(LHS->getType()) > 8113 getTypeSizeInBits(FoundLHS->getType())) { 8114 if (CmpInst::isSigned(FoundPred)) { 8115 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 8116 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 8117 } else { 8118 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 8119 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 8120 } 8121 } 8122 8123 // Canonicalize the query to match the way instcombine will have 8124 // canonicalized the comparison. 8125 if (SimplifyICmpOperands(Pred, LHS, RHS)) 8126 if (LHS == RHS) 8127 return CmpInst::isTrueWhenEqual(Pred); 8128 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 8129 if (FoundLHS == FoundRHS) 8130 return CmpInst::isFalseWhenEqual(FoundPred); 8131 8132 // Check to see if we can make the LHS or RHS match. 8133 if (LHS == FoundRHS || RHS == FoundLHS) { 8134 if (isa<SCEVConstant>(RHS)) { 8135 std::swap(FoundLHS, FoundRHS); 8136 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 8137 } else { 8138 std::swap(LHS, RHS); 8139 Pred = ICmpInst::getSwappedPredicate(Pred); 8140 } 8141 } 8142 8143 // Check whether the found predicate is the same as the desired predicate. 8144 if (FoundPred == Pred) 8145 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 8146 8147 // Check whether swapping the found predicate makes it the same as the 8148 // desired predicate. 8149 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 8150 if (isa<SCEVConstant>(RHS)) 8151 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS); 8152 else 8153 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), 8154 RHS, LHS, FoundLHS, FoundRHS); 8155 } 8156 8157 // Unsigned comparison is the same as signed comparison when both the operands 8158 // are non-negative. 8159 if (CmpInst::isUnsigned(FoundPred) && 8160 CmpInst::getSignedPredicate(FoundPred) == Pred && 8161 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) 8162 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 8163 8164 // Check if we can make progress by sharpening ranges. 8165 if (FoundPred == ICmpInst::ICMP_NE && 8166 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 8167 8168 const SCEVConstant *C = nullptr; 8169 const SCEV *V = nullptr; 8170 8171 if (isa<SCEVConstant>(FoundLHS)) { 8172 C = cast<SCEVConstant>(FoundLHS); 8173 V = FoundRHS; 8174 } else { 8175 C = cast<SCEVConstant>(FoundRHS); 8176 V = FoundLHS; 8177 } 8178 8179 // The guarding predicate tells us that C != V. If the known range 8180 // of V is [C, t), we can sharpen the range to [C + 1, t). The 8181 // range we consider has to correspond to same signedness as the 8182 // predicate we're interested in folding. 8183 8184 APInt Min = ICmpInst::isSigned(Pred) ? 8185 getSignedRange(V).getSignedMin() : getUnsignedRange(V).getUnsignedMin(); 8186 8187 if (Min == C->getAPInt()) { 8188 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 8189 // This is true even if (Min + 1) wraps around -- in case of 8190 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 8191 8192 APInt SharperMin = Min + 1; 8193 8194 switch (Pred) { 8195 case ICmpInst::ICMP_SGE: 8196 case ICmpInst::ICMP_UGE: 8197 // We know V `Pred` SharperMin. If this implies LHS `Pred` 8198 // RHS, we're done. 8199 if (isImpliedCondOperands(Pred, LHS, RHS, V, 8200 getConstant(SharperMin))) 8201 return true; 8202 8203 case ICmpInst::ICMP_SGT: 8204 case ICmpInst::ICMP_UGT: 8205 // We know from the range information that (V `Pred` Min || 8206 // V == Min). We know from the guarding condition that !(V 8207 // == Min). This gives us 8208 // 8209 // V `Pred` Min || V == Min && !(V == Min) 8210 // => V `Pred` Min 8211 // 8212 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 8213 8214 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min))) 8215 return true; 8216 8217 default: 8218 // No change 8219 break; 8220 } 8221 } 8222 } 8223 8224 // Check whether the actual condition is beyond sufficient. 8225 if (FoundPred == ICmpInst::ICMP_EQ) 8226 if (ICmpInst::isTrueWhenEqual(Pred)) 8227 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS)) 8228 return true; 8229 if (Pred == ICmpInst::ICMP_NE) 8230 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 8231 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS)) 8232 return true; 8233 8234 // Otherwise assume the worst. 8235 return false; 8236 } 8237 8238 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 8239 const SCEV *&L, const SCEV *&R, 8240 SCEV::NoWrapFlags &Flags) { 8241 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 8242 if (!AE || AE->getNumOperands() != 2) 8243 return false; 8244 8245 L = AE->getOperand(0); 8246 R = AE->getOperand(1); 8247 Flags = AE->getNoWrapFlags(); 8248 return true; 8249 } 8250 8251 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 8252 const SCEV *Less) { 8253 // We avoid subtracting expressions here because this function is usually 8254 // fairly deep in the call stack (i.e. is called many times). 8255 8256 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 8257 const auto *LAR = cast<SCEVAddRecExpr>(Less); 8258 const auto *MAR = cast<SCEVAddRecExpr>(More); 8259 8260 if (LAR->getLoop() != MAR->getLoop()) 8261 return None; 8262 8263 // We look at affine expressions only; not for correctness but to keep 8264 // getStepRecurrence cheap. 8265 if (!LAR->isAffine() || !MAR->isAffine()) 8266 return None; 8267 8268 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 8269 return None; 8270 8271 Less = LAR->getStart(); 8272 More = MAR->getStart(); 8273 8274 // fall through 8275 } 8276 8277 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 8278 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 8279 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 8280 return M - L; 8281 } 8282 8283 const SCEV *L, *R; 8284 SCEV::NoWrapFlags Flags; 8285 if (splitBinaryAdd(Less, L, R, Flags)) 8286 if (const auto *LC = dyn_cast<SCEVConstant>(L)) 8287 if (R == More) 8288 return -(LC->getAPInt()); 8289 8290 if (splitBinaryAdd(More, L, R, Flags)) 8291 if (const auto *LC = dyn_cast<SCEVConstant>(L)) 8292 if (R == Less) 8293 return LC->getAPInt(); 8294 8295 return None; 8296 } 8297 8298 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 8299 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 8300 const SCEV *FoundLHS, const SCEV *FoundRHS) { 8301 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 8302 return false; 8303 8304 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 8305 if (!AddRecLHS) 8306 return false; 8307 8308 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 8309 if (!AddRecFoundLHS) 8310 return false; 8311 8312 // We'd like to let SCEV reason about control dependencies, so we constrain 8313 // both the inequalities to be about add recurrences on the same loop. This 8314 // way we can use isLoopEntryGuardedByCond later. 8315 8316 const Loop *L = AddRecFoundLHS->getLoop(); 8317 if (L != AddRecLHS->getLoop()) 8318 return false; 8319 8320 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 8321 // 8322 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 8323 // ... (2) 8324 // 8325 // Informal proof for (2), assuming (1) [*]: 8326 // 8327 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 8328 // 8329 // Then 8330 // 8331 // FoundLHS s< FoundRHS s< INT_MIN - C 8332 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 8333 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 8334 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 8335 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 8336 // <=> FoundLHS + C s< FoundRHS + C 8337 // 8338 // [*]: (1) can be proved by ruling out overflow. 8339 // 8340 // [**]: This can be proved by analyzing all the four possibilities: 8341 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 8342 // (A s>= 0, B s>= 0). 8343 // 8344 // Note: 8345 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 8346 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 8347 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 8348 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 8349 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 8350 // C)". 8351 8352 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 8353 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 8354 if (!LDiff || !RDiff || *LDiff != *RDiff) 8355 return false; 8356 8357 if (LDiff->isMinValue()) 8358 return true; 8359 8360 APInt FoundRHSLimit; 8361 8362 if (Pred == CmpInst::ICMP_ULT) { 8363 FoundRHSLimit = -(*RDiff); 8364 } else { 8365 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 8366 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 8367 } 8368 8369 // Try to prove (1) or (2), as needed. 8370 return isLoopEntryGuardedByCond(L, Pred, FoundRHS, 8371 getConstant(FoundRHSLimit)); 8372 } 8373 8374 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 8375 const SCEV *LHS, const SCEV *RHS, 8376 const SCEV *FoundLHS, 8377 const SCEV *FoundRHS) { 8378 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 8379 return true; 8380 8381 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 8382 return true; 8383 8384 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 8385 FoundLHS, FoundRHS) || 8386 // ~x < ~y --> x > y 8387 isImpliedCondOperandsHelper(Pred, LHS, RHS, 8388 getNotSCEV(FoundRHS), 8389 getNotSCEV(FoundLHS)); 8390 } 8391 8392 8393 /// If Expr computes ~A, return A else return nullptr 8394 static const SCEV *MatchNotExpr(const SCEV *Expr) { 8395 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 8396 if (!Add || Add->getNumOperands() != 2 || 8397 !Add->getOperand(0)->isAllOnesValue()) 8398 return nullptr; 8399 8400 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 8401 if (!AddRHS || AddRHS->getNumOperands() != 2 || 8402 !AddRHS->getOperand(0)->isAllOnesValue()) 8403 return nullptr; 8404 8405 return AddRHS->getOperand(1); 8406 } 8407 8408 8409 /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values? 8410 template<typename MaxExprType> 8411 static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr, 8412 const SCEV *Candidate) { 8413 const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr); 8414 if (!MaxExpr) return false; 8415 8416 return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end(); 8417 } 8418 8419 8420 /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values? 8421 template<typename MaxExprType> 8422 static bool IsMinConsistingOf(ScalarEvolution &SE, 8423 const SCEV *MaybeMinExpr, 8424 const SCEV *Candidate) { 8425 const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr); 8426 if (!MaybeMaxExpr) 8427 return false; 8428 8429 return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate)); 8430 } 8431 8432 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 8433 ICmpInst::Predicate Pred, 8434 const SCEV *LHS, const SCEV *RHS) { 8435 8436 // If both sides are affine addrecs for the same loop, with equal 8437 // steps, and we know the recurrences don't wrap, then we only 8438 // need to check the predicate on the starting values. 8439 8440 if (!ICmpInst::isRelational(Pred)) 8441 return false; 8442 8443 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 8444 if (!LAR) 8445 return false; 8446 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 8447 if (!RAR) 8448 return false; 8449 if (LAR->getLoop() != RAR->getLoop()) 8450 return false; 8451 if (!LAR->isAffine() || !RAR->isAffine()) 8452 return false; 8453 8454 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 8455 return false; 8456 8457 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 8458 SCEV::FlagNSW : SCEV::FlagNUW; 8459 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 8460 return false; 8461 8462 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 8463 } 8464 8465 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 8466 /// expression? 8467 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 8468 ICmpInst::Predicate Pred, 8469 const SCEV *LHS, const SCEV *RHS) { 8470 switch (Pred) { 8471 default: 8472 return false; 8473 8474 case ICmpInst::ICMP_SGE: 8475 std::swap(LHS, RHS); 8476 LLVM_FALLTHROUGH; 8477 case ICmpInst::ICMP_SLE: 8478 return 8479 // min(A, ...) <= A 8480 IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) || 8481 // A <= max(A, ...) 8482 IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 8483 8484 case ICmpInst::ICMP_UGE: 8485 std::swap(LHS, RHS); 8486 LLVM_FALLTHROUGH; 8487 case ICmpInst::ICMP_ULE: 8488 return 8489 // min(A, ...) <= A 8490 IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) || 8491 // A <= max(A, ...) 8492 IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 8493 } 8494 8495 llvm_unreachable("covered switch fell through?!"); 8496 } 8497 8498 bool 8499 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 8500 const SCEV *LHS, const SCEV *RHS, 8501 const SCEV *FoundLHS, 8502 const SCEV *FoundRHS) { 8503 auto IsKnownPredicateFull = 8504 [this](ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 8505 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 8506 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 8507 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 8508 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 8509 }; 8510 8511 switch (Pred) { 8512 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 8513 case ICmpInst::ICMP_EQ: 8514 case ICmpInst::ICMP_NE: 8515 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 8516 return true; 8517 break; 8518 case ICmpInst::ICMP_SLT: 8519 case ICmpInst::ICMP_SLE: 8520 if (IsKnownPredicateFull(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 8521 IsKnownPredicateFull(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 8522 return true; 8523 break; 8524 case ICmpInst::ICMP_SGT: 8525 case ICmpInst::ICMP_SGE: 8526 if (IsKnownPredicateFull(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 8527 IsKnownPredicateFull(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 8528 return true; 8529 break; 8530 case ICmpInst::ICMP_ULT: 8531 case ICmpInst::ICMP_ULE: 8532 if (IsKnownPredicateFull(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 8533 IsKnownPredicateFull(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 8534 return true; 8535 break; 8536 case ICmpInst::ICMP_UGT: 8537 case ICmpInst::ICMP_UGE: 8538 if (IsKnownPredicateFull(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 8539 IsKnownPredicateFull(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 8540 return true; 8541 break; 8542 } 8543 8544 return false; 8545 } 8546 8547 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 8548 const SCEV *LHS, 8549 const SCEV *RHS, 8550 const SCEV *FoundLHS, 8551 const SCEV *FoundRHS) { 8552 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 8553 // The restriction on `FoundRHS` be lifted easily -- it exists only to 8554 // reduce the compile time impact of this optimization. 8555 return false; 8556 8557 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 8558 if (!Addend) 8559 return false; 8560 8561 APInt ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 8562 8563 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 8564 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 8565 ConstantRange FoundLHSRange = 8566 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); 8567 8568 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 8569 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 8570 8571 // We can also compute the range of values for `LHS` that satisfy the 8572 // consequent, "`LHS` `Pred` `RHS`": 8573 APInt ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 8574 ConstantRange SatisfyingLHSRange = 8575 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS); 8576 8577 // The antecedent implies the consequent if every value of `LHS` that 8578 // satisfies the antecedent also satisfies the consequent. 8579 return SatisfyingLHSRange.contains(LHSRange); 8580 } 8581 8582 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 8583 bool IsSigned, bool NoWrap) { 8584 assert(isKnownPositive(Stride) && "Positive stride expected!"); 8585 8586 if (NoWrap) return false; 8587 8588 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 8589 const SCEV *One = getOne(Stride->getType()); 8590 8591 if (IsSigned) { 8592 APInt MaxRHS = getSignedRange(RHS).getSignedMax(); 8593 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 8594 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One)) 8595 .getSignedMax(); 8596 8597 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 8598 return (MaxValue - MaxStrideMinusOne).slt(MaxRHS); 8599 } 8600 8601 APInt MaxRHS = getUnsignedRange(RHS).getUnsignedMax(); 8602 APInt MaxValue = APInt::getMaxValue(BitWidth); 8603 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One)) 8604 .getUnsignedMax(); 8605 8606 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 8607 return (MaxValue - MaxStrideMinusOne).ult(MaxRHS); 8608 } 8609 8610 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 8611 bool IsSigned, bool NoWrap) { 8612 if (NoWrap) return false; 8613 8614 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 8615 const SCEV *One = getOne(Stride->getType()); 8616 8617 if (IsSigned) { 8618 APInt MinRHS = getSignedRange(RHS).getSignedMin(); 8619 APInt MinValue = APInt::getSignedMinValue(BitWidth); 8620 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One)) 8621 .getSignedMax(); 8622 8623 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 8624 return (MinValue + MaxStrideMinusOne).sgt(MinRHS); 8625 } 8626 8627 APInt MinRHS = getUnsignedRange(RHS).getUnsignedMin(); 8628 APInt MinValue = APInt::getMinValue(BitWidth); 8629 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One)) 8630 .getUnsignedMax(); 8631 8632 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 8633 return (MinValue + MaxStrideMinusOne).ugt(MinRHS); 8634 } 8635 8636 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step, 8637 bool Equality) { 8638 const SCEV *One = getOne(Step->getType()); 8639 Delta = Equality ? getAddExpr(Delta, Step) 8640 : getAddExpr(Delta, getMinusSCEV(Step, One)); 8641 return getUDivExpr(Delta, Step); 8642 } 8643 8644 ScalarEvolution::ExitLimit 8645 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 8646 const Loop *L, bool IsSigned, 8647 bool ControlsExit, bool AllowPredicates) { 8648 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 8649 // We handle only IV < Invariant 8650 if (!isLoopInvariant(RHS, L)) 8651 return getCouldNotCompute(); 8652 8653 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 8654 bool PredicatedIV = false; 8655 8656 if (!IV && AllowPredicates) { 8657 // Try to make this an AddRec using runtime tests, in the first X 8658 // iterations of this loop, where X is the SCEV expression found by the 8659 // algorithm below. 8660 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 8661 PredicatedIV = true; 8662 } 8663 8664 // Avoid weird loops 8665 if (!IV || IV->getLoop() != L || !IV->isAffine()) 8666 return getCouldNotCompute(); 8667 8668 bool NoWrap = ControlsExit && 8669 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 8670 8671 const SCEV *Stride = IV->getStepRecurrence(*this); 8672 8673 bool PositiveStride = isKnownPositive(Stride); 8674 8675 // Avoid negative or zero stride values. 8676 if (!PositiveStride) { 8677 // We can compute the correct backedge taken count for loops with unknown 8678 // strides if we can prove that the loop is not an infinite loop with side 8679 // effects. Here's the loop structure we are trying to handle - 8680 // 8681 // i = start 8682 // do { 8683 // A[i] = i; 8684 // i += s; 8685 // } while (i < end); 8686 // 8687 // The backedge taken count for such loops is evaluated as - 8688 // (max(end, start + stride) - start - 1) /u stride 8689 // 8690 // The additional preconditions that we need to check to prove correctness 8691 // of the above formula is as follows - 8692 // 8693 // a) IV is either nuw or nsw depending upon signedness (indicated by the 8694 // NoWrap flag). 8695 // b) loop is single exit with no side effects. 8696 // 8697 // 8698 // Precondition a) implies that if the stride is negative, this is a single 8699 // trip loop. The backedge taken count formula reduces to zero in this case. 8700 // 8701 // Precondition b) implies that the unknown stride cannot be zero otherwise 8702 // we have UB. 8703 // 8704 // The positive stride case is the same as isKnownPositive(Stride) returning 8705 // true (original behavior of the function). 8706 // 8707 // We want to make sure that the stride is truly unknown as there are edge 8708 // cases where ScalarEvolution propagates no wrap flags to the 8709 // post-increment/decrement IV even though the increment/decrement operation 8710 // itself is wrapping. The computed backedge taken count may be wrong in 8711 // such cases. This is prevented by checking that the stride is not known to 8712 // be either positive or non-positive. For example, no wrap flags are 8713 // propagated to the post-increment IV of this loop with a trip count of 2 - 8714 // 8715 // unsigned char i; 8716 // for(i=127; i<128; i+=129) 8717 // A[i] = i; 8718 // 8719 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) || 8720 !loopHasNoSideEffects(L)) 8721 return getCouldNotCompute(); 8722 8723 } else if (!Stride->isOne() && 8724 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap)) 8725 // Avoid proven overflow cases: this will ensure that the backedge taken 8726 // count will not generate any unsigned overflow. Relaxed no-overflow 8727 // conditions exploit NoWrapFlags, allowing to optimize in presence of 8728 // undefined behaviors like the case of C language. 8729 return getCouldNotCompute(); 8730 8731 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT 8732 : ICmpInst::ICMP_ULT; 8733 const SCEV *Start = IV->getStart(); 8734 const SCEV *End = RHS; 8735 // If the backedge is taken at least once, then it will be taken 8736 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start 8737 // is the LHS value of the less-than comparison the first time it is evaluated 8738 // and End is the RHS. 8739 const SCEV *BECountIfBackedgeTaken = 8740 computeBECount(getMinusSCEV(End, Start), Stride, false); 8741 // If the loop entry is guarded by the result of the backedge test of the 8742 // first loop iteration, then we know the backedge will be taken at least 8743 // once and so the backedge taken count is as above. If not then we use the 8744 // expression (max(End,Start)-Start)/Stride to describe the backedge count, 8745 // as if the backedge is taken at least once max(End,Start) is End and so the 8746 // result is as above, and if not max(End,Start) is Start so we get a backedge 8747 // count of zero. 8748 const SCEV *BECount; 8749 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) 8750 BECount = BECountIfBackedgeTaken; 8751 else { 8752 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 8753 BECount = computeBECount(getMinusSCEV(End, Start), Stride, false); 8754 } 8755 8756 const SCEV *MaxBECount; 8757 bool MaxOrZero = false; 8758 if (isa<SCEVConstant>(BECount)) 8759 MaxBECount = BECount; 8760 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) { 8761 // If we know exactly how many times the backedge will be taken if it's 8762 // taken at least once, then the backedge count will either be that or 8763 // zero. 8764 MaxBECount = BECountIfBackedgeTaken; 8765 MaxOrZero = true; 8766 } else { 8767 // Calculate the maximum backedge count based on the range of values 8768 // permitted by Start, End, and Stride. 8769 APInt MinStart = IsSigned ? getSignedRange(Start).getSignedMin() 8770 : getUnsignedRange(Start).getUnsignedMin(); 8771 8772 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 8773 8774 APInt StrideForMaxBECount; 8775 8776 if (PositiveStride) 8777 StrideForMaxBECount = 8778 IsSigned ? getSignedRange(Stride).getSignedMin() 8779 : getUnsignedRange(Stride).getUnsignedMin(); 8780 else 8781 // Using a stride of 1 is safe when computing max backedge taken count for 8782 // a loop with unknown stride. 8783 StrideForMaxBECount = APInt(BitWidth, 1, IsSigned); 8784 8785 APInt Limit = 8786 IsSigned ? APInt::getSignedMaxValue(BitWidth) - (StrideForMaxBECount - 1) 8787 : APInt::getMaxValue(BitWidth) - (StrideForMaxBECount - 1); 8788 8789 // Although End can be a MAX expression we estimate MaxEnd considering only 8790 // the case End = RHS. This is safe because in the other case (End - Start) 8791 // is zero, leading to a zero maximum backedge taken count. 8792 APInt MaxEnd = 8793 IsSigned ? APIntOps::smin(getSignedRange(RHS).getSignedMax(), Limit) 8794 : APIntOps::umin(getUnsignedRange(RHS).getUnsignedMax(), Limit); 8795 8796 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart), 8797 getConstant(StrideForMaxBECount), false); 8798 } 8799 8800 if (isa<SCEVCouldNotCompute>(MaxBECount)) 8801 MaxBECount = BECount; 8802 8803 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 8804 } 8805 8806 ScalarEvolution::ExitLimit 8807 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 8808 const Loop *L, bool IsSigned, 8809 bool ControlsExit, bool AllowPredicates) { 8810 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 8811 // We handle only IV > Invariant 8812 if (!isLoopInvariant(RHS, L)) 8813 return getCouldNotCompute(); 8814 8815 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 8816 if (!IV && AllowPredicates) 8817 // Try to make this an AddRec using runtime tests, in the first X 8818 // iterations of this loop, where X is the SCEV expression found by the 8819 // algorithm below. 8820 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 8821 8822 // Avoid weird loops 8823 if (!IV || IV->getLoop() != L || !IV->isAffine()) 8824 return getCouldNotCompute(); 8825 8826 bool NoWrap = ControlsExit && 8827 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 8828 8829 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 8830 8831 // Avoid negative or zero stride values 8832 if (!isKnownPositive(Stride)) 8833 return getCouldNotCompute(); 8834 8835 // Avoid proven overflow cases: this will ensure that the backedge taken count 8836 // will not generate any unsigned overflow. Relaxed no-overflow conditions 8837 // exploit NoWrapFlags, allowing to optimize in presence of undefined 8838 // behaviors like the case of C language. 8839 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap)) 8840 return getCouldNotCompute(); 8841 8842 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT 8843 : ICmpInst::ICMP_UGT; 8844 8845 const SCEV *Start = IV->getStart(); 8846 const SCEV *End = RHS; 8847 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) 8848 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 8849 8850 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false); 8851 8852 APInt MaxStart = IsSigned ? getSignedRange(Start).getSignedMax() 8853 : getUnsignedRange(Start).getUnsignedMax(); 8854 8855 APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin() 8856 : getUnsignedRange(Stride).getUnsignedMin(); 8857 8858 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 8859 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 8860 : APInt::getMinValue(BitWidth) + (MinStride - 1); 8861 8862 // Although End can be a MIN expression we estimate MinEnd considering only 8863 // the case End = RHS. This is safe because in the other case (Start - End) 8864 // is zero, leading to a zero maximum backedge taken count. 8865 APInt MinEnd = 8866 IsSigned ? APIntOps::smax(getSignedRange(RHS).getSignedMin(), Limit) 8867 : APIntOps::umax(getUnsignedRange(RHS).getUnsignedMin(), Limit); 8868 8869 8870 const SCEV *MaxBECount = getCouldNotCompute(); 8871 if (isa<SCEVConstant>(BECount)) 8872 MaxBECount = BECount; 8873 else 8874 MaxBECount = computeBECount(getConstant(MaxStart - MinEnd), 8875 getConstant(MinStride), false); 8876 8877 if (isa<SCEVCouldNotCompute>(MaxBECount)) 8878 MaxBECount = BECount; 8879 8880 return ExitLimit(BECount, MaxBECount, false, Predicates); 8881 } 8882 8883 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 8884 ScalarEvolution &SE) const { 8885 if (Range.isFullSet()) // Infinite loop. 8886 return SE.getCouldNotCompute(); 8887 8888 // If the start is a non-zero constant, shift the range to simplify things. 8889 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 8890 if (!SC->getValue()->isZero()) { 8891 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end()); 8892 Operands[0] = SE.getZero(SC->getType()); 8893 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 8894 getNoWrapFlags(FlagNW)); 8895 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 8896 return ShiftedAddRec->getNumIterationsInRange( 8897 Range.subtract(SC->getAPInt()), SE); 8898 // This is strange and shouldn't happen. 8899 return SE.getCouldNotCompute(); 8900 } 8901 8902 // The only time we can solve this is when we have all constant indices. 8903 // Otherwise, we cannot determine the overflow conditions. 8904 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 8905 return SE.getCouldNotCompute(); 8906 8907 // Okay at this point we know that all elements of the chrec are constants and 8908 // that the start element is zero. 8909 8910 // First check to see if the range contains zero. If not, the first 8911 // iteration exits. 8912 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 8913 if (!Range.contains(APInt(BitWidth, 0))) 8914 return SE.getZero(getType()); 8915 8916 if (isAffine()) { 8917 // If this is an affine expression then we have this situation: 8918 // Solve {0,+,A} in Range === Ax in Range 8919 8920 // We know that zero is in the range. If A is positive then we know that 8921 // the upper value of the range must be the first possible exit value. 8922 // If A is negative then the lower of the range is the last possible loop 8923 // value. Also note that we already checked for a full range. 8924 APInt One(BitWidth,1); 8925 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 8926 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower(); 8927 8928 // The exit value should be (End+A)/A. 8929 APInt ExitVal = (End + A).udiv(A); 8930 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 8931 8932 // Evaluate at the exit value. If we really did fall out of the valid 8933 // range, then we computed our trip count, otherwise wrap around or other 8934 // things must have happened. 8935 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 8936 if (Range.contains(Val->getValue())) 8937 return SE.getCouldNotCompute(); // Something strange happened 8938 8939 // Ensure that the previous value is in the range. This is a sanity check. 8940 assert(Range.contains( 8941 EvaluateConstantChrecAtConstant(this, 8942 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) && 8943 "Linear scev computation is off in a bad way!"); 8944 return SE.getConstant(ExitValue); 8945 } else if (isQuadratic()) { 8946 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the 8947 // quadratic equation to solve it. To do this, we must frame our problem in 8948 // terms of figuring out when zero is crossed, instead of when 8949 // Range.getUpper() is crossed. 8950 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end()); 8951 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper())); 8952 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), FlagAnyWrap); 8953 8954 // Next, solve the constructed addrec 8955 if (auto Roots = 8956 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE)) { 8957 const SCEVConstant *R1 = Roots->first; 8958 const SCEVConstant *R2 = Roots->second; 8959 // Pick the smallest positive root value. 8960 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp( 8961 ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) { 8962 if (!CB->getZExtValue()) 8963 std::swap(R1, R2); // R1 is the minimum root now. 8964 8965 // Make sure the root is not off by one. The returned iteration should 8966 // not be in the range, but the previous one should be. When solving 8967 // for "X*X < 5", for example, we should not return a root of 2. 8968 ConstantInt *R1Val = 8969 EvaluateConstantChrecAtConstant(this, R1->getValue(), SE); 8970 if (Range.contains(R1Val->getValue())) { 8971 // The next iteration must be out of the range... 8972 ConstantInt *NextVal = 8973 ConstantInt::get(SE.getContext(), R1->getAPInt() + 1); 8974 8975 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); 8976 if (!Range.contains(R1Val->getValue())) 8977 return SE.getConstant(NextVal); 8978 return SE.getCouldNotCompute(); // Something strange happened 8979 } 8980 8981 // If R1 was not in the range, then it is a good return value. Make 8982 // sure that R1-1 WAS in the range though, just in case. 8983 ConstantInt *NextVal = 8984 ConstantInt::get(SE.getContext(), R1->getAPInt() - 1); 8985 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); 8986 if (Range.contains(R1Val->getValue())) 8987 return R1; 8988 return SE.getCouldNotCompute(); // Something strange happened 8989 } 8990 } 8991 } 8992 8993 return SE.getCouldNotCompute(); 8994 } 8995 8996 namespace { 8997 struct FindUndefs { 8998 bool Found; 8999 FindUndefs() : Found(false) {} 9000 9001 bool follow(const SCEV *S) { 9002 if (const SCEVUnknown *C = dyn_cast<SCEVUnknown>(S)) { 9003 if (isa<UndefValue>(C->getValue())) 9004 Found = true; 9005 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) { 9006 if (isa<UndefValue>(C->getValue())) 9007 Found = true; 9008 } 9009 9010 // Keep looking if we haven't found it yet. 9011 return !Found; 9012 } 9013 bool isDone() const { 9014 // Stop recursion if we have found an undef. 9015 return Found; 9016 } 9017 }; 9018 } 9019 9020 // Return true when S contains at least an undef value. 9021 static inline bool 9022 containsUndefs(const SCEV *S) { 9023 FindUndefs F; 9024 SCEVTraversal<FindUndefs> ST(F); 9025 ST.visitAll(S); 9026 9027 return F.Found; 9028 } 9029 9030 namespace { 9031 // Collect all steps of SCEV expressions. 9032 struct SCEVCollectStrides { 9033 ScalarEvolution &SE; 9034 SmallVectorImpl<const SCEV *> &Strides; 9035 9036 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) 9037 : SE(SE), Strides(S) {} 9038 9039 bool follow(const SCEV *S) { 9040 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 9041 Strides.push_back(AR->getStepRecurrence(SE)); 9042 return true; 9043 } 9044 bool isDone() const { return false; } 9045 }; 9046 9047 // Collect all SCEVUnknown and SCEVMulExpr expressions. 9048 struct SCEVCollectTerms { 9049 SmallVectorImpl<const SCEV *> &Terms; 9050 9051 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) 9052 : Terms(T) {} 9053 9054 bool follow(const SCEV *S) { 9055 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) || 9056 isa<SCEVSignExtendExpr>(S)) { 9057 if (!containsUndefs(S)) 9058 Terms.push_back(S); 9059 9060 // Stop recursion: once we collected a term, do not walk its operands. 9061 return false; 9062 } 9063 9064 // Keep looking. 9065 return true; 9066 } 9067 bool isDone() const { return false; } 9068 }; 9069 9070 // Check if a SCEV contains an AddRecExpr. 9071 struct SCEVHasAddRec { 9072 bool &ContainsAddRec; 9073 9074 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) { 9075 ContainsAddRec = false; 9076 } 9077 9078 bool follow(const SCEV *S) { 9079 if (isa<SCEVAddRecExpr>(S)) { 9080 ContainsAddRec = true; 9081 9082 // Stop recursion: once we collected a term, do not walk its operands. 9083 return false; 9084 } 9085 9086 // Keep looking. 9087 return true; 9088 } 9089 bool isDone() const { return false; } 9090 }; 9091 9092 // Find factors that are multiplied with an expression that (possibly as a 9093 // subexpression) contains an AddRecExpr. In the expression: 9094 // 9095 // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop)) 9096 // 9097 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)" 9098 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size 9099 // parameters as they form a product with an induction variable. 9100 // 9101 // This collector expects all array size parameters to be in the same MulExpr. 9102 // It might be necessary to later add support for collecting parameters that are 9103 // spread over different nested MulExpr. 9104 struct SCEVCollectAddRecMultiplies { 9105 SmallVectorImpl<const SCEV *> &Terms; 9106 ScalarEvolution &SE; 9107 9108 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE) 9109 : Terms(T), SE(SE) {} 9110 9111 bool follow(const SCEV *S) { 9112 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) { 9113 bool HasAddRec = false; 9114 SmallVector<const SCEV *, 0> Operands; 9115 for (auto Op : Mul->operands()) { 9116 if (isa<SCEVUnknown>(Op)) { 9117 Operands.push_back(Op); 9118 } else { 9119 bool ContainsAddRec; 9120 SCEVHasAddRec ContiansAddRec(ContainsAddRec); 9121 visitAll(Op, ContiansAddRec); 9122 HasAddRec |= ContainsAddRec; 9123 } 9124 } 9125 if (Operands.size() == 0) 9126 return true; 9127 9128 if (!HasAddRec) 9129 return false; 9130 9131 Terms.push_back(SE.getMulExpr(Operands)); 9132 // Stop recursion: once we collected a term, do not walk its operands. 9133 return false; 9134 } 9135 9136 // Keep looking. 9137 return true; 9138 } 9139 bool isDone() const { return false; } 9140 }; 9141 } 9142 9143 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in 9144 /// two places: 9145 /// 1) The strides of AddRec expressions. 9146 /// 2) Unknowns that are multiplied with AddRec expressions. 9147 void ScalarEvolution::collectParametricTerms(const SCEV *Expr, 9148 SmallVectorImpl<const SCEV *> &Terms) { 9149 SmallVector<const SCEV *, 4> Strides; 9150 SCEVCollectStrides StrideCollector(*this, Strides); 9151 visitAll(Expr, StrideCollector); 9152 9153 DEBUG({ 9154 dbgs() << "Strides:\n"; 9155 for (const SCEV *S : Strides) 9156 dbgs() << *S << "\n"; 9157 }); 9158 9159 for (const SCEV *S : Strides) { 9160 SCEVCollectTerms TermCollector(Terms); 9161 visitAll(S, TermCollector); 9162 } 9163 9164 DEBUG({ 9165 dbgs() << "Terms:\n"; 9166 for (const SCEV *T : Terms) 9167 dbgs() << *T << "\n"; 9168 }); 9169 9170 SCEVCollectAddRecMultiplies MulCollector(Terms, *this); 9171 visitAll(Expr, MulCollector); 9172 } 9173 9174 static bool findArrayDimensionsRec(ScalarEvolution &SE, 9175 SmallVectorImpl<const SCEV *> &Terms, 9176 SmallVectorImpl<const SCEV *> &Sizes) { 9177 int Last = Terms.size() - 1; 9178 const SCEV *Step = Terms[Last]; 9179 9180 // End of recursion. 9181 if (Last == 0) { 9182 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { 9183 SmallVector<const SCEV *, 2> Qs; 9184 for (const SCEV *Op : M->operands()) 9185 if (!isa<SCEVConstant>(Op)) 9186 Qs.push_back(Op); 9187 9188 Step = SE.getMulExpr(Qs); 9189 } 9190 9191 Sizes.push_back(Step); 9192 return true; 9193 } 9194 9195 for (const SCEV *&Term : Terms) { 9196 // Normalize the terms before the next call to findArrayDimensionsRec. 9197 const SCEV *Q, *R; 9198 SCEVDivision::divide(SE, Term, Step, &Q, &R); 9199 9200 // Bail out when GCD does not evenly divide one of the terms. 9201 if (!R->isZero()) 9202 return false; 9203 9204 Term = Q; 9205 } 9206 9207 // Remove all SCEVConstants. 9208 Terms.erase( 9209 remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }), 9210 Terms.end()); 9211 9212 if (Terms.size() > 0) 9213 if (!findArrayDimensionsRec(SE, Terms, Sizes)) 9214 return false; 9215 9216 Sizes.push_back(Step); 9217 return true; 9218 } 9219 9220 // Returns true when S contains at least a SCEVUnknown parameter. 9221 static inline bool 9222 containsParameters(const SCEV *S) { 9223 struct FindParameter { 9224 bool FoundParameter; 9225 FindParameter() : FoundParameter(false) {} 9226 9227 bool follow(const SCEV *S) { 9228 if (isa<SCEVUnknown>(S)) { 9229 FoundParameter = true; 9230 // Stop recursion: we found a parameter. 9231 return false; 9232 } 9233 // Keep looking. 9234 return true; 9235 } 9236 bool isDone() const { 9237 // Stop recursion if we have found a parameter. 9238 return FoundParameter; 9239 } 9240 }; 9241 9242 FindParameter F; 9243 SCEVTraversal<FindParameter> ST(F); 9244 ST.visitAll(S); 9245 9246 return F.FoundParameter; 9247 } 9248 9249 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. 9250 static inline bool 9251 containsParameters(SmallVectorImpl<const SCEV *> &Terms) { 9252 for (const SCEV *T : Terms) 9253 if (containsParameters(T)) 9254 return true; 9255 return false; 9256 } 9257 9258 // Return the number of product terms in S. 9259 static inline int numberOfTerms(const SCEV *S) { 9260 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) 9261 return Expr->getNumOperands(); 9262 return 1; 9263 } 9264 9265 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { 9266 if (isa<SCEVConstant>(T)) 9267 return nullptr; 9268 9269 if (isa<SCEVUnknown>(T)) 9270 return T; 9271 9272 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { 9273 SmallVector<const SCEV *, 2> Factors; 9274 for (const SCEV *Op : M->operands()) 9275 if (!isa<SCEVConstant>(Op)) 9276 Factors.push_back(Op); 9277 9278 return SE.getMulExpr(Factors); 9279 } 9280 9281 return T; 9282 } 9283 9284 /// Return the size of an element read or written by Inst. 9285 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 9286 Type *Ty; 9287 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 9288 Ty = Store->getValueOperand()->getType(); 9289 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 9290 Ty = Load->getType(); 9291 else 9292 return nullptr; 9293 9294 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 9295 return getSizeOfExpr(ETy, Ty); 9296 } 9297 9298 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, 9299 SmallVectorImpl<const SCEV *> &Sizes, 9300 const SCEV *ElementSize) const { 9301 if (Terms.size() < 1 || !ElementSize) 9302 return; 9303 9304 // Early return when Terms do not contain parameters: we do not delinearize 9305 // non parametric SCEVs. 9306 if (!containsParameters(Terms)) 9307 return; 9308 9309 DEBUG({ 9310 dbgs() << "Terms:\n"; 9311 for (const SCEV *T : Terms) 9312 dbgs() << *T << "\n"; 9313 }); 9314 9315 // Remove duplicates. 9316 std::sort(Terms.begin(), Terms.end()); 9317 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); 9318 9319 // Put larger terms first. 9320 std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) { 9321 return numberOfTerms(LHS) > numberOfTerms(RHS); 9322 }); 9323 9324 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 9325 9326 // Try to divide all terms by the element size. If term is not divisible by 9327 // element size, proceed with the original term. 9328 for (const SCEV *&Term : Terms) { 9329 const SCEV *Q, *R; 9330 SCEVDivision::divide(SE, Term, ElementSize, &Q, &R); 9331 if (!Q->isZero()) 9332 Term = Q; 9333 } 9334 9335 SmallVector<const SCEV *, 4> NewTerms; 9336 9337 // Remove constant factors. 9338 for (const SCEV *T : Terms) 9339 if (const SCEV *NewT = removeConstantFactors(SE, T)) 9340 NewTerms.push_back(NewT); 9341 9342 DEBUG({ 9343 dbgs() << "Terms after sorting:\n"; 9344 for (const SCEV *T : NewTerms) 9345 dbgs() << *T << "\n"; 9346 }); 9347 9348 if (NewTerms.empty() || 9349 !findArrayDimensionsRec(SE, NewTerms, Sizes)) { 9350 Sizes.clear(); 9351 return; 9352 } 9353 9354 // The last element to be pushed into Sizes is the size of an element. 9355 Sizes.push_back(ElementSize); 9356 9357 DEBUG({ 9358 dbgs() << "Sizes:\n"; 9359 for (const SCEV *S : Sizes) 9360 dbgs() << *S << "\n"; 9361 }); 9362 } 9363 9364 void ScalarEvolution::computeAccessFunctions( 9365 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, 9366 SmallVectorImpl<const SCEV *> &Sizes) { 9367 9368 // Early exit in case this SCEV is not an affine multivariate function. 9369 if (Sizes.empty()) 9370 return; 9371 9372 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr)) 9373 if (!AR->isAffine()) 9374 return; 9375 9376 const SCEV *Res = Expr; 9377 int Last = Sizes.size() - 1; 9378 for (int i = Last; i >= 0; i--) { 9379 const SCEV *Q, *R; 9380 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); 9381 9382 DEBUG({ 9383 dbgs() << "Res: " << *Res << "\n"; 9384 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; 9385 dbgs() << "Res divided by Sizes[i]:\n"; 9386 dbgs() << "Quotient: " << *Q << "\n"; 9387 dbgs() << "Remainder: " << *R << "\n"; 9388 }); 9389 9390 Res = Q; 9391 9392 // Do not record the last subscript corresponding to the size of elements in 9393 // the array. 9394 if (i == Last) { 9395 9396 // Bail out if the remainder is too complex. 9397 if (isa<SCEVAddRecExpr>(R)) { 9398 Subscripts.clear(); 9399 Sizes.clear(); 9400 return; 9401 } 9402 9403 continue; 9404 } 9405 9406 // Record the access function for the current subscript. 9407 Subscripts.push_back(R); 9408 } 9409 9410 // Also push in last position the remainder of the last division: it will be 9411 // the access function of the innermost dimension. 9412 Subscripts.push_back(Res); 9413 9414 std::reverse(Subscripts.begin(), Subscripts.end()); 9415 9416 DEBUG({ 9417 dbgs() << "Subscripts:\n"; 9418 for (const SCEV *S : Subscripts) 9419 dbgs() << *S << "\n"; 9420 }); 9421 } 9422 9423 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and 9424 /// sizes of an array access. Returns the remainder of the delinearization that 9425 /// is the offset start of the array. The SCEV->delinearize algorithm computes 9426 /// the multiples of SCEV coefficients: that is a pattern matching of sub 9427 /// expressions in the stride and base of a SCEV corresponding to the 9428 /// computation of a GCD (greatest common divisor) of base and stride. When 9429 /// SCEV->delinearize fails, it returns the SCEV unchanged. 9430 /// 9431 /// For example: when analyzing the memory access A[i][j][k] in this loop nest 9432 /// 9433 /// void foo(long n, long m, long o, double A[n][m][o]) { 9434 /// 9435 /// for (long i = 0; i < n; i++) 9436 /// for (long j = 0; j < m; j++) 9437 /// for (long k = 0; k < o; k++) 9438 /// A[i][j][k] = 1.0; 9439 /// } 9440 /// 9441 /// the delinearization input is the following AddRec SCEV: 9442 /// 9443 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> 9444 /// 9445 /// From this SCEV, we are able to say that the base offset of the access is %A 9446 /// because it appears as an offset that does not divide any of the strides in 9447 /// the loops: 9448 /// 9449 /// CHECK: Base offset: %A 9450 /// 9451 /// and then SCEV->delinearize determines the size of some of the dimensions of 9452 /// the array as these are the multiples by which the strides are happening: 9453 /// 9454 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. 9455 /// 9456 /// Note that the outermost dimension remains of UnknownSize because there are 9457 /// no strides that would help identifying the size of the last dimension: when 9458 /// the array has been statically allocated, one could compute the size of that 9459 /// dimension by dividing the overall size of the array by the size of the known 9460 /// dimensions: %m * %o * 8. 9461 /// 9462 /// Finally delinearize provides the access functions for the array reference 9463 /// that does correspond to A[i][j][k] of the above C testcase: 9464 /// 9465 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] 9466 /// 9467 /// The testcases are checking the output of a function pass: 9468 /// DelinearizationPass that walks through all loads and stores of a function 9469 /// asking for the SCEV of the memory access with respect to all enclosing 9470 /// loops, calling SCEV->delinearize on that and printing the results. 9471 9472 void ScalarEvolution::delinearize(const SCEV *Expr, 9473 SmallVectorImpl<const SCEV *> &Subscripts, 9474 SmallVectorImpl<const SCEV *> &Sizes, 9475 const SCEV *ElementSize) { 9476 // First step: collect parametric terms. 9477 SmallVector<const SCEV *, 4> Terms; 9478 collectParametricTerms(Expr, Terms); 9479 9480 if (Terms.empty()) 9481 return; 9482 9483 // Second step: find subscript sizes. 9484 findArrayDimensions(Terms, Sizes, ElementSize); 9485 9486 if (Sizes.empty()) 9487 return; 9488 9489 // Third step: compute the access functions for each subscript. 9490 computeAccessFunctions(Expr, Subscripts, Sizes); 9491 9492 if (Subscripts.empty()) 9493 return; 9494 9495 DEBUG({ 9496 dbgs() << "succeeded to delinearize " << *Expr << "\n"; 9497 dbgs() << "ArrayDecl[UnknownSize]"; 9498 for (const SCEV *S : Sizes) 9499 dbgs() << "[" << *S << "]"; 9500 9501 dbgs() << "\nArrayRef"; 9502 for (const SCEV *S : Subscripts) 9503 dbgs() << "[" << *S << "]"; 9504 dbgs() << "\n"; 9505 }); 9506 } 9507 9508 //===----------------------------------------------------------------------===// 9509 // SCEVCallbackVH Class Implementation 9510 //===----------------------------------------------------------------------===// 9511 9512 void ScalarEvolution::SCEVCallbackVH::deleted() { 9513 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 9514 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 9515 SE->ConstantEvolutionLoopExitValue.erase(PN); 9516 SE->eraseValueFromMap(getValPtr()); 9517 // this now dangles! 9518 } 9519 9520 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 9521 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 9522 9523 // Forget all the expressions associated with users of the old value, 9524 // so that future queries will recompute the expressions using the new 9525 // value. 9526 Value *Old = getValPtr(); 9527 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end()); 9528 SmallPtrSet<User *, 8> Visited; 9529 while (!Worklist.empty()) { 9530 User *U = Worklist.pop_back_val(); 9531 // Deleting the Old value will cause this to dangle. Postpone 9532 // that until everything else is done. 9533 if (U == Old) 9534 continue; 9535 if (!Visited.insert(U).second) 9536 continue; 9537 if (PHINode *PN = dyn_cast<PHINode>(U)) 9538 SE->ConstantEvolutionLoopExitValue.erase(PN); 9539 SE->eraseValueFromMap(U); 9540 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end()); 9541 } 9542 // Delete the Old value. 9543 if (PHINode *PN = dyn_cast<PHINode>(Old)) 9544 SE->ConstantEvolutionLoopExitValue.erase(PN); 9545 SE->eraseValueFromMap(Old); 9546 // this now dangles! 9547 } 9548 9549 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 9550 : CallbackVH(V), SE(se) {} 9551 9552 //===----------------------------------------------------------------------===// 9553 // ScalarEvolution Class Implementation 9554 //===----------------------------------------------------------------------===// 9555 9556 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 9557 AssumptionCache &AC, DominatorTree &DT, 9558 LoopInfo &LI) 9559 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 9560 CouldNotCompute(new SCEVCouldNotCompute()), 9561 WalkingBEDominatingConds(false), ProvingSplitPredicate(false), 9562 ValuesAtScopes(64), LoopDispositions(64), BlockDispositions(64), 9563 FirstUnknown(nullptr) { 9564 9565 // To use guards for proving predicates, we need to scan every instruction in 9566 // relevant basic blocks, and not just terminators. Doing this is a waste of 9567 // time if the IR does not actually contain any calls to 9568 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 9569 // 9570 // This pessimizes the case where a pass that preserves ScalarEvolution wants 9571 // to _add_ guards to the module when there weren't any before, and wants 9572 // ScalarEvolution to optimize based on those guards. For now we prefer to be 9573 // efficient in lieu of being smart in that rather obscure case. 9574 9575 auto *GuardDecl = F.getParent()->getFunction( 9576 Intrinsic::getName(Intrinsic::experimental_guard)); 9577 HasGuards = GuardDecl && !GuardDecl->use_empty(); 9578 } 9579 9580 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 9581 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 9582 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 9583 ValueExprMap(std::move(Arg.ValueExprMap)), 9584 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 9585 WalkingBEDominatingConds(false), ProvingSplitPredicate(false), 9586 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 9587 PredicatedBackedgeTakenCounts( 9588 std::move(Arg.PredicatedBackedgeTakenCounts)), 9589 ConstantEvolutionLoopExitValue( 9590 std::move(Arg.ConstantEvolutionLoopExitValue)), 9591 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 9592 LoopDispositions(std::move(Arg.LoopDispositions)), 9593 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 9594 BlockDispositions(std::move(Arg.BlockDispositions)), 9595 UnsignedRanges(std::move(Arg.UnsignedRanges)), 9596 SignedRanges(std::move(Arg.SignedRanges)), 9597 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 9598 UniquePreds(std::move(Arg.UniquePreds)), 9599 SCEVAllocator(std::move(Arg.SCEVAllocator)), 9600 FirstUnknown(Arg.FirstUnknown) { 9601 Arg.FirstUnknown = nullptr; 9602 } 9603 9604 ScalarEvolution::~ScalarEvolution() { 9605 // Iterate through all the SCEVUnknown instances and call their 9606 // destructors, so that they release their references to their values. 9607 for (SCEVUnknown *U = FirstUnknown; U;) { 9608 SCEVUnknown *Tmp = U; 9609 U = U->Next; 9610 Tmp->~SCEVUnknown(); 9611 } 9612 FirstUnknown = nullptr; 9613 9614 ExprValueMap.clear(); 9615 ValueExprMap.clear(); 9616 HasRecMap.clear(); 9617 9618 // Free any extra memory created for ExitNotTakenInfo in the unlikely event 9619 // that a loop had multiple computable exits. 9620 for (auto &BTCI : BackedgeTakenCounts) 9621 BTCI.second.clear(); 9622 for (auto &BTCI : PredicatedBackedgeTakenCounts) 9623 BTCI.second.clear(); 9624 9625 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 9626 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 9627 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 9628 } 9629 9630 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 9631 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 9632 } 9633 9634 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 9635 const Loop *L) { 9636 // Print all inner loops first 9637 for (Loop *I : *L) 9638 PrintLoopInfo(OS, SE, I); 9639 9640 OS << "Loop "; 9641 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 9642 OS << ": "; 9643 9644 SmallVector<BasicBlock *, 8> ExitBlocks; 9645 L->getExitBlocks(ExitBlocks); 9646 if (ExitBlocks.size() != 1) 9647 OS << "<multiple exits> "; 9648 9649 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 9650 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L); 9651 } else { 9652 OS << "Unpredictable backedge-taken count. "; 9653 } 9654 9655 OS << "\n" 9656 "Loop "; 9657 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 9658 OS << ": "; 9659 9660 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) { 9661 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L); 9662 if (SE->isBackedgeTakenCountMaxOrZero(L)) 9663 OS << ", actual taken count either this or zero."; 9664 } else { 9665 OS << "Unpredictable max backedge-taken count. "; 9666 } 9667 9668 OS << "\n" 9669 "Loop "; 9670 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 9671 OS << ": "; 9672 9673 SCEVUnionPredicate Pred; 9674 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); 9675 if (!isa<SCEVCouldNotCompute>(PBT)) { 9676 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 9677 OS << " Predicates:\n"; 9678 Pred.print(OS, 4); 9679 } else { 9680 OS << "Unpredictable predicated backedge-taken count. "; 9681 } 9682 OS << "\n"; 9683 } 9684 9685 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 9686 switch (LD) { 9687 case ScalarEvolution::LoopVariant: 9688 return "Variant"; 9689 case ScalarEvolution::LoopInvariant: 9690 return "Invariant"; 9691 case ScalarEvolution::LoopComputable: 9692 return "Computable"; 9693 } 9694 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 9695 } 9696 9697 void ScalarEvolution::print(raw_ostream &OS) const { 9698 // ScalarEvolution's implementation of the print method is to print 9699 // out SCEV values of all instructions that are interesting. Doing 9700 // this potentially causes it to create new SCEV objects though, 9701 // which technically conflicts with the const qualifier. This isn't 9702 // observable from outside the class though, so casting away the 9703 // const isn't dangerous. 9704 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 9705 9706 OS << "Classifying expressions for: "; 9707 F.printAsOperand(OS, /*PrintType=*/false); 9708 OS << "\n"; 9709 for (Instruction &I : instructions(F)) 9710 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 9711 OS << I << '\n'; 9712 OS << " --> "; 9713 const SCEV *SV = SE.getSCEV(&I); 9714 SV->print(OS); 9715 if (!isa<SCEVCouldNotCompute>(SV)) { 9716 OS << " U: "; 9717 SE.getUnsignedRange(SV).print(OS); 9718 OS << " S: "; 9719 SE.getSignedRange(SV).print(OS); 9720 } 9721 9722 const Loop *L = LI.getLoopFor(I.getParent()); 9723 9724 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 9725 if (AtUse != SV) { 9726 OS << " --> "; 9727 AtUse->print(OS); 9728 if (!isa<SCEVCouldNotCompute>(AtUse)) { 9729 OS << " U: "; 9730 SE.getUnsignedRange(AtUse).print(OS); 9731 OS << " S: "; 9732 SE.getSignedRange(AtUse).print(OS); 9733 } 9734 } 9735 9736 if (L) { 9737 OS << "\t\t" "Exits: "; 9738 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 9739 if (!SE.isLoopInvariant(ExitValue, L)) { 9740 OS << "<<Unknown>>"; 9741 } else { 9742 OS << *ExitValue; 9743 } 9744 9745 bool First = true; 9746 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 9747 if (First) { 9748 OS << "\t\t" "LoopDispositions: { "; 9749 First = false; 9750 } else { 9751 OS << ", "; 9752 } 9753 9754 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 9755 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 9756 } 9757 9758 for (auto *InnerL : depth_first(L)) { 9759 if (InnerL == L) 9760 continue; 9761 if (First) { 9762 OS << "\t\t" "LoopDispositions: { "; 9763 First = false; 9764 } else { 9765 OS << ", "; 9766 } 9767 9768 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 9769 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 9770 } 9771 9772 OS << " }"; 9773 } 9774 9775 OS << "\n"; 9776 } 9777 9778 OS << "Determining loop execution counts for: "; 9779 F.printAsOperand(OS, /*PrintType=*/false); 9780 OS << "\n"; 9781 for (Loop *I : LI) 9782 PrintLoopInfo(OS, &SE, I); 9783 } 9784 9785 ScalarEvolution::LoopDisposition 9786 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 9787 auto &Values = LoopDispositions[S]; 9788 for (auto &V : Values) { 9789 if (V.getPointer() == L) 9790 return V.getInt(); 9791 } 9792 Values.emplace_back(L, LoopVariant); 9793 LoopDisposition D = computeLoopDisposition(S, L); 9794 auto &Values2 = LoopDispositions[S]; 9795 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 9796 if (V.getPointer() == L) { 9797 V.setInt(D); 9798 break; 9799 } 9800 } 9801 return D; 9802 } 9803 9804 ScalarEvolution::LoopDisposition 9805 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 9806 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 9807 case scConstant: 9808 return LoopInvariant; 9809 case scTruncate: 9810 case scZeroExtend: 9811 case scSignExtend: 9812 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 9813 case scAddRecExpr: { 9814 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 9815 9816 // If L is the addrec's loop, it's computable. 9817 if (AR->getLoop() == L) 9818 return LoopComputable; 9819 9820 // Add recurrences are never invariant in the function-body (null loop). 9821 if (!L) 9822 return LoopVariant; 9823 9824 // This recurrence is variant w.r.t. L if L contains AR's loop. 9825 if (L->contains(AR->getLoop())) 9826 return LoopVariant; 9827 9828 // This recurrence is invariant w.r.t. L if AR's loop contains L. 9829 if (AR->getLoop()->contains(L)) 9830 return LoopInvariant; 9831 9832 // This recurrence is variant w.r.t. L if any of its operands 9833 // are variant. 9834 for (auto *Op : AR->operands()) 9835 if (!isLoopInvariant(Op, L)) 9836 return LoopVariant; 9837 9838 // Otherwise it's loop-invariant. 9839 return LoopInvariant; 9840 } 9841 case scAddExpr: 9842 case scMulExpr: 9843 case scUMaxExpr: 9844 case scSMaxExpr: { 9845 bool HasVarying = false; 9846 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 9847 LoopDisposition D = getLoopDisposition(Op, L); 9848 if (D == LoopVariant) 9849 return LoopVariant; 9850 if (D == LoopComputable) 9851 HasVarying = true; 9852 } 9853 return HasVarying ? LoopComputable : LoopInvariant; 9854 } 9855 case scUDivExpr: { 9856 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 9857 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 9858 if (LD == LoopVariant) 9859 return LoopVariant; 9860 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 9861 if (RD == LoopVariant) 9862 return LoopVariant; 9863 return (LD == LoopInvariant && RD == LoopInvariant) ? 9864 LoopInvariant : LoopComputable; 9865 } 9866 case scUnknown: 9867 // All non-instruction values are loop invariant. All instructions are loop 9868 // invariant if they are not contained in the specified loop. 9869 // Instructions are never considered invariant in the function body 9870 // (null loop) because they are defined within the "loop". 9871 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 9872 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 9873 return LoopInvariant; 9874 case scCouldNotCompute: 9875 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 9876 } 9877 llvm_unreachable("Unknown SCEV kind!"); 9878 } 9879 9880 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 9881 return getLoopDisposition(S, L) == LoopInvariant; 9882 } 9883 9884 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 9885 return getLoopDisposition(S, L) == LoopComputable; 9886 } 9887 9888 ScalarEvolution::BlockDisposition 9889 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 9890 auto &Values = BlockDispositions[S]; 9891 for (auto &V : Values) { 9892 if (V.getPointer() == BB) 9893 return V.getInt(); 9894 } 9895 Values.emplace_back(BB, DoesNotDominateBlock); 9896 BlockDisposition D = computeBlockDisposition(S, BB); 9897 auto &Values2 = BlockDispositions[S]; 9898 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 9899 if (V.getPointer() == BB) { 9900 V.setInt(D); 9901 break; 9902 } 9903 } 9904 return D; 9905 } 9906 9907 ScalarEvolution::BlockDisposition 9908 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 9909 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 9910 case scConstant: 9911 return ProperlyDominatesBlock; 9912 case scTruncate: 9913 case scZeroExtend: 9914 case scSignExtend: 9915 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 9916 case scAddRecExpr: { 9917 // This uses a "dominates" query instead of "properly dominates" query 9918 // to test for proper dominance too, because the instruction which 9919 // produces the addrec's value is a PHI, and a PHI effectively properly 9920 // dominates its entire containing block. 9921 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 9922 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 9923 return DoesNotDominateBlock; 9924 9925 // Fall through into SCEVNAryExpr handling. 9926 LLVM_FALLTHROUGH; 9927 } 9928 case scAddExpr: 9929 case scMulExpr: 9930 case scUMaxExpr: 9931 case scSMaxExpr: { 9932 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 9933 bool Proper = true; 9934 for (const SCEV *NAryOp : NAry->operands()) { 9935 BlockDisposition D = getBlockDisposition(NAryOp, BB); 9936 if (D == DoesNotDominateBlock) 9937 return DoesNotDominateBlock; 9938 if (D == DominatesBlock) 9939 Proper = false; 9940 } 9941 return Proper ? ProperlyDominatesBlock : DominatesBlock; 9942 } 9943 case scUDivExpr: { 9944 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 9945 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 9946 BlockDisposition LD = getBlockDisposition(LHS, BB); 9947 if (LD == DoesNotDominateBlock) 9948 return DoesNotDominateBlock; 9949 BlockDisposition RD = getBlockDisposition(RHS, BB); 9950 if (RD == DoesNotDominateBlock) 9951 return DoesNotDominateBlock; 9952 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 9953 ProperlyDominatesBlock : DominatesBlock; 9954 } 9955 case scUnknown: 9956 if (Instruction *I = 9957 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 9958 if (I->getParent() == BB) 9959 return DominatesBlock; 9960 if (DT.properlyDominates(I->getParent(), BB)) 9961 return ProperlyDominatesBlock; 9962 return DoesNotDominateBlock; 9963 } 9964 return ProperlyDominatesBlock; 9965 case scCouldNotCompute: 9966 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 9967 } 9968 llvm_unreachable("Unknown SCEV kind!"); 9969 } 9970 9971 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 9972 return getBlockDisposition(S, BB) >= DominatesBlock; 9973 } 9974 9975 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 9976 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 9977 } 9978 9979 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 9980 // Search for a SCEV expression node within an expression tree. 9981 // Implements SCEVTraversal::Visitor. 9982 struct SCEVSearch { 9983 const SCEV *Node; 9984 bool IsFound; 9985 9986 SCEVSearch(const SCEV *N): Node(N), IsFound(false) {} 9987 9988 bool follow(const SCEV *S) { 9989 IsFound |= (S == Node); 9990 return !IsFound; 9991 } 9992 bool isDone() const { return IsFound; } 9993 }; 9994 9995 SCEVSearch Search(Op); 9996 visitAll(S, Search); 9997 return Search.IsFound; 9998 } 9999 10000 void ScalarEvolution::forgetMemoizedResults(const SCEV *S) { 10001 ValuesAtScopes.erase(S); 10002 LoopDispositions.erase(S); 10003 BlockDispositions.erase(S); 10004 UnsignedRanges.erase(S); 10005 SignedRanges.erase(S); 10006 ExprValueMap.erase(S); 10007 HasRecMap.erase(S); 10008 10009 auto RemoveSCEVFromBackedgeMap = 10010 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 10011 for (auto I = Map.begin(), E = Map.end(); I != E;) { 10012 BackedgeTakenInfo &BEInfo = I->second; 10013 if (BEInfo.hasOperand(S, this)) { 10014 BEInfo.clear(); 10015 Map.erase(I++); 10016 } else 10017 ++I; 10018 } 10019 }; 10020 10021 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); 10022 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); 10023 } 10024 10025 typedef DenseMap<const Loop *, std::string> VerifyMap; 10026 10027 /// replaceSubString - Replaces all occurrences of From in Str with To. 10028 static void replaceSubString(std::string &Str, StringRef From, StringRef To) { 10029 size_t Pos = 0; 10030 while ((Pos = Str.find(From, Pos)) != std::string::npos) { 10031 Str.replace(Pos, From.size(), To.data(), To.size()); 10032 Pos += To.size(); 10033 } 10034 } 10035 10036 /// getLoopBackedgeTakenCounts - Helper method for verifyAnalysis. 10037 static void 10038 getLoopBackedgeTakenCounts(Loop *L, VerifyMap &Map, ScalarEvolution &SE) { 10039 std::string &S = Map[L]; 10040 if (S.empty()) { 10041 raw_string_ostream OS(S); 10042 SE.getBackedgeTakenCount(L)->print(OS); 10043 10044 // false and 0 are semantically equivalent. This can happen in dead loops. 10045 replaceSubString(OS.str(), "false", "0"); 10046 // Remove wrap flags, their use in SCEV is highly fragile. 10047 // FIXME: Remove this when SCEV gets smarter about them. 10048 replaceSubString(OS.str(), "<nw>", ""); 10049 replaceSubString(OS.str(), "<nsw>", ""); 10050 replaceSubString(OS.str(), "<nuw>", ""); 10051 } 10052 10053 for (auto *R : reverse(*L)) 10054 getLoopBackedgeTakenCounts(R, Map, SE); // recurse. 10055 } 10056 10057 void ScalarEvolution::verify() const { 10058 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 10059 10060 // Gather stringified backedge taken counts for all loops using SCEV's caches. 10061 // FIXME: It would be much better to store actual values instead of strings, 10062 // but SCEV pointers will change if we drop the caches. 10063 VerifyMap BackedgeDumpsOld, BackedgeDumpsNew; 10064 for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I) 10065 getLoopBackedgeTakenCounts(*I, BackedgeDumpsOld, SE); 10066 10067 // Gather stringified backedge taken counts for all loops using a fresh 10068 // ScalarEvolution object. 10069 ScalarEvolution SE2(F, TLI, AC, DT, LI); 10070 for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I) 10071 getLoopBackedgeTakenCounts(*I, BackedgeDumpsNew, SE2); 10072 10073 // Now compare whether they're the same with and without caches. This allows 10074 // verifying that no pass changed the cache. 10075 assert(BackedgeDumpsOld.size() == BackedgeDumpsNew.size() && 10076 "New loops suddenly appeared!"); 10077 10078 for (VerifyMap::iterator OldI = BackedgeDumpsOld.begin(), 10079 OldE = BackedgeDumpsOld.end(), 10080 NewI = BackedgeDumpsNew.begin(); 10081 OldI != OldE; ++OldI, ++NewI) { 10082 assert(OldI->first == NewI->first && "Loop order changed!"); 10083 10084 // Compare the stringified SCEVs. We don't care if undef backedgetaken count 10085 // changes. 10086 // FIXME: We currently ignore SCEV changes from/to CouldNotCompute. This 10087 // means that a pass is buggy or SCEV has to learn a new pattern but is 10088 // usually not harmful. 10089 if (OldI->second != NewI->second && 10090 OldI->second.find("undef") == std::string::npos && 10091 NewI->second.find("undef") == std::string::npos && 10092 OldI->second != "***COULDNOTCOMPUTE***" && 10093 NewI->second != "***COULDNOTCOMPUTE***") { 10094 dbgs() << "SCEVValidator: SCEV for loop '" 10095 << OldI->first->getHeader()->getName() 10096 << "' changed from '" << OldI->second 10097 << "' to '" << NewI->second << "'!\n"; 10098 std::abort(); 10099 } 10100 } 10101 10102 // TODO: Verify more things. 10103 } 10104 10105 char ScalarEvolutionAnalysis::PassID; 10106 10107 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 10108 FunctionAnalysisManager &AM) { 10109 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 10110 AM.getResult<AssumptionAnalysis>(F), 10111 AM.getResult<DominatorTreeAnalysis>(F), 10112 AM.getResult<LoopAnalysis>(F)); 10113 } 10114 10115 PreservedAnalyses 10116 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 10117 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 10118 return PreservedAnalyses::all(); 10119 } 10120 10121 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 10122 "Scalar Evolution Analysis", false, true) 10123 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 10124 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 10125 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 10126 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 10127 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 10128 "Scalar Evolution Analysis", false, true) 10129 char ScalarEvolutionWrapperPass::ID = 0; 10130 10131 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 10132 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 10133 } 10134 10135 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 10136 SE.reset(new ScalarEvolution( 10137 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(), 10138 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 10139 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 10140 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 10141 return false; 10142 } 10143 10144 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 10145 10146 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 10147 SE->print(OS); 10148 } 10149 10150 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 10151 if (!VerifySCEV) 10152 return; 10153 10154 SE->verify(); 10155 } 10156 10157 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 10158 AU.setPreservesAll(); 10159 AU.addRequiredTransitive<AssumptionCacheTracker>(); 10160 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 10161 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 10162 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 10163 } 10164 10165 const SCEVPredicate * 10166 ScalarEvolution::getEqualPredicate(const SCEVUnknown *LHS, 10167 const SCEVConstant *RHS) { 10168 FoldingSetNodeID ID; 10169 // Unique this node based on the arguments 10170 ID.AddInteger(SCEVPredicate::P_Equal); 10171 ID.AddPointer(LHS); 10172 ID.AddPointer(RHS); 10173 void *IP = nullptr; 10174 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 10175 return S; 10176 SCEVEqualPredicate *Eq = new (SCEVAllocator) 10177 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 10178 UniquePreds.InsertNode(Eq, IP); 10179 return Eq; 10180 } 10181 10182 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 10183 const SCEVAddRecExpr *AR, 10184 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 10185 FoldingSetNodeID ID; 10186 // Unique this node based on the arguments 10187 ID.AddInteger(SCEVPredicate::P_Wrap); 10188 ID.AddPointer(AR); 10189 ID.AddInteger(AddedFlags); 10190 void *IP = nullptr; 10191 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 10192 return S; 10193 auto *OF = new (SCEVAllocator) 10194 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 10195 UniquePreds.InsertNode(OF, IP); 10196 return OF; 10197 } 10198 10199 namespace { 10200 10201 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 10202 public: 10203 /// Rewrites \p S in the context of a loop L and the SCEV predication 10204 /// infrastructure. 10205 /// 10206 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 10207 /// equivalences present in \p Pred. 10208 /// 10209 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 10210 /// \p NewPreds such that the result will be an AddRecExpr. 10211 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 10212 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 10213 SCEVUnionPredicate *Pred) { 10214 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 10215 return Rewriter.visit(S); 10216 } 10217 10218 SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 10219 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 10220 SCEVUnionPredicate *Pred) 10221 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 10222 10223 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 10224 if (Pred) { 10225 auto ExprPreds = Pred->getPredicatesForExpr(Expr); 10226 for (auto *Pred : ExprPreds) 10227 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) 10228 if (IPred->getLHS() == Expr) 10229 return IPred->getRHS(); 10230 } 10231 10232 return Expr; 10233 } 10234 10235 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 10236 const SCEV *Operand = visit(Expr->getOperand()); 10237 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 10238 if (AR && AR->getLoop() == L && AR->isAffine()) { 10239 // This couldn't be folded because the operand didn't have the nuw 10240 // flag. Add the nusw flag as an assumption that we could make. 10241 const SCEV *Step = AR->getStepRecurrence(SE); 10242 Type *Ty = Expr->getType(); 10243 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 10244 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 10245 SE.getSignExtendExpr(Step, Ty), L, 10246 AR->getNoWrapFlags()); 10247 } 10248 return SE.getZeroExtendExpr(Operand, Expr->getType()); 10249 } 10250 10251 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 10252 const SCEV *Operand = visit(Expr->getOperand()); 10253 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 10254 if (AR && AR->getLoop() == L && AR->isAffine()) { 10255 // This couldn't be folded because the operand didn't have the nsw 10256 // flag. Add the nssw flag as an assumption that we could make. 10257 const SCEV *Step = AR->getStepRecurrence(SE); 10258 Type *Ty = Expr->getType(); 10259 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 10260 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 10261 SE.getSignExtendExpr(Step, Ty), L, 10262 AR->getNoWrapFlags()); 10263 } 10264 return SE.getSignExtendExpr(Operand, Expr->getType()); 10265 } 10266 10267 private: 10268 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 10269 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 10270 auto *A = SE.getWrapPredicate(AR, AddedFlags); 10271 if (!NewPreds) { 10272 // Check if we've already made this assumption. 10273 return Pred && Pred->implies(A); 10274 } 10275 NewPreds->insert(A); 10276 return true; 10277 } 10278 10279 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 10280 SCEVUnionPredicate *Pred; 10281 const Loop *L; 10282 }; 10283 } // end anonymous namespace 10284 10285 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 10286 SCEVUnionPredicate &Preds) { 10287 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 10288 } 10289 10290 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 10291 const SCEV *S, const Loop *L, 10292 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 10293 10294 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 10295 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 10296 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 10297 10298 if (!AddRec) 10299 return nullptr; 10300 10301 // Since the transformation was successful, we can now transfer the SCEV 10302 // predicates. 10303 for (auto *P : TransformPreds) 10304 Preds.insert(P); 10305 10306 return AddRec; 10307 } 10308 10309 /// SCEV predicates 10310 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 10311 SCEVPredicateKind Kind) 10312 : FastID(ID), Kind(Kind) {} 10313 10314 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 10315 const SCEVUnknown *LHS, 10316 const SCEVConstant *RHS) 10317 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {} 10318 10319 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 10320 const auto *Op = dyn_cast<SCEVEqualPredicate>(N); 10321 10322 if (!Op) 10323 return false; 10324 10325 return Op->LHS == LHS && Op->RHS == RHS; 10326 } 10327 10328 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 10329 10330 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 10331 10332 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 10333 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 10334 } 10335 10336 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 10337 const SCEVAddRecExpr *AR, 10338 IncrementWrapFlags Flags) 10339 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 10340 10341 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 10342 10343 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 10344 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 10345 10346 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 10347 } 10348 10349 bool SCEVWrapPredicate::isAlwaysTrue() const { 10350 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 10351 IncrementWrapFlags IFlags = Flags; 10352 10353 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 10354 IFlags = clearFlags(IFlags, IncrementNSSW); 10355 10356 return IFlags == IncrementAnyWrap; 10357 } 10358 10359 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 10360 OS.indent(Depth) << *getExpr() << " Added Flags: "; 10361 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 10362 OS << "<nusw>"; 10363 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 10364 OS << "<nssw>"; 10365 OS << "\n"; 10366 } 10367 10368 SCEVWrapPredicate::IncrementWrapFlags 10369 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 10370 ScalarEvolution &SE) { 10371 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 10372 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 10373 10374 // We can safely transfer the NSW flag as NSSW. 10375 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 10376 ImpliedFlags = IncrementNSSW; 10377 10378 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 10379 // If the increment is positive, the SCEV NUW flag will also imply the 10380 // WrapPredicate NUSW flag. 10381 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 10382 if (Step->getValue()->getValue().isNonNegative()) 10383 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 10384 } 10385 10386 return ImpliedFlags; 10387 } 10388 10389 /// Union predicates don't get cached so create a dummy set ID for it. 10390 SCEVUnionPredicate::SCEVUnionPredicate() 10391 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 10392 10393 bool SCEVUnionPredicate::isAlwaysTrue() const { 10394 return all_of(Preds, 10395 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 10396 } 10397 10398 ArrayRef<const SCEVPredicate *> 10399 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 10400 auto I = SCEVToPreds.find(Expr); 10401 if (I == SCEVToPreds.end()) 10402 return ArrayRef<const SCEVPredicate *>(); 10403 return I->second; 10404 } 10405 10406 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 10407 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 10408 return all_of(Set->Preds, 10409 [this](const SCEVPredicate *I) { return this->implies(I); }); 10410 10411 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 10412 if (ScevPredsIt == SCEVToPreds.end()) 10413 return false; 10414 auto &SCEVPreds = ScevPredsIt->second; 10415 10416 return any_of(SCEVPreds, 10417 [N](const SCEVPredicate *I) { return I->implies(N); }); 10418 } 10419 10420 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 10421 10422 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 10423 for (auto Pred : Preds) 10424 Pred->print(OS, Depth); 10425 } 10426 10427 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 10428 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 10429 for (auto Pred : Set->Preds) 10430 add(Pred); 10431 return; 10432 } 10433 10434 if (implies(N)) 10435 return; 10436 10437 const SCEV *Key = N->getExpr(); 10438 assert(Key && "Only SCEVUnionPredicate doesn't have an " 10439 " associated expression!"); 10440 10441 SCEVToPreds[Key].push_back(N); 10442 Preds.push_back(N); 10443 } 10444 10445 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 10446 Loop &L) 10447 : SE(SE), L(L), Generation(0), BackedgeCount(nullptr) {} 10448 10449 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 10450 const SCEV *Expr = SE.getSCEV(V); 10451 RewriteEntry &Entry = RewriteMap[Expr]; 10452 10453 // If we already have an entry and the version matches, return it. 10454 if (Entry.second && Generation == Entry.first) 10455 return Entry.second; 10456 10457 // We found an entry but it's stale. Rewrite the stale entry 10458 // acording to the current predicate. 10459 if (Entry.second) 10460 Expr = Entry.second; 10461 10462 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 10463 Entry = {Generation, NewSCEV}; 10464 10465 return NewSCEV; 10466 } 10467 10468 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 10469 if (!BackedgeCount) { 10470 SCEVUnionPredicate BackedgePred; 10471 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); 10472 addPredicate(BackedgePred); 10473 } 10474 return BackedgeCount; 10475 } 10476 10477 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 10478 if (Preds.implies(&Pred)) 10479 return; 10480 Preds.add(&Pred); 10481 updateGeneration(); 10482 } 10483 10484 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 10485 return Preds; 10486 } 10487 10488 void PredicatedScalarEvolution::updateGeneration() { 10489 // If the generation number wrapped recompute everything. 10490 if (++Generation == 0) { 10491 for (auto &II : RewriteMap) { 10492 const SCEV *Rewritten = II.second.second; 10493 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 10494 } 10495 } 10496 } 10497 10498 void PredicatedScalarEvolution::setNoOverflow( 10499 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 10500 const SCEV *Expr = getSCEV(V); 10501 const auto *AR = cast<SCEVAddRecExpr>(Expr); 10502 10503 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 10504 10505 // Clear the statically implied flags. 10506 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 10507 addPredicate(*SE.getWrapPredicate(AR, Flags)); 10508 10509 auto II = FlagsMap.insert({V, Flags}); 10510 if (!II.second) 10511 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 10512 } 10513 10514 bool PredicatedScalarEvolution::hasNoOverflow( 10515 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 10516 const SCEV *Expr = getSCEV(V); 10517 const auto *AR = cast<SCEVAddRecExpr>(Expr); 10518 10519 Flags = SCEVWrapPredicate::clearFlags( 10520 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 10521 10522 auto II = FlagsMap.find(V); 10523 10524 if (II != FlagsMap.end()) 10525 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 10526 10527 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 10528 } 10529 10530 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 10531 const SCEV *Expr = this->getSCEV(V); 10532 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 10533 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 10534 10535 if (!New) 10536 return nullptr; 10537 10538 for (auto *P : NewPreds) 10539 Preds.add(P); 10540 10541 updateGeneration(); 10542 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 10543 return New; 10544 } 10545 10546 PredicatedScalarEvolution::PredicatedScalarEvolution( 10547 const PredicatedScalarEvolution &Init) 10548 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 10549 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 10550 for (const auto &I : Init.FlagsMap) 10551 FlagsMap.insert(I); 10552 } 10553 10554 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 10555 // For each block. 10556 for (auto *BB : L.getBlocks()) 10557 for (auto &I : *BB) { 10558 if (!SE.isSCEVable(I.getType())) 10559 continue; 10560 10561 auto *Expr = SE.getSCEV(&I); 10562 auto II = RewriteMap.find(Expr); 10563 10564 if (II == RewriteMap.end()) 10565 continue; 10566 10567 // Don't print things that are not interesting. 10568 if (II->second.second == Expr) 10569 continue; 10570 10571 OS.indent(Depth) << "[PSE]" << I << ":\n"; 10572 OS.indent(Depth + 2) << *Expr << "\n"; 10573 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 10574 } 10575 } 10576