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/SmallPtrSet.h" 65 #include "llvm/ADT/Statistic.h" 66 #include "llvm/Analysis/AssumptionCache.h" 67 #include "llvm/Analysis/ConstantFolding.h" 68 #include "llvm/Analysis/InstructionSimplify.h" 69 #include "llvm/Analysis/LoopInfo.h" 70 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 71 #include "llvm/Analysis/TargetLibraryInfo.h" 72 #include "llvm/Analysis/ValueTracking.h" 73 #include "llvm/IR/ConstantRange.h" 74 #include "llvm/IR/Constants.h" 75 #include "llvm/IR/DataLayout.h" 76 #include "llvm/IR/DerivedTypes.h" 77 #include "llvm/IR/Dominators.h" 78 #include "llvm/IR/GetElementPtrTypeIterator.h" 79 #include "llvm/IR/GlobalAlias.h" 80 #include "llvm/IR/GlobalVariable.h" 81 #include "llvm/IR/InstIterator.h" 82 #include "llvm/IR/Instructions.h" 83 #include "llvm/IR/LLVMContext.h" 84 #include "llvm/IR/Metadata.h" 85 #include "llvm/IR/Operator.h" 86 #include "llvm/IR/PatternMatch.h" 87 #include "llvm/Support/CommandLine.h" 88 #include "llvm/Support/Debug.h" 89 #include "llvm/Support/ErrorHandling.h" 90 #include "llvm/Support/MathExtras.h" 91 #include "llvm/Support/raw_ostream.h" 92 #include "llvm/Support/SaveAndRestore.h" 93 #include <algorithm> 94 using namespace llvm; 95 96 #define DEBUG_TYPE "scalar-evolution" 97 98 STATISTIC(NumArrayLenItCounts, 99 "Number of trip counts computed with array length"); 100 STATISTIC(NumTripCountsComputed, 101 "Number of loops with predictable loop counts"); 102 STATISTIC(NumTripCountsNotComputed, 103 "Number of loops without predictable loop counts"); 104 STATISTIC(NumBruteForceTripCountsComputed, 105 "Number of loops with trip counts computed by force"); 106 107 static cl::opt<unsigned> 108 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, 109 cl::desc("Maximum number of iterations SCEV will " 110 "symbolically execute a constant " 111 "derived loop"), 112 cl::init(100)); 113 114 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean. 115 static cl::opt<bool> 116 VerifySCEV("verify-scev", 117 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)")); 118 static cl::opt<bool> 119 VerifySCEVMap("verify-scev-maps", 120 cl::desc("Verify no dangling value in ScalarEvolution's " 121 "ExprValueMap (slow)")); 122 123 //===----------------------------------------------------------------------===// 124 // SCEV class definitions 125 //===----------------------------------------------------------------------===// 126 127 //===----------------------------------------------------------------------===// 128 // Implementation of the SCEV class. 129 // 130 131 LLVM_DUMP_METHOD 132 void SCEV::dump() const { 133 print(dbgs()); 134 dbgs() << '\n'; 135 } 136 137 void SCEV::print(raw_ostream &OS) const { 138 switch (static_cast<SCEVTypes>(getSCEVType())) { 139 case scConstant: 140 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false); 141 return; 142 case scTruncate: { 143 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this); 144 const SCEV *Op = Trunc->getOperand(); 145 OS << "(trunc " << *Op->getType() << " " << *Op << " to " 146 << *Trunc->getType() << ")"; 147 return; 148 } 149 case scZeroExtend: { 150 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this); 151 const SCEV *Op = ZExt->getOperand(); 152 OS << "(zext " << *Op->getType() << " " << *Op << " to " 153 << *ZExt->getType() << ")"; 154 return; 155 } 156 case scSignExtend: { 157 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this); 158 const SCEV *Op = SExt->getOperand(); 159 OS << "(sext " << *Op->getType() << " " << *Op << " to " 160 << *SExt->getType() << ")"; 161 return; 162 } 163 case scAddRecExpr: { 164 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this); 165 OS << "{" << *AR->getOperand(0); 166 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i) 167 OS << ",+," << *AR->getOperand(i); 168 OS << "}<"; 169 if (AR->hasNoUnsignedWrap()) 170 OS << "nuw><"; 171 if (AR->hasNoSignedWrap()) 172 OS << "nsw><"; 173 if (AR->hasNoSelfWrap() && 174 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW))) 175 OS << "nw><"; 176 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false); 177 OS << ">"; 178 return; 179 } 180 case scAddExpr: 181 case scMulExpr: 182 case scUMaxExpr: 183 case scSMaxExpr: { 184 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this); 185 const char *OpStr = nullptr; 186 switch (NAry->getSCEVType()) { 187 case scAddExpr: OpStr = " + "; break; 188 case scMulExpr: OpStr = " * "; break; 189 case scUMaxExpr: OpStr = " umax "; break; 190 case scSMaxExpr: OpStr = " smax "; break; 191 } 192 OS << "("; 193 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end(); 194 I != E; ++I) { 195 OS << **I; 196 if (std::next(I) != E) 197 OS << OpStr; 198 } 199 OS << ")"; 200 switch (NAry->getSCEVType()) { 201 case scAddExpr: 202 case scMulExpr: 203 if (NAry->hasNoUnsignedWrap()) 204 OS << "<nuw>"; 205 if (NAry->hasNoSignedWrap()) 206 OS << "<nsw>"; 207 } 208 return; 209 } 210 case scUDivExpr: { 211 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this); 212 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")"; 213 return; 214 } 215 case scUnknown: { 216 const SCEVUnknown *U = cast<SCEVUnknown>(this); 217 Type *AllocTy; 218 if (U->isSizeOf(AllocTy)) { 219 OS << "sizeof(" << *AllocTy << ")"; 220 return; 221 } 222 if (U->isAlignOf(AllocTy)) { 223 OS << "alignof(" << *AllocTy << ")"; 224 return; 225 } 226 227 Type *CTy; 228 Constant *FieldNo; 229 if (U->isOffsetOf(CTy, FieldNo)) { 230 OS << "offsetof(" << *CTy << ", "; 231 FieldNo->printAsOperand(OS, false); 232 OS << ")"; 233 return; 234 } 235 236 // Otherwise just print it normally. 237 U->getValue()->printAsOperand(OS, false); 238 return; 239 } 240 case scCouldNotCompute: 241 OS << "***COULDNOTCOMPUTE***"; 242 return; 243 } 244 llvm_unreachable("Unknown SCEV kind!"); 245 } 246 247 Type *SCEV::getType() const { 248 switch (static_cast<SCEVTypes>(getSCEVType())) { 249 case scConstant: 250 return cast<SCEVConstant>(this)->getType(); 251 case scTruncate: 252 case scZeroExtend: 253 case scSignExtend: 254 return cast<SCEVCastExpr>(this)->getType(); 255 case scAddRecExpr: 256 case scMulExpr: 257 case scUMaxExpr: 258 case scSMaxExpr: 259 return cast<SCEVNAryExpr>(this)->getType(); 260 case scAddExpr: 261 return cast<SCEVAddExpr>(this)->getType(); 262 case scUDivExpr: 263 return cast<SCEVUDivExpr>(this)->getType(); 264 case scUnknown: 265 return cast<SCEVUnknown>(this)->getType(); 266 case scCouldNotCompute: 267 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 268 } 269 llvm_unreachable("Unknown SCEV kind!"); 270 } 271 272 bool SCEV::isZero() const { 273 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 274 return SC->getValue()->isZero(); 275 return false; 276 } 277 278 bool SCEV::isOne() const { 279 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 280 return SC->getValue()->isOne(); 281 return false; 282 } 283 284 bool SCEV::isAllOnesValue() const { 285 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 286 return SC->getValue()->isAllOnesValue(); 287 return false; 288 } 289 290 bool SCEV::isNonConstantNegative() const { 291 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this); 292 if (!Mul) return false; 293 294 // If there is a constant factor, it will be first. 295 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); 296 if (!SC) return false; 297 298 // Return true if the value is negative, this matches things like (-42 * V). 299 return SC->getAPInt().isNegative(); 300 } 301 302 SCEVCouldNotCompute::SCEVCouldNotCompute() : 303 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {} 304 305 bool SCEVCouldNotCompute::classof(const SCEV *S) { 306 return S->getSCEVType() == scCouldNotCompute; 307 } 308 309 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) { 310 FoldingSetNodeID ID; 311 ID.AddInteger(scConstant); 312 ID.AddPointer(V); 313 void *IP = nullptr; 314 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 315 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V); 316 UniqueSCEVs.InsertNode(S, IP); 317 return S; 318 } 319 320 const SCEV *ScalarEvolution::getConstant(const APInt &Val) { 321 return getConstant(ConstantInt::get(getContext(), Val)); 322 } 323 324 const SCEV * 325 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) { 326 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty)); 327 return getConstant(ConstantInt::get(ITy, V, isSigned)); 328 } 329 330 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, 331 unsigned SCEVTy, const SCEV *op, Type *ty) 332 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {} 333 334 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, 335 const SCEV *op, Type *ty) 336 : SCEVCastExpr(ID, scTruncate, op, ty) { 337 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && 338 (Ty->isIntegerTy() || Ty->isPointerTy()) && 339 "Cannot truncate non-integer value!"); 340 } 341 342 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, 343 const SCEV *op, Type *ty) 344 : SCEVCastExpr(ID, scZeroExtend, op, ty) { 345 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && 346 (Ty->isIntegerTy() || Ty->isPointerTy()) && 347 "Cannot zero extend non-integer value!"); 348 } 349 350 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, 351 const SCEV *op, Type *ty) 352 : SCEVCastExpr(ID, scSignExtend, op, ty) { 353 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && 354 (Ty->isIntegerTy() || Ty->isPointerTy()) && 355 "Cannot sign extend non-integer value!"); 356 } 357 358 void SCEVUnknown::deleted() { 359 // Clear this SCEVUnknown from various maps. 360 SE->forgetMemoizedResults(this); 361 362 // Remove this SCEVUnknown from the uniquing map. 363 SE->UniqueSCEVs.RemoveNode(this); 364 365 // Release the value. 366 setValPtr(nullptr); 367 } 368 369 void SCEVUnknown::allUsesReplacedWith(Value *New) { 370 // Clear this SCEVUnknown from various maps. 371 SE->forgetMemoizedResults(this); 372 373 // Remove this SCEVUnknown from the uniquing map. 374 SE->UniqueSCEVs.RemoveNode(this); 375 376 // Update this SCEVUnknown to point to the new value. This is needed 377 // because there may still be outstanding SCEVs which still point to 378 // this SCEVUnknown. 379 setValPtr(New); 380 } 381 382 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const { 383 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 384 if (VCE->getOpcode() == Instruction::PtrToInt) 385 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 386 if (CE->getOpcode() == Instruction::GetElementPtr && 387 CE->getOperand(0)->isNullValue() && 388 CE->getNumOperands() == 2) 389 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1))) 390 if (CI->isOne()) { 391 AllocTy = cast<PointerType>(CE->getOperand(0)->getType()) 392 ->getElementType(); 393 return true; 394 } 395 396 return false; 397 } 398 399 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const { 400 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 401 if (VCE->getOpcode() == Instruction::PtrToInt) 402 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 403 if (CE->getOpcode() == Instruction::GetElementPtr && 404 CE->getOperand(0)->isNullValue()) { 405 Type *Ty = 406 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 407 if (StructType *STy = dyn_cast<StructType>(Ty)) 408 if (!STy->isPacked() && 409 CE->getNumOperands() == 3 && 410 CE->getOperand(1)->isNullValue()) { 411 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2))) 412 if (CI->isOne() && 413 STy->getNumElements() == 2 && 414 STy->getElementType(0)->isIntegerTy(1)) { 415 AllocTy = STy->getElementType(1); 416 return true; 417 } 418 } 419 } 420 421 return false; 422 } 423 424 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const { 425 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 426 if (VCE->getOpcode() == Instruction::PtrToInt) 427 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 428 if (CE->getOpcode() == Instruction::GetElementPtr && 429 CE->getNumOperands() == 3 && 430 CE->getOperand(0)->isNullValue() && 431 CE->getOperand(1)->isNullValue()) { 432 Type *Ty = 433 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 434 // Ignore vector types here so that ScalarEvolutionExpander doesn't 435 // emit getelementptrs that index into vectors. 436 if (Ty->isStructTy() || Ty->isArrayTy()) { 437 CTy = Ty; 438 FieldNo = CE->getOperand(2); 439 return true; 440 } 441 } 442 443 return false; 444 } 445 446 //===----------------------------------------------------------------------===// 447 // SCEV Utilities 448 //===----------------------------------------------------------------------===// 449 450 namespace { 451 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less 452 /// than the complexity of the RHS. This comparator is used to canonicalize 453 /// expressions. 454 class SCEVComplexityCompare { 455 const LoopInfo *const LI; 456 public: 457 explicit SCEVComplexityCompare(const LoopInfo *li) : LI(li) {} 458 459 // Return true or false if LHS is less than, or at least RHS, respectively. 460 bool operator()(const SCEV *LHS, const SCEV *RHS) const { 461 return compare(LHS, RHS) < 0; 462 } 463 464 // Return negative, zero, or positive, if LHS is less than, equal to, or 465 // greater than RHS, respectively. A three-way result allows recursive 466 // comparisons to be more efficient. 467 int compare(const SCEV *LHS, const SCEV *RHS) const { 468 // Fast-path: SCEVs are uniqued so we can do a quick equality check. 469 if (LHS == RHS) 470 return 0; 471 472 // Primarily, sort the SCEVs by their getSCEVType(). 473 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType(); 474 if (LType != RType) 475 return (int)LType - (int)RType; 476 477 // Aside from the getSCEVType() ordering, the particular ordering 478 // isn't very important except that it's beneficial to be consistent, 479 // so that (a + b) and (b + a) don't end up as different expressions. 480 switch (static_cast<SCEVTypes>(LType)) { 481 case scUnknown: { 482 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS); 483 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); 484 485 // Sort SCEVUnknown values with some loose heuristics. TODO: This is 486 // not as complete as it could be. 487 const Value *LV = LU->getValue(), *RV = RU->getValue(); 488 489 // Order pointer values after integer values. This helps SCEVExpander 490 // form GEPs. 491 bool LIsPointer = LV->getType()->isPointerTy(), 492 RIsPointer = RV->getType()->isPointerTy(); 493 if (LIsPointer != RIsPointer) 494 return (int)LIsPointer - (int)RIsPointer; 495 496 // Compare getValueID values. 497 unsigned LID = LV->getValueID(), 498 RID = RV->getValueID(); 499 if (LID != RID) 500 return (int)LID - (int)RID; 501 502 // Sort arguments by their position. 503 if (const Argument *LA = dyn_cast<Argument>(LV)) { 504 const Argument *RA = cast<Argument>(RV); 505 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo(); 506 return (int)LArgNo - (int)RArgNo; 507 } 508 509 // For instructions, compare their loop depth, and their operand 510 // count. This is pretty loose. 511 if (const Instruction *LInst = dyn_cast<Instruction>(LV)) { 512 const Instruction *RInst = cast<Instruction>(RV); 513 514 // Compare loop depths. 515 const BasicBlock *LParent = LInst->getParent(), 516 *RParent = RInst->getParent(); 517 if (LParent != RParent) { 518 unsigned LDepth = LI->getLoopDepth(LParent), 519 RDepth = LI->getLoopDepth(RParent); 520 if (LDepth != RDepth) 521 return (int)LDepth - (int)RDepth; 522 } 523 524 // Compare the number of operands. 525 unsigned LNumOps = LInst->getNumOperands(), 526 RNumOps = RInst->getNumOperands(); 527 return (int)LNumOps - (int)RNumOps; 528 } 529 530 return 0; 531 } 532 533 case scConstant: { 534 const SCEVConstant *LC = cast<SCEVConstant>(LHS); 535 const SCEVConstant *RC = cast<SCEVConstant>(RHS); 536 537 // Compare constant values. 538 const APInt &LA = LC->getAPInt(); 539 const APInt &RA = RC->getAPInt(); 540 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth(); 541 if (LBitWidth != RBitWidth) 542 return (int)LBitWidth - (int)RBitWidth; 543 return LA.ult(RA) ? -1 : 1; 544 } 545 546 case scAddRecExpr: { 547 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); 548 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); 549 550 // Compare addrec loop depths. 551 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); 552 if (LLoop != RLoop) { 553 unsigned LDepth = LLoop->getLoopDepth(), 554 RDepth = RLoop->getLoopDepth(); 555 if (LDepth != RDepth) 556 return (int)LDepth - (int)RDepth; 557 } 558 559 // Addrec complexity grows with operand count. 560 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands(); 561 if (LNumOps != RNumOps) 562 return (int)LNumOps - (int)RNumOps; 563 564 // Lexicographically compare. 565 for (unsigned i = 0; i != LNumOps; ++i) { 566 long X = compare(LA->getOperand(i), RA->getOperand(i)); 567 if (X != 0) 568 return X; 569 } 570 571 return 0; 572 } 573 574 case scAddExpr: 575 case scMulExpr: 576 case scSMaxExpr: 577 case scUMaxExpr: { 578 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); 579 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); 580 581 // Lexicographically compare n-ary expressions. 582 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); 583 if (LNumOps != RNumOps) 584 return (int)LNumOps - (int)RNumOps; 585 586 for (unsigned i = 0; i != LNumOps; ++i) { 587 if (i >= RNumOps) 588 return 1; 589 long X = compare(LC->getOperand(i), RC->getOperand(i)); 590 if (X != 0) 591 return X; 592 } 593 return (int)LNumOps - (int)RNumOps; 594 } 595 596 case scUDivExpr: { 597 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); 598 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); 599 600 // Lexicographically compare udiv expressions. 601 long X = compare(LC->getLHS(), RC->getLHS()); 602 if (X != 0) 603 return X; 604 return compare(LC->getRHS(), RC->getRHS()); 605 } 606 607 case scTruncate: 608 case scZeroExtend: 609 case scSignExtend: { 610 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS); 611 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS); 612 613 // Compare cast expressions by operand. 614 return compare(LC->getOperand(), RC->getOperand()); 615 } 616 617 case scCouldNotCompute: 618 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 619 } 620 llvm_unreachable("Unknown SCEV kind!"); 621 } 622 }; 623 } // end anonymous namespace 624 625 /// Given a list of SCEV objects, order them by their complexity, and group 626 /// objects of the same complexity together by value. When this routine is 627 /// finished, we know that any duplicates in the vector are consecutive and that 628 /// complexity is monotonically increasing. 629 /// 630 /// Note that we go take special precautions to ensure that we get deterministic 631 /// results from this routine. In other words, we don't want the results of 632 /// this to depend on where the addresses of various SCEV objects happened to 633 /// land in memory. 634 /// 635 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, 636 LoopInfo *LI) { 637 if (Ops.size() < 2) return; // Noop 638 if (Ops.size() == 2) { 639 // This is the common case, which also happens to be trivially simple. 640 // Special case it. 641 const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; 642 if (SCEVComplexityCompare(LI)(RHS, LHS)) 643 std::swap(LHS, RHS); 644 return; 645 } 646 647 // Do the rough sort by complexity. 648 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI)); 649 650 // Now that we are sorted by complexity, group elements of the same 651 // complexity. Note that this is, at worst, N^2, but the vector is likely to 652 // be extremely short in practice. Note that we take this approach because we 653 // do not want to depend on the addresses of the objects we are grouping. 654 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { 655 const SCEV *S = Ops[i]; 656 unsigned Complexity = S->getSCEVType(); 657 658 // If there are any objects of the same complexity and same value as this 659 // one, group them. 660 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { 661 if (Ops[j] == S) { // Found a duplicate. 662 // Move it to immediately after i'th element. 663 std::swap(Ops[i+1], Ops[j]); 664 ++i; // no need to rescan it. 665 if (i == e-2) return; // Done! 666 } 667 } 668 } 669 } 670 671 // Returns the size of the SCEV S. 672 static inline int sizeOfSCEV(const SCEV *S) { 673 struct FindSCEVSize { 674 int Size; 675 FindSCEVSize() : Size(0) {} 676 677 bool follow(const SCEV *S) { 678 ++Size; 679 // Keep looking at all operands of S. 680 return true; 681 } 682 bool isDone() const { 683 return false; 684 } 685 }; 686 687 FindSCEVSize F; 688 SCEVTraversal<FindSCEVSize> ST(F); 689 ST.visitAll(S); 690 return F.Size; 691 } 692 693 namespace { 694 695 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> { 696 public: 697 // Computes the Quotient and Remainder of the division of Numerator by 698 // Denominator. 699 static void divide(ScalarEvolution &SE, const SCEV *Numerator, 700 const SCEV *Denominator, const SCEV **Quotient, 701 const SCEV **Remainder) { 702 assert(Numerator && Denominator && "Uninitialized SCEV"); 703 704 SCEVDivision D(SE, Numerator, Denominator); 705 706 // Check for the trivial case here to avoid having to check for it in the 707 // rest of the code. 708 if (Numerator == Denominator) { 709 *Quotient = D.One; 710 *Remainder = D.Zero; 711 return; 712 } 713 714 if (Numerator->isZero()) { 715 *Quotient = D.Zero; 716 *Remainder = D.Zero; 717 return; 718 } 719 720 // A simple case when N/1. The quotient is N. 721 if (Denominator->isOne()) { 722 *Quotient = Numerator; 723 *Remainder = D.Zero; 724 return; 725 } 726 727 // Split the Denominator when it is a product. 728 if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) { 729 const SCEV *Q, *R; 730 *Quotient = Numerator; 731 for (const SCEV *Op : T->operands()) { 732 divide(SE, *Quotient, Op, &Q, &R); 733 *Quotient = Q; 734 735 // Bail out when the Numerator is not divisible by one of the terms of 736 // the Denominator. 737 if (!R->isZero()) { 738 *Quotient = D.Zero; 739 *Remainder = Numerator; 740 return; 741 } 742 } 743 *Remainder = D.Zero; 744 return; 745 } 746 747 D.visit(Numerator); 748 *Quotient = D.Quotient; 749 *Remainder = D.Remainder; 750 } 751 752 // Except in the trivial case described above, we do not know how to divide 753 // Expr by Denominator for the following functions with empty implementation. 754 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {} 755 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {} 756 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {} 757 void visitUDivExpr(const SCEVUDivExpr *Numerator) {} 758 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {} 759 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {} 760 void visitUnknown(const SCEVUnknown *Numerator) {} 761 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {} 762 763 void visitConstant(const SCEVConstant *Numerator) { 764 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) { 765 APInt NumeratorVal = Numerator->getAPInt(); 766 APInt DenominatorVal = D->getAPInt(); 767 uint32_t NumeratorBW = NumeratorVal.getBitWidth(); 768 uint32_t DenominatorBW = DenominatorVal.getBitWidth(); 769 770 if (NumeratorBW > DenominatorBW) 771 DenominatorVal = DenominatorVal.sext(NumeratorBW); 772 else if (NumeratorBW < DenominatorBW) 773 NumeratorVal = NumeratorVal.sext(DenominatorBW); 774 775 APInt QuotientVal(NumeratorVal.getBitWidth(), 0); 776 APInt RemainderVal(NumeratorVal.getBitWidth(), 0); 777 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal); 778 Quotient = SE.getConstant(QuotientVal); 779 Remainder = SE.getConstant(RemainderVal); 780 return; 781 } 782 } 783 784 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) { 785 const SCEV *StartQ, *StartR, *StepQ, *StepR; 786 if (!Numerator->isAffine()) 787 return cannotDivide(Numerator); 788 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR); 789 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR); 790 // Bail out if the types do not match. 791 Type *Ty = Denominator->getType(); 792 if (Ty != StartQ->getType() || Ty != StartR->getType() || 793 Ty != StepQ->getType() || Ty != StepR->getType()) 794 return cannotDivide(Numerator); 795 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(), 796 Numerator->getNoWrapFlags()); 797 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(), 798 Numerator->getNoWrapFlags()); 799 } 800 801 void visitAddExpr(const SCEVAddExpr *Numerator) { 802 SmallVector<const SCEV *, 2> Qs, Rs; 803 Type *Ty = Denominator->getType(); 804 805 for (const SCEV *Op : Numerator->operands()) { 806 const SCEV *Q, *R; 807 divide(SE, Op, Denominator, &Q, &R); 808 809 // Bail out if types do not match. 810 if (Ty != Q->getType() || Ty != R->getType()) 811 return cannotDivide(Numerator); 812 813 Qs.push_back(Q); 814 Rs.push_back(R); 815 } 816 817 if (Qs.size() == 1) { 818 Quotient = Qs[0]; 819 Remainder = Rs[0]; 820 return; 821 } 822 823 Quotient = SE.getAddExpr(Qs); 824 Remainder = SE.getAddExpr(Rs); 825 } 826 827 void visitMulExpr(const SCEVMulExpr *Numerator) { 828 SmallVector<const SCEV *, 2> Qs; 829 Type *Ty = Denominator->getType(); 830 831 bool FoundDenominatorTerm = false; 832 for (const SCEV *Op : Numerator->operands()) { 833 // Bail out if types do not match. 834 if (Ty != Op->getType()) 835 return cannotDivide(Numerator); 836 837 if (FoundDenominatorTerm) { 838 Qs.push_back(Op); 839 continue; 840 } 841 842 // Check whether Denominator divides one of the product operands. 843 const SCEV *Q, *R; 844 divide(SE, Op, Denominator, &Q, &R); 845 if (!R->isZero()) { 846 Qs.push_back(Op); 847 continue; 848 } 849 850 // Bail out if types do not match. 851 if (Ty != Q->getType()) 852 return cannotDivide(Numerator); 853 854 FoundDenominatorTerm = true; 855 Qs.push_back(Q); 856 } 857 858 if (FoundDenominatorTerm) { 859 Remainder = Zero; 860 if (Qs.size() == 1) 861 Quotient = Qs[0]; 862 else 863 Quotient = SE.getMulExpr(Qs); 864 return; 865 } 866 867 if (!isa<SCEVUnknown>(Denominator)) 868 return cannotDivide(Numerator); 869 870 // The Remainder is obtained by replacing Denominator by 0 in Numerator. 871 ValueToValueMap RewriteMap; 872 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 873 cast<SCEVConstant>(Zero)->getValue(); 874 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 875 876 if (Remainder->isZero()) { 877 // The Quotient is obtained by replacing Denominator by 1 in Numerator. 878 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 879 cast<SCEVConstant>(One)->getValue(); 880 Quotient = 881 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 882 return; 883 } 884 885 // Quotient is (Numerator - Remainder) divided by Denominator. 886 const SCEV *Q, *R; 887 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder); 888 // This SCEV does not seem to simplify: fail the division here. 889 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator)) 890 return cannotDivide(Numerator); 891 divide(SE, Diff, Denominator, &Q, &R); 892 if (R != Zero) 893 return cannotDivide(Numerator); 894 Quotient = Q; 895 } 896 897 private: 898 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator, 899 const SCEV *Denominator) 900 : SE(S), Denominator(Denominator) { 901 Zero = SE.getZero(Denominator->getType()); 902 One = SE.getOne(Denominator->getType()); 903 904 // We generally do not know how to divide Expr by Denominator. We 905 // initialize the division to a "cannot divide" state to simplify the rest 906 // of the code. 907 cannotDivide(Numerator); 908 } 909 910 // Convenience function for giving up on the division. We set the quotient to 911 // be equal to zero and the remainder to be equal to the numerator. 912 void cannotDivide(const SCEV *Numerator) { 913 Quotient = Zero; 914 Remainder = Numerator; 915 } 916 917 ScalarEvolution &SE; 918 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One; 919 }; 920 921 } 922 923 //===----------------------------------------------------------------------===// 924 // Simple SCEV method implementations 925 //===----------------------------------------------------------------------===// 926 927 /// Compute BC(It, K). The result has width W. Assume, K > 0. 928 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, 929 ScalarEvolution &SE, 930 Type *ResultTy) { 931 // Handle the simplest case efficiently. 932 if (K == 1) 933 return SE.getTruncateOrZeroExtend(It, ResultTy); 934 935 // We are using the following formula for BC(It, K): 936 // 937 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! 938 // 939 // Suppose, W is the bitwidth of the return value. We must be prepared for 940 // overflow. Hence, we must assure that the result of our computation is 941 // equal to the accurate one modulo 2^W. Unfortunately, division isn't 942 // safe in modular arithmetic. 943 // 944 // However, this code doesn't use exactly that formula; the formula it uses 945 // is something like the following, where T is the number of factors of 2 in 946 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is 947 // exponentiation: 948 // 949 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) 950 // 951 // This formula is trivially equivalent to the previous formula. However, 952 // this formula can be implemented much more efficiently. The trick is that 953 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular 954 // arithmetic. To do exact division in modular arithmetic, all we have 955 // to do is multiply by the inverse. Therefore, this step can be done at 956 // width W. 957 // 958 // The next issue is how to safely do the division by 2^T. The way this 959 // is done is by doing the multiplication step at a width of at least W + T 960 // bits. This way, the bottom W+T bits of the product are accurate. Then, 961 // when we perform the division by 2^T (which is equivalent to a right shift 962 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get 963 // truncated out after the division by 2^T. 964 // 965 // In comparison to just directly using the first formula, this technique 966 // is much more efficient; using the first formula requires W * K bits, 967 // but this formula less than W + K bits. Also, the first formula requires 968 // a division step, whereas this formula only requires multiplies and shifts. 969 // 970 // It doesn't matter whether the subtraction step is done in the calculation 971 // width or the input iteration count's width; if the subtraction overflows, 972 // the result must be zero anyway. We prefer here to do it in the width of 973 // the induction variable because it helps a lot for certain cases; CodeGen 974 // isn't smart enough to ignore the overflow, which leads to much less 975 // efficient code if the width of the subtraction is wider than the native 976 // register width. 977 // 978 // (It's possible to not widen at all by pulling out factors of 2 before 979 // the multiplication; for example, K=2 can be calculated as 980 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires 981 // extra arithmetic, so it's not an obvious win, and it gets 982 // much more complicated for K > 3.) 983 984 // Protection from insane SCEVs; this bound is conservative, 985 // but it probably doesn't matter. 986 if (K > 1000) 987 return SE.getCouldNotCompute(); 988 989 unsigned W = SE.getTypeSizeInBits(ResultTy); 990 991 // Calculate K! / 2^T and T; we divide out the factors of two before 992 // multiplying for calculating K! / 2^T to avoid overflow. 993 // Other overflow doesn't matter because we only care about the bottom 994 // W bits of the result. 995 APInt OddFactorial(W, 1); 996 unsigned T = 1; 997 for (unsigned i = 3; i <= K; ++i) { 998 APInt Mult(W, i); 999 unsigned TwoFactors = Mult.countTrailingZeros(); 1000 T += TwoFactors; 1001 Mult = Mult.lshr(TwoFactors); 1002 OddFactorial *= Mult; 1003 } 1004 1005 // We need at least W + T bits for the multiplication step 1006 unsigned CalculationBits = W + T; 1007 1008 // Calculate 2^T, at width T+W. 1009 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T); 1010 1011 // Calculate the multiplicative inverse of K! / 2^T; 1012 // this multiplication factor will perform the exact division by 1013 // K! / 2^T. 1014 APInt Mod = APInt::getSignedMinValue(W+1); 1015 APInt MultiplyFactor = OddFactorial.zext(W+1); 1016 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); 1017 MultiplyFactor = MultiplyFactor.trunc(W); 1018 1019 // Calculate the product, at width T+W 1020 IntegerType *CalculationTy = IntegerType::get(SE.getContext(), 1021 CalculationBits); 1022 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); 1023 for (unsigned i = 1; i != K; ++i) { 1024 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); 1025 Dividend = SE.getMulExpr(Dividend, 1026 SE.getTruncateOrZeroExtend(S, CalculationTy)); 1027 } 1028 1029 // Divide by 2^T 1030 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); 1031 1032 // Truncate the result, and divide by K! / 2^T. 1033 1034 return SE.getMulExpr(SE.getConstant(MultiplyFactor), 1035 SE.getTruncateOrZeroExtend(DivResult, ResultTy)); 1036 } 1037 1038 /// Return the value of this chain of recurrences at the specified iteration 1039 /// number. We can evaluate this recurrence by multiplying each element in the 1040 /// chain by the binomial coefficient corresponding to it. In other words, we 1041 /// can evaluate {A,+,B,+,C,+,D} as: 1042 /// 1043 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) 1044 /// 1045 /// where BC(It, k) stands for binomial coefficient. 1046 /// 1047 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, 1048 ScalarEvolution &SE) const { 1049 const SCEV *Result = getStart(); 1050 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 1051 // The computation is correct in the face of overflow provided that the 1052 // multiplication is performed _after_ the evaluation of the binomial 1053 // coefficient. 1054 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType()); 1055 if (isa<SCEVCouldNotCompute>(Coeff)) 1056 return Coeff; 1057 1058 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff)); 1059 } 1060 return Result; 1061 } 1062 1063 //===----------------------------------------------------------------------===// 1064 // SCEV Expression folder implementations 1065 //===----------------------------------------------------------------------===// 1066 1067 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, 1068 Type *Ty) { 1069 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && 1070 "This is not a truncating conversion!"); 1071 assert(isSCEVable(Ty) && 1072 "This is not a conversion to a SCEVable type!"); 1073 Ty = getEffectiveSCEVType(Ty); 1074 1075 FoldingSetNodeID ID; 1076 ID.AddInteger(scTruncate); 1077 ID.AddPointer(Op); 1078 ID.AddPointer(Ty); 1079 void *IP = nullptr; 1080 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1081 1082 // Fold if the operand is constant. 1083 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1084 return getConstant( 1085 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); 1086 1087 // trunc(trunc(x)) --> trunc(x) 1088 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) 1089 return getTruncateExpr(ST->getOperand(), Ty); 1090 1091 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing 1092 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1093 return getTruncateOrSignExtend(SS->getOperand(), Ty); 1094 1095 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing 1096 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1097 return getTruncateOrZeroExtend(SZ->getOperand(), Ty); 1098 1099 // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can 1100 // eliminate all the truncates, or we replace other casts with truncates. 1101 if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) { 1102 SmallVector<const SCEV *, 4> Operands; 1103 bool hasTrunc = false; 1104 for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) { 1105 const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty); 1106 if (!isa<SCEVCastExpr>(SA->getOperand(i))) 1107 hasTrunc = isa<SCEVTruncateExpr>(S); 1108 Operands.push_back(S); 1109 } 1110 if (!hasTrunc) 1111 return getAddExpr(Operands); 1112 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL. 1113 } 1114 1115 // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can 1116 // eliminate all the truncates, or we replace other casts with truncates. 1117 if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) { 1118 SmallVector<const SCEV *, 4> Operands; 1119 bool hasTrunc = false; 1120 for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) { 1121 const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty); 1122 if (!isa<SCEVCastExpr>(SM->getOperand(i))) 1123 hasTrunc = isa<SCEVTruncateExpr>(S); 1124 Operands.push_back(S); 1125 } 1126 if (!hasTrunc) 1127 return getMulExpr(Operands); 1128 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL. 1129 } 1130 1131 // If the input value is a chrec scev, truncate the chrec's operands. 1132 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 1133 SmallVector<const SCEV *, 4> Operands; 1134 for (const SCEV *Op : AddRec->operands()) 1135 Operands.push_back(getTruncateExpr(Op, Ty)); 1136 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap); 1137 } 1138 1139 // The cast wasn't folded; create an explicit cast node. We can reuse 1140 // the existing insert position since if we get here, we won't have 1141 // made any changes which would invalidate it. 1142 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), 1143 Op, Ty); 1144 UniqueSCEVs.InsertNode(S, IP); 1145 return S; 1146 } 1147 1148 // Get the limit of a recurrence such that incrementing by Step cannot cause 1149 // signed overflow as long as the value of the recurrence within the 1150 // loop does not exceed this limit before incrementing. 1151 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step, 1152 ICmpInst::Predicate *Pred, 1153 ScalarEvolution *SE) { 1154 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1155 if (SE->isKnownPositive(Step)) { 1156 *Pred = ICmpInst::ICMP_SLT; 1157 return SE->getConstant(APInt::getSignedMinValue(BitWidth) - 1158 SE->getSignedRange(Step).getSignedMax()); 1159 } 1160 if (SE->isKnownNegative(Step)) { 1161 *Pred = ICmpInst::ICMP_SGT; 1162 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - 1163 SE->getSignedRange(Step).getSignedMin()); 1164 } 1165 return nullptr; 1166 } 1167 1168 // Get the limit of a recurrence such that incrementing by Step cannot cause 1169 // unsigned overflow as long as the value of the recurrence within the loop does 1170 // not exceed this limit before incrementing. 1171 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step, 1172 ICmpInst::Predicate *Pred, 1173 ScalarEvolution *SE) { 1174 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1175 *Pred = ICmpInst::ICMP_ULT; 1176 1177 return SE->getConstant(APInt::getMinValue(BitWidth) - 1178 SE->getUnsignedRange(Step).getUnsignedMax()); 1179 } 1180 1181 namespace { 1182 1183 struct ExtendOpTraitsBase { 1184 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *); 1185 }; 1186 1187 // Used to make code generic over signed and unsigned overflow. 1188 template <typename ExtendOp> struct ExtendOpTraits { 1189 // Members present: 1190 // 1191 // static const SCEV::NoWrapFlags WrapType; 1192 // 1193 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr; 1194 // 1195 // static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1196 // ICmpInst::Predicate *Pred, 1197 // ScalarEvolution *SE); 1198 }; 1199 1200 template <> 1201 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase { 1202 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW; 1203 1204 static const GetExtendExprTy GetExtendExpr; 1205 1206 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1207 ICmpInst::Predicate *Pred, 1208 ScalarEvolution *SE) { 1209 return getSignedOverflowLimitForStep(Step, Pred, SE); 1210 } 1211 }; 1212 1213 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1214 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr; 1215 1216 template <> 1217 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase { 1218 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW; 1219 1220 static const GetExtendExprTy GetExtendExpr; 1221 1222 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1223 ICmpInst::Predicate *Pred, 1224 ScalarEvolution *SE) { 1225 return getUnsignedOverflowLimitForStep(Step, Pred, SE); 1226 } 1227 }; 1228 1229 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1230 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr; 1231 } 1232 1233 // The recurrence AR has been shown to have no signed/unsigned wrap or something 1234 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as 1235 // easily prove NSW/NUW for its preincrement or postincrement sibling. This 1236 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step + 1237 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the 1238 // expression "Step + sext/zext(PreIncAR)" is congruent with 1239 // "sext/zext(PostIncAR)" 1240 template <typename ExtendOpTy> 1241 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, 1242 ScalarEvolution *SE) { 1243 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1244 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1245 1246 const Loop *L = AR->getLoop(); 1247 const SCEV *Start = AR->getStart(); 1248 const SCEV *Step = AR->getStepRecurrence(*SE); 1249 1250 // Check for a simple looking step prior to loop entry. 1251 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); 1252 if (!SA) 1253 return nullptr; 1254 1255 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV 1256 // subtraction is expensive. For this purpose, perform a quick and dirty 1257 // difference, by checking for Step in the operand list. 1258 SmallVector<const SCEV *, 4> DiffOps; 1259 for (const SCEV *Op : SA->operands()) 1260 if (Op != Step) 1261 DiffOps.push_back(Op); 1262 1263 if (DiffOps.size() == SA->getNumOperands()) 1264 return nullptr; 1265 1266 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` + 1267 // `Step`: 1268 1269 // 1. NSW/NUW flags on the step increment. 1270 auto PreStartFlags = 1271 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW); 1272 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags); 1273 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( 1274 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); 1275 1276 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies 1277 // "S+X does not sign/unsign-overflow". 1278 // 1279 1280 const SCEV *BECount = SE->getBackedgeTakenCount(L); 1281 if (PreAR && PreAR->getNoWrapFlags(WrapType) && 1282 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) 1283 return PreStart; 1284 1285 // 2. Direct overflow check on the step operation's expression. 1286 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); 1287 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); 1288 const SCEV *OperandExtendedStart = 1289 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy), 1290 (SE->*GetExtendExpr)(Step, WideTy)); 1291 if ((SE->*GetExtendExpr)(Start, WideTy) == OperandExtendedStart) { 1292 if (PreAR && AR->getNoWrapFlags(WrapType)) { 1293 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW 1294 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then 1295 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. 1296 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType); 1297 } 1298 return PreStart; 1299 } 1300 1301 // 3. Loop precondition. 1302 ICmpInst::Predicate Pred; 1303 const SCEV *OverflowLimit = 1304 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); 1305 1306 if (OverflowLimit && 1307 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) 1308 return PreStart; 1309 1310 return nullptr; 1311 } 1312 1313 // Get the normalized zero or sign extended expression for this AddRec's Start. 1314 template <typename ExtendOpTy> 1315 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, 1316 ScalarEvolution *SE) { 1317 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1318 1319 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE); 1320 if (!PreStart) 1321 return (SE->*GetExtendExpr)(AR->getStart(), Ty); 1322 1323 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty), 1324 (SE->*GetExtendExpr)(PreStart, Ty)); 1325 } 1326 1327 // Try to prove away overflow by looking at "nearby" add recurrences. A 1328 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it 1329 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. 1330 // 1331 // Formally: 1332 // 1333 // {S,+,X} == {S-T,+,X} + T 1334 // => Ext({S,+,X}) == Ext({S-T,+,X} + T) 1335 // 1336 // If ({S-T,+,X} + T) does not overflow ... (1) 1337 // 1338 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) 1339 // 1340 // If {S-T,+,X} does not overflow ... (2) 1341 // 1342 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) 1343 // == {Ext(S-T)+Ext(T),+,Ext(X)} 1344 // 1345 // If (S-T)+T does not overflow ... (3) 1346 // 1347 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} 1348 // == {Ext(S),+,Ext(X)} == LHS 1349 // 1350 // Thus, if (1), (2) and (3) are true for some T, then 1351 // Ext({S,+,X}) == {Ext(S),+,Ext(X)} 1352 // 1353 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) 1354 // does not overflow" restricted to the 0th iteration. Therefore we only need 1355 // to check for (1) and (2). 1356 // 1357 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T 1358 // is `Delta` (defined below). 1359 // 1360 template <typename ExtendOpTy> 1361 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, 1362 const SCEV *Step, 1363 const Loop *L) { 1364 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1365 1366 // We restrict `Start` to a constant to prevent SCEV from spending too much 1367 // time here. It is correct (but more expensive) to continue with a 1368 // non-constant `Start` and do a general SCEV subtraction to compute 1369 // `PreStart` below. 1370 // 1371 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); 1372 if (!StartC) 1373 return false; 1374 1375 APInt StartAI = StartC->getAPInt(); 1376 1377 for (unsigned Delta : {-2, -1, 1, 2}) { 1378 const SCEV *PreStart = getConstant(StartAI - Delta); 1379 1380 FoldingSetNodeID ID; 1381 ID.AddInteger(scAddRecExpr); 1382 ID.AddPointer(PreStart); 1383 ID.AddPointer(Step); 1384 ID.AddPointer(L); 1385 void *IP = nullptr; 1386 const auto *PreAR = 1387 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 1388 1389 // Give up if we don't already have the add recurrence we need because 1390 // actually constructing an add recurrence is relatively expensive. 1391 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2) 1392 const SCEV *DeltaS = getConstant(StartC->getType(), Delta); 1393 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; 1394 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep( 1395 DeltaS, &Pred, this); 1396 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1) 1397 return true; 1398 } 1399 } 1400 1401 return false; 1402 } 1403 1404 const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op, 1405 Type *Ty) { 1406 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1407 "This is not an extending conversion!"); 1408 assert(isSCEVable(Ty) && 1409 "This is not a conversion to a SCEVable type!"); 1410 Ty = getEffectiveSCEVType(Ty); 1411 1412 // Fold if the operand is constant. 1413 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1414 return getConstant( 1415 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty))); 1416 1417 // zext(zext(x)) --> zext(x) 1418 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1419 return getZeroExtendExpr(SZ->getOperand(), Ty); 1420 1421 // Before doing any expensive analysis, check to see if we've already 1422 // computed a SCEV for this Op and Ty. 1423 FoldingSetNodeID ID; 1424 ID.AddInteger(scZeroExtend); 1425 ID.AddPointer(Op); 1426 ID.AddPointer(Ty); 1427 void *IP = nullptr; 1428 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1429 1430 // zext(trunc(x)) --> zext(x) or x or trunc(x) 1431 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1432 // It's possible the bits taken off by the truncate were all zero bits. If 1433 // so, we should be able to simplify this further. 1434 const SCEV *X = ST->getOperand(); 1435 ConstantRange CR = getUnsignedRange(X); 1436 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1437 unsigned NewBits = getTypeSizeInBits(Ty); 1438 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( 1439 CR.zextOrTrunc(NewBits))) 1440 return getTruncateOrZeroExtend(X, Ty); 1441 } 1442 1443 // If the input value is a chrec scev, and we can prove that the value 1444 // did not overflow the old, smaller, value, we can zero extend all of the 1445 // operands (often constants). This allows analysis of something like 1446 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } 1447 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1448 if (AR->isAffine()) { 1449 const SCEV *Start = AR->getStart(); 1450 const SCEV *Step = AR->getStepRecurrence(*this); 1451 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1452 const Loop *L = AR->getLoop(); 1453 1454 if (!AR->hasNoUnsignedWrap()) { 1455 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1456 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1457 } 1458 1459 // If we have special knowledge that this addrec won't overflow, 1460 // we don't need to do any further analysis. 1461 if (AR->hasNoUnsignedWrap()) 1462 return getAddRecExpr( 1463 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), 1464 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1465 1466 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1467 // Note that this serves two purposes: It filters out loops that are 1468 // simply not analyzable, and it covers the case where this code is 1469 // being called from within backedge-taken count analysis, such that 1470 // attempting to ask for the backedge-taken count would likely result 1471 // in infinite recursion. In the later case, the analysis code will 1472 // cope with a conservative value, and it will take care to purge 1473 // that value once it has finished. 1474 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); 1475 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1476 // Manually compute the final value for AR, checking for 1477 // overflow. 1478 1479 // Check whether the backedge-taken count can be losslessly casted to 1480 // the addrec's type. The count is always unsigned. 1481 const SCEV *CastedMaxBECount = 1482 getTruncateOrZeroExtend(MaxBECount, Start->getType()); 1483 const SCEV *RecastedMaxBECount = 1484 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); 1485 if (MaxBECount == RecastedMaxBECount) { 1486 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1487 // Check whether Start+Step*MaxBECount has no unsigned overflow. 1488 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step); 1489 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul), WideTy); 1490 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy); 1491 const SCEV *WideMaxBECount = 1492 getZeroExtendExpr(CastedMaxBECount, WideTy); 1493 const SCEV *OperandExtendedAdd = 1494 getAddExpr(WideStart, 1495 getMulExpr(WideMaxBECount, 1496 getZeroExtendExpr(Step, WideTy))); 1497 if (ZAdd == OperandExtendedAdd) { 1498 // Cache knowledge of AR NUW, which is propagated to this AddRec. 1499 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1500 // Return the expression with the addrec on the outside. 1501 return getAddRecExpr( 1502 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), 1503 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1504 } 1505 // Similar to above, only this time treat the step value as signed. 1506 // This covers loops that count down. 1507 OperandExtendedAdd = 1508 getAddExpr(WideStart, 1509 getMulExpr(WideMaxBECount, 1510 getSignExtendExpr(Step, WideTy))); 1511 if (ZAdd == OperandExtendedAdd) { 1512 // Cache knowledge of AR NW, which is propagated to this AddRec. 1513 // Negative step causes unsigned wrap, but it still can't self-wrap. 1514 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1515 // Return the expression with the addrec on the outside. 1516 return getAddRecExpr( 1517 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), 1518 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1519 } 1520 } 1521 } 1522 1523 // Normally, in the cases we can prove no-overflow via a 1524 // backedge guarding condition, we can also compute a backedge 1525 // taken count for the loop. The exceptions are assumptions and 1526 // guards present in the loop -- SCEV is not great at exploiting 1527 // these to compute max backedge taken counts, but can still use 1528 // these to prove lack of overflow. Use this fact to avoid 1529 // doing extra work that may not pay off. 1530 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1531 !AC.assumptions().empty()) { 1532 // If the backedge is guarded by a comparison with the pre-inc 1533 // value the addrec is safe. Also, if the entry is guarded by 1534 // a comparison with the start value and the backedge is 1535 // guarded by a comparison with the post-inc value, the addrec 1536 // is safe. 1537 if (isKnownPositive(Step)) { 1538 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 1539 getUnsignedRange(Step).getUnsignedMax()); 1540 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 1541 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) && 1542 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, 1543 AR->getPostIncExpr(*this), N))) { 1544 // Cache knowledge of AR NUW, which is propagated to this 1545 // AddRec. 1546 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1547 // Return the expression with the addrec on the outside. 1548 return getAddRecExpr( 1549 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), 1550 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1551 } 1552 } else if (isKnownNegative(Step)) { 1553 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - 1554 getSignedRange(Step).getSignedMin()); 1555 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || 1556 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) && 1557 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, 1558 AR->getPostIncExpr(*this), N))) { 1559 // Cache knowledge of AR NW, which is propagated to this 1560 // AddRec. Negative step causes unsigned wrap, but it 1561 // still can't self-wrap. 1562 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1563 // Return the expression with the addrec on the outside. 1564 return getAddRecExpr( 1565 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), 1566 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1567 } 1568 } 1569 } 1570 1571 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { 1572 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1573 return getAddRecExpr( 1574 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), 1575 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1576 } 1577 } 1578 1579 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1580 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> 1581 if (SA->hasNoUnsignedWrap()) { 1582 // If the addition does not unsign overflow then we can, by definition, 1583 // commute the zero extension with the addition operation. 1584 SmallVector<const SCEV *, 4> Ops; 1585 for (const auto *Op : SA->operands()) 1586 Ops.push_back(getZeroExtendExpr(Op, Ty)); 1587 return getAddExpr(Ops, SCEV::FlagNUW); 1588 } 1589 } 1590 1591 // The cast wasn't folded; create an explicit cast node. 1592 // Recompute the insert position, as it may have been invalidated. 1593 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1594 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1595 Op, Ty); 1596 UniqueSCEVs.InsertNode(S, IP); 1597 return S; 1598 } 1599 1600 const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op, 1601 Type *Ty) { 1602 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1603 "This is not an extending conversion!"); 1604 assert(isSCEVable(Ty) && 1605 "This is not a conversion to a SCEVable type!"); 1606 Ty = getEffectiveSCEVType(Ty); 1607 1608 // Fold if the operand is constant. 1609 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1610 return getConstant( 1611 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); 1612 1613 // sext(sext(x)) --> sext(x) 1614 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1615 return getSignExtendExpr(SS->getOperand(), Ty); 1616 1617 // sext(zext(x)) --> zext(x) 1618 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1619 return getZeroExtendExpr(SZ->getOperand(), Ty); 1620 1621 // Before doing any expensive analysis, check to see if we've already 1622 // computed a SCEV for this Op and Ty. 1623 FoldingSetNodeID ID; 1624 ID.AddInteger(scSignExtend); 1625 ID.AddPointer(Op); 1626 ID.AddPointer(Ty); 1627 void *IP = nullptr; 1628 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1629 1630 // sext(trunc(x)) --> sext(x) or x or trunc(x) 1631 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1632 // It's possible the bits taken off by the truncate were all sign bits. If 1633 // so, we should be able to simplify this further. 1634 const SCEV *X = ST->getOperand(); 1635 ConstantRange CR = getSignedRange(X); 1636 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1637 unsigned NewBits = getTypeSizeInBits(Ty); 1638 if (CR.truncate(TruncBits).signExtend(NewBits).contains( 1639 CR.sextOrTrunc(NewBits))) 1640 return getTruncateOrSignExtend(X, Ty); 1641 } 1642 1643 // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2 1644 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1645 if (SA->getNumOperands() == 2) { 1646 auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0)); 1647 auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1)); 1648 if (SMul && SC1) { 1649 if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) { 1650 const APInt &C1 = SC1->getAPInt(); 1651 const APInt &C2 = SC2->getAPInt(); 1652 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && 1653 C2.ugt(C1) && C2.isPowerOf2()) 1654 return getAddExpr(getSignExtendExpr(SC1, Ty), 1655 getSignExtendExpr(SMul, Ty)); 1656 } 1657 } 1658 } 1659 1660 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 1661 if (SA->hasNoSignedWrap()) { 1662 // If the addition does not sign overflow then we can, by definition, 1663 // commute the sign extension with the addition operation. 1664 SmallVector<const SCEV *, 4> Ops; 1665 for (const auto *Op : SA->operands()) 1666 Ops.push_back(getSignExtendExpr(Op, Ty)); 1667 return getAddExpr(Ops, SCEV::FlagNSW); 1668 } 1669 } 1670 // If the input value is a chrec scev, and we can prove that the value 1671 // did not overflow the old, smaller, value, we can sign extend all of the 1672 // operands (often constants). This allows analysis of something like 1673 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 1674 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1675 if (AR->isAffine()) { 1676 const SCEV *Start = AR->getStart(); 1677 const SCEV *Step = AR->getStepRecurrence(*this); 1678 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1679 const Loop *L = AR->getLoop(); 1680 1681 if (!AR->hasNoSignedWrap()) { 1682 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1683 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1684 } 1685 1686 // If we have special knowledge that this addrec won't overflow, 1687 // we don't need to do any further analysis. 1688 if (AR->hasNoSignedWrap()) 1689 return getAddRecExpr( 1690 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), 1691 getSignExtendExpr(Step, Ty), L, SCEV::FlagNSW); 1692 1693 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1694 // Note that this serves two purposes: It filters out loops that are 1695 // simply not analyzable, and it covers the case where this code is 1696 // being called from within backedge-taken count analysis, such that 1697 // attempting to ask for the backedge-taken count would likely result 1698 // in infinite recursion. In the later case, the analysis code will 1699 // cope with a conservative value, and it will take care to purge 1700 // that value once it has finished. 1701 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); 1702 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1703 // Manually compute the final value for AR, checking for 1704 // overflow. 1705 1706 // Check whether the backedge-taken count can be losslessly casted to 1707 // the addrec's type. The count is always unsigned. 1708 const SCEV *CastedMaxBECount = 1709 getTruncateOrZeroExtend(MaxBECount, Start->getType()); 1710 const SCEV *RecastedMaxBECount = 1711 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); 1712 if (MaxBECount == RecastedMaxBECount) { 1713 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1714 // Check whether Start+Step*MaxBECount has no signed overflow. 1715 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step); 1716 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul), WideTy); 1717 const SCEV *WideStart = getSignExtendExpr(Start, WideTy); 1718 const SCEV *WideMaxBECount = 1719 getZeroExtendExpr(CastedMaxBECount, WideTy); 1720 const SCEV *OperandExtendedAdd = 1721 getAddExpr(WideStart, 1722 getMulExpr(WideMaxBECount, 1723 getSignExtendExpr(Step, WideTy))); 1724 if (SAdd == OperandExtendedAdd) { 1725 // Cache knowledge of AR NSW, which is propagated to this AddRec. 1726 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1727 // Return the expression with the addrec on the outside. 1728 return getAddRecExpr( 1729 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), 1730 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1731 } 1732 // Similar to above, only this time treat the step value as unsigned. 1733 // This covers loops that count up with an unsigned step. 1734 OperandExtendedAdd = 1735 getAddExpr(WideStart, 1736 getMulExpr(WideMaxBECount, 1737 getZeroExtendExpr(Step, WideTy))); 1738 if (SAdd == OperandExtendedAdd) { 1739 // If AR wraps around then 1740 // 1741 // abs(Step) * MaxBECount > unsigned-max(AR->getType()) 1742 // => SAdd != OperandExtendedAdd 1743 // 1744 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> 1745 // (SAdd == OperandExtendedAdd => AR is NW) 1746 1747 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1748 1749 // Return the expression with the addrec on the outside. 1750 return getAddRecExpr( 1751 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), 1752 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1753 } 1754 } 1755 } 1756 1757 // Normally, in the cases we can prove no-overflow via a 1758 // backedge guarding condition, we can also compute a backedge 1759 // taken count for the loop. The exceptions are assumptions and 1760 // guards present in the loop -- SCEV is not great at exploiting 1761 // these to compute max backedge taken counts, but can still use 1762 // these to prove lack of overflow. Use this fact to avoid 1763 // doing extra work that may not pay off. 1764 1765 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1766 !AC.assumptions().empty()) { 1767 // If the backedge is guarded by a comparison with the pre-inc 1768 // value the addrec is safe. Also, if the entry is guarded by 1769 // a comparison with the start value and the backedge is 1770 // guarded by a comparison with the post-inc value, the addrec 1771 // is safe. 1772 ICmpInst::Predicate Pred; 1773 const SCEV *OverflowLimit = 1774 getSignedOverflowLimitForStep(Step, &Pred, this); 1775 if (OverflowLimit && 1776 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 1777 (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) && 1778 isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this), 1779 OverflowLimit)))) { 1780 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec. 1781 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1782 return getAddRecExpr( 1783 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), 1784 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1785 } 1786 } 1787 1788 // If Start and Step are constants, check if we can apply this 1789 // transformation: 1790 // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2 1791 auto *SC1 = dyn_cast<SCEVConstant>(Start); 1792 auto *SC2 = dyn_cast<SCEVConstant>(Step); 1793 if (SC1 && SC2) { 1794 const APInt &C1 = SC1->getAPInt(); 1795 const APInt &C2 = SC2->getAPInt(); 1796 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) && 1797 C2.isPowerOf2()) { 1798 Start = getSignExtendExpr(Start, Ty); 1799 const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L, 1800 AR->getNoWrapFlags()); 1801 return getAddExpr(Start, getSignExtendExpr(NewAR, Ty)); 1802 } 1803 } 1804 1805 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { 1806 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1807 return getAddRecExpr( 1808 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), 1809 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1810 } 1811 } 1812 1813 // If the input value is provably positive and we could not simplify 1814 // away the sext build a zext instead. 1815 if (isKnownNonNegative(Op)) 1816 return getZeroExtendExpr(Op, Ty); 1817 1818 // The cast wasn't folded; create an explicit cast node. 1819 // Recompute the insert position, as it may have been invalidated. 1820 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1821 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1822 Op, Ty); 1823 UniqueSCEVs.InsertNode(S, IP); 1824 return S; 1825 } 1826 1827 /// getAnyExtendExpr - Return a SCEV for the given operand extended with 1828 /// unspecified bits out to the given type. 1829 /// 1830 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, 1831 Type *Ty) { 1832 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1833 "This is not an extending conversion!"); 1834 assert(isSCEVable(Ty) && 1835 "This is not a conversion to a SCEVable type!"); 1836 Ty = getEffectiveSCEVType(Ty); 1837 1838 // Sign-extend negative constants. 1839 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1840 if (SC->getAPInt().isNegative()) 1841 return getSignExtendExpr(Op, Ty); 1842 1843 // Peel off a truncate cast. 1844 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { 1845 const SCEV *NewOp = T->getOperand(); 1846 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) 1847 return getAnyExtendExpr(NewOp, Ty); 1848 return getTruncateOrNoop(NewOp, Ty); 1849 } 1850 1851 // Next try a zext cast. If the cast is folded, use it. 1852 const SCEV *ZExt = getZeroExtendExpr(Op, Ty); 1853 if (!isa<SCEVZeroExtendExpr>(ZExt)) 1854 return ZExt; 1855 1856 // Next try a sext cast. If the cast is folded, use it. 1857 const SCEV *SExt = getSignExtendExpr(Op, Ty); 1858 if (!isa<SCEVSignExtendExpr>(SExt)) 1859 return SExt; 1860 1861 // Force the cast to be folded into the operands of an addrec. 1862 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { 1863 SmallVector<const SCEV *, 4> Ops; 1864 for (const SCEV *Op : AR->operands()) 1865 Ops.push_back(getAnyExtendExpr(Op, Ty)); 1866 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); 1867 } 1868 1869 // If the expression is obviously signed, use the sext cast value. 1870 if (isa<SCEVSMaxExpr>(Op)) 1871 return SExt; 1872 1873 // Absent any other information, use the zext cast value. 1874 return ZExt; 1875 } 1876 1877 /// Process the given Ops list, which is a list of operands to be added under 1878 /// the given scale, update the given map. This is a helper function for 1879 /// getAddRecExpr. As an example of what it does, given a sequence of operands 1880 /// that would form an add expression like this: 1881 /// 1882 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r) 1883 /// 1884 /// where A and B are constants, update the map with these values: 1885 /// 1886 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) 1887 /// 1888 /// and add 13 + A*B*29 to AccumulatedConstant. 1889 /// This will allow getAddRecExpr to produce this: 1890 /// 1891 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) 1892 /// 1893 /// This form often exposes folding opportunities that are hidden in 1894 /// the original operand list. 1895 /// 1896 /// Return true iff it appears that any interesting folding opportunities 1897 /// may be exposed. This helps getAddRecExpr short-circuit extra work in 1898 /// the common case where no interesting opportunities are present, and 1899 /// is also used as a check to avoid infinite recursion. 1900 /// 1901 static bool 1902 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, 1903 SmallVectorImpl<const SCEV *> &NewOps, 1904 APInt &AccumulatedConstant, 1905 const SCEV *const *Ops, size_t NumOperands, 1906 const APInt &Scale, 1907 ScalarEvolution &SE) { 1908 bool Interesting = false; 1909 1910 // Iterate over the add operands. They are sorted, with constants first. 1911 unsigned i = 0; 1912 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 1913 ++i; 1914 // Pull a buried constant out to the outside. 1915 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) 1916 Interesting = true; 1917 AccumulatedConstant += Scale * C->getAPInt(); 1918 } 1919 1920 // Next comes everything else. We're especially interested in multiplies 1921 // here, but they're in the middle, so just visit the rest with one loop. 1922 for (; i != NumOperands; ++i) { 1923 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); 1924 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { 1925 APInt NewScale = 1926 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); 1927 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { 1928 // A multiplication of a constant with another add; recurse. 1929 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); 1930 Interesting |= 1931 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 1932 Add->op_begin(), Add->getNumOperands(), 1933 NewScale, SE); 1934 } else { 1935 // A multiplication of a constant with some other value. Update 1936 // the map. 1937 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end()); 1938 const SCEV *Key = SE.getMulExpr(MulOps); 1939 auto Pair = M.insert({Key, NewScale}); 1940 if (Pair.second) { 1941 NewOps.push_back(Pair.first->first); 1942 } else { 1943 Pair.first->second += NewScale; 1944 // The map already had an entry for this value, which may indicate 1945 // a folding opportunity. 1946 Interesting = true; 1947 } 1948 } 1949 } else { 1950 // An ordinary operand. Update the map. 1951 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = 1952 M.insert({Ops[i], Scale}); 1953 if (Pair.second) { 1954 NewOps.push_back(Pair.first->first); 1955 } else { 1956 Pair.first->second += Scale; 1957 // The map already had an entry for this value, which may indicate 1958 // a folding opportunity. 1959 Interesting = true; 1960 } 1961 } 1962 } 1963 1964 return Interesting; 1965 } 1966 1967 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and 1968 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of 1969 // can't-overflow flags for the operation if possible. 1970 static SCEV::NoWrapFlags 1971 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, 1972 const SmallVectorImpl<const SCEV *> &Ops, 1973 SCEV::NoWrapFlags Flags) { 1974 using namespace std::placeholders; 1975 typedef OverflowingBinaryOperator OBO; 1976 1977 bool CanAnalyze = 1978 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; 1979 (void)CanAnalyze; 1980 assert(CanAnalyze && "don't call from other places!"); 1981 1982 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 1983 SCEV::NoWrapFlags SignOrUnsignWrap = 1984 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 1985 1986 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 1987 auto IsKnownNonNegative = [&](const SCEV *S) { 1988 return SE->isKnownNonNegative(S); 1989 }; 1990 1991 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) 1992 Flags = 1993 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); 1994 1995 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 1996 1997 if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr && 1998 Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) { 1999 2000 // (A + C) --> (A + C)<nsw> if the addition does not sign overflow 2001 // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow 2002 2003 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); 2004 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { 2005 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2006 Instruction::Add, C, OBO::NoSignedWrap); 2007 if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) 2008 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2009 } 2010 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { 2011 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2012 Instruction::Add, C, OBO::NoUnsignedWrap); 2013 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) 2014 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2015 } 2016 } 2017 2018 return Flags; 2019 } 2020 2021 /// Get a canonical add expression, or something simpler if possible. 2022 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2023 SCEV::NoWrapFlags Flags) { 2024 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && 2025 "only nuw or nsw allowed"); 2026 assert(!Ops.empty() && "Cannot get empty add!"); 2027 if (Ops.size() == 1) return Ops[0]; 2028 #ifndef NDEBUG 2029 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2030 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2031 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2032 "SCEVAddExpr operand types don't match!"); 2033 #endif 2034 2035 // Sort by complexity, this groups all similar expression types together. 2036 GroupByComplexity(Ops, &LI); 2037 2038 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags); 2039 2040 // If there are any constants, fold them together. 2041 unsigned Idx = 0; 2042 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2043 ++Idx; 2044 assert(Idx < Ops.size()); 2045 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2046 // We found two constants, fold them together! 2047 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); 2048 if (Ops.size() == 2) return Ops[0]; 2049 Ops.erase(Ops.begin()+1); // Erase the folded element 2050 LHSC = cast<SCEVConstant>(Ops[0]); 2051 } 2052 2053 // If we are left with a constant zero being added, strip it off. 2054 if (LHSC->getValue()->isZero()) { 2055 Ops.erase(Ops.begin()); 2056 --Idx; 2057 } 2058 2059 if (Ops.size() == 1) return Ops[0]; 2060 } 2061 2062 // Okay, check to see if the same value occurs in the operand list more than 2063 // once. If so, merge them together into an multiply expression. Since we 2064 // sorted the list, these values are required to be adjacent. 2065 Type *Ty = Ops[0]->getType(); 2066 bool FoundMatch = false; 2067 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 2068 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 2069 // Scan ahead to count how many equal operands there are. 2070 unsigned Count = 2; 2071 while (i+Count != e && Ops[i+Count] == Ops[i]) 2072 ++Count; 2073 // Merge the values into a multiply. 2074 const SCEV *Scale = getConstant(Ty, Count); 2075 const SCEV *Mul = getMulExpr(Scale, Ops[i]); 2076 if (Ops.size() == Count) 2077 return Mul; 2078 Ops[i] = Mul; 2079 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 2080 --i; e -= Count - 1; 2081 FoundMatch = true; 2082 } 2083 if (FoundMatch) 2084 return getAddExpr(Ops, Flags); 2085 2086 // Check for truncates. If all the operands are truncated from the same 2087 // type, see if factoring out the truncate would permit the result to be 2088 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n) 2089 // if the contents of the resulting outer trunc fold to something simple. 2090 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) { 2091 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]); 2092 Type *DstType = Trunc->getType(); 2093 Type *SrcType = Trunc->getOperand()->getType(); 2094 SmallVector<const SCEV *, 8> LargeOps; 2095 bool Ok = true; 2096 // Check all the operands to see if they can be represented in the 2097 // source type of the truncate. 2098 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 2099 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 2100 if (T->getOperand()->getType() != SrcType) { 2101 Ok = false; 2102 break; 2103 } 2104 LargeOps.push_back(T->getOperand()); 2105 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2106 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 2107 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 2108 SmallVector<const SCEV *, 8> LargeMulOps; 2109 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 2110 if (const SCEVTruncateExpr *T = 2111 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 2112 if (T->getOperand()->getType() != SrcType) { 2113 Ok = false; 2114 break; 2115 } 2116 LargeMulOps.push_back(T->getOperand()); 2117 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { 2118 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 2119 } else { 2120 Ok = false; 2121 break; 2122 } 2123 } 2124 if (Ok) 2125 LargeOps.push_back(getMulExpr(LargeMulOps)); 2126 } else { 2127 Ok = false; 2128 break; 2129 } 2130 } 2131 if (Ok) { 2132 // Evaluate the expression in the larger type. 2133 const SCEV *Fold = getAddExpr(LargeOps, Flags); 2134 // If it folds to something simple, use it. Otherwise, don't. 2135 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 2136 return getTruncateExpr(Fold, DstType); 2137 } 2138 } 2139 2140 // Skip past any other cast SCEVs. 2141 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 2142 ++Idx; 2143 2144 // If there are add operands they would be next. 2145 if (Idx < Ops.size()) { 2146 bool DeletedAdd = false; 2147 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2148 // If we have an add, expand the add operands onto the end of the operands 2149 // list. 2150 Ops.erase(Ops.begin()+Idx); 2151 Ops.append(Add->op_begin(), Add->op_end()); 2152 DeletedAdd = true; 2153 } 2154 2155 // If we deleted at least one add, we added operands to the end of the list, 2156 // and they are not necessarily sorted. Recurse to resort and resimplify 2157 // any operands we just acquired. 2158 if (DeletedAdd) 2159 return getAddExpr(Ops); 2160 } 2161 2162 // Skip over the add expression until we get to a multiply. 2163 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2164 ++Idx; 2165 2166 // Check to see if there are any folding opportunities present with 2167 // operands multiplied by constant values. 2168 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2169 uint64_t BitWidth = getTypeSizeInBits(Ty); 2170 DenseMap<const SCEV *, APInt> M; 2171 SmallVector<const SCEV *, 8> NewOps; 2172 APInt AccumulatedConstant(BitWidth, 0); 2173 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2174 Ops.data(), Ops.size(), 2175 APInt(BitWidth, 1), *this)) { 2176 struct APIntCompare { 2177 bool operator()(const APInt &LHS, const APInt &RHS) const { 2178 return LHS.ult(RHS); 2179 } 2180 }; 2181 2182 // Some interesting folding opportunity is present, so its worthwhile to 2183 // re-generate the operands list. Group the operands by constant scale, 2184 // to avoid multiplying by the same constant scale multiple times. 2185 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2186 for (const SCEV *NewOp : NewOps) 2187 MulOpLists[M.find(NewOp)->second].push_back(NewOp); 2188 // Re-generate the operands list. 2189 Ops.clear(); 2190 if (AccumulatedConstant != 0) 2191 Ops.push_back(getConstant(AccumulatedConstant)); 2192 for (auto &MulOp : MulOpLists) 2193 if (MulOp.first != 0) 2194 Ops.push_back(getMulExpr(getConstant(MulOp.first), 2195 getAddExpr(MulOp.second))); 2196 if (Ops.empty()) 2197 return getZero(Ty); 2198 if (Ops.size() == 1) 2199 return Ops[0]; 2200 return getAddExpr(Ops); 2201 } 2202 } 2203 2204 // If we are adding something to a multiply expression, make sure the 2205 // something is not already an operand of the multiply. If so, merge it into 2206 // the multiply. 2207 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2208 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2209 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2210 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2211 if (isa<SCEVConstant>(MulOpSCEV)) 2212 continue; 2213 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2214 if (MulOpSCEV == Ops[AddOp]) { 2215 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2216 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2217 if (Mul->getNumOperands() != 2) { 2218 // If the multiply has more than two operands, we must get the 2219 // Y*Z term. 2220 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2221 Mul->op_begin()+MulOp); 2222 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2223 InnerMul = getMulExpr(MulOps); 2224 } 2225 const SCEV *One = getOne(Ty); 2226 const SCEV *AddOne = getAddExpr(One, InnerMul); 2227 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV); 2228 if (Ops.size() == 2) return OuterMul; 2229 if (AddOp < Idx) { 2230 Ops.erase(Ops.begin()+AddOp); 2231 Ops.erase(Ops.begin()+Idx-1); 2232 } else { 2233 Ops.erase(Ops.begin()+Idx); 2234 Ops.erase(Ops.begin()+AddOp-1); 2235 } 2236 Ops.push_back(OuterMul); 2237 return getAddExpr(Ops); 2238 } 2239 2240 // Check this multiply against other multiplies being added together. 2241 for (unsigned OtherMulIdx = Idx+1; 2242 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2243 ++OtherMulIdx) { 2244 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2245 // If MulOp occurs in OtherMul, we can fold the two multiplies 2246 // together. 2247 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2248 OMulOp != e; ++OMulOp) 2249 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2250 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2251 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2252 if (Mul->getNumOperands() != 2) { 2253 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2254 Mul->op_begin()+MulOp); 2255 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2256 InnerMul1 = getMulExpr(MulOps); 2257 } 2258 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2259 if (OtherMul->getNumOperands() != 2) { 2260 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2261 OtherMul->op_begin()+OMulOp); 2262 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2263 InnerMul2 = getMulExpr(MulOps); 2264 } 2265 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2); 2266 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum); 2267 if (Ops.size() == 2) return OuterMul; 2268 Ops.erase(Ops.begin()+Idx); 2269 Ops.erase(Ops.begin()+OtherMulIdx-1); 2270 Ops.push_back(OuterMul); 2271 return getAddExpr(Ops); 2272 } 2273 } 2274 } 2275 } 2276 2277 // If there are any add recurrences in the operands list, see if any other 2278 // added values are loop invariant. If so, we can fold them into the 2279 // recurrence. 2280 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2281 ++Idx; 2282 2283 // Scan over all recurrences, trying to fold loop invariants into them. 2284 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2285 // Scan all of the other operands to this add and add them to the vector if 2286 // they are loop invariant w.r.t. the recurrence. 2287 SmallVector<const SCEV *, 8> LIOps; 2288 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2289 const Loop *AddRecLoop = AddRec->getLoop(); 2290 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2291 if (isLoopInvariant(Ops[i], AddRecLoop)) { 2292 LIOps.push_back(Ops[i]); 2293 Ops.erase(Ops.begin()+i); 2294 --i; --e; 2295 } 2296 2297 // If we found some loop invariants, fold them into the recurrence. 2298 if (!LIOps.empty()) { 2299 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2300 LIOps.push_back(AddRec->getStart()); 2301 2302 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2303 AddRec->op_end()); 2304 // This follows from the fact that the no-wrap flags on the outer add 2305 // expression are applicable on the 0th iteration, when the add recurrence 2306 // will be equal to its start value. 2307 AddRecOps[0] = getAddExpr(LIOps, Flags); 2308 2309 // Build the new addrec. Propagate the NUW and NSW flags if both the 2310 // outer add and the inner addrec are guaranteed to have no overflow. 2311 // Always propagate NW. 2312 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2313 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2314 2315 // If all of the other operands were loop invariant, we are done. 2316 if (Ops.size() == 1) return NewRec; 2317 2318 // Otherwise, add the folded AddRec by the non-invariant parts. 2319 for (unsigned i = 0;; ++i) 2320 if (Ops[i] == AddRec) { 2321 Ops[i] = NewRec; 2322 break; 2323 } 2324 return getAddExpr(Ops); 2325 } 2326 2327 // Okay, if there weren't any loop invariants to be folded, check to see if 2328 // there are multiple AddRec's with the same loop induction variable being 2329 // added together. If so, we can fold them. 2330 for (unsigned OtherIdx = Idx+1; 2331 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2332 ++OtherIdx) 2333 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2334 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2335 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2336 AddRec->op_end()); 2337 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2338 ++OtherIdx) 2339 if (const auto *OtherAddRec = dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx])) 2340 if (OtherAddRec->getLoop() == AddRecLoop) { 2341 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2342 i != e; ++i) { 2343 if (i >= AddRecOps.size()) { 2344 AddRecOps.append(OtherAddRec->op_begin()+i, 2345 OtherAddRec->op_end()); 2346 break; 2347 } 2348 AddRecOps[i] = getAddExpr(AddRecOps[i], 2349 OtherAddRec->getOperand(i)); 2350 } 2351 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2352 } 2353 // Step size has changed, so we cannot guarantee no self-wraparound. 2354 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2355 return getAddExpr(Ops); 2356 } 2357 2358 // Otherwise couldn't fold anything into this recurrence. Move onto the 2359 // next one. 2360 } 2361 2362 // Okay, it looks like we really DO need an add expr. Check to see if we 2363 // already have one, otherwise create a new one. 2364 FoldingSetNodeID ID; 2365 ID.AddInteger(scAddExpr); 2366 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2367 ID.AddPointer(Ops[i]); 2368 void *IP = nullptr; 2369 SCEVAddExpr *S = 2370 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2371 if (!S) { 2372 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2373 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2374 S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator), 2375 O, Ops.size()); 2376 UniqueSCEVs.InsertNode(S, IP); 2377 } 2378 S->setNoWrapFlags(Flags); 2379 return S; 2380 } 2381 2382 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2383 uint64_t k = i*j; 2384 if (j > 1 && k / j != i) Overflow = true; 2385 return k; 2386 } 2387 2388 /// Compute the result of "n choose k", the binomial coefficient. If an 2389 /// intermediate computation overflows, Overflow will be set and the return will 2390 /// be garbage. Overflow is not cleared on absence of overflow. 2391 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 2392 // We use the multiplicative formula: 2393 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 2394 // At each iteration, we take the n-th term of the numeral and divide by the 2395 // (k-n)th term of the denominator. This division will always produce an 2396 // integral result, and helps reduce the chance of overflow in the 2397 // intermediate computations. However, we can still overflow even when the 2398 // final result would fit. 2399 2400 if (n == 0 || n == k) return 1; 2401 if (k > n) return 0; 2402 2403 if (k > n/2) 2404 k = n-k; 2405 2406 uint64_t r = 1; 2407 for (uint64_t i = 1; i <= k; ++i) { 2408 r = umul_ov(r, n-(i-1), Overflow); 2409 r /= i; 2410 } 2411 return r; 2412 } 2413 2414 /// Determine if any of the operands in this SCEV are a constant or if 2415 /// any of the add or multiply expressions in this SCEV contain a constant. 2416 static bool containsConstantSomewhere(const SCEV *StartExpr) { 2417 SmallVector<const SCEV *, 4> Ops; 2418 Ops.push_back(StartExpr); 2419 while (!Ops.empty()) { 2420 const SCEV *CurrentExpr = Ops.pop_back_val(); 2421 if (isa<SCEVConstant>(*CurrentExpr)) 2422 return true; 2423 2424 if (isa<SCEVAddExpr>(*CurrentExpr) || isa<SCEVMulExpr>(*CurrentExpr)) { 2425 const auto *CurrentNAry = cast<SCEVNAryExpr>(CurrentExpr); 2426 Ops.append(CurrentNAry->op_begin(), CurrentNAry->op_end()); 2427 } 2428 } 2429 return false; 2430 } 2431 2432 /// Get a canonical multiply expression, or something simpler if possible. 2433 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2434 SCEV::NoWrapFlags Flags) { 2435 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && 2436 "only nuw or nsw allowed"); 2437 assert(!Ops.empty() && "Cannot get empty mul!"); 2438 if (Ops.size() == 1) return Ops[0]; 2439 #ifndef NDEBUG 2440 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2441 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2442 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2443 "SCEVMulExpr operand types don't match!"); 2444 #endif 2445 2446 // Sort by complexity, this groups all similar expression types together. 2447 GroupByComplexity(Ops, &LI); 2448 2449 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags); 2450 2451 // If there are any constants, fold them together. 2452 unsigned Idx = 0; 2453 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2454 2455 // C1*(C2+V) -> C1*C2 + C1*V 2456 if (Ops.size() == 2) 2457 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 2458 // If any of Add's ops are Adds or Muls with a constant, 2459 // apply this transformation as well. 2460 if (Add->getNumOperands() == 2) 2461 if (containsConstantSomewhere(Add)) 2462 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)), 2463 getMulExpr(LHSC, Add->getOperand(1))); 2464 2465 ++Idx; 2466 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2467 // We found two constants, fold them together! 2468 ConstantInt *Fold = 2469 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt()); 2470 Ops[0] = getConstant(Fold); 2471 Ops.erase(Ops.begin()+1); // Erase the folded element 2472 if (Ops.size() == 1) return Ops[0]; 2473 LHSC = cast<SCEVConstant>(Ops[0]); 2474 } 2475 2476 // If we are left with a constant one being multiplied, strip it off. 2477 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) { 2478 Ops.erase(Ops.begin()); 2479 --Idx; 2480 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) { 2481 // If we have a multiply of zero, it will always be zero. 2482 return Ops[0]; 2483 } else if (Ops[0]->isAllOnesValue()) { 2484 // If we have a mul by -1 of an add, try distributing the -1 among the 2485 // add operands. 2486 if (Ops.size() == 2) { 2487 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 2488 SmallVector<const SCEV *, 4> NewOps; 2489 bool AnyFolded = false; 2490 for (const SCEV *AddOp : Add->operands()) { 2491 const SCEV *Mul = getMulExpr(Ops[0], AddOp); 2492 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 2493 NewOps.push_back(Mul); 2494 } 2495 if (AnyFolded) 2496 return getAddExpr(NewOps); 2497 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 2498 // Negation preserves a recurrence's no self-wrap property. 2499 SmallVector<const SCEV *, 4> Operands; 2500 for (const SCEV *AddRecOp : AddRec->operands()) 2501 Operands.push_back(getMulExpr(Ops[0], AddRecOp)); 2502 2503 return getAddRecExpr(Operands, AddRec->getLoop(), 2504 AddRec->getNoWrapFlags(SCEV::FlagNW)); 2505 } 2506 } 2507 } 2508 2509 if (Ops.size() == 1) 2510 return Ops[0]; 2511 } 2512 2513 // Skip over the add expression until we get to a multiply. 2514 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2515 ++Idx; 2516 2517 // If there are mul operands inline them all into this expression. 2518 if (Idx < Ops.size()) { 2519 bool DeletedMul = false; 2520 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2521 // If we have an mul, expand the mul operands onto the end of the operands 2522 // list. 2523 Ops.erase(Ops.begin()+Idx); 2524 Ops.append(Mul->op_begin(), Mul->op_end()); 2525 DeletedMul = true; 2526 } 2527 2528 // If we deleted at least one mul, we added operands to the end of the list, 2529 // and they are not necessarily sorted. Recurse to resort and resimplify 2530 // any operands we just acquired. 2531 if (DeletedMul) 2532 return getMulExpr(Ops); 2533 } 2534 2535 // If there are any add recurrences in the operands list, see if any other 2536 // added values are loop invariant. If so, we can fold them into the 2537 // recurrence. 2538 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2539 ++Idx; 2540 2541 // Scan over all recurrences, trying to fold loop invariants into them. 2542 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2543 // Scan all of the other operands to this mul and add them to the vector if 2544 // they are loop invariant w.r.t. the recurrence. 2545 SmallVector<const SCEV *, 8> LIOps; 2546 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2547 const Loop *AddRecLoop = AddRec->getLoop(); 2548 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2549 if (isLoopInvariant(Ops[i], AddRecLoop)) { 2550 LIOps.push_back(Ops[i]); 2551 Ops.erase(Ops.begin()+i); 2552 --i; --e; 2553 } 2554 2555 // If we found some loop invariants, fold them into the recurrence. 2556 if (!LIOps.empty()) { 2557 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 2558 SmallVector<const SCEV *, 4> NewOps; 2559 NewOps.reserve(AddRec->getNumOperands()); 2560 const SCEV *Scale = getMulExpr(LIOps); 2561 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 2562 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i))); 2563 2564 // Build the new addrec. Propagate the NUW and NSW flags if both the 2565 // outer mul and the inner addrec are guaranteed to have no overflow. 2566 // 2567 // No self-wrap cannot be guaranteed after changing the step size, but 2568 // will be inferred if either NUW or NSW is true. 2569 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW)); 2570 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags); 2571 2572 // If all of the other operands were loop invariant, we are done. 2573 if (Ops.size() == 1) return NewRec; 2574 2575 // Otherwise, multiply the folded AddRec by the non-invariant parts. 2576 for (unsigned i = 0;; ++i) 2577 if (Ops[i] == AddRec) { 2578 Ops[i] = NewRec; 2579 break; 2580 } 2581 return getMulExpr(Ops); 2582 } 2583 2584 // Okay, if there weren't any loop invariants to be folded, check to see if 2585 // there are multiple AddRec's with the same loop induction variable being 2586 // multiplied together. If so, we can fold them. 2587 2588 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 2589 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 2590 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 2591 // ]]],+,...up to x=2n}. 2592 // Note that the arguments to choose() are always integers with values 2593 // known at compile time, never SCEV objects. 2594 // 2595 // The implementation avoids pointless extra computations when the two 2596 // addrec's are of different length (mathematically, it's equivalent to 2597 // an infinite stream of zeros on the right). 2598 bool OpsModified = false; 2599 for (unsigned OtherIdx = Idx+1; 2600 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2601 ++OtherIdx) { 2602 const SCEVAddRecExpr *OtherAddRec = 2603 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2604 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 2605 continue; 2606 2607 bool Overflow = false; 2608 Type *Ty = AddRec->getType(); 2609 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 2610 SmallVector<const SCEV*, 7> AddRecOps; 2611 for (int x = 0, xe = AddRec->getNumOperands() + 2612 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 2613 const SCEV *Term = getZero(Ty); 2614 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 2615 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 2616 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 2617 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 2618 z < ze && !Overflow; ++z) { 2619 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 2620 uint64_t Coeff; 2621 if (LargerThan64Bits) 2622 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 2623 else 2624 Coeff = Coeff1*Coeff2; 2625 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 2626 const SCEV *Term1 = AddRec->getOperand(y-z); 2627 const SCEV *Term2 = OtherAddRec->getOperand(z); 2628 Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1,Term2)); 2629 } 2630 } 2631 AddRecOps.push_back(Term); 2632 } 2633 if (!Overflow) { 2634 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(), 2635 SCEV::FlagAnyWrap); 2636 if (Ops.size() == 2) return NewAddRec; 2637 Ops[Idx] = NewAddRec; 2638 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2639 OpsModified = true; 2640 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 2641 if (!AddRec) 2642 break; 2643 } 2644 } 2645 if (OpsModified) 2646 return getMulExpr(Ops); 2647 2648 // Otherwise couldn't fold anything into this recurrence. Move onto the 2649 // next one. 2650 } 2651 2652 // Okay, it looks like we really DO need an mul expr. Check to see if we 2653 // already have one, otherwise create a new one. 2654 FoldingSetNodeID ID; 2655 ID.AddInteger(scMulExpr); 2656 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2657 ID.AddPointer(Ops[i]); 2658 void *IP = nullptr; 2659 SCEVMulExpr *S = 2660 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2661 if (!S) { 2662 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2663 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2664 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2665 O, Ops.size()); 2666 UniqueSCEVs.InsertNode(S, IP); 2667 } 2668 S->setNoWrapFlags(Flags); 2669 return S; 2670 } 2671 2672 /// Get a canonical unsigned division expression, or something simpler if 2673 /// possible. 2674 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 2675 const SCEV *RHS) { 2676 assert(getEffectiveSCEVType(LHS->getType()) == 2677 getEffectiveSCEVType(RHS->getType()) && 2678 "SCEVUDivExpr operand types don't match!"); 2679 2680 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 2681 if (RHSC->getValue()->equalsInt(1)) 2682 return LHS; // X udiv 1 --> x 2683 // If the denominator is zero, the result of the udiv is undefined. Don't 2684 // try to analyze it, because the resolution chosen here may differ from 2685 // the resolution chosen in other parts of the compiler. 2686 if (!RHSC->getValue()->isZero()) { 2687 // Determine if the division can be folded into the operands of 2688 // its operands. 2689 // TODO: Generalize this to non-constants by using known-bits information. 2690 Type *Ty = LHS->getType(); 2691 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 2692 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 2693 // For non-power-of-two values, effectively round the value up to the 2694 // nearest power of two. 2695 if (!RHSC->getAPInt().isPowerOf2()) 2696 ++MaxShiftAmt; 2697 IntegerType *ExtTy = 2698 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 2699 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 2700 if (const SCEVConstant *Step = 2701 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 2702 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 2703 const APInt &StepInt = Step->getAPInt(); 2704 const APInt &DivInt = RHSC->getAPInt(); 2705 if (!StepInt.urem(DivInt) && 2706 getZeroExtendExpr(AR, ExtTy) == 2707 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 2708 getZeroExtendExpr(Step, ExtTy), 2709 AR->getLoop(), SCEV::FlagAnyWrap)) { 2710 SmallVector<const SCEV *, 4> Operands; 2711 for (const SCEV *Op : AR->operands()) 2712 Operands.push_back(getUDivExpr(Op, RHS)); 2713 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 2714 } 2715 /// Get a canonical UDivExpr for a recurrence. 2716 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 2717 // We can currently only fold X%N if X is constant. 2718 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 2719 if (StartC && !DivInt.urem(StepInt) && 2720 getZeroExtendExpr(AR, ExtTy) == 2721 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 2722 getZeroExtendExpr(Step, ExtTy), 2723 AR->getLoop(), SCEV::FlagAnyWrap)) { 2724 const APInt &StartInt = StartC->getAPInt(); 2725 const APInt &StartRem = StartInt.urem(StepInt); 2726 if (StartRem != 0) 2727 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step, 2728 AR->getLoop(), SCEV::FlagNW); 2729 } 2730 } 2731 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 2732 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 2733 SmallVector<const SCEV *, 4> Operands; 2734 for (const SCEV *Op : M->operands()) 2735 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 2736 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 2737 // Find an operand that's safely divisible. 2738 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 2739 const SCEV *Op = M->getOperand(i); 2740 const SCEV *Div = getUDivExpr(Op, RHSC); 2741 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 2742 Operands = SmallVector<const SCEV *, 4>(M->op_begin(), 2743 M->op_end()); 2744 Operands[i] = Div; 2745 return getMulExpr(Operands); 2746 } 2747 } 2748 } 2749 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 2750 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 2751 SmallVector<const SCEV *, 4> Operands; 2752 for (const SCEV *Op : A->operands()) 2753 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 2754 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 2755 Operands.clear(); 2756 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 2757 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 2758 if (isa<SCEVUDivExpr>(Op) || 2759 getMulExpr(Op, RHS) != A->getOperand(i)) 2760 break; 2761 Operands.push_back(Op); 2762 } 2763 if (Operands.size() == A->getNumOperands()) 2764 return getAddExpr(Operands); 2765 } 2766 } 2767 2768 // Fold if both operands are constant. 2769 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 2770 Constant *LHSCV = LHSC->getValue(); 2771 Constant *RHSCV = RHSC->getValue(); 2772 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 2773 RHSCV))); 2774 } 2775 } 2776 } 2777 2778 FoldingSetNodeID ID; 2779 ID.AddInteger(scUDivExpr); 2780 ID.AddPointer(LHS); 2781 ID.AddPointer(RHS); 2782 void *IP = nullptr; 2783 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 2784 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 2785 LHS, RHS); 2786 UniqueSCEVs.InsertNode(S, IP); 2787 return S; 2788 } 2789 2790 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 2791 APInt A = C1->getAPInt().abs(); 2792 APInt B = C2->getAPInt().abs(); 2793 uint32_t ABW = A.getBitWidth(); 2794 uint32_t BBW = B.getBitWidth(); 2795 2796 if (ABW > BBW) 2797 B = B.zext(ABW); 2798 else if (ABW < BBW) 2799 A = A.zext(BBW); 2800 2801 return APIntOps::GreatestCommonDivisor(A, B); 2802 } 2803 2804 /// Get a canonical unsigned division expression, or something simpler if 2805 /// possible. There is no representation for an exact udiv in SCEV IR, but we 2806 /// can attempt to remove factors from the LHS and RHS. We can't do this when 2807 /// it's not exact because the udiv may be clearing bits. 2808 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 2809 const SCEV *RHS) { 2810 // TODO: we could try to find factors in all sorts of things, but for now we 2811 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 2812 // end of this file for inspiration. 2813 2814 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 2815 if (!Mul) 2816 return getUDivExpr(LHS, RHS); 2817 2818 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 2819 // If the mulexpr multiplies by a constant, then that constant must be the 2820 // first element of the mulexpr. 2821 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 2822 if (LHSCst == RHSCst) { 2823 SmallVector<const SCEV *, 2> Operands; 2824 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 2825 return getMulExpr(Operands); 2826 } 2827 2828 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 2829 // that there's a factor provided by one of the other terms. We need to 2830 // check. 2831 APInt Factor = gcd(LHSCst, RHSCst); 2832 if (!Factor.isIntN(1)) { 2833 LHSCst = 2834 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 2835 RHSCst = 2836 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 2837 SmallVector<const SCEV *, 2> Operands; 2838 Operands.push_back(LHSCst); 2839 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 2840 LHS = getMulExpr(Operands); 2841 RHS = RHSCst; 2842 Mul = dyn_cast<SCEVMulExpr>(LHS); 2843 if (!Mul) 2844 return getUDivExactExpr(LHS, RHS); 2845 } 2846 } 2847 } 2848 2849 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 2850 if (Mul->getOperand(i) == RHS) { 2851 SmallVector<const SCEV *, 2> Operands; 2852 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 2853 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 2854 return getMulExpr(Operands); 2855 } 2856 } 2857 2858 return getUDivExpr(LHS, RHS); 2859 } 2860 2861 /// Get an add recurrence expression for the specified loop. Simplify the 2862 /// expression as much as possible. 2863 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 2864 const Loop *L, 2865 SCEV::NoWrapFlags Flags) { 2866 SmallVector<const SCEV *, 4> Operands; 2867 Operands.push_back(Start); 2868 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 2869 if (StepChrec->getLoop() == L) { 2870 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 2871 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 2872 } 2873 2874 Operands.push_back(Step); 2875 return getAddRecExpr(Operands, L, Flags); 2876 } 2877 2878 /// Get an add recurrence expression for the specified loop. Simplify the 2879 /// expression as much as possible. 2880 const SCEV * 2881 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 2882 const Loop *L, SCEV::NoWrapFlags Flags) { 2883 if (Operands.size() == 1) return Operands[0]; 2884 #ifndef NDEBUG 2885 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 2886 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 2887 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 2888 "SCEVAddRecExpr operand types don't match!"); 2889 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 2890 assert(isLoopInvariant(Operands[i], L) && 2891 "SCEVAddRecExpr operand is not loop-invariant!"); 2892 #endif 2893 2894 if (Operands.back()->isZero()) { 2895 Operands.pop_back(); 2896 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 2897 } 2898 2899 // It's tempting to want to call getMaxBackedgeTakenCount count here and 2900 // use that information to infer NUW and NSW flags. However, computing a 2901 // BE count requires calling getAddRecExpr, so we may not yet have a 2902 // meaningful BE count at this point (and if we don't, we'd be stuck 2903 // with a SCEVCouldNotCompute as the cached BE count). 2904 2905 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 2906 2907 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 2908 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 2909 const Loop *NestedLoop = NestedAR->getLoop(); 2910 if (L->contains(NestedLoop) 2911 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 2912 : (!NestedLoop->contains(L) && 2913 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 2914 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(), 2915 NestedAR->op_end()); 2916 Operands[0] = NestedAR->getStart(); 2917 // AddRecs require their operands be loop-invariant with respect to their 2918 // loops. Don't perform this transformation if it would break this 2919 // requirement. 2920 bool AllInvariant = all_of( 2921 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 2922 2923 if (AllInvariant) { 2924 // Create a recurrence for the outer loop with the same step size. 2925 // 2926 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 2927 // inner recurrence has the same property. 2928 SCEV::NoWrapFlags OuterFlags = 2929 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 2930 2931 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 2932 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 2933 return isLoopInvariant(Op, NestedLoop); 2934 }); 2935 2936 if (AllInvariant) { 2937 // Ok, both add recurrences are valid after the transformation. 2938 // 2939 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 2940 // the outer recurrence has the same property. 2941 SCEV::NoWrapFlags InnerFlags = 2942 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 2943 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 2944 } 2945 } 2946 // Reset Operands to its original state. 2947 Operands[0] = NestedAR; 2948 } 2949 } 2950 2951 // Okay, it looks like we really DO need an addrec expr. Check to see if we 2952 // already have one, otherwise create a new one. 2953 FoldingSetNodeID ID; 2954 ID.AddInteger(scAddRecExpr); 2955 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 2956 ID.AddPointer(Operands[i]); 2957 ID.AddPointer(L); 2958 void *IP = nullptr; 2959 SCEVAddRecExpr *S = 2960 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2961 if (!S) { 2962 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size()); 2963 std::uninitialized_copy(Operands.begin(), Operands.end(), O); 2964 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator), 2965 O, Operands.size(), L); 2966 UniqueSCEVs.InsertNode(S, IP); 2967 } 2968 S->setNoWrapFlags(Flags); 2969 return S; 2970 } 2971 2972 const SCEV * 2973 ScalarEvolution::getGEPExpr(Type *PointeeType, const SCEV *BaseExpr, 2974 const SmallVectorImpl<const SCEV *> &IndexExprs, 2975 bool InBounds) { 2976 // getSCEV(Base)->getType() has the same address space as Base->getType() 2977 // because SCEV::getType() preserves the address space. 2978 Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType()); 2979 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP 2980 // instruction to its SCEV, because the Instruction may be guarded by control 2981 // flow and the no-overflow bits may not be valid for the expression in any 2982 // context. This can be fixed similarly to how these flags are handled for 2983 // adds. 2984 SCEV::NoWrapFlags Wrap = InBounds ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 2985 2986 const SCEV *TotalOffset = getZero(IntPtrTy); 2987 // The address space is unimportant. The first thing we do on CurTy is getting 2988 // its element type. 2989 Type *CurTy = PointerType::getUnqual(PointeeType); 2990 for (const SCEV *IndexExpr : IndexExprs) { 2991 // Compute the (potentially symbolic) offset in bytes for this index. 2992 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 2993 // For a struct, add the member offset. 2994 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 2995 unsigned FieldNo = Index->getZExtValue(); 2996 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo); 2997 2998 // Add the field offset to the running total offset. 2999 TotalOffset = getAddExpr(TotalOffset, FieldOffset); 3000 3001 // Update CurTy to the type of the field at Index. 3002 CurTy = STy->getTypeAtIndex(Index); 3003 } else { 3004 // Update CurTy to its element type. 3005 CurTy = cast<SequentialType>(CurTy)->getElementType(); 3006 // For an array, add the element offset, explicitly scaled. 3007 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy); 3008 // Getelementptr indices are signed. 3009 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy); 3010 3011 // Multiply the index by the element size to compute the element offset. 3012 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap); 3013 3014 // Add the element offset to the running total offset. 3015 TotalOffset = getAddExpr(TotalOffset, LocalOffset); 3016 } 3017 } 3018 3019 // Add the total offset from all the GEP indices to the base. 3020 return getAddExpr(BaseExpr, TotalOffset, Wrap); 3021 } 3022 3023 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, 3024 const SCEV *RHS) { 3025 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3026 return getSMaxExpr(Ops); 3027 } 3028 3029 const SCEV * 3030 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3031 assert(!Ops.empty() && "Cannot get empty smax!"); 3032 if (Ops.size() == 1) return Ops[0]; 3033 #ifndef NDEBUG 3034 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3035 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3036 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3037 "SCEVSMaxExpr operand types don't match!"); 3038 #endif 3039 3040 // Sort by complexity, this groups all similar expression types together. 3041 GroupByComplexity(Ops, &LI); 3042 3043 // If there are any constants, fold them together. 3044 unsigned Idx = 0; 3045 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3046 ++Idx; 3047 assert(Idx < Ops.size()); 3048 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3049 // We found two constants, fold them together! 3050 ConstantInt *Fold = ConstantInt::get( 3051 getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt())); 3052 Ops[0] = getConstant(Fold); 3053 Ops.erase(Ops.begin()+1); // Erase the folded element 3054 if (Ops.size() == 1) return Ops[0]; 3055 LHSC = cast<SCEVConstant>(Ops[0]); 3056 } 3057 3058 // If we are left with a constant minimum-int, strip it off. 3059 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) { 3060 Ops.erase(Ops.begin()); 3061 --Idx; 3062 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) { 3063 // If we have an smax with a constant maximum-int, it will always be 3064 // maximum-int. 3065 return Ops[0]; 3066 } 3067 3068 if (Ops.size() == 1) return Ops[0]; 3069 } 3070 3071 // Find the first SMax 3072 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr) 3073 ++Idx; 3074 3075 // Check to see if one of the operands is an SMax. If so, expand its operands 3076 // onto our operand list, and recurse to simplify. 3077 if (Idx < Ops.size()) { 3078 bool DeletedSMax = false; 3079 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) { 3080 Ops.erase(Ops.begin()+Idx); 3081 Ops.append(SMax->op_begin(), SMax->op_end()); 3082 DeletedSMax = true; 3083 } 3084 3085 if (DeletedSMax) 3086 return getSMaxExpr(Ops); 3087 } 3088 3089 // Okay, check to see if the same value occurs in the operand list twice. If 3090 // so, delete one. Since we sorted the list, these values are required to 3091 // be adjacent. 3092 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 3093 // X smax Y smax Y --> X smax Y 3094 // X smax Y --> X, if X is always greater than Y 3095 if (Ops[i] == Ops[i+1] || 3096 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) { 3097 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); 3098 --i; --e; 3099 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) { 3100 Ops.erase(Ops.begin()+i, Ops.begin()+i+1); 3101 --i; --e; 3102 } 3103 3104 if (Ops.size() == 1) return Ops[0]; 3105 3106 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3107 3108 // Okay, it looks like we really DO need an smax expr. Check to see if we 3109 // already have one, otherwise create a new one. 3110 FoldingSetNodeID ID; 3111 ID.AddInteger(scSMaxExpr); 3112 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3113 ID.AddPointer(Ops[i]); 3114 void *IP = nullptr; 3115 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3116 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3117 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3118 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator), 3119 O, Ops.size()); 3120 UniqueSCEVs.InsertNode(S, IP); 3121 return S; 3122 } 3123 3124 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, 3125 const SCEV *RHS) { 3126 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3127 return getUMaxExpr(Ops); 3128 } 3129 3130 const SCEV * 3131 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3132 assert(!Ops.empty() && "Cannot get empty umax!"); 3133 if (Ops.size() == 1) return Ops[0]; 3134 #ifndef NDEBUG 3135 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3136 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3137 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3138 "SCEVUMaxExpr operand types don't match!"); 3139 #endif 3140 3141 // Sort by complexity, this groups all similar expression types together. 3142 GroupByComplexity(Ops, &LI); 3143 3144 // If there are any constants, fold them together. 3145 unsigned Idx = 0; 3146 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3147 ++Idx; 3148 assert(Idx < Ops.size()); 3149 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3150 // We found two constants, fold them together! 3151 ConstantInt *Fold = ConstantInt::get( 3152 getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt())); 3153 Ops[0] = getConstant(Fold); 3154 Ops.erase(Ops.begin()+1); // Erase the folded element 3155 if (Ops.size() == 1) return Ops[0]; 3156 LHSC = cast<SCEVConstant>(Ops[0]); 3157 } 3158 3159 // If we are left with a constant minimum-int, strip it off. 3160 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) { 3161 Ops.erase(Ops.begin()); 3162 --Idx; 3163 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) { 3164 // If we have an umax with a constant maximum-int, it will always be 3165 // maximum-int. 3166 return Ops[0]; 3167 } 3168 3169 if (Ops.size() == 1) return Ops[0]; 3170 } 3171 3172 // Find the first UMax 3173 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr) 3174 ++Idx; 3175 3176 // Check to see if one of the operands is a UMax. If so, expand its operands 3177 // onto our operand list, and recurse to simplify. 3178 if (Idx < Ops.size()) { 3179 bool DeletedUMax = false; 3180 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) { 3181 Ops.erase(Ops.begin()+Idx); 3182 Ops.append(UMax->op_begin(), UMax->op_end()); 3183 DeletedUMax = true; 3184 } 3185 3186 if (DeletedUMax) 3187 return getUMaxExpr(Ops); 3188 } 3189 3190 // Okay, check to see if the same value occurs in the operand list twice. If 3191 // so, delete one. Since we sorted the list, these values are required to 3192 // be adjacent. 3193 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 3194 // X umax Y umax Y --> X umax Y 3195 // X umax Y --> X, if X is always greater than Y 3196 if (Ops[i] == Ops[i+1] || 3197 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) { 3198 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); 3199 --i; --e; 3200 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) { 3201 Ops.erase(Ops.begin()+i, Ops.begin()+i+1); 3202 --i; --e; 3203 } 3204 3205 if (Ops.size() == 1) return Ops[0]; 3206 3207 assert(!Ops.empty() && "Reduced umax down to nothing!"); 3208 3209 // Okay, it looks like we really DO need a umax expr. Check to see if we 3210 // already have one, otherwise create a new one. 3211 FoldingSetNodeID ID; 3212 ID.AddInteger(scUMaxExpr); 3213 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3214 ID.AddPointer(Ops[i]); 3215 void *IP = nullptr; 3216 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3217 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3218 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3219 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator), 3220 O, Ops.size()); 3221 UniqueSCEVs.InsertNode(S, IP); 3222 return S; 3223 } 3224 3225 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 3226 const SCEV *RHS) { 3227 // ~smax(~x, ~y) == smin(x, y). 3228 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS))); 3229 } 3230 3231 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, 3232 const SCEV *RHS) { 3233 // ~umax(~x, ~y) == umin(x, y) 3234 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS))); 3235 } 3236 3237 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 3238 // We can bypass creating a target-independent 3239 // constant expression and then folding it back into a ConstantInt. 3240 // This is just a compile-time optimization. 3241 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 3242 } 3243 3244 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 3245 StructType *STy, 3246 unsigned FieldNo) { 3247 // We can bypass creating a target-independent 3248 // constant expression and then folding it back into a ConstantInt. 3249 // This is just a compile-time optimization. 3250 return getConstant( 3251 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 3252 } 3253 3254 const SCEV *ScalarEvolution::getUnknown(Value *V) { 3255 // Don't attempt to do anything other than create a SCEVUnknown object 3256 // here. createSCEV only calls getUnknown after checking for all other 3257 // interesting possibilities, and any other code that calls getUnknown 3258 // is doing so in order to hide a value from SCEV canonicalization. 3259 3260 FoldingSetNodeID ID; 3261 ID.AddInteger(scUnknown); 3262 ID.AddPointer(V); 3263 void *IP = nullptr; 3264 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 3265 assert(cast<SCEVUnknown>(S)->getValue() == V && 3266 "Stale SCEVUnknown in uniquing map!"); 3267 return S; 3268 } 3269 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 3270 FirstUnknown); 3271 FirstUnknown = cast<SCEVUnknown>(S); 3272 UniqueSCEVs.InsertNode(S, IP); 3273 return S; 3274 } 3275 3276 //===----------------------------------------------------------------------===// 3277 // Basic SCEV Analysis and PHI Idiom Recognition Code 3278 // 3279 3280 /// Test if values of the given type are analyzable within the SCEV 3281 /// framework. This primarily includes integer types, and it can optionally 3282 /// include pointer types if the ScalarEvolution class has access to 3283 /// target-specific information. 3284 bool ScalarEvolution::isSCEVable(Type *Ty) const { 3285 // Integers and pointers are always SCEVable. 3286 return Ty->isIntegerTy() || Ty->isPointerTy(); 3287 } 3288 3289 /// Return the size in bits of the specified type, for which isSCEVable must 3290 /// return true. 3291 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 3292 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3293 return getDataLayout().getTypeSizeInBits(Ty); 3294 } 3295 3296 /// Return a type with the same bitwidth as the given type and which represents 3297 /// how SCEV will treat the given type, for which isSCEVable must return 3298 /// true. For pointer types, this is the pointer-sized integer type. 3299 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 3300 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3301 3302 if (Ty->isIntegerTy()) 3303 return Ty; 3304 3305 // The only other support type is pointer. 3306 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 3307 return getDataLayout().getIntPtrType(Ty); 3308 } 3309 3310 const SCEV *ScalarEvolution::getCouldNotCompute() { 3311 return CouldNotCompute.get(); 3312 } 3313 3314 3315 bool ScalarEvolution::checkValidity(const SCEV *S) const { 3316 // Helper class working with SCEVTraversal to figure out if a SCEV contains 3317 // a SCEVUnknown with null value-pointer. FindInvalidSCEVUnknown::FindOne 3318 // is set iff if find such SCEVUnknown. 3319 // 3320 struct FindInvalidSCEVUnknown { 3321 bool FindOne; 3322 FindInvalidSCEVUnknown() { FindOne = false; } 3323 bool follow(const SCEV *S) { 3324 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 3325 case scConstant: 3326 return false; 3327 case scUnknown: 3328 if (!cast<SCEVUnknown>(S)->getValue()) 3329 FindOne = true; 3330 return false; 3331 default: 3332 return true; 3333 } 3334 } 3335 bool isDone() const { return FindOne; } 3336 }; 3337 3338 FindInvalidSCEVUnknown F; 3339 SCEVTraversal<FindInvalidSCEVUnknown> ST(F); 3340 ST.visitAll(S); 3341 3342 return !F.FindOne; 3343 } 3344 3345 namespace { 3346 // Helper class working with SCEVTraversal to figure out if a SCEV contains 3347 // a sub SCEV of scAddRecExpr type. FindInvalidSCEVUnknown::FoundOne is set 3348 // iff if such sub scAddRecExpr type SCEV is found. 3349 struct FindAddRecurrence { 3350 bool FoundOne; 3351 FindAddRecurrence() : FoundOne(false) {} 3352 3353 bool follow(const SCEV *S) { 3354 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 3355 case scAddRecExpr: 3356 FoundOne = true; 3357 case scConstant: 3358 case scUnknown: 3359 case scCouldNotCompute: 3360 return false; 3361 default: 3362 return true; 3363 } 3364 } 3365 bool isDone() const { return FoundOne; } 3366 }; 3367 } 3368 3369 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 3370 HasRecMapType::iterator I = HasRecMap.find_as(S); 3371 if (I != HasRecMap.end()) 3372 return I->second; 3373 3374 FindAddRecurrence F; 3375 SCEVTraversal<FindAddRecurrence> ST(F); 3376 ST.visitAll(S); 3377 HasRecMap.insert({S, F.FoundOne}); 3378 return F.FoundOne; 3379 } 3380 3381 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. 3382 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an 3383 /// offset I, then return {S', I}, else return {\p S, nullptr}. 3384 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { 3385 const auto *Add = dyn_cast<SCEVAddExpr>(S); 3386 if (!Add) 3387 return {S, nullptr}; 3388 3389 if (Add->getNumOperands() != 2) 3390 return {S, nullptr}; 3391 3392 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); 3393 if (!ConstOp) 3394 return {S, nullptr}; 3395 3396 return {Add->getOperand(1), ConstOp->getValue()}; 3397 } 3398 3399 /// Return the ValueOffsetPair set for \p S. \p S can be represented 3400 /// by the value and offset from any ValueOffsetPair in the set. 3401 SetVector<ScalarEvolution::ValueOffsetPair> * 3402 ScalarEvolution::getSCEVValues(const SCEV *S) { 3403 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 3404 if (SI == ExprValueMap.end()) 3405 return nullptr; 3406 #ifndef NDEBUG 3407 if (VerifySCEVMap) { 3408 // Check there is no dangling Value in the set returned. 3409 for (const auto &VE : SI->second) 3410 assert(ValueExprMap.count(VE.first)); 3411 } 3412 #endif 3413 return &SI->second; 3414 } 3415 3416 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) 3417 /// cannot be used separately. eraseValueFromMap should be used to remove 3418 /// V from ValueExprMap and ExprValueMap at the same time. 3419 void ScalarEvolution::eraseValueFromMap(Value *V) { 3420 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3421 if (I != ValueExprMap.end()) { 3422 const SCEV *S = I->second; 3423 // Remove {V, 0} from the set of ExprValueMap[S] 3424 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S)) 3425 SV->remove({V, nullptr}); 3426 3427 // Remove {V, Offset} from the set of ExprValueMap[Stripped] 3428 const SCEV *Stripped; 3429 ConstantInt *Offset; 3430 std::tie(Stripped, Offset) = splitAddExpr(S); 3431 if (Offset != nullptr) { 3432 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped)) 3433 SV->remove({V, Offset}); 3434 } 3435 ValueExprMap.erase(V); 3436 } 3437 } 3438 3439 /// Return an existing SCEV if it exists, otherwise analyze the expression and 3440 /// create a new one. 3441 const SCEV *ScalarEvolution::getSCEV(Value *V) { 3442 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3443 3444 const SCEV *S = getExistingSCEV(V); 3445 if (S == nullptr) { 3446 S = createSCEV(V); 3447 // During PHI resolution, it is possible to create two SCEVs for the same 3448 // V, so it is needed to double check whether V->S is inserted into 3449 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 3450 std::pair<ValueExprMapType::iterator, bool> Pair = 3451 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 3452 if (Pair.second) { 3453 ExprValueMap[S].insert({V, nullptr}); 3454 3455 // If S == Stripped + Offset, add Stripped -> {V, Offset} into 3456 // ExprValueMap. 3457 const SCEV *Stripped = S; 3458 ConstantInt *Offset = nullptr; 3459 std::tie(Stripped, Offset) = splitAddExpr(S); 3460 // If stripped is SCEVUnknown, don't bother to save 3461 // Stripped -> {V, offset}. It doesn't simplify and sometimes even 3462 // increase the complexity of the expansion code. 3463 // If V is GetElementPtrInst, don't save Stripped -> {V, offset} 3464 // because it may generate add/sub instead of GEP in SCEV expansion. 3465 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && 3466 !isa<GetElementPtrInst>(V)) 3467 ExprValueMap[Stripped].insert({V, Offset}); 3468 } 3469 } 3470 return S; 3471 } 3472 3473 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 3474 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3475 3476 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3477 if (I != ValueExprMap.end()) { 3478 const SCEV *S = I->second; 3479 if (checkValidity(S)) 3480 return S; 3481 eraseValueFromMap(V); 3482 forgetMemoizedResults(S); 3483 } 3484 return nullptr; 3485 } 3486 3487 /// Return a SCEV corresponding to -V = -1*V 3488 /// 3489 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 3490 SCEV::NoWrapFlags Flags) { 3491 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3492 return getConstant( 3493 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 3494 3495 Type *Ty = V->getType(); 3496 Ty = getEffectiveSCEVType(Ty); 3497 return getMulExpr( 3498 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags); 3499 } 3500 3501 /// Return a SCEV corresponding to ~V = -1-V 3502 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 3503 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3504 return getConstant( 3505 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 3506 3507 Type *Ty = V->getType(); 3508 Ty = getEffectiveSCEVType(Ty); 3509 const SCEV *AllOnes = 3510 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))); 3511 return getMinusSCEV(AllOnes, V); 3512 } 3513 3514 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 3515 SCEV::NoWrapFlags Flags) { 3516 // Fast path: X - X --> 0. 3517 if (LHS == RHS) 3518 return getZero(LHS->getType()); 3519 3520 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 3521 // makes it so that we cannot make much use of NUW. 3522 auto AddFlags = SCEV::FlagAnyWrap; 3523 const bool RHSIsNotMinSigned = 3524 !getSignedRange(RHS).getSignedMin().isMinSignedValue(); 3525 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) { 3526 // Let M be the minimum representable signed value. Then (-1)*RHS 3527 // signed-wraps if and only if RHS is M. That can happen even for 3528 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 3529 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 3530 // (-1)*RHS, we need to prove that RHS != M. 3531 // 3532 // If LHS is non-negative and we know that LHS - RHS does not 3533 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 3534 // either by proving that RHS > M or that LHS >= 0. 3535 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 3536 AddFlags = SCEV::FlagNSW; 3537 } 3538 } 3539 3540 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 3541 // RHS is NSW and LHS >= 0. 3542 // 3543 // The difficulty here is that the NSW flag may have been proven 3544 // relative to a loop that is to be found in a recurrence in LHS and 3545 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 3546 // larger scope than intended. 3547 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3548 3549 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags); 3550 } 3551 3552 const SCEV * 3553 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) { 3554 Type *SrcTy = V->getType(); 3555 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3556 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3557 "Cannot truncate or zero extend with non-integer arguments!"); 3558 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3559 return V; // No conversion 3560 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 3561 return getTruncateExpr(V, Ty); 3562 return getZeroExtendExpr(V, Ty); 3563 } 3564 3565 const SCEV * 3566 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, 3567 Type *Ty) { 3568 Type *SrcTy = V->getType(); 3569 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3570 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3571 "Cannot truncate or zero extend with non-integer arguments!"); 3572 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3573 return V; // No conversion 3574 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 3575 return getTruncateExpr(V, Ty); 3576 return getSignExtendExpr(V, Ty); 3577 } 3578 3579 const SCEV * 3580 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 3581 Type *SrcTy = V->getType(); 3582 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3583 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3584 "Cannot noop or zero extend with non-integer arguments!"); 3585 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3586 "getNoopOrZeroExtend cannot truncate!"); 3587 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3588 return V; // No conversion 3589 return getZeroExtendExpr(V, Ty); 3590 } 3591 3592 const SCEV * 3593 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 3594 Type *SrcTy = V->getType(); 3595 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3596 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3597 "Cannot noop or sign extend with non-integer arguments!"); 3598 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3599 "getNoopOrSignExtend cannot truncate!"); 3600 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3601 return V; // No conversion 3602 return getSignExtendExpr(V, Ty); 3603 } 3604 3605 const SCEV * 3606 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 3607 Type *SrcTy = V->getType(); 3608 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3609 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3610 "Cannot noop or any extend with non-integer arguments!"); 3611 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3612 "getNoopOrAnyExtend cannot truncate!"); 3613 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3614 return V; // No conversion 3615 return getAnyExtendExpr(V, Ty); 3616 } 3617 3618 const SCEV * 3619 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 3620 Type *SrcTy = V->getType(); 3621 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3622 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3623 "Cannot truncate or noop with non-integer arguments!"); 3624 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 3625 "getTruncateOrNoop cannot extend!"); 3626 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3627 return V; // No conversion 3628 return getTruncateExpr(V, Ty); 3629 } 3630 3631 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 3632 const SCEV *RHS) { 3633 const SCEV *PromotedLHS = LHS; 3634 const SCEV *PromotedRHS = RHS; 3635 3636 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 3637 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 3638 else 3639 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 3640 3641 return getUMaxExpr(PromotedLHS, PromotedRHS); 3642 } 3643 3644 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 3645 const SCEV *RHS) { 3646 const SCEV *PromotedLHS = LHS; 3647 const SCEV *PromotedRHS = RHS; 3648 3649 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 3650 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 3651 else 3652 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 3653 3654 return getUMinExpr(PromotedLHS, PromotedRHS); 3655 } 3656 3657 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 3658 // A pointer operand may evaluate to a nonpointer expression, such as null. 3659 if (!V->getType()->isPointerTy()) 3660 return V; 3661 3662 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) { 3663 return getPointerBase(Cast->getOperand()); 3664 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) { 3665 const SCEV *PtrOp = nullptr; 3666 for (const SCEV *NAryOp : NAry->operands()) { 3667 if (NAryOp->getType()->isPointerTy()) { 3668 // Cannot find the base of an expression with multiple pointer operands. 3669 if (PtrOp) 3670 return V; 3671 PtrOp = NAryOp; 3672 } 3673 } 3674 if (!PtrOp) 3675 return V; 3676 return getPointerBase(PtrOp); 3677 } 3678 return V; 3679 } 3680 3681 /// Push users of the given Instruction onto the given Worklist. 3682 static void 3683 PushDefUseChildren(Instruction *I, 3684 SmallVectorImpl<Instruction *> &Worklist) { 3685 // Push the def-use children onto the Worklist stack. 3686 for (User *U : I->users()) 3687 Worklist.push_back(cast<Instruction>(U)); 3688 } 3689 3690 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { 3691 SmallVector<Instruction *, 16> Worklist; 3692 PushDefUseChildren(PN, Worklist); 3693 3694 SmallPtrSet<Instruction *, 8> Visited; 3695 Visited.insert(PN); 3696 while (!Worklist.empty()) { 3697 Instruction *I = Worklist.pop_back_val(); 3698 if (!Visited.insert(I).second) 3699 continue; 3700 3701 auto It = ValueExprMap.find_as(static_cast<Value *>(I)); 3702 if (It != ValueExprMap.end()) { 3703 const SCEV *Old = It->second; 3704 3705 // Short-circuit the def-use traversal if the symbolic name 3706 // ceases to appear in expressions. 3707 if (Old != SymName && !hasOperand(Old, SymName)) 3708 continue; 3709 3710 // SCEVUnknown for a PHI either means that it has an unrecognized 3711 // structure, it's a PHI that's in the progress of being computed 3712 // by createNodeForPHI, or it's a single-value PHI. In the first case, 3713 // additional loop trip count information isn't going to change anything. 3714 // In the second case, createNodeForPHI will perform the necessary 3715 // updates on its own when it gets to that point. In the third, we do 3716 // want to forget the SCEVUnknown. 3717 if (!isa<PHINode>(I) || 3718 !isa<SCEVUnknown>(Old) || 3719 (I != PN && Old == SymName)) { 3720 eraseValueFromMap(It->first); 3721 forgetMemoizedResults(Old); 3722 } 3723 } 3724 3725 PushDefUseChildren(I, Worklist); 3726 } 3727 } 3728 3729 namespace { 3730 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 3731 public: 3732 static const SCEV *rewrite(const SCEV *S, const Loop *L, 3733 ScalarEvolution &SE) { 3734 SCEVInitRewriter Rewriter(L, SE); 3735 const SCEV *Result = Rewriter.visit(S); 3736 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 3737 } 3738 3739 SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 3740 : SCEVRewriteVisitor(SE), L(L), Valid(true) {} 3741 3742 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 3743 if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant)) 3744 Valid = false; 3745 return Expr; 3746 } 3747 3748 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 3749 // Only allow AddRecExprs for this loop. 3750 if (Expr->getLoop() == L) 3751 return Expr->getStart(); 3752 Valid = false; 3753 return Expr; 3754 } 3755 3756 bool isValid() { return Valid; } 3757 3758 private: 3759 const Loop *L; 3760 bool Valid; 3761 }; 3762 3763 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 3764 public: 3765 static const SCEV *rewrite(const SCEV *S, const Loop *L, 3766 ScalarEvolution &SE) { 3767 SCEVShiftRewriter Rewriter(L, SE); 3768 const SCEV *Result = Rewriter.visit(S); 3769 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 3770 } 3771 3772 SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 3773 : SCEVRewriteVisitor(SE), L(L), Valid(true) {} 3774 3775 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 3776 // Only allow AddRecExprs for this loop. 3777 if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant)) 3778 Valid = false; 3779 return Expr; 3780 } 3781 3782 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 3783 if (Expr->getLoop() == L && Expr->isAffine()) 3784 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 3785 Valid = false; 3786 return Expr; 3787 } 3788 bool isValid() { return Valid; } 3789 3790 private: 3791 const Loop *L; 3792 bool Valid; 3793 }; 3794 } // end anonymous namespace 3795 3796 SCEV::NoWrapFlags 3797 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 3798 if (!AR->isAffine()) 3799 return SCEV::FlagAnyWrap; 3800 3801 typedef OverflowingBinaryOperator OBO; 3802 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 3803 3804 if (!AR->hasNoSignedWrap()) { 3805 ConstantRange AddRecRange = getSignedRange(AR); 3806 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 3807 3808 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 3809 Instruction::Add, IncRange, OBO::NoSignedWrap); 3810 if (NSWRegion.contains(AddRecRange)) 3811 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 3812 } 3813 3814 if (!AR->hasNoUnsignedWrap()) { 3815 ConstantRange AddRecRange = getUnsignedRange(AR); 3816 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 3817 3818 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 3819 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 3820 if (NUWRegion.contains(AddRecRange)) 3821 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 3822 } 3823 3824 return Result; 3825 } 3826 3827 namespace { 3828 /// Represents an abstract binary operation. This may exist as a 3829 /// normal instruction or constant expression, or may have been 3830 /// derived from an expression tree. 3831 struct BinaryOp { 3832 unsigned Opcode; 3833 Value *LHS; 3834 Value *RHS; 3835 bool IsNSW; 3836 bool IsNUW; 3837 3838 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 3839 /// constant expression. 3840 Operator *Op; 3841 3842 explicit BinaryOp(Operator *Op) 3843 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 3844 IsNSW(false), IsNUW(false), Op(Op) { 3845 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 3846 IsNSW = OBO->hasNoSignedWrap(); 3847 IsNUW = OBO->hasNoUnsignedWrap(); 3848 } 3849 } 3850 3851 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 3852 bool IsNUW = false) 3853 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW), 3854 Op(nullptr) {} 3855 }; 3856 } 3857 3858 3859 /// Try to map \p V into a BinaryOp, and return \c None on failure. 3860 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 3861 auto *Op = dyn_cast<Operator>(V); 3862 if (!Op) 3863 return None; 3864 3865 // Implementation detail: all the cleverness here should happen without 3866 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 3867 // SCEV expressions when possible, and we should not break that. 3868 3869 switch (Op->getOpcode()) { 3870 case Instruction::Add: 3871 case Instruction::Sub: 3872 case Instruction::Mul: 3873 case Instruction::UDiv: 3874 case Instruction::And: 3875 case Instruction::Or: 3876 case Instruction::AShr: 3877 case Instruction::Shl: 3878 return BinaryOp(Op); 3879 3880 case Instruction::Xor: 3881 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 3882 // If the RHS of the xor is a signbit, then this is just an add. 3883 // Instcombine turns add of signbit into xor as a strength reduction step. 3884 if (RHSC->getValue().isSignBit()) 3885 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 3886 return BinaryOp(Op); 3887 3888 case Instruction::LShr: 3889 // Turn logical shift right of a constant into a unsigned divide. 3890 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 3891 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 3892 3893 // If the shift count is not less than the bitwidth, the result of 3894 // the shift is undefined. Don't try to analyze it, because the 3895 // resolution chosen here may differ from the resolution chosen in 3896 // other parts of the compiler. 3897 if (SA->getValue().ult(BitWidth)) { 3898 Constant *X = 3899 ConstantInt::get(SA->getContext(), 3900 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 3901 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 3902 } 3903 } 3904 return BinaryOp(Op); 3905 3906 case Instruction::ExtractValue: { 3907 auto *EVI = cast<ExtractValueInst>(Op); 3908 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 3909 break; 3910 3911 auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand()); 3912 if (!CI) 3913 break; 3914 3915 if (auto *F = CI->getCalledFunction()) 3916 switch (F->getIntrinsicID()) { 3917 case Intrinsic::sadd_with_overflow: 3918 case Intrinsic::uadd_with_overflow: { 3919 if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT)) 3920 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 3921 CI->getArgOperand(1)); 3922 3923 // Now that we know that all uses of the arithmetic-result component of 3924 // CI are guarded by the overflow check, we can go ahead and pretend 3925 // that the arithmetic is non-overflowing. 3926 if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow) 3927 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 3928 CI->getArgOperand(1), /* IsNSW = */ true, 3929 /* IsNUW = */ false); 3930 else 3931 return BinaryOp(Instruction::Add, CI->getArgOperand(0), 3932 CI->getArgOperand(1), /* IsNSW = */ false, 3933 /* IsNUW*/ true); 3934 } 3935 3936 case Intrinsic::ssub_with_overflow: 3937 case Intrinsic::usub_with_overflow: 3938 return BinaryOp(Instruction::Sub, CI->getArgOperand(0), 3939 CI->getArgOperand(1)); 3940 3941 case Intrinsic::smul_with_overflow: 3942 case Intrinsic::umul_with_overflow: 3943 return BinaryOp(Instruction::Mul, CI->getArgOperand(0), 3944 CI->getArgOperand(1)); 3945 default: 3946 break; 3947 } 3948 } 3949 3950 default: 3951 break; 3952 } 3953 3954 return None; 3955 } 3956 3957 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 3958 const Loop *L = LI.getLoopFor(PN->getParent()); 3959 if (!L || L->getHeader() != PN->getParent()) 3960 return nullptr; 3961 3962 // The loop may have multiple entrances or multiple exits; we can analyze 3963 // this phi as an addrec if it has a unique entry value and a unique 3964 // backedge value. 3965 Value *BEValueV = nullptr, *StartValueV = nullptr; 3966 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 3967 Value *V = PN->getIncomingValue(i); 3968 if (L->contains(PN->getIncomingBlock(i))) { 3969 if (!BEValueV) { 3970 BEValueV = V; 3971 } else if (BEValueV != V) { 3972 BEValueV = nullptr; 3973 break; 3974 } 3975 } else if (!StartValueV) { 3976 StartValueV = V; 3977 } else if (StartValueV != V) { 3978 StartValueV = nullptr; 3979 break; 3980 } 3981 } 3982 if (BEValueV && StartValueV) { 3983 // While we are analyzing this PHI node, handle its value symbolically. 3984 const SCEV *SymbolicName = getUnknown(PN); 3985 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 3986 "PHI node already processed?"); 3987 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); 3988 3989 // Using this symbolic name for the PHI, analyze the value coming around 3990 // the back-edge. 3991 const SCEV *BEValue = getSCEV(BEValueV); 3992 3993 // NOTE: If BEValue is loop invariant, we know that the PHI node just 3994 // has a special value for the first iteration of the loop. 3995 3996 // If the value coming around the backedge is an add with the symbolic 3997 // value we just inserted, then we found a simple induction variable! 3998 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 3999 // If there is a single occurrence of the symbolic value, replace it 4000 // with a recurrence. 4001 unsigned FoundIndex = Add->getNumOperands(); 4002 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4003 if (Add->getOperand(i) == SymbolicName) 4004 if (FoundIndex == e) { 4005 FoundIndex = i; 4006 break; 4007 } 4008 4009 if (FoundIndex != Add->getNumOperands()) { 4010 // Create an add with everything but the specified operand. 4011 SmallVector<const SCEV *, 8> Ops; 4012 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4013 if (i != FoundIndex) 4014 Ops.push_back(Add->getOperand(i)); 4015 const SCEV *Accum = getAddExpr(Ops); 4016 4017 // This is not a valid addrec if the step amount is varying each 4018 // loop iteration, but is not itself an addrec in this loop. 4019 if (isLoopInvariant(Accum, L) || 4020 (isa<SCEVAddRecExpr>(Accum) && 4021 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 4022 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 4023 4024 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 4025 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 4026 if (BO->IsNUW) 4027 Flags = setFlags(Flags, SCEV::FlagNUW); 4028 if (BO->IsNSW) 4029 Flags = setFlags(Flags, SCEV::FlagNSW); 4030 } 4031 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 4032 // If the increment is an inbounds GEP, then we know the address 4033 // space cannot be wrapped around. We cannot make any guarantee 4034 // about signed or unsigned overflow because pointers are 4035 // unsigned but we may have a negative index from the base 4036 // pointer. We can guarantee that no unsigned wrap occurs if the 4037 // indices form a positive value. 4038 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 4039 Flags = setFlags(Flags, SCEV::FlagNW); 4040 4041 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 4042 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 4043 Flags = setFlags(Flags, SCEV::FlagNUW); 4044 } 4045 4046 // We cannot transfer nuw and nsw flags from subtraction 4047 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 4048 // for instance. 4049 } 4050 4051 const SCEV *StartVal = getSCEV(StartValueV); 4052 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 4053 4054 // Okay, for the entire analysis of this edge we assumed the PHI 4055 // to be symbolic. We now need to go back and purge all of the 4056 // entries for the scalars that use the symbolic expression. 4057 forgetSymbolicName(PN, SymbolicName); 4058 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 4059 4060 // We can add Flags to the post-inc expression only if we 4061 // know that it us *undefined behavior* for BEValueV to 4062 // overflow. 4063 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 4064 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 4065 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 4066 4067 return PHISCEV; 4068 } 4069 } 4070 } else { 4071 // Otherwise, this could be a loop like this: 4072 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 4073 // In this case, j = {1,+,1} and BEValue is j. 4074 // Because the other in-value of i (0) fits the evolution of BEValue 4075 // i really is an addrec evolution. 4076 // 4077 // We can generalize this saying that i is the shifted value of BEValue 4078 // by one iteration: 4079 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 4080 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 4081 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this); 4082 if (Shifted != getCouldNotCompute() && 4083 Start != getCouldNotCompute()) { 4084 const SCEV *StartVal = getSCEV(StartValueV); 4085 if (Start == StartVal) { 4086 // Okay, for the entire analysis of this edge we assumed the PHI 4087 // to be symbolic. We now need to go back and purge all of the 4088 // entries for the scalars that use the symbolic expression. 4089 forgetSymbolicName(PN, SymbolicName); 4090 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; 4091 return Shifted; 4092 } 4093 } 4094 } 4095 4096 // Remove the temporary PHI node SCEV that has been inserted while intending 4097 // to create an AddRecExpr for this PHI node. We can not keep this temporary 4098 // as it will prevent later (possibly simpler) SCEV expressions to be added 4099 // to the ValueExprMap. 4100 eraseValueFromMap(PN); 4101 } 4102 4103 return nullptr; 4104 } 4105 4106 // Checks if the SCEV S is available at BB. S is considered available at BB 4107 // if S can be materialized at BB without introducing a fault. 4108 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 4109 BasicBlock *BB) { 4110 struct CheckAvailable { 4111 bool TraversalDone = false; 4112 bool Available = true; 4113 4114 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 4115 BasicBlock *BB = nullptr; 4116 DominatorTree &DT; 4117 4118 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 4119 : L(L), BB(BB), DT(DT) {} 4120 4121 bool setUnavailable() { 4122 TraversalDone = true; 4123 Available = false; 4124 return false; 4125 } 4126 4127 bool follow(const SCEV *S) { 4128 switch (S->getSCEVType()) { 4129 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend: 4130 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr: 4131 // These expressions are available if their operand(s) is/are. 4132 return true; 4133 4134 case scAddRecExpr: { 4135 // We allow add recurrences that are on the loop BB is in, or some 4136 // outer loop. This guarantees availability because the value of the 4137 // add recurrence at BB is simply the "current" value of the induction 4138 // variable. We can relax this in the future; for instance an add 4139 // recurrence on a sibling dominating loop is also available at BB. 4140 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 4141 if (L && (ARLoop == L || ARLoop->contains(L))) 4142 return true; 4143 4144 return setUnavailable(); 4145 } 4146 4147 case scUnknown: { 4148 // For SCEVUnknown, we check for simple dominance. 4149 const auto *SU = cast<SCEVUnknown>(S); 4150 Value *V = SU->getValue(); 4151 4152 if (isa<Argument>(V)) 4153 return false; 4154 4155 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 4156 return false; 4157 4158 return setUnavailable(); 4159 } 4160 4161 case scUDivExpr: 4162 case scCouldNotCompute: 4163 // We do not try to smart about these at all. 4164 return setUnavailable(); 4165 } 4166 llvm_unreachable("switch should be fully covered!"); 4167 } 4168 4169 bool isDone() { return TraversalDone; } 4170 }; 4171 4172 CheckAvailable CA(L, BB, DT); 4173 SCEVTraversal<CheckAvailable> ST(CA); 4174 4175 ST.visitAll(S); 4176 return CA.Available; 4177 } 4178 4179 // Try to match a control flow sequence that branches out at BI and merges back 4180 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 4181 // match. 4182 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 4183 Value *&C, Value *&LHS, Value *&RHS) { 4184 C = BI->getCondition(); 4185 4186 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 4187 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 4188 4189 if (!LeftEdge.isSingleEdge()) 4190 return false; 4191 4192 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 4193 4194 Use &LeftUse = Merge->getOperandUse(0); 4195 Use &RightUse = Merge->getOperandUse(1); 4196 4197 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 4198 LHS = LeftUse; 4199 RHS = RightUse; 4200 return true; 4201 } 4202 4203 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 4204 LHS = RightUse; 4205 RHS = LeftUse; 4206 return true; 4207 } 4208 4209 return false; 4210 } 4211 4212 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 4213 auto IsReachable = 4214 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 4215 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 4216 const Loop *L = LI.getLoopFor(PN->getParent()); 4217 4218 // We don't want to break LCSSA, even in a SCEV expression tree. 4219 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 4220 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 4221 return nullptr; 4222 4223 // Try to match 4224 // 4225 // br %cond, label %left, label %right 4226 // left: 4227 // br label %merge 4228 // right: 4229 // br label %merge 4230 // merge: 4231 // V = phi [ %x, %left ], [ %y, %right ] 4232 // 4233 // as "select %cond, %x, %y" 4234 4235 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 4236 assert(IDom && "At least the entry block should dominate PN"); 4237 4238 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 4239 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 4240 4241 if (BI && BI->isConditional() && 4242 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 4243 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 4244 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 4245 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 4246 } 4247 4248 return nullptr; 4249 } 4250 4251 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 4252 if (const SCEV *S = createAddRecFromPHI(PN)) 4253 return S; 4254 4255 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 4256 return S; 4257 4258 // If the PHI has a single incoming value, follow that value, unless the 4259 // PHI's incoming blocks are in a different loop, in which case doing so 4260 // risks breaking LCSSA form. Instcombine would normally zap these, but 4261 // it doesn't have DominatorTree information, so it may miss cases. 4262 if (Value *V = SimplifyInstruction(PN, getDataLayout(), &TLI, &DT, &AC)) 4263 if (LI.replacementPreservesLCSSAForm(PN, V)) 4264 return getSCEV(V); 4265 4266 // If it's not a loop phi, we can't handle it yet. 4267 return getUnknown(PN); 4268 } 4269 4270 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, 4271 Value *Cond, 4272 Value *TrueVal, 4273 Value *FalseVal) { 4274 // Handle "constant" branch or select. This can occur for instance when a 4275 // loop pass transforms an inner loop and moves on to process the outer loop. 4276 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 4277 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 4278 4279 // Try to match some simple smax or umax patterns. 4280 auto *ICI = dyn_cast<ICmpInst>(Cond); 4281 if (!ICI) 4282 return getUnknown(I); 4283 4284 Value *LHS = ICI->getOperand(0); 4285 Value *RHS = ICI->getOperand(1); 4286 4287 switch (ICI->getPredicate()) { 4288 case ICmpInst::ICMP_SLT: 4289 case ICmpInst::ICMP_SLE: 4290 std::swap(LHS, RHS); 4291 LLVM_FALLTHROUGH; 4292 case ICmpInst::ICMP_SGT: 4293 case ICmpInst::ICMP_SGE: 4294 // a >s b ? a+x : b+x -> smax(a, b)+x 4295 // a >s b ? b+x : a+x -> smin(a, b)+x 4296 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 4297 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType()); 4298 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType()); 4299 const SCEV *LA = getSCEV(TrueVal); 4300 const SCEV *RA = getSCEV(FalseVal); 4301 const SCEV *LDiff = getMinusSCEV(LA, LS); 4302 const SCEV *RDiff = getMinusSCEV(RA, RS); 4303 if (LDiff == RDiff) 4304 return getAddExpr(getSMaxExpr(LS, RS), LDiff); 4305 LDiff = getMinusSCEV(LA, RS); 4306 RDiff = getMinusSCEV(RA, LS); 4307 if (LDiff == RDiff) 4308 return getAddExpr(getSMinExpr(LS, RS), LDiff); 4309 } 4310 break; 4311 case ICmpInst::ICMP_ULT: 4312 case ICmpInst::ICMP_ULE: 4313 std::swap(LHS, RHS); 4314 LLVM_FALLTHROUGH; 4315 case ICmpInst::ICMP_UGT: 4316 case ICmpInst::ICMP_UGE: 4317 // a >u b ? a+x : b+x -> umax(a, b)+x 4318 // a >u b ? b+x : a+x -> umin(a, b)+x 4319 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 4320 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 4321 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType()); 4322 const SCEV *LA = getSCEV(TrueVal); 4323 const SCEV *RA = getSCEV(FalseVal); 4324 const SCEV *LDiff = getMinusSCEV(LA, LS); 4325 const SCEV *RDiff = getMinusSCEV(RA, RS); 4326 if (LDiff == RDiff) 4327 return getAddExpr(getUMaxExpr(LS, RS), LDiff); 4328 LDiff = getMinusSCEV(LA, RS); 4329 RDiff = getMinusSCEV(RA, LS); 4330 if (LDiff == RDiff) 4331 return getAddExpr(getUMinExpr(LS, RS), LDiff); 4332 } 4333 break; 4334 case ICmpInst::ICMP_NE: 4335 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 4336 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 4337 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 4338 const SCEV *One = getOne(I->getType()); 4339 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 4340 const SCEV *LA = getSCEV(TrueVal); 4341 const SCEV *RA = getSCEV(FalseVal); 4342 const SCEV *LDiff = getMinusSCEV(LA, LS); 4343 const SCEV *RDiff = getMinusSCEV(RA, One); 4344 if (LDiff == RDiff) 4345 return getAddExpr(getUMaxExpr(One, LS), LDiff); 4346 } 4347 break; 4348 case ICmpInst::ICMP_EQ: 4349 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 4350 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 4351 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 4352 const SCEV *One = getOne(I->getType()); 4353 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 4354 const SCEV *LA = getSCEV(TrueVal); 4355 const SCEV *RA = getSCEV(FalseVal); 4356 const SCEV *LDiff = getMinusSCEV(LA, One); 4357 const SCEV *RDiff = getMinusSCEV(RA, LS); 4358 if (LDiff == RDiff) 4359 return getAddExpr(getUMaxExpr(One, LS), LDiff); 4360 } 4361 break; 4362 default: 4363 break; 4364 } 4365 4366 return getUnknown(I); 4367 } 4368 4369 /// Expand GEP instructions into add and multiply operations. This allows them 4370 /// to be analyzed by regular SCEV code. 4371 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 4372 // Don't attempt to analyze GEPs over unsized objects. 4373 if (!GEP->getSourceElementType()->isSized()) 4374 return getUnknown(GEP); 4375 4376 SmallVector<const SCEV *, 4> IndexExprs; 4377 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) 4378 IndexExprs.push_back(getSCEV(*Index)); 4379 return getGEPExpr(GEP->getSourceElementType(), 4380 getSCEV(GEP->getPointerOperand()), 4381 IndexExprs, GEP->isInBounds()); 4382 } 4383 4384 uint32_t 4385 ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 4386 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 4387 return C->getAPInt().countTrailingZeros(); 4388 4389 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 4390 return std::min(GetMinTrailingZeros(T->getOperand()), 4391 (uint32_t)getTypeSizeInBits(T->getType())); 4392 4393 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 4394 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 4395 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ? 4396 getTypeSizeInBits(E->getType()) : OpRes; 4397 } 4398 4399 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 4400 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 4401 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ? 4402 getTypeSizeInBits(E->getType()) : OpRes; 4403 } 4404 4405 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 4406 // The result is the min of all operands results. 4407 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 4408 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 4409 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 4410 return MinOpRes; 4411 } 4412 4413 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 4414 // The result is the sum of all operands results. 4415 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 4416 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 4417 for (unsigned i = 1, e = M->getNumOperands(); 4418 SumOpRes != BitWidth && i != e; ++i) 4419 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), 4420 BitWidth); 4421 return SumOpRes; 4422 } 4423 4424 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 4425 // The result is the min of all operands results. 4426 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 4427 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 4428 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 4429 return MinOpRes; 4430 } 4431 4432 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 4433 // The result is the min of all operands results. 4434 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 4435 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 4436 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 4437 return MinOpRes; 4438 } 4439 4440 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 4441 // The result is the min of all operands results. 4442 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 4443 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 4444 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 4445 return MinOpRes; 4446 } 4447 4448 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 4449 // For a SCEVUnknown, ask ValueTracking. 4450 unsigned BitWidth = getTypeSizeInBits(U->getType()); 4451 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0); 4452 computeKnownBits(U->getValue(), Zeros, Ones, getDataLayout(), 0, &AC, 4453 nullptr, &DT); 4454 return Zeros.countTrailingOnes(); 4455 } 4456 4457 // SCEVUDivExpr 4458 return 0; 4459 } 4460 4461 /// Helper method to assign a range to V from metadata present in the IR. 4462 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 4463 if (Instruction *I = dyn_cast<Instruction>(V)) 4464 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 4465 return getConstantRangeFromMetadata(*MD); 4466 4467 return None; 4468 } 4469 4470 /// Determine the range for a particular SCEV. If SignHint is 4471 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 4472 /// with a "cleaner" unsigned (resp. signed) representation. 4473 ConstantRange 4474 ScalarEvolution::getRange(const SCEV *S, 4475 ScalarEvolution::RangeSignHint SignHint) { 4476 DenseMap<const SCEV *, ConstantRange> &Cache = 4477 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 4478 : SignedRanges; 4479 4480 // See if we've computed this range already. 4481 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 4482 if (I != Cache.end()) 4483 return I->second; 4484 4485 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 4486 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 4487 4488 unsigned BitWidth = getTypeSizeInBits(S->getType()); 4489 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 4490 4491 // If the value has known zeros, the maximum value will have those known zeros 4492 // as well. 4493 uint32_t TZ = GetMinTrailingZeros(S); 4494 if (TZ != 0) { 4495 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 4496 ConservativeResult = 4497 ConstantRange(APInt::getMinValue(BitWidth), 4498 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 4499 else 4500 ConservativeResult = ConstantRange( 4501 APInt::getSignedMinValue(BitWidth), 4502 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 4503 } 4504 4505 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 4506 ConstantRange X = getRange(Add->getOperand(0), SignHint); 4507 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 4508 X = X.add(getRange(Add->getOperand(i), SignHint)); 4509 return setRange(Add, SignHint, ConservativeResult.intersectWith(X)); 4510 } 4511 4512 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 4513 ConstantRange X = getRange(Mul->getOperand(0), SignHint); 4514 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 4515 X = X.multiply(getRange(Mul->getOperand(i), SignHint)); 4516 return setRange(Mul, SignHint, ConservativeResult.intersectWith(X)); 4517 } 4518 4519 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 4520 ConstantRange X = getRange(SMax->getOperand(0), SignHint); 4521 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 4522 X = X.smax(getRange(SMax->getOperand(i), SignHint)); 4523 return setRange(SMax, SignHint, ConservativeResult.intersectWith(X)); 4524 } 4525 4526 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 4527 ConstantRange X = getRange(UMax->getOperand(0), SignHint); 4528 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 4529 X = X.umax(getRange(UMax->getOperand(i), SignHint)); 4530 return setRange(UMax, SignHint, ConservativeResult.intersectWith(X)); 4531 } 4532 4533 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 4534 ConstantRange X = getRange(UDiv->getLHS(), SignHint); 4535 ConstantRange Y = getRange(UDiv->getRHS(), SignHint); 4536 return setRange(UDiv, SignHint, 4537 ConservativeResult.intersectWith(X.udiv(Y))); 4538 } 4539 4540 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 4541 ConstantRange X = getRange(ZExt->getOperand(), SignHint); 4542 return setRange(ZExt, SignHint, 4543 ConservativeResult.intersectWith(X.zeroExtend(BitWidth))); 4544 } 4545 4546 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 4547 ConstantRange X = getRange(SExt->getOperand(), SignHint); 4548 return setRange(SExt, SignHint, 4549 ConservativeResult.intersectWith(X.signExtend(BitWidth))); 4550 } 4551 4552 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 4553 ConstantRange X = getRange(Trunc->getOperand(), SignHint); 4554 return setRange(Trunc, SignHint, 4555 ConservativeResult.intersectWith(X.truncate(BitWidth))); 4556 } 4557 4558 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 4559 // If there's no unsigned wrap, the value will never be less than its 4560 // initial value. 4561 if (AddRec->hasNoUnsignedWrap()) 4562 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart())) 4563 if (!C->getValue()->isZero()) 4564 ConservativeResult = ConservativeResult.intersectWith( 4565 ConstantRange(C->getAPInt(), APInt(BitWidth, 0))); 4566 4567 // If there's no signed wrap, and all the operands have the same sign or 4568 // zero, the value won't ever change sign. 4569 if (AddRec->hasNoSignedWrap()) { 4570 bool AllNonNeg = true; 4571 bool AllNonPos = true; 4572 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 4573 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false; 4574 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false; 4575 } 4576 if (AllNonNeg) 4577 ConservativeResult = ConservativeResult.intersectWith( 4578 ConstantRange(APInt(BitWidth, 0), 4579 APInt::getSignedMinValue(BitWidth))); 4580 else if (AllNonPos) 4581 ConservativeResult = ConservativeResult.intersectWith( 4582 ConstantRange(APInt::getSignedMinValue(BitWidth), 4583 APInt(BitWidth, 1))); 4584 } 4585 4586 // TODO: non-affine addrec 4587 if (AddRec->isAffine()) { 4588 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop()); 4589 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 4590 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 4591 auto RangeFromAffine = getRangeForAffineAR( 4592 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 4593 BitWidth); 4594 if (!RangeFromAffine.isFullSet()) 4595 ConservativeResult = 4596 ConservativeResult.intersectWith(RangeFromAffine); 4597 4598 auto RangeFromFactoring = getRangeViaFactoring( 4599 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 4600 BitWidth); 4601 if (!RangeFromFactoring.isFullSet()) 4602 ConservativeResult = 4603 ConservativeResult.intersectWith(RangeFromFactoring); 4604 } 4605 } 4606 4607 return setRange(AddRec, SignHint, ConservativeResult); 4608 } 4609 4610 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 4611 // Check if the IR explicitly contains !range metadata. 4612 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 4613 if (MDRange.hasValue()) 4614 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue()); 4615 4616 // Split here to avoid paying the compile-time cost of calling both 4617 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted 4618 // if needed. 4619 const DataLayout &DL = getDataLayout(); 4620 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) { 4621 // For a SCEVUnknown, ask ValueTracking. 4622 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0); 4623 computeKnownBits(U->getValue(), Zeros, Ones, DL, 0, &AC, nullptr, &DT); 4624 if (Ones != ~Zeros + 1) 4625 ConservativeResult = 4626 ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1)); 4627 } else { 4628 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED && 4629 "generalize as needed!"); 4630 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 4631 if (NS > 1) 4632 ConservativeResult = ConservativeResult.intersectWith( 4633 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 4634 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1)); 4635 } 4636 4637 return setRange(U, SignHint, ConservativeResult); 4638 } 4639 4640 return setRange(S, SignHint, ConservativeResult); 4641 } 4642 4643 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 4644 const SCEV *Step, 4645 const SCEV *MaxBECount, 4646 unsigned BitWidth) { 4647 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 4648 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 4649 "Precondition!"); 4650 4651 ConstantRange Result(BitWidth, /* isFullSet = */ true); 4652 4653 // Check for overflow. This must be done with ConstantRange arithmetic 4654 // because we could be called from within the ScalarEvolution overflow 4655 // checking code. 4656 4657 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 4658 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount); 4659 ConstantRange ZExtMaxBECountRange = 4660 MaxBECountRange.zextOrTrunc(BitWidth * 2 + 1); 4661 4662 ConstantRange StepSRange = getSignedRange(Step); 4663 ConstantRange SExtStepSRange = StepSRange.sextOrTrunc(BitWidth * 2 + 1); 4664 4665 ConstantRange StartURange = getUnsignedRange(Start); 4666 ConstantRange EndURange = 4667 StartURange.add(MaxBECountRange.multiply(StepSRange)); 4668 4669 // Check for unsigned overflow. 4670 ConstantRange ZExtStartURange = StartURange.zextOrTrunc(BitWidth * 2 + 1); 4671 ConstantRange ZExtEndURange = EndURange.zextOrTrunc(BitWidth * 2 + 1); 4672 if (ZExtStartURange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) == 4673 ZExtEndURange) { 4674 APInt Min = APIntOps::umin(StartURange.getUnsignedMin(), 4675 EndURange.getUnsignedMin()); 4676 APInt Max = APIntOps::umax(StartURange.getUnsignedMax(), 4677 EndURange.getUnsignedMax()); 4678 bool IsFullRange = Min.isMinValue() && Max.isMaxValue(); 4679 if (!IsFullRange) 4680 Result = 4681 Result.intersectWith(ConstantRange(Min, Max + 1)); 4682 } 4683 4684 ConstantRange StartSRange = getSignedRange(Start); 4685 ConstantRange EndSRange = 4686 StartSRange.add(MaxBECountRange.multiply(StepSRange)); 4687 4688 // Check for signed overflow. This must be done with ConstantRange 4689 // arithmetic because we could be called from within the ScalarEvolution 4690 // overflow checking code. 4691 ConstantRange SExtStartSRange = StartSRange.sextOrTrunc(BitWidth * 2 + 1); 4692 ConstantRange SExtEndSRange = EndSRange.sextOrTrunc(BitWidth * 2 + 1); 4693 if (SExtStartSRange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) == 4694 SExtEndSRange) { 4695 APInt Min = 4696 APIntOps::smin(StartSRange.getSignedMin(), EndSRange.getSignedMin()); 4697 APInt Max = 4698 APIntOps::smax(StartSRange.getSignedMax(), EndSRange.getSignedMax()); 4699 bool IsFullRange = Min.isMinSignedValue() && Max.isMaxSignedValue(); 4700 if (!IsFullRange) 4701 Result = 4702 Result.intersectWith(ConstantRange(Min, Max + 1)); 4703 } 4704 4705 return Result; 4706 } 4707 4708 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 4709 const SCEV *Step, 4710 const SCEV *MaxBECount, 4711 unsigned BitWidth) { 4712 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 4713 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 4714 4715 struct SelectPattern { 4716 Value *Condition = nullptr; 4717 APInt TrueValue; 4718 APInt FalseValue; 4719 4720 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 4721 const SCEV *S) { 4722 Optional<unsigned> CastOp; 4723 APInt Offset(BitWidth, 0); 4724 4725 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 4726 "Should be!"); 4727 4728 // Peel off a constant offset: 4729 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 4730 // In the future we could consider being smarter here and handle 4731 // {Start+Step,+,Step} too. 4732 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 4733 return; 4734 4735 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 4736 S = SA->getOperand(1); 4737 } 4738 4739 // Peel off a cast operation 4740 if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) { 4741 CastOp = SCast->getSCEVType(); 4742 S = SCast->getOperand(); 4743 } 4744 4745 using namespace llvm::PatternMatch; 4746 4747 auto *SU = dyn_cast<SCEVUnknown>(S); 4748 const APInt *TrueVal, *FalseVal; 4749 if (!SU || 4750 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 4751 m_APInt(FalseVal)))) { 4752 Condition = nullptr; 4753 return; 4754 } 4755 4756 TrueValue = *TrueVal; 4757 FalseValue = *FalseVal; 4758 4759 // Re-apply the cast we peeled off earlier 4760 if (CastOp.hasValue()) 4761 switch (*CastOp) { 4762 default: 4763 llvm_unreachable("Unknown SCEV cast type!"); 4764 4765 case scTruncate: 4766 TrueValue = TrueValue.trunc(BitWidth); 4767 FalseValue = FalseValue.trunc(BitWidth); 4768 break; 4769 case scZeroExtend: 4770 TrueValue = TrueValue.zext(BitWidth); 4771 FalseValue = FalseValue.zext(BitWidth); 4772 break; 4773 case scSignExtend: 4774 TrueValue = TrueValue.sext(BitWidth); 4775 FalseValue = FalseValue.sext(BitWidth); 4776 break; 4777 } 4778 4779 // Re-apply the constant offset we peeled off earlier 4780 TrueValue += Offset; 4781 FalseValue += Offset; 4782 } 4783 4784 bool isRecognized() { return Condition != nullptr; } 4785 }; 4786 4787 SelectPattern StartPattern(*this, BitWidth, Start); 4788 if (!StartPattern.isRecognized()) 4789 return ConstantRange(BitWidth, /* isFullSet = */ true); 4790 4791 SelectPattern StepPattern(*this, BitWidth, Step); 4792 if (!StepPattern.isRecognized()) 4793 return ConstantRange(BitWidth, /* isFullSet = */ true); 4794 4795 if (StartPattern.Condition != StepPattern.Condition) { 4796 // We don't handle this case today; but we could, by considering four 4797 // possibilities below instead of two. I'm not sure if there are cases where 4798 // that will help over what getRange already does, though. 4799 return ConstantRange(BitWidth, /* isFullSet = */ true); 4800 } 4801 4802 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 4803 // construct arbitrary general SCEV expressions here. This function is called 4804 // from deep in the call stack, and calling getSCEV (on a sext instruction, 4805 // say) can end up caching a suboptimal value. 4806 4807 // FIXME: without the explicit `this` receiver below, MSVC errors out with 4808 // C2352 and C2512 (otherwise it isn't needed). 4809 4810 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 4811 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 4812 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 4813 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 4814 4815 ConstantRange TrueRange = 4816 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 4817 ConstantRange FalseRange = 4818 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 4819 4820 return TrueRange.unionWith(FalseRange); 4821 } 4822 4823 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 4824 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 4825 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 4826 4827 // Return early if there are no flags to propagate to the SCEV. 4828 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 4829 if (BinOp->hasNoUnsignedWrap()) 4830 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 4831 if (BinOp->hasNoSignedWrap()) 4832 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 4833 if (Flags == SCEV::FlagAnyWrap) 4834 return SCEV::FlagAnyWrap; 4835 4836 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 4837 } 4838 4839 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 4840 // Here we check that I is in the header of the innermost loop containing I, 4841 // since we only deal with instructions in the loop header. The actual loop we 4842 // need to check later will come from an add recurrence, but getting that 4843 // requires computing the SCEV of the operands, which can be expensive. This 4844 // check we can do cheaply to rule out some cases early. 4845 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent()); 4846 if (InnermostContainingLoop == nullptr || 4847 InnermostContainingLoop->getHeader() != I->getParent()) 4848 return false; 4849 4850 // Only proceed if we can prove that I does not yield poison. 4851 if (!isKnownNotFullPoison(I)) return false; 4852 4853 // At this point we know that if I is executed, then it does not wrap 4854 // according to at least one of NSW or NUW. If I is not executed, then we do 4855 // not know if the calculation that I represents would wrap. Multiple 4856 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 4857 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 4858 // derived from other instructions that map to the same SCEV. We cannot make 4859 // that guarantee for cases where I is not executed. So we need to find the 4860 // loop that I is considered in relation to and prove that I is executed for 4861 // every iteration of that loop. That implies that the value that I 4862 // calculates does not wrap anywhere in the loop, so then we can apply the 4863 // flags to the SCEV. 4864 // 4865 // We check isLoopInvariant to disambiguate in case we are adding recurrences 4866 // from different loops, so that we know which loop to prove that I is 4867 // executed in. 4868 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) { 4869 // I could be an extractvalue from a call to an overflow intrinsic. 4870 // TODO: We can do better here in some cases. 4871 if (!isSCEVable(I->getOperand(OpIndex)->getType())) 4872 return false; 4873 const SCEV *Op = getSCEV(I->getOperand(OpIndex)); 4874 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 4875 bool AllOtherOpsLoopInvariant = true; 4876 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands(); 4877 ++OtherOpIndex) { 4878 if (OtherOpIndex != OpIndex) { 4879 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex)); 4880 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) { 4881 AllOtherOpsLoopInvariant = false; 4882 break; 4883 } 4884 } 4885 } 4886 if (AllOtherOpsLoopInvariant && 4887 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop())) 4888 return true; 4889 } 4890 } 4891 return false; 4892 } 4893 4894 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 4895 // If we know that \c I can never be poison period, then that's enough. 4896 if (isSCEVExprNeverPoison(I)) 4897 return true; 4898 4899 // For an add recurrence specifically, we assume that infinite loops without 4900 // side effects are undefined behavior, and then reason as follows: 4901 // 4902 // If the add recurrence is poison in any iteration, it is poison on all 4903 // future iterations (since incrementing poison yields poison). If the result 4904 // of the add recurrence is fed into the loop latch condition and the loop 4905 // does not contain any throws or exiting blocks other than the latch, we now 4906 // have the ability to "choose" whether the backedge is taken or not (by 4907 // choosing a sufficiently evil value for the poison feeding into the branch) 4908 // for every iteration including and after the one in which \p I first became 4909 // poison. There are two possibilities (let's call the iteration in which \p 4910 // I first became poison as K): 4911 // 4912 // 1. In the set of iterations including and after K, the loop body executes 4913 // no side effects. In this case executing the backege an infinte number 4914 // of times will yield undefined behavior. 4915 // 4916 // 2. In the set of iterations including and after K, the loop body executes 4917 // at least one side effect. In this case, that specific instance of side 4918 // effect is control dependent on poison, which also yields undefined 4919 // behavior. 4920 4921 auto *ExitingBB = L->getExitingBlock(); 4922 auto *LatchBB = L->getLoopLatch(); 4923 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 4924 return false; 4925 4926 SmallPtrSet<const Instruction *, 16> Pushed; 4927 SmallVector<const Instruction *, 8> PoisonStack; 4928 4929 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 4930 // things that are known to be fully poison under that assumption go on the 4931 // PoisonStack. 4932 Pushed.insert(I); 4933 PoisonStack.push_back(I); 4934 4935 bool LatchControlDependentOnPoison = false; 4936 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 4937 const Instruction *Poison = PoisonStack.pop_back_val(); 4938 4939 for (auto *PoisonUser : Poison->users()) { 4940 if (propagatesFullPoison(cast<Instruction>(PoisonUser))) { 4941 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 4942 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 4943 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 4944 assert(BI->isConditional() && "Only possibility!"); 4945 if (BI->getParent() == LatchBB) { 4946 LatchControlDependentOnPoison = true; 4947 break; 4948 } 4949 } 4950 } 4951 } 4952 4953 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 4954 } 4955 4956 bool ScalarEvolution::loopHasNoSideEffects(const Loop *L) { 4957 auto Itr = LoopHasNoSideEffects.find(L); 4958 if (Itr == LoopHasNoSideEffects.end()) { 4959 auto NoSideEffectsInBB = [&](BasicBlock *BB) { 4960 return all_of(*BB, [](Instruction &I) { 4961 // Non-atomic, non-volatile stores are ok. 4962 if (auto *SI = dyn_cast<StoreInst>(&I)) 4963 return SI->isSimple(); 4964 4965 return !I.mayHaveSideEffects(); 4966 }); 4967 }; 4968 4969 auto InsertPair = LoopHasNoSideEffects.insert( 4970 {L, all_of(L->getBlocks(), NoSideEffectsInBB)}); 4971 assert(InsertPair.second && "We just checked!"); 4972 Itr = InsertPair.first; 4973 } 4974 4975 return Itr->second; 4976 } 4977 4978 bool ScalarEvolution::loopHasNoAbnormalExits(const Loop *L) { 4979 auto Itr = LoopHasNoAbnormalExits.find(L); 4980 if (Itr == LoopHasNoAbnormalExits.end()) { 4981 auto NoAbnormalExitInBB = [&](BasicBlock *BB) { 4982 return all_of(*BB, [](Instruction &I) { 4983 return isGuaranteedToTransferExecutionToSuccessor(&I); 4984 }); 4985 }; 4986 4987 auto InsertPair = LoopHasNoAbnormalExits.insert( 4988 {L, all_of(L->getBlocks(), NoAbnormalExitInBB)}); 4989 assert(InsertPair.second && "We just checked!"); 4990 Itr = InsertPair.first; 4991 } 4992 4993 return Itr->second; 4994 } 4995 4996 const SCEV *ScalarEvolution::createSCEV(Value *V) { 4997 if (!isSCEVable(V->getType())) 4998 return getUnknown(V); 4999 5000 if (Instruction *I = dyn_cast<Instruction>(V)) { 5001 // Don't attempt to analyze instructions in blocks that aren't 5002 // reachable. Such instructions don't matter, and they aren't required 5003 // to obey basic rules for definitions dominating uses which this 5004 // analysis depends on. 5005 if (!DT.isReachableFromEntry(I->getParent())) 5006 return getUnknown(V); 5007 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 5008 return getConstant(CI); 5009 else if (isa<ConstantPointerNull>(V)) 5010 return getZero(V->getType()); 5011 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 5012 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 5013 else if (!isa<ConstantExpr>(V)) 5014 return getUnknown(V); 5015 5016 Operator *U = cast<Operator>(V); 5017 if (auto BO = MatchBinaryOp(U, DT)) { 5018 switch (BO->Opcode) { 5019 case Instruction::Add: { 5020 // The simple thing to do would be to just call getSCEV on both operands 5021 // and call getAddExpr with the result. However if we're looking at a 5022 // bunch of things all added together, this can be quite inefficient, 5023 // because it leads to N-1 getAddExpr calls for N ultimate operands. 5024 // Instead, gather up all the operands and make a single getAddExpr call. 5025 // LLVM IR canonical form means we need only traverse the left operands. 5026 SmallVector<const SCEV *, 4> AddOps; 5027 do { 5028 if (BO->Op) { 5029 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 5030 AddOps.push_back(OpSCEV); 5031 break; 5032 } 5033 5034 // If a NUW or NSW flag can be applied to the SCEV for this 5035 // addition, then compute the SCEV for this addition by itself 5036 // with a separate call to getAddExpr. We need to do that 5037 // instead of pushing the operands of the addition onto AddOps, 5038 // since the flags are only known to apply to this particular 5039 // addition - they may not apply to other additions that can be 5040 // formed with operands from AddOps. 5041 const SCEV *RHS = getSCEV(BO->RHS); 5042 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 5043 if (Flags != SCEV::FlagAnyWrap) { 5044 const SCEV *LHS = getSCEV(BO->LHS); 5045 if (BO->Opcode == Instruction::Sub) 5046 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 5047 else 5048 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 5049 break; 5050 } 5051 } 5052 5053 if (BO->Opcode == Instruction::Sub) 5054 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 5055 else 5056 AddOps.push_back(getSCEV(BO->RHS)); 5057 5058 auto NewBO = MatchBinaryOp(BO->LHS, DT); 5059 if (!NewBO || (NewBO->Opcode != Instruction::Add && 5060 NewBO->Opcode != Instruction::Sub)) { 5061 AddOps.push_back(getSCEV(BO->LHS)); 5062 break; 5063 } 5064 BO = NewBO; 5065 } while (true); 5066 5067 return getAddExpr(AddOps); 5068 } 5069 5070 case Instruction::Mul: { 5071 SmallVector<const SCEV *, 4> MulOps; 5072 do { 5073 if (BO->Op) { 5074 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 5075 MulOps.push_back(OpSCEV); 5076 break; 5077 } 5078 5079 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 5080 if (Flags != SCEV::FlagAnyWrap) { 5081 MulOps.push_back( 5082 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 5083 break; 5084 } 5085 } 5086 5087 MulOps.push_back(getSCEV(BO->RHS)); 5088 auto NewBO = MatchBinaryOp(BO->LHS, DT); 5089 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 5090 MulOps.push_back(getSCEV(BO->LHS)); 5091 break; 5092 } 5093 BO = NewBO; 5094 } while (true); 5095 5096 return getMulExpr(MulOps); 5097 } 5098 case Instruction::UDiv: 5099 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 5100 case Instruction::Sub: { 5101 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5102 if (BO->Op) 5103 Flags = getNoWrapFlagsFromUB(BO->Op); 5104 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 5105 } 5106 case Instruction::And: 5107 // For an expression like x&255 that merely masks off the high bits, 5108 // use zext(trunc(x)) as the SCEV expression. 5109 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 5110 if (CI->isNullValue()) 5111 return getSCEV(BO->RHS); 5112 if (CI->isAllOnesValue()) 5113 return getSCEV(BO->LHS); 5114 const APInt &A = CI->getValue(); 5115 5116 // Instcombine's ShrinkDemandedConstant may strip bits out of 5117 // constants, obscuring what would otherwise be a low-bits mask. 5118 // Use computeKnownBits to compute what ShrinkDemandedConstant 5119 // knew about to reconstruct a low-bits mask value. 5120 unsigned LZ = A.countLeadingZeros(); 5121 unsigned TZ = A.countTrailingZeros(); 5122 unsigned BitWidth = A.getBitWidth(); 5123 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0); 5124 computeKnownBits(BO->LHS, KnownZero, KnownOne, getDataLayout(), 5125 0, &AC, nullptr, &DT); 5126 5127 APInt EffectiveMask = 5128 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 5129 if ((LZ != 0 || TZ != 0) && !((~A & ~KnownZero) & EffectiveMask)) { 5130 const SCEV *MulCount = getConstant(ConstantInt::get( 5131 getContext(), APInt::getOneBitSet(BitWidth, TZ))); 5132 return getMulExpr( 5133 getZeroExtendExpr( 5134 getTruncateExpr( 5135 getUDivExactExpr(getSCEV(BO->LHS), MulCount), 5136 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 5137 BO->LHS->getType()), 5138 MulCount); 5139 } 5140 } 5141 break; 5142 5143 case Instruction::Or: 5144 // If the RHS of the Or is a constant, we may have something like: 5145 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 5146 // optimizations will transparently handle this case. 5147 // 5148 // In order for this transformation to be safe, the LHS must be of the 5149 // form X*(2^n) and the Or constant must be less than 2^n. 5150 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 5151 const SCEV *LHS = getSCEV(BO->LHS); 5152 const APInt &CIVal = CI->getValue(); 5153 if (GetMinTrailingZeros(LHS) >= 5154 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 5155 // Build a plain add SCEV. 5156 const SCEV *S = getAddExpr(LHS, getSCEV(CI)); 5157 // If the LHS of the add was an addrec and it has no-wrap flags, 5158 // transfer the no-wrap flags, since an or won't introduce a wrap. 5159 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) { 5160 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS); 5161 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags( 5162 OldAR->getNoWrapFlags()); 5163 } 5164 return S; 5165 } 5166 } 5167 break; 5168 5169 case Instruction::Xor: 5170 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 5171 // If the RHS of xor is -1, then this is a not operation. 5172 if (CI->isAllOnesValue()) 5173 return getNotSCEV(getSCEV(BO->LHS)); 5174 5175 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 5176 // This is a variant of the check for xor with -1, and it handles 5177 // the case where instcombine has trimmed non-demanded bits out 5178 // of an xor with -1. 5179 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 5180 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 5181 if (LBO->getOpcode() == Instruction::And && 5182 LCI->getValue() == CI->getValue()) 5183 if (const SCEVZeroExtendExpr *Z = 5184 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 5185 Type *UTy = BO->LHS->getType(); 5186 const SCEV *Z0 = Z->getOperand(); 5187 Type *Z0Ty = Z0->getType(); 5188 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 5189 5190 // If C is a low-bits mask, the zero extend is serving to 5191 // mask off the high bits. Complement the operand and 5192 // re-apply the zext. 5193 if (APIntOps::isMask(Z0TySize, CI->getValue())) 5194 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 5195 5196 // If C is a single bit, it may be in the sign-bit position 5197 // before the zero-extend. In this case, represent the xor 5198 // using an add, which is equivalent, and re-apply the zext. 5199 APInt Trunc = CI->getValue().trunc(Z0TySize); 5200 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 5201 Trunc.isSignBit()) 5202 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 5203 UTy); 5204 } 5205 } 5206 break; 5207 5208 case Instruction::Shl: 5209 // Turn shift left of a constant amount into a multiply. 5210 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 5211 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 5212 5213 // If the shift count is not less than the bitwidth, the result of 5214 // the shift is undefined. Don't try to analyze it, because the 5215 // resolution chosen here may differ from the resolution chosen in 5216 // other parts of the compiler. 5217 if (SA->getValue().uge(BitWidth)) 5218 break; 5219 5220 // It is currently not resolved how to interpret NSW for left 5221 // shift by BitWidth - 1, so we avoid applying flags in that 5222 // case. Remove this check (or this comment) once the situation 5223 // is resolved. See 5224 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html 5225 // and http://reviews.llvm.org/D8890 . 5226 auto Flags = SCEV::FlagAnyWrap; 5227 if (BO->Op && SA->getValue().ult(BitWidth - 1)) 5228 Flags = getNoWrapFlagsFromUB(BO->Op); 5229 5230 Constant *X = ConstantInt::get(getContext(), 5231 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 5232 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 5233 } 5234 break; 5235 5236 case Instruction::AShr: 5237 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression. 5238 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) 5239 if (Operator *L = dyn_cast<Operator>(BO->LHS)) 5240 if (L->getOpcode() == Instruction::Shl && 5241 L->getOperand(1) == BO->RHS) { 5242 uint64_t BitWidth = getTypeSizeInBits(BO->LHS->getType()); 5243 5244 // If the shift count is not less than the bitwidth, the result of 5245 // the shift is undefined. Don't try to analyze it, because the 5246 // resolution chosen here may differ from the resolution chosen in 5247 // other parts of the compiler. 5248 if (CI->getValue().uge(BitWidth)) 5249 break; 5250 5251 uint64_t Amt = BitWidth - CI->getZExtValue(); 5252 if (Amt == BitWidth) 5253 return getSCEV(L->getOperand(0)); // shift by zero --> noop 5254 return getSignExtendExpr( 5255 getTruncateExpr(getSCEV(L->getOperand(0)), 5256 IntegerType::get(getContext(), Amt)), 5257 BO->LHS->getType()); 5258 } 5259 break; 5260 } 5261 } 5262 5263 switch (U->getOpcode()) { 5264 case Instruction::Trunc: 5265 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 5266 5267 case Instruction::ZExt: 5268 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 5269 5270 case Instruction::SExt: 5271 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 5272 5273 case Instruction::BitCast: 5274 // BitCasts are no-op casts so we just eliminate the cast. 5275 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 5276 return getSCEV(U->getOperand(0)); 5277 break; 5278 5279 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can 5280 // lead to pointer expressions which cannot safely be expanded to GEPs, 5281 // because ScalarEvolution doesn't respect the GEP aliasing rules when 5282 // simplifying integer expressions. 5283 5284 case Instruction::GetElementPtr: 5285 return createNodeForGEP(cast<GEPOperator>(U)); 5286 5287 case Instruction::PHI: 5288 return createNodeForPHI(cast<PHINode>(U)); 5289 5290 case Instruction::Select: 5291 // U can also be a select constant expr, which let fall through. Since 5292 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 5293 // constant expressions cannot have instructions as operands, we'd have 5294 // returned getUnknown for a select constant expressions anyway. 5295 if (isa<Instruction>(U)) 5296 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 5297 U->getOperand(1), U->getOperand(2)); 5298 break; 5299 5300 case Instruction::Call: 5301 case Instruction::Invoke: 5302 if (Value *RV = CallSite(U).getReturnedArgOperand()) 5303 return getSCEV(RV); 5304 break; 5305 } 5306 5307 return getUnknown(V); 5308 } 5309 5310 5311 5312 //===----------------------------------------------------------------------===// 5313 // Iteration Count Computation Code 5314 // 5315 5316 unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L) { 5317 if (BasicBlock *ExitingBB = L->getExitingBlock()) 5318 return getSmallConstantTripCount(L, ExitingBB); 5319 5320 // No trip count information for multiple exits. 5321 return 0; 5322 } 5323 5324 unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L, 5325 BasicBlock *ExitingBlock) { 5326 assert(ExitingBlock && "Must pass a non-null exiting block!"); 5327 assert(L->isLoopExiting(ExitingBlock) && 5328 "Exiting block must actually branch out of the loop!"); 5329 const SCEVConstant *ExitCount = 5330 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 5331 if (!ExitCount) 5332 return 0; 5333 5334 ConstantInt *ExitConst = ExitCount->getValue(); 5335 5336 // Guard against huge trip counts. 5337 if (ExitConst->getValue().getActiveBits() > 32) 5338 return 0; 5339 5340 // In case of integer overflow, this returns 0, which is correct. 5341 return ((unsigned)ExitConst->getZExtValue()) + 1; 5342 } 5343 5344 unsigned ScalarEvolution::getSmallConstantTripMultiple(Loop *L) { 5345 if (BasicBlock *ExitingBB = L->getExitingBlock()) 5346 return getSmallConstantTripMultiple(L, ExitingBB); 5347 5348 // No trip multiple information for multiple exits. 5349 return 0; 5350 } 5351 5352 /// Returns the largest constant divisor of the trip count of this loop as a 5353 /// normal unsigned value, if possible. This means that the actual trip count is 5354 /// always a multiple of the returned value (don't forget the trip count could 5355 /// very well be zero as well!). 5356 /// 5357 /// Returns 1 if the trip count is unknown or not guaranteed to be the 5358 /// multiple of a constant (which is also the case if the trip count is simply 5359 /// constant, use getSmallConstantTripCount for that case), Will also return 1 5360 /// if the trip count is very large (>= 2^32). 5361 /// 5362 /// As explained in the comments for getSmallConstantTripCount, this assumes 5363 /// that control exits the loop via ExitingBlock. 5364 unsigned 5365 ScalarEvolution::getSmallConstantTripMultiple(Loop *L, 5366 BasicBlock *ExitingBlock) { 5367 assert(ExitingBlock && "Must pass a non-null exiting block!"); 5368 assert(L->isLoopExiting(ExitingBlock) && 5369 "Exiting block must actually branch out of the loop!"); 5370 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 5371 if (ExitCount == getCouldNotCompute()) 5372 return 1; 5373 5374 // Get the trip count from the BE count by adding 1. 5375 const SCEV *TCMul = getAddExpr(ExitCount, getOne(ExitCount->getType())); 5376 // FIXME: SCEV distributes multiplication as V1*C1 + V2*C1. We could attempt 5377 // to factor simple cases. 5378 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(TCMul)) 5379 TCMul = Mul->getOperand(0); 5380 5381 const SCEVConstant *MulC = dyn_cast<SCEVConstant>(TCMul); 5382 if (!MulC) 5383 return 1; 5384 5385 ConstantInt *Result = MulC->getValue(); 5386 5387 // Guard against huge trip counts (this requires checking 5388 // for zero to handle the case where the trip count == -1 and the 5389 // addition wraps). 5390 if (!Result || Result->getValue().getActiveBits() > 32 || 5391 Result->getValue().getActiveBits() == 0) 5392 return 1; 5393 5394 return (unsigned)Result->getZExtValue(); 5395 } 5396 5397 /// Get the expression for the number of loop iterations for which this loop is 5398 /// guaranteed not to exit via ExitingBlock. Otherwise return 5399 /// SCEVCouldNotCompute. 5400 const SCEV *ScalarEvolution::getExitCount(Loop *L, BasicBlock *ExitingBlock) { 5401 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 5402 } 5403 5404 const SCEV * 5405 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 5406 SCEVUnionPredicate &Preds) { 5407 return getPredicatedBackedgeTakenInfo(L).getExact(this, &Preds); 5408 } 5409 5410 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) { 5411 return getBackedgeTakenInfo(L).getExact(this); 5412 } 5413 5414 /// Similar to getBackedgeTakenCount, except return the least SCEV value that is 5415 /// known never to be less than the actual backedge taken count. 5416 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) { 5417 return getBackedgeTakenInfo(L).getMax(this); 5418 } 5419 5420 /// Push PHI nodes in the header of the given loop onto the given Worklist. 5421 static void 5422 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { 5423 BasicBlock *Header = L->getHeader(); 5424 5425 // Push all Loop-header PHIs onto the Worklist stack. 5426 for (BasicBlock::iterator I = Header->begin(); 5427 PHINode *PN = dyn_cast<PHINode>(I); ++I) 5428 Worklist.push_back(PN); 5429 } 5430 5431 const ScalarEvolution::BackedgeTakenInfo & 5432 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 5433 auto &BTI = getBackedgeTakenInfo(L); 5434 if (BTI.hasFullInfo()) 5435 return BTI; 5436 5437 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 5438 5439 if (!Pair.second) 5440 return Pair.first->second; 5441 5442 BackedgeTakenInfo Result = 5443 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 5444 5445 return PredicatedBackedgeTakenCounts.find(L)->second = Result; 5446 } 5447 5448 const ScalarEvolution::BackedgeTakenInfo & 5449 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 5450 // Initially insert an invalid entry for this loop. If the insertion 5451 // succeeds, proceed to actually compute a backedge-taken count and 5452 // update the value. The temporary CouldNotCompute value tells SCEV 5453 // code elsewhere that it shouldn't attempt to request a new 5454 // backedge-taken count, which could result in infinite recursion. 5455 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 5456 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 5457 if (!Pair.second) 5458 return Pair.first->second; 5459 5460 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 5461 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 5462 // must be cleared in this scope. 5463 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 5464 5465 if (Result.getExact(this) != getCouldNotCompute()) { 5466 assert(isLoopInvariant(Result.getExact(this), L) && 5467 isLoopInvariant(Result.getMax(this), L) && 5468 "Computed backedge-taken count isn't loop invariant for loop!"); 5469 ++NumTripCountsComputed; 5470 } 5471 else if (Result.getMax(this) == getCouldNotCompute() && 5472 isa<PHINode>(L->getHeader()->begin())) { 5473 // Only count loops that have phi nodes as not being computable. 5474 ++NumTripCountsNotComputed; 5475 } 5476 5477 // Now that we know more about the trip count for this loop, forget any 5478 // existing SCEV values for PHI nodes in this loop since they are only 5479 // conservative estimates made without the benefit of trip count 5480 // information. This is similar to the code in forgetLoop, except that 5481 // it handles SCEVUnknown PHI nodes specially. 5482 if (Result.hasAnyInfo()) { 5483 SmallVector<Instruction *, 16> Worklist; 5484 PushLoopPHIs(L, Worklist); 5485 5486 SmallPtrSet<Instruction *, 8> Visited; 5487 while (!Worklist.empty()) { 5488 Instruction *I = Worklist.pop_back_val(); 5489 if (!Visited.insert(I).second) 5490 continue; 5491 5492 ValueExprMapType::iterator It = 5493 ValueExprMap.find_as(static_cast<Value *>(I)); 5494 if (It != ValueExprMap.end()) { 5495 const SCEV *Old = It->second; 5496 5497 // SCEVUnknown for a PHI either means that it has an unrecognized 5498 // structure, or it's a PHI that's in the progress of being computed 5499 // by createNodeForPHI. In the former case, additional loop trip 5500 // count information isn't going to change anything. In the later 5501 // case, createNodeForPHI will perform the necessary updates on its 5502 // own when it gets to that point. 5503 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 5504 eraseValueFromMap(It->first); 5505 forgetMemoizedResults(Old); 5506 } 5507 if (PHINode *PN = dyn_cast<PHINode>(I)) 5508 ConstantEvolutionLoopExitValue.erase(PN); 5509 } 5510 5511 PushDefUseChildren(I, Worklist); 5512 } 5513 } 5514 5515 // Re-lookup the insert position, since the call to 5516 // computeBackedgeTakenCount above could result in a 5517 // recusive call to getBackedgeTakenInfo (on a different 5518 // loop), which would invalidate the iterator computed 5519 // earlier. 5520 return BackedgeTakenCounts.find(L)->second = Result; 5521 } 5522 5523 void ScalarEvolution::forgetLoop(const Loop *L) { 5524 // Drop any stored trip count value. 5525 auto RemoveLoopFromBackedgeMap = 5526 [L](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 5527 auto BTCPos = Map.find(L); 5528 if (BTCPos != Map.end()) { 5529 BTCPos->second.clear(); 5530 Map.erase(BTCPos); 5531 } 5532 }; 5533 5534 RemoveLoopFromBackedgeMap(BackedgeTakenCounts); 5535 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts); 5536 5537 // Drop information about expressions based on loop-header PHIs. 5538 SmallVector<Instruction *, 16> Worklist; 5539 PushLoopPHIs(L, Worklist); 5540 5541 SmallPtrSet<Instruction *, 8> Visited; 5542 while (!Worklist.empty()) { 5543 Instruction *I = Worklist.pop_back_val(); 5544 if (!Visited.insert(I).second) 5545 continue; 5546 5547 ValueExprMapType::iterator It = 5548 ValueExprMap.find_as(static_cast<Value *>(I)); 5549 if (It != ValueExprMap.end()) { 5550 eraseValueFromMap(It->first); 5551 forgetMemoizedResults(It->second); 5552 if (PHINode *PN = dyn_cast<PHINode>(I)) 5553 ConstantEvolutionLoopExitValue.erase(PN); 5554 } 5555 5556 PushDefUseChildren(I, Worklist); 5557 } 5558 5559 // Forget all contained loops too, to avoid dangling entries in the 5560 // ValuesAtScopes map. 5561 for (Loop *I : *L) 5562 forgetLoop(I); 5563 5564 LoopHasNoAbnormalExits.erase(L); 5565 LoopHasNoSideEffects.erase(L); 5566 } 5567 5568 void ScalarEvolution::forgetValue(Value *V) { 5569 Instruction *I = dyn_cast<Instruction>(V); 5570 if (!I) return; 5571 5572 // Drop information about expressions based on loop-header PHIs. 5573 SmallVector<Instruction *, 16> Worklist; 5574 Worklist.push_back(I); 5575 5576 SmallPtrSet<Instruction *, 8> Visited; 5577 while (!Worklist.empty()) { 5578 I = Worklist.pop_back_val(); 5579 if (!Visited.insert(I).second) 5580 continue; 5581 5582 ValueExprMapType::iterator It = 5583 ValueExprMap.find_as(static_cast<Value *>(I)); 5584 if (It != ValueExprMap.end()) { 5585 eraseValueFromMap(It->first); 5586 forgetMemoizedResults(It->second); 5587 if (PHINode *PN = dyn_cast<PHINode>(I)) 5588 ConstantEvolutionLoopExitValue.erase(PN); 5589 } 5590 5591 PushDefUseChildren(I, Worklist); 5592 } 5593 } 5594 5595 /// Get the exact loop backedge taken count considering all loop exits. A 5596 /// computable result can only be returned for loops with a single exit. 5597 /// Returning the minimum taken count among all exits is incorrect because one 5598 /// of the loop's exit limit's may have been skipped. howFarToZero assumes that 5599 /// the limit of each loop test is never skipped. This is a valid assumption as 5600 /// long as the loop exits via that test. For precise results, it is the 5601 /// caller's responsibility to specify the relevant loop exit using 5602 /// getExact(ExitingBlock, SE). 5603 const SCEV * 5604 ScalarEvolution::BackedgeTakenInfo::getExact( 5605 ScalarEvolution *SE, SCEVUnionPredicate *Preds) const { 5606 // If any exits were not computable, the loop is not computable. 5607 if (!ExitNotTaken.isCompleteList()) return SE->getCouldNotCompute(); 5608 5609 // We need exactly one computable exit. 5610 if (!ExitNotTaken.ExitingBlock) return SE->getCouldNotCompute(); 5611 assert(ExitNotTaken.ExactNotTaken && "uninitialized not-taken info"); 5612 5613 const SCEV *BECount = nullptr; 5614 for (auto &ENT : ExitNotTaken) { 5615 assert(ENT.ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV"); 5616 5617 if (!BECount) 5618 BECount = ENT.ExactNotTaken; 5619 else if (BECount != ENT.ExactNotTaken) 5620 return SE->getCouldNotCompute(); 5621 if (Preds && ENT.getPred()) 5622 Preds->add(ENT.getPred()); 5623 5624 assert((Preds || ENT.hasAlwaysTruePred()) && 5625 "Predicate should be always true!"); 5626 } 5627 5628 assert(BECount && "Invalid not taken count for loop exit"); 5629 return BECount; 5630 } 5631 5632 /// Get the exact not taken count for this loop exit. 5633 const SCEV * 5634 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock, 5635 ScalarEvolution *SE) const { 5636 for (auto &ENT : ExitNotTaken) 5637 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePred()) 5638 return ENT.ExactNotTaken; 5639 5640 return SE->getCouldNotCompute(); 5641 } 5642 5643 /// getMax - Get the max backedge taken count for the loop. 5644 const SCEV * 5645 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const { 5646 for (auto &ENT : ExitNotTaken) 5647 if (!ENT.hasAlwaysTruePred()) 5648 return SE->getCouldNotCompute(); 5649 5650 return Max ? Max : SE->getCouldNotCompute(); 5651 } 5652 5653 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S, 5654 ScalarEvolution *SE) const { 5655 if (Max && Max != SE->getCouldNotCompute() && SE->hasOperand(Max, S)) 5656 return true; 5657 5658 if (!ExitNotTaken.ExitingBlock) 5659 return false; 5660 5661 for (auto &ENT : ExitNotTaken) 5662 if (ENT.ExactNotTaken != SE->getCouldNotCompute() && 5663 SE->hasOperand(ENT.ExactNotTaken, S)) 5664 return true; 5665 5666 return false; 5667 } 5668 5669 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 5670 /// computable exit into a persistent ExitNotTakenInfo array. 5671 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 5672 SmallVectorImpl<EdgeInfo> &ExitCounts, bool Complete, const SCEV *MaxCount) 5673 : Max(MaxCount) { 5674 5675 if (!Complete) 5676 ExitNotTaken.setIncomplete(); 5677 5678 unsigned NumExits = ExitCounts.size(); 5679 if (NumExits == 0) return; 5680 5681 ExitNotTaken.ExitingBlock = ExitCounts[0].ExitBlock; 5682 ExitNotTaken.ExactNotTaken = ExitCounts[0].Taken; 5683 5684 // Determine the number of ExitNotTakenExtras structures that we need. 5685 unsigned ExtraInfoSize = 0; 5686 if (NumExits > 1) 5687 ExtraInfoSize = 1 + std::count_if(std::next(ExitCounts.begin()), 5688 ExitCounts.end(), [](EdgeInfo &Entry) { 5689 return !Entry.Pred.isAlwaysTrue(); 5690 }); 5691 else if (!ExitCounts[0].Pred.isAlwaysTrue()) 5692 ExtraInfoSize = 1; 5693 5694 ExitNotTakenExtras *ENT = nullptr; 5695 5696 // Allocate the ExitNotTakenExtras structures and initialize the first 5697 // element (ExitNotTaken). 5698 if (ExtraInfoSize > 0) { 5699 ENT = new ExitNotTakenExtras[ExtraInfoSize]; 5700 ExitNotTaken.ExtraInfo = &ENT[0]; 5701 *ExitNotTaken.getPred() = std::move(ExitCounts[0].Pred); 5702 } 5703 5704 if (NumExits == 1) 5705 return; 5706 5707 assert(ENT && "ExitNotTakenExtras is NULL while having more than one exit"); 5708 5709 auto &Exits = ExitNotTaken.ExtraInfo->Exits; 5710 5711 // Handle the rare case of multiple computable exits. 5712 for (unsigned i = 1, PredPos = 1; i < NumExits; ++i) { 5713 ExitNotTakenExtras *Ptr = nullptr; 5714 if (!ExitCounts[i].Pred.isAlwaysTrue()) { 5715 Ptr = &ENT[PredPos++]; 5716 Ptr->Pred = std::move(ExitCounts[i].Pred); 5717 } 5718 5719 Exits.emplace_back(ExitCounts[i].ExitBlock, ExitCounts[i].Taken, Ptr); 5720 } 5721 } 5722 5723 /// Invalidate this result and free the ExitNotTakenInfo array. 5724 void ScalarEvolution::BackedgeTakenInfo::clear() { 5725 ExitNotTaken.ExitingBlock = nullptr; 5726 ExitNotTaken.ExactNotTaken = nullptr; 5727 delete[] ExitNotTaken.ExtraInfo; 5728 } 5729 5730 /// Compute the number of times the backedge of the specified loop will execute. 5731 ScalarEvolution::BackedgeTakenInfo 5732 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 5733 bool AllowPredicates) { 5734 SmallVector<BasicBlock *, 8> ExitingBlocks; 5735 L->getExitingBlocks(ExitingBlocks); 5736 5737 SmallVector<EdgeInfo, 4> ExitCounts; 5738 bool CouldComputeBECount = true; 5739 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 5740 const SCEV *MustExitMaxBECount = nullptr; 5741 const SCEV *MayExitMaxBECount = nullptr; 5742 5743 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 5744 // and compute maxBECount. 5745 // Do a union of all the predicates here. 5746 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 5747 BasicBlock *ExitBB = ExitingBlocks[i]; 5748 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 5749 5750 assert((AllowPredicates || EL.Pred.isAlwaysTrue()) && 5751 "Predicated exit limit when predicates are not allowed!"); 5752 5753 // 1. For each exit that can be computed, add an entry to ExitCounts. 5754 // CouldComputeBECount is true only if all exits can be computed. 5755 if (EL.Exact == getCouldNotCompute()) 5756 // We couldn't compute an exact value for this exit, so 5757 // we won't be able to compute an exact value for the loop. 5758 CouldComputeBECount = false; 5759 else 5760 ExitCounts.emplace_back(EdgeInfo(ExitBB, EL.Exact, EL.Pred)); 5761 5762 // 2. Derive the loop's MaxBECount from each exit's max number of 5763 // non-exiting iterations. Partition the loop exits into two kinds: 5764 // LoopMustExits and LoopMayExits. 5765 // 5766 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 5767 // is a LoopMayExit. If any computable LoopMustExit is found, then 5768 // MaxBECount is the minimum EL.Max of computable LoopMustExits. Otherwise, 5769 // MaxBECount is conservatively the maximum EL.Max, where CouldNotCompute is 5770 // considered greater than any computable EL.Max. 5771 if (EL.Max != getCouldNotCompute() && Latch && 5772 DT.dominates(ExitBB, Latch)) { 5773 if (!MustExitMaxBECount) 5774 MustExitMaxBECount = EL.Max; 5775 else { 5776 MustExitMaxBECount = 5777 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.Max); 5778 } 5779 } else if (MayExitMaxBECount != getCouldNotCompute()) { 5780 if (!MayExitMaxBECount || EL.Max == getCouldNotCompute()) 5781 MayExitMaxBECount = EL.Max; 5782 else { 5783 MayExitMaxBECount = 5784 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.Max); 5785 } 5786 } 5787 } 5788 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 5789 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 5790 return BackedgeTakenInfo(ExitCounts, CouldComputeBECount, MaxBECount); 5791 } 5792 5793 ScalarEvolution::ExitLimit 5794 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 5795 bool AllowPredicates) { 5796 5797 // Okay, we've chosen an exiting block. See what condition causes us to exit 5798 // at this block and remember the exit block and whether all other targets 5799 // lead to the loop header. 5800 bool MustExecuteLoopHeader = true; 5801 BasicBlock *Exit = nullptr; 5802 for (auto *SBB : successors(ExitingBlock)) 5803 if (!L->contains(SBB)) { 5804 if (Exit) // Multiple exit successors. 5805 return getCouldNotCompute(); 5806 Exit = SBB; 5807 } else if (SBB != L->getHeader()) { 5808 MustExecuteLoopHeader = false; 5809 } 5810 5811 // At this point, we know we have a conditional branch that determines whether 5812 // the loop is exited. However, we don't know if the branch is executed each 5813 // time through the loop. If not, then the execution count of the branch will 5814 // not be equal to the trip count of the loop. 5815 // 5816 // Currently we check for this by checking to see if the Exit branch goes to 5817 // the loop header. If so, we know it will always execute the same number of 5818 // times as the loop. We also handle the case where the exit block *is* the 5819 // loop header. This is common for un-rotated loops. 5820 // 5821 // If both of those tests fail, walk up the unique predecessor chain to the 5822 // header, stopping if there is an edge that doesn't exit the loop. If the 5823 // header is reached, the execution count of the branch will be equal to the 5824 // trip count of the loop. 5825 // 5826 // More extensive analysis could be done to handle more cases here. 5827 // 5828 if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) { 5829 // The simple checks failed, try climbing the unique predecessor chain 5830 // up to the header. 5831 bool Ok = false; 5832 for (BasicBlock *BB = ExitingBlock; BB; ) { 5833 BasicBlock *Pred = BB->getUniquePredecessor(); 5834 if (!Pred) 5835 return getCouldNotCompute(); 5836 TerminatorInst *PredTerm = Pred->getTerminator(); 5837 for (const BasicBlock *PredSucc : PredTerm->successors()) { 5838 if (PredSucc == BB) 5839 continue; 5840 // If the predecessor has a successor that isn't BB and isn't 5841 // outside the loop, assume the worst. 5842 if (L->contains(PredSucc)) 5843 return getCouldNotCompute(); 5844 } 5845 if (Pred == L->getHeader()) { 5846 Ok = true; 5847 break; 5848 } 5849 BB = Pred; 5850 } 5851 if (!Ok) 5852 return getCouldNotCompute(); 5853 } 5854 5855 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 5856 TerminatorInst *Term = ExitingBlock->getTerminator(); 5857 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 5858 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 5859 // Proceed to the next level to examine the exit condition expression. 5860 return computeExitLimitFromCond( 5861 L, BI->getCondition(), BI->getSuccessor(0), BI->getSuccessor(1), 5862 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 5863 } 5864 5865 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) 5866 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 5867 /*ControlsExit=*/IsOnlyExit); 5868 5869 return getCouldNotCompute(); 5870 } 5871 5872 ScalarEvolution::ExitLimit 5873 ScalarEvolution::computeExitLimitFromCond(const Loop *L, 5874 Value *ExitCond, 5875 BasicBlock *TBB, 5876 BasicBlock *FBB, 5877 bool ControlsExit, 5878 bool AllowPredicates) { 5879 // Check if the controlling expression for this loop is an And or Or. 5880 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) { 5881 if (BO->getOpcode() == Instruction::And) { 5882 // Recurse on the operands of the and. 5883 bool EitherMayExit = L->contains(TBB); 5884 ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB, 5885 ControlsExit && !EitherMayExit, 5886 AllowPredicates); 5887 ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB, 5888 ControlsExit && !EitherMayExit, 5889 AllowPredicates); 5890 const SCEV *BECount = getCouldNotCompute(); 5891 const SCEV *MaxBECount = getCouldNotCompute(); 5892 if (EitherMayExit) { 5893 // Both conditions must be true for the loop to continue executing. 5894 // Choose the less conservative count. 5895 if (EL0.Exact == getCouldNotCompute() || 5896 EL1.Exact == getCouldNotCompute()) 5897 BECount = getCouldNotCompute(); 5898 else 5899 BECount = getUMinFromMismatchedTypes(EL0.Exact, EL1.Exact); 5900 if (EL0.Max == getCouldNotCompute()) 5901 MaxBECount = EL1.Max; 5902 else if (EL1.Max == getCouldNotCompute()) 5903 MaxBECount = EL0.Max; 5904 else 5905 MaxBECount = getUMinFromMismatchedTypes(EL0.Max, EL1.Max); 5906 } else { 5907 // Both conditions must be true at the same time for the loop to exit. 5908 // For now, be conservative. 5909 assert(L->contains(FBB) && "Loop block has no successor in loop!"); 5910 if (EL0.Max == EL1.Max) 5911 MaxBECount = EL0.Max; 5912 if (EL0.Exact == EL1.Exact) 5913 BECount = EL0.Exact; 5914 } 5915 5916 SCEVUnionPredicate NP; 5917 NP.add(&EL0.Pred); 5918 NP.add(&EL1.Pred); 5919 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 5920 // to be more aggressive when computing BECount than when computing 5921 // MaxBECount. In these cases it is possible for EL0.Exact and EL1.Exact 5922 // to match, but for EL0.Max and EL1.Max to not. 5923 if (isa<SCEVCouldNotCompute>(MaxBECount) && 5924 !isa<SCEVCouldNotCompute>(BECount)) 5925 MaxBECount = BECount; 5926 5927 return ExitLimit(BECount, MaxBECount, NP); 5928 } 5929 if (BO->getOpcode() == Instruction::Or) { 5930 // Recurse on the operands of the or. 5931 bool EitherMayExit = L->contains(FBB); 5932 ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB, 5933 ControlsExit && !EitherMayExit, 5934 AllowPredicates); 5935 ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB, 5936 ControlsExit && !EitherMayExit, 5937 AllowPredicates); 5938 const SCEV *BECount = getCouldNotCompute(); 5939 const SCEV *MaxBECount = getCouldNotCompute(); 5940 if (EitherMayExit) { 5941 // Both conditions must be false for the loop to continue executing. 5942 // Choose the less conservative count. 5943 if (EL0.Exact == getCouldNotCompute() || 5944 EL1.Exact == getCouldNotCompute()) 5945 BECount = getCouldNotCompute(); 5946 else 5947 BECount = getUMinFromMismatchedTypes(EL0.Exact, EL1.Exact); 5948 if (EL0.Max == getCouldNotCompute()) 5949 MaxBECount = EL1.Max; 5950 else if (EL1.Max == getCouldNotCompute()) 5951 MaxBECount = EL0.Max; 5952 else 5953 MaxBECount = getUMinFromMismatchedTypes(EL0.Max, EL1.Max); 5954 } else { 5955 // Both conditions must be false at the same time for the loop to exit. 5956 // For now, be conservative. 5957 assert(L->contains(TBB) && "Loop block has no successor in loop!"); 5958 if (EL0.Max == EL1.Max) 5959 MaxBECount = EL0.Max; 5960 if (EL0.Exact == EL1.Exact) 5961 BECount = EL0.Exact; 5962 } 5963 5964 SCEVUnionPredicate NP; 5965 NP.add(&EL0.Pred); 5966 NP.add(&EL1.Pred); 5967 return ExitLimit(BECount, MaxBECount, NP); 5968 } 5969 } 5970 5971 // With an icmp, it may be feasible to compute an exact backedge-taken count. 5972 // Proceed to the next level to examine the icmp. 5973 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 5974 ExitLimit EL = 5975 computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit); 5976 if (EL.hasFullInfo() || !AllowPredicates) 5977 return EL; 5978 5979 // Try again, but use SCEV predicates this time. 5980 return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit, 5981 /*AllowPredicates=*/true); 5982 } 5983 5984 // Check for a constant condition. These are normally stripped out by 5985 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 5986 // preserve the CFG and is temporarily leaving constant conditions 5987 // in place. 5988 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 5989 if (L->contains(FBB) == !CI->getZExtValue()) 5990 // The backedge is always taken. 5991 return getCouldNotCompute(); 5992 else 5993 // The backedge is never taken. 5994 return getZero(CI->getType()); 5995 } 5996 5997 // If it's not an integer or pointer comparison then compute it the hard way. 5998 return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB)); 5999 } 6000 6001 ScalarEvolution::ExitLimit 6002 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 6003 ICmpInst *ExitCond, 6004 BasicBlock *TBB, 6005 BasicBlock *FBB, 6006 bool ControlsExit, 6007 bool AllowPredicates) { 6008 6009 // If the condition was exit on true, convert the condition to exit on false 6010 ICmpInst::Predicate Cond; 6011 if (!L->contains(FBB)) 6012 Cond = ExitCond->getPredicate(); 6013 else 6014 Cond = ExitCond->getInversePredicate(); 6015 6016 // Handle common loops like: for (X = "string"; *X; ++X) 6017 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 6018 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 6019 ExitLimit ItCnt = 6020 computeLoadConstantCompareExitLimit(LI, RHS, L, Cond); 6021 if (ItCnt.hasAnyInfo()) 6022 return ItCnt; 6023 } 6024 6025 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 6026 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 6027 6028 // Try to evaluate any dependencies out of the loop. 6029 LHS = getSCEVAtScope(LHS, L); 6030 RHS = getSCEVAtScope(RHS, L); 6031 6032 // At this point, we would like to compute how many iterations of the 6033 // loop the predicate will return true for these inputs. 6034 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 6035 // If there is a loop-invariant, force it into the RHS. 6036 std::swap(LHS, RHS); 6037 Cond = ICmpInst::getSwappedPredicate(Cond); 6038 } 6039 6040 // Simplify the operands before analyzing them. 6041 (void)SimplifyICmpOperands(Cond, LHS, RHS); 6042 6043 // If we have a comparison of a chrec against a constant, try to use value 6044 // ranges to answer this query. 6045 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 6046 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 6047 if (AddRec->getLoop() == L) { 6048 // Form the constant range. 6049 ConstantRange CompRange( 6050 ICmpInst::makeConstantRange(Cond, RHSC->getAPInt())); 6051 6052 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 6053 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 6054 } 6055 6056 switch (Cond) { 6057 case ICmpInst::ICMP_NE: { // while (X != Y) 6058 // Convert to: while (X-Y != 0) 6059 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 6060 AllowPredicates); 6061 if (EL.hasAnyInfo()) return EL; 6062 break; 6063 } 6064 case ICmpInst::ICMP_EQ: { // while (X == Y) 6065 // Convert to: while (X-Y == 0) 6066 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 6067 if (EL.hasAnyInfo()) return EL; 6068 break; 6069 } 6070 case ICmpInst::ICMP_SLT: 6071 case ICmpInst::ICMP_ULT: { // while (X < Y) 6072 bool IsSigned = Cond == ICmpInst::ICMP_SLT; 6073 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 6074 AllowPredicates); 6075 if (EL.hasAnyInfo()) return EL; 6076 break; 6077 } 6078 case ICmpInst::ICMP_SGT: 6079 case ICmpInst::ICMP_UGT: { // while (X > Y) 6080 bool IsSigned = Cond == ICmpInst::ICMP_SGT; 6081 ExitLimit EL = 6082 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 6083 AllowPredicates); 6084 if (EL.hasAnyInfo()) return EL; 6085 break; 6086 } 6087 default: 6088 break; 6089 } 6090 6091 auto *ExhaustiveCount = 6092 computeExitCountExhaustively(L, ExitCond, !L->contains(TBB)); 6093 6094 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 6095 return ExhaustiveCount; 6096 6097 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 6098 ExitCond->getOperand(1), L, Cond); 6099 } 6100 6101 ScalarEvolution::ExitLimit 6102 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 6103 SwitchInst *Switch, 6104 BasicBlock *ExitingBlock, 6105 bool ControlsExit) { 6106 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 6107 6108 // Give up if the exit is the default dest of a switch. 6109 if (Switch->getDefaultDest() == ExitingBlock) 6110 return getCouldNotCompute(); 6111 6112 assert(L->contains(Switch->getDefaultDest()) && 6113 "Default case must not exit the loop!"); 6114 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 6115 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 6116 6117 // while (X != Y) --> while (X-Y != 0) 6118 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 6119 if (EL.hasAnyInfo()) 6120 return EL; 6121 6122 return getCouldNotCompute(); 6123 } 6124 6125 static ConstantInt * 6126 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 6127 ScalarEvolution &SE) { 6128 const SCEV *InVal = SE.getConstant(C); 6129 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 6130 assert(isa<SCEVConstant>(Val) && 6131 "Evaluation of SCEV at constant didn't fold correctly?"); 6132 return cast<SCEVConstant>(Val)->getValue(); 6133 } 6134 6135 /// Given an exit condition of 'icmp op load X, cst', try to see if we can 6136 /// compute the backedge execution count. 6137 ScalarEvolution::ExitLimit 6138 ScalarEvolution::computeLoadConstantCompareExitLimit( 6139 LoadInst *LI, 6140 Constant *RHS, 6141 const Loop *L, 6142 ICmpInst::Predicate predicate) { 6143 6144 if (LI->isVolatile()) return getCouldNotCompute(); 6145 6146 // Check to see if the loaded pointer is a getelementptr of a global. 6147 // TODO: Use SCEV instead of manually grubbing with GEPs. 6148 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 6149 if (!GEP) return getCouldNotCompute(); 6150 6151 // Make sure that it is really a constant global we are gepping, with an 6152 // initializer, and make sure the first IDX is really 0. 6153 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 6154 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || 6155 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 6156 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 6157 return getCouldNotCompute(); 6158 6159 // Okay, we allow one non-constant index into the GEP instruction. 6160 Value *VarIdx = nullptr; 6161 std::vector<Constant*> Indexes; 6162 unsigned VarIdxNum = 0; 6163 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 6164 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 6165 Indexes.push_back(CI); 6166 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 6167 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. 6168 VarIdx = GEP->getOperand(i); 6169 VarIdxNum = i-2; 6170 Indexes.push_back(nullptr); 6171 } 6172 6173 // Loop-invariant loads may be a byproduct of loop optimization. Skip them. 6174 if (!VarIdx) 6175 return getCouldNotCompute(); 6176 6177 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 6178 // Check to see if X is a loop variant variable value now. 6179 const SCEV *Idx = getSCEV(VarIdx); 6180 Idx = getSCEVAtScope(Idx, L); 6181 6182 // We can only recognize very limited forms of loop index expressions, in 6183 // particular, only affine AddRec's like {C1,+,C2}. 6184 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 6185 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) || 6186 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 6187 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 6188 return getCouldNotCompute(); 6189 6190 unsigned MaxSteps = MaxBruteForceIterations; 6191 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 6192 ConstantInt *ItCst = ConstantInt::get( 6193 cast<IntegerType>(IdxExpr->getType()), IterationNum); 6194 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 6195 6196 // Form the GEP offset. 6197 Indexes[VarIdxNum] = Val; 6198 6199 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), 6200 Indexes); 6201 if (!Result) break; // Cannot compute! 6202 6203 // Evaluate the condition for this iteration. 6204 Result = ConstantExpr::getICmp(predicate, Result, RHS); 6205 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 6206 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 6207 ++NumArrayLenItCounts; 6208 return getConstant(ItCst); // Found terminating iteration! 6209 } 6210 } 6211 return getCouldNotCompute(); 6212 } 6213 6214 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 6215 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 6216 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 6217 if (!RHS) 6218 return getCouldNotCompute(); 6219 6220 const BasicBlock *Latch = L->getLoopLatch(); 6221 if (!Latch) 6222 return getCouldNotCompute(); 6223 6224 const BasicBlock *Predecessor = L->getLoopPredecessor(); 6225 if (!Predecessor) 6226 return getCouldNotCompute(); 6227 6228 // Return true if V is of the form "LHS `shift_op` <positive constant>". 6229 // Return LHS in OutLHS and shift_opt in OutOpCode. 6230 auto MatchPositiveShift = 6231 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 6232 6233 using namespace PatternMatch; 6234 6235 ConstantInt *ShiftAmt; 6236 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 6237 OutOpCode = Instruction::LShr; 6238 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 6239 OutOpCode = Instruction::AShr; 6240 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 6241 OutOpCode = Instruction::Shl; 6242 else 6243 return false; 6244 6245 return ShiftAmt->getValue().isStrictlyPositive(); 6246 }; 6247 6248 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 6249 // 6250 // loop: 6251 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 6252 // %iv.shifted = lshr i32 %iv, <positive constant> 6253 // 6254 // Return true on a succesful match. Return the corresponding PHI node (%iv 6255 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 6256 auto MatchShiftRecurrence = 6257 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 6258 Optional<Instruction::BinaryOps> PostShiftOpCode; 6259 6260 { 6261 Instruction::BinaryOps OpC; 6262 Value *V; 6263 6264 // If we encounter a shift instruction, "peel off" the shift operation, 6265 // and remember that we did so. Later when we inspect %iv's backedge 6266 // value, we will make sure that the backedge value uses the same 6267 // operation. 6268 // 6269 // Note: the peeled shift operation does not have to be the same 6270 // instruction as the one feeding into the PHI's backedge value. We only 6271 // really care about it being the same *kind* of shift instruction -- 6272 // that's all that is required for our later inferences to hold. 6273 if (MatchPositiveShift(LHS, V, OpC)) { 6274 PostShiftOpCode = OpC; 6275 LHS = V; 6276 } 6277 } 6278 6279 PNOut = dyn_cast<PHINode>(LHS); 6280 if (!PNOut || PNOut->getParent() != L->getHeader()) 6281 return false; 6282 6283 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 6284 Value *OpLHS; 6285 6286 return 6287 // The backedge value for the PHI node must be a shift by a positive 6288 // amount 6289 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 6290 6291 // of the PHI node itself 6292 OpLHS == PNOut && 6293 6294 // and the kind of shift should be match the kind of shift we peeled 6295 // off, if any. 6296 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 6297 }; 6298 6299 PHINode *PN; 6300 Instruction::BinaryOps OpCode; 6301 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 6302 return getCouldNotCompute(); 6303 6304 const DataLayout &DL = getDataLayout(); 6305 6306 // The key rationale for this optimization is that for some kinds of shift 6307 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 6308 // within a finite number of iterations. If the condition guarding the 6309 // backedge (in the sense that the backedge is taken if the condition is true) 6310 // is false for the value the shift recurrence stabilizes to, then we know 6311 // that the backedge is taken only a finite number of times. 6312 6313 ConstantInt *StableValue = nullptr; 6314 switch (OpCode) { 6315 default: 6316 llvm_unreachable("Impossible case!"); 6317 6318 case Instruction::AShr: { 6319 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 6320 // bitwidth(K) iterations. 6321 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 6322 bool KnownZero, KnownOne; 6323 ComputeSignBit(FirstValue, KnownZero, KnownOne, DL, 0, nullptr, 6324 Predecessor->getTerminator(), &DT); 6325 auto *Ty = cast<IntegerType>(RHS->getType()); 6326 if (KnownZero) 6327 StableValue = ConstantInt::get(Ty, 0); 6328 else if (KnownOne) 6329 StableValue = ConstantInt::get(Ty, -1, true); 6330 else 6331 return getCouldNotCompute(); 6332 6333 break; 6334 } 6335 case Instruction::LShr: 6336 case Instruction::Shl: 6337 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 6338 // stabilize to 0 in at most bitwidth(K) iterations. 6339 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 6340 break; 6341 } 6342 6343 auto *Result = 6344 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 6345 assert(Result->getType()->isIntegerTy(1) && 6346 "Otherwise cannot be an operand to a branch instruction"); 6347 6348 if (Result->isZeroValue()) { 6349 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 6350 const SCEV *UpperBound = 6351 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 6352 SCEVUnionPredicate P; 6353 return ExitLimit(getCouldNotCompute(), UpperBound, P); 6354 } 6355 6356 return getCouldNotCompute(); 6357 } 6358 6359 /// Return true if we can constant fold an instruction of the specified type, 6360 /// assuming that all operands were constants. 6361 static bool CanConstantFold(const Instruction *I) { 6362 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 6363 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 6364 isa<LoadInst>(I)) 6365 return true; 6366 6367 if (const CallInst *CI = dyn_cast<CallInst>(I)) 6368 if (const Function *F = CI->getCalledFunction()) 6369 return canConstantFoldCallTo(F); 6370 return false; 6371 } 6372 6373 /// Determine whether this instruction can constant evolve within this loop 6374 /// assuming its operands can all constant evolve. 6375 static bool canConstantEvolve(Instruction *I, const Loop *L) { 6376 // An instruction outside of the loop can't be derived from a loop PHI. 6377 if (!L->contains(I)) return false; 6378 6379 if (isa<PHINode>(I)) { 6380 // We don't currently keep track of the control flow needed to evaluate 6381 // PHIs, so we cannot handle PHIs inside of loops. 6382 return L->getHeader() == I->getParent(); 6383 } 6384 6385 // If we won't be able to constant fold this expression even if the operands 6386 // are constants, bail early. 6387 return CanConstantFold(I); 6388 } 6389 6390 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 6391 /// recursing through each instruction operand until reaching a loop header phi. 6392 static PHINode * 6393 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 6394 DenseMap<Instruction *, PHINode *> &PHIMap) { 6395 6396 // Otherwise, we can evaluate this instruction if all of its operands are 6397 // constant or derived from a PHI node themselves. 6398 PHINode *PHI = nullptr; 6399 for (Value *Op : UseInst->operands()) { 6400 if (isa<Constant>(Op)) continue; 6401 6402 Instruction *OpInst = dyn_cast<Instruction>(Op); 6403 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 6404 6405 PHINode *P = dyn_cast<PHINode>(OpInst); 6406 if (!P) 6407 // If this operand is already visited, reuse the prior result. 6408 // We may have P != PHI if this is the deepest point at which the 6409 // inconsistent paths meet. 6410 P = PHIMap.lookup(OpInst); 6411 if (!P) { 6412 // Recurse and memoize the results, whether a phi is found or not. 6413 // This recursive call invalidates pointers into PHIMap. 6414 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap); 6415 PHIMap[OpInst] = P; 6416 } 6417 if (!P) 6418 return nullptr; // Not evolving from PHI 6419 if (PHI && PHI != P) 6420 return nullptr; // Evolving from multiple different PHIs. 6421 PHI = P; 6422 } 6423 // This is a expression evolving from a constant PHI! 6424 return PHI; 6425 } 6426 6427 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 6428 /// in the loop that V is derived from. We allow arbitrary operations along the 6429 /// way, but the operands of an operation must either be constants or a value 6430 /// derived from a constant PHI. If this expression does not fit with these 6431 /// constraints, return null. 6432 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 6433 Instruction *I = dyn_cast<Instruction>(V); 6434 if (!I || !canConstantEvolve(I, L)) return nullptr; 6435 6436 if (PHINode *PN = dyn_cast<PHINode>(I)) 6437 return PN; 6438 6439 // Record non-constant instructions contained by the loop. 6440 DenseMap<Instruction *, PHINode *> PHIMap; 6441 return getConstantEvolvingPHIOperands(I, L, PHIMap); 6442 } 6443 6444 /// EvaluateExpression - Given an expression that passes the 6445 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 6446 /// in the loop has the value PHIVal. If we can't fold this expression for some 6447 /// reason, return null. 6448 static Constant *EvaluateExpression(Value *V, const Loop *L, 6449 DenseMap<Instruction *, Constant *> &Vals, 6450 const DataLayout &DL, 6451 const TargetLibraryInfo *TLI) { 6452 // Convenient constant check, but redundant for recursive calls. 6453 if (Constant *C = dyn_cast<Constant>(V)) return C; 6454 Instruction *I = dyn_cast<Instruction>(V); 6455 if (!I) return nullptr; 6456 6457 if (Constant *C = Vals.lookup(I)) return C; 6458 6459 // An instruction inside the loop depends on a value outside the loop that we 6460 // weren't given a mapping for, or a value such as a call inside the loop. 6461 if (!canConstantEvolve(I, L)) return nullptr; 6462 6463 // An unmapped PHI can be due to a branch or another loop inside this loop, 6464 // or due to this not being the initial iteration through a loop where we 6465 // couldn't compute the evolution of this particular PHI last time. 6466 if (isa<PHINode>(I)) return nullptr; 6467 6468 std::vector<Constant*> Operands(I->getNumOperands()); 6469 6470 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 6471 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 6472 if (!Operand) { 6473 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 6474 if (!Operands[i]) return nullptr; 6475 continue; 6476 } 6477 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 6478 Vals[Operand] = C; 6479 if (!C) return nullptr; 6480 Operands[i] = C; 6481 } 6482 6483 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 6484 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 6485 Operands[1], DL, TLI); 6486 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 6487 if (!LI->isVolatile()) 6488 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 6489 } 6490 return ConstantFoldInstOperands(I, Operands, DL, TLI); 6491 } 6492 6493 6494 // If every incoming value to PN except the one for BB is a specific Constant, 6495 // return that, else return nullptr. 6496 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 6497 Constant *IncomingVal = nullptr; 6498 6499 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 6500 if (PN->getIncomingBlock(i) == BB) 6501 continue; 6502 6503 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 6504 if (!CurrentVal) 6505 return nullptr; 6506 6507 if (IncomingVal != CurrentVal) { 6508 if (IncomingVal) 6509 return nullptr; 6510 IncomingVal = CurrentVal; 6511 } 6512 } 6513 6514 return IncomingVal; 6515 } 6516 6517 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 6518 /// in the header of its containing loop, we know the loop executes a 6519 /// constant number of times, and the PHI node is just a recurrence 6520 /// involving constants, fold it. 6521 Constant * 6522 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 6523 const APInt &BEs, 6524 const Loop *L) { 6525 auto I = ConstantEvolutionLoopExitValue.find(PN); 6526 if (I != ConstantEvolutionLoopExitValue.end()) 6527 return I->second; 6528 6529 if (BEs.ugt(MaxBruteForceIterations)) 6530 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 6531 6532 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 6533 6534 DenseMap<Instruction *, Constant *> CurrentIterVals; 6535 BasicBlock *Header = L->getHeader(); 6536 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 6537 6538 BasicBlock *Latch = L->getLoopLatch(); 6539 if (!Latch) 6540 return nullptr; 6541 6542 for (auto &I : *Header) { 6543 PHINode *PHI = dyn_cast<PHINode>(&I); 6544 if (!PHI) break; 6545 auto *StartCST = getOtherIncomingValue(PHI, Latch); 6546 if (!StartCST) continue; 6547 CurrentIterVals[PHI] = StartCST; 6548 } 6549 if (!CurrentIterVals.count(PN)) 6550 return RetVal = nullptr; 6551 6552 Value *BEValue = PN->getIncomingValueForBlock(Latch); 6553 6554 // Execute the loop symbolically to determine the exit value. 6555 if (BEs.getActiveBits() >= 32) 6556 return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it! 6557 6558 unsigned NumIterations = BEs.getZExtValue(); // must be in range 6559 unsigned IterationNum = 0; 6560 const DataLayout &DL = getDataLayout(); 6561 for (; ; ++IterationNum) { 6562 if (IterationNum == NumIterations) 6563 return RetVal = CurrentIterVals[PN]; // Got exit value! 6564 6565 // Compute the value of the PHIs for the next iteration. 6566 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 6567 DenseMap<Instruction *, Constant *> NextIterVals; 6568 Constant *NextPHI = 6569 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 6570 if (!NextPHI) 6571 return nullptr; // Couldn't evaluate! 6572 NextIterVals[PN] = NextPHI; 6573 6574 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 6575 6576 // Also evaluate the other PHI nodes. However, we don't get to stop if we 6577 // cease to be able to evaluate one of them or if they stop evolving, 6578 // because that doesn't necessarily prevent us from computing PN. 6579 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 6580 for (const auto &I : CurrentIterVals) { 6581 PHINode *PHI = dyn_cast<PHINode>(I.first); 6582 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 6583 PHIsToCompute.emplace_back(PHI, I.second); 6584 } 6585 // We use two distinct loops because EvaluateExpression may invalidate any 6586 // iterators into CurrentIterVals. 6587 for (const auto &I : PHIsToCompute) { 6588 PHINode *PHI = I.first; 6589 Constant *&NextPHI = NextIterVals[PHI]; 6590 if (!NextPHI) { // Not already computed. 6591 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 6592 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 6593 } 6594 if (NextPHI != I.second) 6595 StoppedEvolving = false; 6596 } 6597 6598 // If all entries in CurrentIterVals == NextIterVals then we can stop 6599 // iterating, the loop can't continue to change. 6600 if (StoppedEvolving) 6601 return RetVal = CurrentIterVals[PN]; 6602 6603 CurrentIterVals.swap(NextIterVals); 6604 } 6605 } 6606 6607 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 6608 Value *Cond, 6609 bool ExitWhen) { 6610 PHINode *PN = getConstantEvolvingPHI(Cond, L); 6611 if (!PN) return getCouldNotCompute(); 6612 6613 // If the loop is canonicalized, the PHI will have exactly two entries. 6614 // That's the only form we support here. 6615 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 6616 6617 DenseMap<Instruction *, Constant *> CurrentIterVals; 6618 BasicBlock *Header = L->getHeader(); 6619 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 6620 6621 BasicBlock *Latch = L->getLoopLatch(); 6622 assert(Latch && "Should follow from NumIncomingValues == 2!"); 6623 6624 for (auto &I : *Header) { 6625 PHINode *PHI = dyn_cast<PHINode>(&I); 6626 if (!PHI) 6627 break; 6628 auto *StartCST = getOtherIncomingValue(PHI, Latch); 6629 if (!StartCST) continue; 6630 CurrentIterVals[PHI] = StartCST; 6631 } 6632 if (!CurrentIterVals.count(PN)) 6633 return getCouldNotCompute(); 6634 6635 // Okay, we find a PHI node that defines the trip count of this loop. Execute 6636 // the loop symbolically to determine when the condition gets a value of 6637 // "ExitWhen". 6638 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 6639 const DataLayout &DL = getDataLayout(); 6640 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 6641 auto *CondVal = dyn_cast_or_null<ConstantInt>( 6642 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 6643 6644 // Couldn't symbolically evaluate. 6645 if (!CondVal) return getCouldNotCompute(); 6646 6647 if (CondVal->getValue() == uint64_t(ExitWhen)) { 6648 ++NumBruteForceTripCountsComputed; 6649 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 6650 } 6651 6652 // Update all the PHI nodes for the next iteration. 6653 DenseMap<Instruction *, Constant *> NextIterVals; 6654 6655 // Create a list of which PHIs we need to compute. We want to do this before 6656 // calling EvaluateExpression on them because that may invalidate iterators 6657 // into CurrentIterVals. 6658 SmallVector<PHINode *, 8> PHIsToCompute; 6659 for (const auto &I : CurrentIterVals) { 6660 PHINode *PHI = dyn_cast<PHINode>(I.first); 6661 if (!PHI || PHI->getParent() != Header) continue; 6662 PHIsToCompute.push_back(PHI); 6663 } 6664 for (PHINode *PHI : PHIsToCompute) { 6665 Constant *&NextPHI = NextIterVals[PHI]; 6666 if (NextPHI) continue; // Already computed! 6667 6668 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 6669 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 6670 } 6671 CurrentIterVals.swap(NextIterVals); 6672 } 6673 6674 // Too many iterations were needed to evaluate. 6675 return getCouldNotCompute(); 6676 } 6677 6678 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 6679 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 6680 ValuesAtScopes[V]; 6681 // Check to see if we've folded this expression at this loop before. 6682 for (auto &LS : Values) 6683 if (LS.first == L) 6684 return LS.second ? LS.second : V; 6685 6686 Values.emplace_back(L, nullptr); 6687 6688 // Otherwise compute it. 6689 const SCEV *C = computeSCEVAtScope(V, L); 6690 for (auto &LS : reverse(ValuesAtScopes[V])) 6691 if (LS.first == L) { 6692 LS.second = C; 6693 break; 6694 } 6695 return C; 6696 } 6697 6698 /// This builds up a Constant using the ConstantExpr interface. That way, we 6699 /// will return Constants for objects which aren't represented by a 6700 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 6701 /// Returns NULL if the SCEV isn't representable as a Constant. 6702 static Constant *BuildConstantFromSCEV(const SCEV *V) { 6703 switch (static_cast<SCEVTypes>(V->getSCEVType())) { 6704 case scCouldNotCompute: 6705 case scAddRecExpr: 6706 break; 6707 case scConstant: 6708 return cast<SCEVConstant>(V)->getValue(); 6709 case scUnknown: 6710 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 6711 case scSignExtend: { 6712 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 6713 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 6714 return ConstantExpr::getSExt(CastOp, SS->getType()); 6715 break; 6716 } 6717 case scZeroExtend: { 6718 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 6719 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 6720 return ConstantExpr::getZExt(CastOp, SZ->getType()); 6721 break; 6722 } 6723 case scTruncate: { 6724 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 6725 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 6726 return ConstantExpr::getTrunc(CastOp, ST->getType()); 6727 break; 6728 } 6729 case scAddExpr: { 6730 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 6731 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 6732 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 6733 unsigned AS = PTy->getAddressSpace(); 6734 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 6735 C = ConstantExpr::getBitCast(C, DestPtrTy); 6736 } 6737 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 6738 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 6739 if (!C2) return nullptr; 6740 6741 // First pointer! 6742 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 6743 unsigned AS = C2->getType()->getPointerAddressSpace(); 6744 std::swap(C, C2); 6745 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 6746 // The offsets have been converted to bytes. We can add bytes to an 6747 // i8* by GEP with the byte count in the first index. 6748 C = ConstantExpr::getBitCast(C, DestPtrTy); 6749 } 6750 6751 // Don't bother trying to sum two pointers. We probably can't 6752 // statically compute a load that results from it anyway. 6753 if (C2->getType()->isPointerTy()) 6754 return nullptr; 6755 6756 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 6757 if (PTy->getElementType()->isStructTy()) 6758 C2 = ConstantExpr::getIntegerCast( 6759 C2, Type::getInt32Ty(C->getContext()), true); 6760 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); 6761 } else 6762 C = ConstantExpr::getAdd(C, C2); 6763 } 6764 return C; 6765 } 6766 break; 6767 } 6768 case scMulExpr: { 6769 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 6770 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 6771 // Don't bother with pointers at all. 6772 if (C->getType()->isPointerTy()) return nullptr; 6773 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 6774 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 6775 if (!C2 || C2->getType()->isPointerTy()) return nullptr; 6776 C = ConstantExpr::getMul(C, C2); 6777 } 6778 return C; 6779 } 6780 break; 6781 } 6782 case scUDivExpr: { 6783 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 6784 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 6785 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 6786 if (LHS->getType() == RHS->getType()) 6787 return ConstantExpr::getUDiv(LHS, RHS); 6788 break; 6789 } 6790 case scSMaxExpr: 6791 case scUMaxExpr: 6792 break; // TODO: smax, umax. 6793 } 6794 return nullptr; 6795 } 6796 6797 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 6798 if (isa<SCEVConstant>(V)) return V; 6799 6800 // If this instruction is evolved from a constant-evolving PHI, compute the 6801 // exit value from the loop without using SCEVs. 6802 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 6803 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 6804 const Loop *LI = this->LI[I->getParent()]; 6805 if (LI && LI->getParentLoop() == L) // Looking for loop exit value. 6806 if (PHINode *PN = dyn_cast<PHINode>(I)) 6807 if (PN->getParent() == LI->getHeader()) { 6808 // Okay, there is no closed form solution for the PHI node. Check 6809 // to see if the loop that contains it has a known backedge-taken 6810 // count. If so, we may be able to force computation of the exit 6811 // value. 6812 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI); 6813 if (const SCEVConstant *BTCC = 6814 dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 6815 // Okay, we know how many times the containing loop executes. If 6816 // this is a constant evolving PHI node, get the final value at 6817 // the specified iteration number. 6818 Constant *RV = 6819 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI); 6820 if (RV) return getSCEV(RV); 6821 } 6822 } 6823 6824 // Okay, this is an expression that we cannot symbolically evaluate 6825 // into a SCEV. Check to see if it's possible to symbolically evaluate 6826 // the arguments into constants, and if so, try to constant propagate the 6827 // result. This is particularly useful for computing loop exit values. 6828 if (CanConstantFold(I)) { 6829 SmallVector<Constant *, 4> Operands; 6830 bool MadeImprovement = false; 6831 for (Value *Op : I->operands()) { 6832 if (Constant *C = dyn_cast<Constant>(Op)) { 6833 Operands.push_back(C); 6834 continue; 6835 } 6836 6837 // If any of the operands is non-constant and if they are 6838 // non-integer and non-pointer, don't even try to analyze them 6839 // with scev techniques. 6840 if (!isSCEVable(Op->getType())) 6841 return V; 6842 6843 const SCEV *OrigV = getSCEV(Op); 6844 const SCEV *OpV = getSCEVAtScope(OrigV, L); 6845 MadeImprovement |= OrigV != OpV; 6846 6847 Constant *C = BuildConstantFromSCEV(OpV); 6848 if (!C) return V; 6849 if (C->getType() != Op->getType()) 6850 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 6851 Op->getType(), 6852 false), 6853 C, Op->getType()); 6854 Operands.push_back(C); 6855 } 6856 6857 // Check to see if getSCEVAtScope actually made an improvement. 6858 if (MadeImprovement) { 6859 Constant *C = nullptr; 6860 const DataLayout &DL = getDataLayout(); 6861 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 6862 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 6863 Operands[1], DL, &TLI); 6864 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) { 6865 if (!LI->isVolatile()) 6866 C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 6867 } else 6868 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 6869 if (!C) return V; 6870 return getSCEV(C); 6871 } 6872 } 6873 } 6874 6875 // This is some other type of SCEVUnknown, just return it. 6876 return V; 6877 } 6878 6879 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 6880 // Avoid performing the look-up in the common case where the specified 6881 // expression has no loop-variant portions. 6882 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 6883 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 6884 if (OpAtScope != Comm->getOperand(i)) { 6885 // Okay, at least one of these operands is loop variant but might be 6886 // foldable. Build a new instance of the folded commutative expression. 6887 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 6888 Comm->op_begin()+i); 6889 NewOps.push_back(OpAtScope); 6890 6891 for (++i; i != e; ++i) { 6892 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 6893 NewOps.push_back(OpAtScope); 6894 } 6895 if (isa<SCEVAddExpr>(Comm)) 6896 return getAddExpr(NewOps); 6897 if (isa<SCEVMulExpr>(Comm)) 6898 return getMulExpr(NewOps); 6899 if (isa<SCEVSMaxExpr>(Comm)) 6900 return getSMaxExpr(NewOps); 6901 if (isa<SCEVUMaxExpr>(Comm)) 6902 return getUMaxExpr(NewOps); 6903 llvm_unreachable("Unknown commutative SCEV type!"); 6904 } 6905 } 6906 // If we got here, all operands are loop invariant. 6907 return Comm; 6908 } 6909 6910 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 6911 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 6912 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 6913 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 6914 return Div; // must be loop invariant 6915 return getUDivExpr(LHS, RHS); 6916 } 6917 6918 // If this is a loop recurrence for a loop that does not contain L, then we 6919 // are dealing with the final value computed by the loop. 6920 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 6921 // First, attempt to evaluate each operand. 6922 // Avoid performing the look-up in the common case where the specified 6923 // expression has no loop-variant portions. 6924 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 6925 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 6926 if (OpAtScope == AddRec->getOperand(i)) 6927 continue; 6928 6929 // Okay, at least one of these operands is loop variant but might be 6930 // foldable. Build a new instance of the folded commutative expression. 6931 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 6932 AddRec->op_begin()+i); 6933 NewOps.push_back(OpAtScope); 6934 for (++i; i != e; ++i) 6935 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 6936 6937 const SCEV *FoldedRec = 6938 getAddRecExpr(NewOps, AddRec->getLoop(), 6939 AddRec->getNoWrapFlags(SCEV::FlagNW)); 6940 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 6941 // The addrec may be folded to a nonrecurrence, for example, if the 6942 // induction variable is multiplied by zero after constant folding. Go 6943 // ahead and return the folded value. 6944 if (!AddRec) 6945 return FoldedRec; 6946 break; 6947 } 6948 6949 // If the scope is outside the addrec's loop, evaluate it by using the 6950 // loop exit value of the addrec. 6951 if (!AddRec->getLoop()->contains(L)) { 6952 // To evaluate this recurrence, we need to know how many times the AddRec 6953 // loop iterates. Compute this now. 6954 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 6955 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 6956 6957 // Then, evaluate the AddRec. 6958 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 6959 } 6960 6961 return AddRec; 6962 } 6963 6964 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 6965 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 6966 if (Op == Cast->getOperand()) 6967 return Cast; // must be loop invariant 6968 return getZeroExtendExpr(Op, Cast->getType()); 6969 } 6970 6971 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 6972 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 6973 if (Op == Cast->getOperand()) 6974 return Cast; // must be loop invariant 6975 return getSignExtendExpr(Op, Cast->getType()); 6976 } 6977 6978 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 6979 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 6980 if (Op == Cast->getOperand()) 6981 return Cast; // must be loop invariant 6982 return getTruncateExpr(Op, Cast->getType()); 6983 } 6984 6985 llvm_unreachable("Unknown SCEV type!"); 6986 } 6987 6988 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 6989 return getSCEVAtScope(getSCEV(V), L); 6990 } 6991 6992 /// Finds the minimum unsigned root of the following equation: 6993 /// 6994 /// A * X = B (mod N) 6995 /// 6996 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 6997 /// A and B isn't important. 6998 /// 6999 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 7000 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B, 7001 ScalarEvolution &SE) { 7002 uint32_t BW = A.getBitWidth(); 7003 assert(BW == B.getBitWidth() && "Bit widths must be the same."); 7004 assert(A != 0 && "A must be non-zero."); 7005 7006 // 1. D = gcd(A, N) 7007 // 7008 // The gcd of A and N may have only one prime factor: 2. The number of 7009 // trailing zeros in A is its multiplicity 7010 uint32_t Mult2 = A.countTrailingZeros(); 7011 // D = 2^Mult2 7012 7013 // 2. Check if B is divisible by D. 7014 // 7015 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 7016 // is not less than multiplicity of this prime factor for D. 7017 if (B.countTrailingZeros() < Mult2) 7018 return SE.getCouldNotCompute(); 7019 7020 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 7021 // modulo (N / D). 7022 // 7023 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this 7024 // bit width during computations. 7025 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 7026 APInt Mod(BW + 1, 0); 7027 Mod.setBit(BW - Mult2); // Mod = N / D 7028 APInt I = AD.multiplicativeInverse(Mod); 7029 7030 // 4. Compute the minimum unsigned root of the equation: 7031 // I * (B / D) mod (N / D) 7032 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod); 7033 7034 // The result is guaranteed to be less than 2^BW so we may truncate it to BW 7035 // bits. 7036 return SE.getConstant(Result.trunc(BW)); 7037 } 7038 7039 /// Find the roots of the quadratic equation for the given quadratic chrec 7040 /// {L,+,M,+,N}. This returns either the two roots (which might be the same) or 7041 /// two SCEVCouldNotCompute objects. 7042 /// 7043 static Optional<std::pair<const SCEVConstant *,const SCEVConstant *>> 7044 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 7045 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 7046 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 7047 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 7048 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 7049 7050 // We currently can only solve this if the coefficients are constants. 7051 if (!LC || !MC || !NC) 7052 return None; 7053 7054 uint32_t BitWidth = LC->getAPInt().getBitWidth(); 7055 const APInt &L = LC->getAPInt(); 7056 const APInt &M = MC->getAPInt(); 7057 const APInt &N = NC->getAPInt(); 7058 APInt Two(BitWidth, 2); 7059 APInt Four(BitWidth, 4); 7060 7061 { 7062 using namespace APIntOps; 7063 const APInt& C = L; 7064 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C 7065 // The B coefficient is M-N/2 7066 APInt B(M); 7067 B -= sdiv(N,Two); 7068 7069 // The A coefficient is N/2 7070 APInt A(N.sdiv(Two)); 7071 7072 // Compute the B^2-4ac term. 7073 APInt SqrtTerm(B); 7074 SqrtTerm *= B; 7075 SqrtTerm -= Four * (A * C); 7076 7077 if (SqrtTerm.isNegative()) { 7078 // The loop is provably infinite. 7079 return None; 7080 } 7081 7082 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest 7083 // integer value or else APInt::sqrt() will assert. 7084 APInt SqrtVal(SqrtTerm.sqrt()); 7085 7086 // Compute the two solutions for the quadratic formula. 7087 // The divisions must be performed as signed divisions. 7088 APInt NegB(-B); 7089 APInt TwoA(A << 1); 7090 if (TwoA.isMinValue()) 7091 return None; 7092 7093 LLVMContext &Context = SE.getContext(); 7094 7095 ConstantInt *Solution1 = 7096 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA)); 7097 ConstantInt *Solution2 = 7098 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA)); 7099 7100 return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)), 7101 cast<SCEVConstant>(SE.getConstant(Solution2))); 7102 } // end APIntOps namespace 7103 } 7104 7105 ScalarEvolution::ExitLimit 7106 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 7107 bool AllowPredicates) { 7108 7109 // This is only used for loops with a "x != y" exit test. The exit condition 7110 // is now expressed as a single expression, V = x-y. So the exit test is 7111 // effectively V != 0. We know and take advantage of the fact that this 7112 // expression only being used in a comparison by zero context. 7113 7114 SCEVUnionPredicate P; 7115 // If the value is a constant 7116 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 7117 // If the value is already zero, the branch will execute zero times. 7118 if (C->getValue()->isZero()) return C; 7119 return getCouldNotCompute(); // Otherwise it will loop infinitely. 7120 } 7121 7122 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V); 7123 if (!AddRec && AllowPredicates) 7124 // Try to make this an AddRec using runtime tests, in the first X 7125 // iterations of this loop, where X is the SCEV expression found by the 7126 // algorithm below. 7127 AddRec = convertSCEVToAddRecWithPredicates(V, L, P); 7128 7129 if (!AddRec || AddRec->getLoop() != L) 7130 return getCouldNotCompute(); 7131 7132 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 7133 // the quadratic equation to solve it. 7134 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 7135 if (auto Roots = SolveQuadraticEquation(AddRec, *this)) { 7136 const SCEVConstant *R1 = Roots->first; 7137 const SCEVConstant *R2 = Roots->second; 7138 // Pick the smallest positive root value. 7139 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp( 7140 CmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) { 7141 if (!CB->getZExtValue()) 7142 std::swap(R1, R2); // R1 is the minimum root now. 7143 7144 // We can only use this value if the chrec ends up with an exact zero 7145 // value at this index. When solving for "X*X != 5", for example, we 7146 // should not accept a root of 2. 7147 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this); 7148 if (Val->isZero()) 7149 return ExitLimit(R1, R1, P); // We found a quadratic root! 7150 } 7151 } 7152 return getCouldNotCompute(); 7153 } 7154 7155 // Otherwise we can only handle this if it is affine. 7156 if (!AddRec->isAffine()) 7157 return getCouldNotCompute(); 7158 7159 // If this is an affine expression, the execution count of this branch is 7160 // the minimum unsigned root of the following equation: 7161 // 7162 // Start + Step*N = 0 (mod 2^BW) 7163 // 7164 // equivalent to: 7165 // 7166 // Step*N = -Start (mod 2^BW) 7167 // 7168 // where BW is the common bit width of Start and Step. 7169 7170 // Get the initial value for the loop. 7171 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 7172 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 7173 7174 // For now we handle only constant steps. 7175 // 7176 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 7177 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 7178 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 7179 // We have not yet seen any such cases. 7180 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 7181 if (!StepC || StepC->getValue()->equalsInt(0)) 7182 return getCouldNotCompute(); 7183 7184 // For positive steps (counting up until unsigned overflow): 7185 // N = -Start/Step (as unsigned) 7186 // For negative steps (counting down to zero): 7187 // N = Start/-Step 7188 // First compute the unsigned distance from zero in the direction of Step. 7189 bool CountDown = StepC->getAPInt().isNegative(); 7190 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 7191 7192 // Handle unitary steps, which cannot wraparound. 7193 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 7194 // N = Distance (as unsigned) 7195 if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) { 7196 ConstantRange CR = getUnsignedRange(Start); 7197 const SCEV *MaxBECount; 7198 if (!CountDown && CR.getUnsignedMin().isMinValue()) 7199 // When counting up, the worst starting value is 1, not 0. 7200 MaxBECount = CR.getUnsignedMax().isMinValue() 7201 ? getConstant(APInt::getMinValue(CR.getBitWidth())) 7202 : getConstant(APInt::getMaxValue(CR.getBitWidth())); 7203 else 7204 MaxBECount = getConstant(CountDown ? CR.getUnsignedMax() 7205 : -CR.getUnsignedMin()); 7206 return ExitLimit(Distance, MaxBECount, P); 7207 } 7208 7209 // As a special case, handle the instance where Step is a positive power of 7210 // two. In this case, determining whether Step divides Distance evenly can be 7211 // done by counting and comparing the number of trailing zeros of Step and 7212 // Distance. 7213 if (!CountDown) { 7214 const APInt &StepV = StepC->getAPInt(); 7215 // StepV.isPowerOf2() returns true if StepV is an positive power of two. It 7216 // also returns true if StepV is maximally negative (eg, INT_MIN), but that 7217 // case is not handled as this code is guarded by !CountDown. 7218 if (StepV.isPowerOf2() && 7219 GetMinTrailingZeros(Distance) >= StepV.countTrailingZeros()) { 7220 // Here we've constrained the equation to be of the form 7221 // 7222 // 2^(N + k) * Distance' = (StepV == 2^N) * X (mod 2^W) ... (0) 7223 // 7224 // where we're operating on a W bit wide integer domain and k is 7225 // non-negative. The smallest unsigned solution for X is the trip count. 7226 // 7227 // (0) is equivalent to: 7228 // 7229 // 2^(N + k) * Distance' - 2^N * X = L * 2^W 7230 // <=> 2^N(2^k * Distance' - X) = L * 2^(W - N) * 2^N 7231 // <=> 2^k * Distance' - X = L * 2^(W - N) 7232 // <=> 2^k * Distance' = L * 2^(W - N) + X ... (1) 7233 // 7234 // The smallest X satisfying (1) is unsigned remainder of dividing the LHS 7235 // by 2^(W - N). 7236 // 7237 // <=> X = 2^k * Distance' URem 2^(W - N) ... (2) 7238 // 7239 // E.g. say we're solving 7240 // 7241 // 2 * Val = 2 * X (in i8) ... (3) 7242 // 7243 // then from (2), we get X = Val URem i8 128 (k = 0 in this case). 7244 // 7245 // Note: It is tempting to solve (3) by setting X = Val, but Val is not 7246 // necessarily the smallest unsigned value of X that satisfies (3). 7247 // E.g. if Val is i8 -127 then the smallest value of X that satisfies (3) 7248 // is i8 1, not i8 -127 7249 7250 const auto *ModuloResult = getUDivExactExpr(Distance, Step); 7251 7252 // Since SCEV does not have a URem node, we construct one using a truncate 7253 // and a zero extend. 7254 7255 unsigned NarrowWidth = StepV.getBitWidth() - StepV.countTrailingZeros(); 7256 auto *NarrowTy = IntegerType::get(getContext(), NarrowWidth); 7257 auto *WideTy = Distance->getType(); 7258 7259 const SCEV *Limit = 7260 getZeroExtendExpr(getTruncateExpr(ModuloResult, NarrowTy), WideTy); 7261 return ExitLimit(Limit, Limit, P); 7262 } 7263 } 7264 7265 // If the condition controls loop exit (the loop exits only if the expression 7266 // is true) and the addition is no-wrap we can use unsigned divide to 7267 // compute the backedge count. In this case, the step may not divide the 7268 // distance, but we don't care because if the condition is "missed" the loop 7269 // will have undefined behavior due to wrapping. 7270 if (ControlsExit && AddRec->hasNoSelfWrap() && 7271 loopHasNoAbnormalExits(AddRec->getLoop())) { 7272 const SCEV *Exact = 7273 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 7274 return ExitLimit(Exact, Exact, P); 7275 } 7276 7277 // Then, try to solve the above equation provided that Start is constant. 7278 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) { 7279 const SCEV *E = SolveLinEquationWithOverflow( 7280 StepC->getValue()->getValue(), -StartC->getValue()->getValue(), *this); 7281 return ExitLimit(E, E, P); 7282 } 7283 return getCouldNotCompute(); 7284 } 7285 7286 ScalarEvolution::ExitLimit 7287 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 7288 // Loops that look like: while (X == 0) are very strange indeed. We don't 7289 // handle them yet except for the trivial case. This could be expanded in the 7290 // future as needed. 7291 7292 // If the value is a constant, check to see if it is known to be non-zero 7293 // already. If so, the backedge will execute zero times. 7294 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 7295 if (!C->getValue()->isNullValue()) 7296 return getZero(C->getType()); 7297 return getCouldNotCompute(); // Otherwise it will loop infinitely. 7298 } 7299 7300 // We could implement others, but I really doubt anyone writes loops like 7301 // this, and if they did, they would already be constant folded. 7302 return getCouldNotCompute(); 7303 } 7304 7305 std::pair<BasicBlock *, BasicBlock *> 7306 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) { 7307 // If the block has a unique predecessor, then there is no path from the 7308 // predecessor to the block that does not go through the direct edge 7309 // from the predecessor to the block. 7310 if (BasicBlock *Pred = BB->getSinglePredecessor()) 7311 return {Pred, BB}; 7312 7313 // A loop's header is defined to be a block that dominates the loop. 7314 // If the header has a unique predecessor outside the loop, it must be 7315 // a block that has exactly one successor that can reach the loop. 7316 if (Loop *L = LI.getLoopFor(BB)) 7317 return {L->getLoopPredecessor(), L->getHeader()}; 7318 7319 return {nullptr, nullptr}; 7320 } 7321 7322 /// SCEV structural equivalence is usually sufficient for testing whether two 7323 /// expressions are equal, however for the purposes of looking for a condition 7324 /// guarding a loop, it can be useful to be a little more general, since a 7325 /// front-end may have replicated the controlling expression. 7326 /// 7327 static bool HasSameValue(const SCEV *A, const SCEV *B) { 7328 // Quick check to see if they are the same SCEV. 7329 if (A == B) return true; 7330 7331 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 7332 // Not all instructions that are "identical" compute the same value. For 7333 // instance, two distinct alloca instructions allocating the same type are 7334 // identical and do not read memory; but compute distinct values. 7335 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 7336 }; 7337 7338 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 7339 // two different instructions with the same value. Check for this case. 7340 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 7341 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 7342 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 7343 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 7344 if (ComputesEqualValues(AI, BI)) 7345 return true; 7346 7347 // Otherwise assume they may have a different value. 7348 return false; 7349 } 7350 7351 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 7352 const SCEV *&LHS, const SCEV *&RHS, 7353 unsigned Depth) { 7354 bool Changed = false; 7355 7356 // If we hit the max recursion limit bail out. 7357 if (Depth >= 3) 7358 return false; 7359 7360 // Canonicalize a constant to the right side. 7361 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 7362 // Check for both operands constant. 7363 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 7364 if (ConstantExpr::getICmp(Pred, 7365 LHSC->getValue(), 7366 RHSC->getValue())->isNullValue()) 7367 goto trivially_false; 7368 else 7369 goto trivially_true; 7370 } 7371 // Otherwise swap the operands to put the constant on the right. 7372 std::swap(LHS, RHS); 7373 Pred = ICmpInst::getSwappedPredicate(Pred); 7374 Changed = true; 7375 } 7376 7377 // If we're comparing an addrec with a value which is loop-invariant in the 7378 // addrec's loop, put the addrec on the left. Also make a dominance check, 7379 // as both operands could be addrecs loop-invariant in each other's loop. 7380 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 7381 const Loop *L = AR->getLoop(); 7382 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 7383 std::swap(LHS, RHS); 7384 Pred = ICmpInst::getSwappedPredicate(Pred); 7385 Changed = true; 7386 } 7387 } 7388 7389 // If there's a constant operand, canonicalize comparisons with boundary 7390 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 7391 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 7392 const APInt &RA = RC->getAPInt(); 7393 switch (Pred) { 7394 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 7395 case ICmpInst::ICMP_EQ: 7396 case ICmpInst::ICMP_NE: 7397 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 7398 if (!RA) 7399 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 7400 if (const SCEVMulExpr *ME = dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 7401 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 7402 ME->getOperand(0)->isAllOnesValue()) { 7403 RHS = AE->getOperand(1); 7404 LHS = ME->getOperand(1); 7405 Changed = true; 7406 } 7407 break; 7408 case ICmpInst::ICMP_UGE: 7409 if ((RA - 1).isMinValue()) { 7410 Pred = ICmpInst::ICMP_NE; 7411 RHS = getConstant(RA - 1); 7412 Changed = true; 7413 break; 7414 } 7415 if (RA.isMaxValue()) { 7416 Pred = ICmpInst::ICMP_EQ; 7417 Changed = true; 7418 break; 7419 } 7420 if (RA.isMinValue()) goto trivially_true; 7421 7422 Pred = ICmpInst::ICMP_UGT; 7423 RHS = getConstant(RA - 1); 7424 Changed = true; 7425 break; 7426 case ICmpInst::ICMP_ULE: 7427 if ((RA + 1).isMaxValue()) { 7428 Pred = ICmpInst::ICMP_NE; 7429 RHS = getConstant(RA + 1); 7430 Changed = true; 7431 break; 7432 } 7433 if (RA.isMinValue()) { 7434 Pred = ICmpInst::ICMP_EQ; 7435 Changed = true; 7436 break; 7437 } 7438 if (RA.isMaxValue()) goto trivially_true; 7439 7440 Pred = ICmpInst::ICMP_ULT; 7441 RHS = getConstant(RA + 1); 7442 Changed = true; 7443 break; 7444 case ICmpInst::ICMP_SGE: 7445 if ((RA - 1).isMinSignedValue()) { 7446 Pred = ICmpInst::ICMP_NE; 7447 RHS = getConstant(RA - 1); 7448 Changed = true; 7449 break; 7450 } 7451 if (RA.isMaxSignedValue()) { 7452 Pred = ICmpInst::ICMP_EQ; 7453 Changed = true; 7454 break; 7455 } 7456 if (RA.isMinSignedValue()) goto trivially_true; 7457 7458 Pred = ICmpInst::ICMP_SGT; 7459 RHS = getConstant(RA - 1); 7460 Changed = true; 7461 break; 7462 case ICmpInst::ICMP_SLE: 7463 if ((RA + 1).isMaxSignedValue()) { 7464 Pred = ICmpInst::ICMP_NE; 7465 RHS = getConstant(RA + 1); 7466 Changed = true; 7467 break; 7468 } 7469 if (RA.isMinSignedValue()) { 7470 Pred = ICmpInst::ICMP_EQ; 7471 Changed = true; 7472 break; 7473 } 7474 if (RA.isMaxSignedValue()) goto trivially_true; 7475 7476 Pred = ICmpInst::ICMP_SLT; 7477 RHS = getConstant(RA + 1); 7478 Changed = true; 7479 break; 7480 case ICmpInst::ICMP_UGT: 7481 if (RA.isMinValue()) { 7482 Pred = ICmpInst::ICMP_NE; 7483 Changed = true; 7484 break; 7485 } 7486 if ((RA + 1).isMaxValue()) { 7487 Pred = ICmpInst::ICMP_EQ; 7488 RHS = getConstant(RA + 1); 7489 Changed = true; 7490 break; 7491 } 7492 if (RA.isMaxValue()) goto trivially_false; 7493 break; 7494 case ICmpInst::ICMP_ULT: 7495 if (RA.isMaxValue()) { 7496 Pred = ICmpInst::ICMP_NE; 7497 Changed = true; 7498 break; 7499 } 7500 if ((RA - 1).isMinValue()) { 7501 Pred = ICmpInst::ICMP_EQ; 7502 RHS = getConstant(RA - 1); 7503 Changed = true; 7504 break; 7505 } 7506 if (RA.isMinValue()) goto trivially_false; 7507 break; 7508 case ICmpInst::ICMP_SGT: 7509 if (RA.isMinSignedValue()) { 7510 Pred = ICmpInst::ICMP_NE; 7511 Changed = true; 7512 break; 7513 } 7514 if ((RA + 1).isMaxSignedValue()) { 7515 Pred = ICmpInst::ICMP_EQ; 7516 RHS = getConstant(RA + 1); 7517 Changed = true; 7518 break; 7519 } 7520 if (RA.isMaxSignedValue()) goto trivially_false; 7521 break; 7522 case ICmpInst::ICMP_SLT: 7523 if (RA.isMaxSignedValue()) { 7524 Pred = ICmpInst::ICMP_NE; 7525 Changed = true; 7526 break; 7527 } 7528 if ((RA - 1).isMinSignedValue()) { 7529 Pred = ICmpInst::ICMP_EQ; 7530 RHS = getConstant(RA - 1); 7531 Changed = true; 7532 break; 7533 } 7534 if (RA.isMinSignedValue()) goto trivially_false; 7535 break; 7536 } 7537 } 7538 7539 // Check for obvious equality. 7540 if (HasSameValue(LHS, RHS)) { 7541 if (ICmpInst::isTrueWhenEqual(Pred)) 7542 goto trivially_true; 7543 if (ICmpInst::isFalseWhenEqual(Pred)) 7544 goto trivially_false; 7545 } 7546 7547 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 7548 // adding or subtracting 1 from one of the operands. 7549 switch (Pred) { 7550 case ICmpInst::ICMP_SLE: 7551 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) { 7552 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 7553 SCEV::FlagNSW); 7554 Pred = ICmpInst::ICMP_SLT; 7555 Changed = true; 7556 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) { 7557 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 7558 SCEV::FlagNSW); 7559 Pred = ICmpInst::ICMP_SLT; 7560 Changed = true; 7561 } 7562 break; 7563 case ICmpInst::ICMP_SGE: 7564 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) { 7565 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 7566 SCEV::FlagNSW); 7567 Pred = ICmpInst::ICMP_SGT; 7568 Changed = true; 7569 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) { 7570 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 7571 SCEV::FlagNSW); 7572 Pred = ICmpInst::ICMP_SGT; 7573 Changed = true; 7574 } 7575 break; 7576 case ICmpInst::ICMP_ULE: 7577 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) { 7578 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 7579 SCEV::FlagNUW); 7580 Pred = ICmpInst::ICMP_ULT; 7581 Changed = true; 7582 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) { 7583 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 7584 Pred = ICmpInst::ICMP_ULT; 7585 Changed = true; 7586 } 7587 break; 7588 case ICmpInst::ICMP_UGE: 7589 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) { 7590 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 7591 Pred = ICmpInst::ICMP_UGT; 7592 Changed = true; 7593 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) { 7594 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 7595 SCEV::FlagNUW); 7596 Pred = ICmpInst::ICMP_UGT; 7597 Changed = true; 7598 } 7599 break; 7600 default: 7601 break; 7602 } 7603 7604 // TODO: More simplifications are possible here. 7605 7606 // Recursively simplify until we either hit a recursion limit or nothing 7607 // changes. 7608 if (Changed) 7609 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 7610 7611 return Changed; 7612 7613 trivially_true: 7614 // Return 0 == 0. 7615 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 7616 Pred = ICmpInst::ICMP_EQ; 7617 return true; 7618 7619 trivially_false: 7620 // Return 0 != 0. 7621 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 7622 Pred = ICmpInst::ICMP_NE; 7623 return true; 7624 } 7625 7626 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 7627 return getSignedRange(S).getSignedMax().isNegative(); 7628 } 7629 7630 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 7631 return getSignedRange(S).getSignedMin().isStrictlyPositive(); 7632 } 7633 7634 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 7635 return !getSignedRange(S).getSignedMin().isNegative(); 7636 } 7637 7638 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 7639 return !getSignedRange(S).getSignedMax().isStrictlyPositive(); 7640 } 7641 7642 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 7643 return isKnownNegative(S) || isKnownPositive(S); 7644 } 7645 7646 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 7647 const SCEV *LHS, const SCEV *RHS) { 7648 // Canonicalize the inputs first. 7649 (void)SimplifyICmpOperands(Pred, LHS, RHS); 7650 7651 // If LHS or RHS is an addrec, check to see if the condition is true in 7652 // every iteration of the loop. 7653 // If LHS and RHS are both addrec, both conditions must be true in 7654 // every iteration of the loop. 7655 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 7656 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 7657 bool LeftGuarded = false; 7658 bool RightGuarded = false; 7659 if (LAR) { 7660 const Loop *L = LAR->getLoop(); 7661 if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) && 7662 isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) { 7663 if (!RAR) return true; 7664 LeftGuarded = true; 7665 } 7666 } 7667 if (RAR) { 7668 const Loop *L = RAR->getLoop(); 7669 if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) && 7670 isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) { 7671 if (!LAR) return true; 7672 RightGuarded = true; 7673 } 7674 } 7675 if (LeftGuarded && RightGuarded) 7676 return true; 7677 7678 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 7679 return true; 7680 7681 // Otherwise see what can be done with known constant ranges. 7682 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS); 7683 } 7684 7685 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS, 7686 ICmpInst::Predicate Pred, 7687 bool &Increasing) { 7688 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing); 7689 7690 #ifndef NDEBUG 7691 // Verify an invariant: inverting the predicate should turn a monotonically 7692 // increasing change to a monotonically decreasing one, and vice versa. 7693 bool IncreasingSwapped; 7694 bool ResultSwapped = isMonotonicPredicateImpl( 7695 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped); 7696 7697 assert(Result == ResultSwapped && "should be able to analyze both!"); 7698 if (ResultSwapped) 7699 assert(Increasing == !IncreasingSwapped && 7700 "monotonicity should flip as we flip the predicate"); 7701 #endif 7702 7703 return Result; 7704 } 7705 7706 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS, 7707 ICmpInst::Predicate Pred, 7708 bool &Increasing) { 7709 7710 // A zero step value for LHS means the induction variable is essentially a 7711 // loop invariant value. We don't really depend on the predicate actually 7712 // flipping from false to true (for increasing predicates, and the other way 7713 // around for decreasing predicates), all we care about is that *if* the 7714 // predicate changes then it only changes from false to true. 7715 // 7716 // A zero step value in itself is not very useful, but there may be places 7717 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 7718 // as general as possible. 7719 7720 switch (Pred) { 7721 default: 7722 return false; // Conservative answer 7723 7724 case ICmpInst::ICMP_UGT: 7725 case ICmpInst::ICMP_UGE: 7726 case ICmpInst::ICMP_ULT: 7727 case ICmpInst::ICMP_ULE: 7728 if (!LHS->hasNoUnsignedWrap()) 7729 return false; 7730 7731 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE; 7732 return true; 7733 7734 case ICmpInst::ICMP_SGT: 7735 case ICmpInst::ICMP_SGE: 7736 case ICmpInst::ICMP_SLT: 7737 case ICmpInst::ICMP_SLE: { 7738 if (!LHS->hasNoSignedWrap()) 7739 return false; 7740 7741 const SCEV *Step = LHS->getStepRecurrence(*this); 7742 7743 if (isKnownNonNegative(Step)) { 7744 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE; 7745 return true; 7746 } 7747 7748 if (isKnownNonPositive(Step)) { 7749 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE; 7750 return true; 7751 } 7752 7753 return false; 7754 } 7755 7756 } 7757 7758 llvm_unreachable("switch has default clause!"); 7759 } 7760 7761 bool ScalarEvolution::isLoopInvariantPredicate( 7762 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 7763 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS, 7764 const SCEV *&InvariantRHS) { 7765 7766 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 7767 if (!isLoopInvariant(RHS, L)) { 7768 if (!isLoopInvariant(LHS, L)) 7769 return false; 7770 7771 std::swap(LHS, RHS); 7772 Pred = ICmpInst::getSwappedPredicate(Pred); 7773 } 7774 7775 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 7776 if (!ArLHS || ArLHS->getLoop() != L) 7777 return false; 7778 7779 bool Increasing; 7780 if (!isMonotonicPredicate(ArLHS, Pred, Increasing)) 7781 return false; 7782 7783 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 7784 // true as the loop iterates, and the backedge is control dependent on 7785 // "ArLHS `Pred` RHS" == true then we can reason as follows: 7786 // 7787 // * if the predicate was false in the first iteration then the predicate 7788 // is never evaluated again, since the loop exits without taking the 7789 // backedge. 7790 // * if the predicate was true in the first iteration then it will 7791 // continue to be true for all future iterations since it is 7792 // monotonically increasing. 7793 // 7794 // For both the above possibilities, we can replace the loop varying 7795 // predicate with its value on the first iteration of the loop (which is 7796 // loop invariant). 7797 // 7798 // A similar reasoning applies for a monotonically decreasing predicate, by 7799 // replacing true with false and false with true in the above two bullets. 7800 7801 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 7802 7803 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 7804 return false; 7805 7806 InvariantPred = Pred; 7807 InvariantLHS = ArLHS->getStart(); 7808 InvariantRHS = RHS; 7809 return true; 7810 } 7811 7812 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 7813 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 7814 if (HasSameValue(LHS, RHS)) 7815 return ICmpInst::isTrueWhenEqual(Pred); 7816 7817 // This code is split out from isKnownPredicate because it is called from 7818 // within isLoopEntryGuardedByCond. 7819 7820 auto CheckRanges = 7821 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) { 7822 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS) 7823 .contains(RangeLHS); 7824 }; 7825 7826 // The check at the top of the function catches the case where the values are 7827 // known to be equal. 7828 if (Pred == CmpInst::ICMP_EQ) 7829 return false; 7830 7831 if (Pred == CmpInst::ICMP_NE) 7832 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 7833 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) || 7834 isKnownNonZero(getMinusSCEV(LHS, RHS)); 7835 7836 if (CmpInst::isSigned(Pred)) 7837 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 7838 7839 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 7840 } 7841 7842 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 7843 const SCEV *LHS, 7844 const SCEV *RHS) { 7845 7846 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer. 7847 // Return Y via OutY. 7848 auto MatchBinaryAddToConst = 7849 [this](const SCEV *Result, const SCEV *X, APInt &OutY, 7850 SCEV::NoWrapFlags ExpectedFlags) { 7851 const SCEV *NonConstOp, *ConstOp; 7852 SCEV::NoWrapFlags FlagsPresent; 7853 7854 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) || 7855 !isa<SCEVConstant>(ConstOp) || NonConstOp != X) 7856 return false; 7857 7858 OutY = cast<SCEVConstant>(ConstOp)->getAPInt(); 7859 return (FlagsPresent & ExpectedFlags) == ExpectedFlags; 7860 }; 7861 7862 APInt C; 7863 7864 switch (Pred) { 7865 default: 7866 break; 7867 7868 case ICmpInst::ICMP_SGE: 7869 std::swap(LHS, RHS); 7870 case ICmpInst::ICMP_SLE: 7871 // X s<= (X + C)<nsw> if C >= 0 7872 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative()) 7873 return true; 7874 7875 // (X + C)<nsw> s<= X if C <= 0 7876 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && 7877 !C.isStrictlyPositive()) 7878 return true; 7879 break; 7880 7881 case ICmpInst::ICMP_SGT: 7882 std::swap(LHS, RHS); 7883 case ICmpInst::ICMP_SLT: 7884 // X s< (X + C)<nsw> if C > 0 7885 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && 7886 C.isStrictlyPositive()) 7887 return true; 7888 7889 // (X + C)<nsw> s< X if C < 0 7890 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative()) 7891 return true; 7892 break; 7893 } 7894 7895 return false; 7896 } 7897 7898 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 7899 const SCEV *LHS, 7900 const SCEV *RHS) { 7901 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 7902 return false; 7903 7904 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 7905 // the stack can result in exponential time complexity. 7906 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 7907 7908 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 7909 // 7910 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 7911 // isKnownPredicate. isKnownPredicate is more powerful, but also more 7912 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 7913 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 7914 // use isKnownPredicate later if needed. 7915 return isKnownNonNegative(RHS) && 7916 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 7917 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 7918 } 7919 7920 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB, 7921 ICmpInst::Predicate Pred, 7922 const SCEV *LHS, const SCEV *RHS) { 7923 // No need to even try if we know the module has no guards. 7924 if (!HasGuards) 7925 return false; 7926 7927 return any_of(*BB, [&](Instruction &I) { 7928 using namespace llvm::PatternMatch; 7929 7930 Value *Condition; 7931 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 7932 m_Value(Condition))) && 7933 isImpliedCond(Pred, LHS, RHS, Condition, false); 7934 }); 7935 } 7936 7937 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 7938 /// protected by a conditional between LHS and RHS. This is used to 7939 /// to eliminate casts. 7940 bool 7941 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 7942 ICmpInst::Predicate Pred, 7943 const SCEV *LHS, const SCEV *RHS) { 7944 // Interpret a null as meaning no loop, where there is obviously no guard 7945 // (interprocedural conditions notwithstanding). 7946 if (!L) return true; 7947 7948 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS)) 7949 return true; 7950 7951 BasicBlock *Latch = L->getLoopLatch(); 7952 if (!Latch) 7953 return false; 7954 7955 BranchInst *LoopContinuePredicate = 7956 dyn_cast<BranchInst>(Latch->getTerminator()); 7957 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 7958 isImpliedCond(Pred, LHS, RHS, 7959 LoopContinuePredicate->getCondition(), 7960 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 7961 return true; 7962 7963 // We don't want more than one activation of the following loops on the stack 7964 // -- that can lead to O(n!) time complexity. 7965 if (WalkingBEDominatingConds) 7966 return false; 7967 7968 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 7969 7970 // See if we can exploit a trip count to prove the predicate. 7971 const auto &BETakenInfo = getBackedgeTakenInfo(L); 7972 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 7973 if (LatchBECount != getCouldNotCompute()) { 7974 // We know that Latch branches back to the loop header exactly 7975 // LatchBECount times. This means the backdege condition at Latch is 7976 // equivalent to "{0,+,1} u< LatchBECount". 7977 Type *Ty = LatchBECount->getType(); 7978 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 7979 const SCEV *LoopCounter = 7980 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 7981 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 7982 LatchBECount)) 7983 return true; 7984 } 7985 7986 // Check conditions due to any @llvm.assume intrinsics. 7987 for (auto &AssumeVH : AC.assumptions()) { 7988 if (!AssumeVH) 7989 continue; 7990 auto *CI = cast<CallInst>(AssumeVH); 7991 if (!DT.dominates(CI, Latch->getTerminator())) 7992 continue; 7993 7994 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 7995 return true; 7996 } 7997 7998 // If the loop is not reachable from the entry block, we risk running into an 7999 // infinite loop as we walk up into the dom tree. These loops do not matter 8000 // anyway, so we just return a conservative answer when we see them. 8001 if (!DT.isReachableFromEntry(L->getHeader())) 8002 return false; 8003 8004 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 8005 return true; 8006 8007 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 8008 DTN != HeaderDTN; DTN = DTN->getIDom()) { 8009 8010 assert(DTN && "should reach the loop header before reaching the root!"); 8011 8012 BasicBlock *BB = DTN->getBlock(); 8013 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 8014 return true; 8015 8016 BasicBlock *PBB = BB->getSinglePredecessor(); 8017 if (!PBB) 8018 continue; 8019 8020 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 8021 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 8022 continue; 8023 8024 Value *Condition = ContinuePredicate->getCondition(); 8025 8026 // If we have an edge `E` within the loop body that dominates the only 8027 // latch, the condition guarding `E` also guards the backedge. This 8028 // reasoning works only for loops with a single latch. 8029 8030 BasicBlockEdge DominatingEdge(PBB, BB); 8031 if (DominatingEdge.isSingleEdge()) { 8032 // We're constructively (and conservatively) enumerating edges within the 8033 // loop body that dominate the latch. The dominator tree better agree 8034 // with us on this: 8035 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 8036 8037 if (isImpliedCond(Pred, LHS, RHS, Condition, 8038 BB != ContinuePredicate->getSuccessor(0))) 8039 return true; 8040 } 8041 } 8042 8043 return false; 8044 } 8045 8046 bool 8047 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 8048 ICmpInst::Predicate Pred, 8049 const SCEV *LHS, const SCEV *RHS) { 8050 // Interpret a null as meaning no loop, where there is obviously no guard 8051 // (interprocedural conditions notwithstanding). 8052 if (!L) return false; 8053 8054 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS)) 8055 return true; 8056 8057 // Starting at the loop predecessor, climb up the predecessor chain, as long 8058 // as there are predecessors that can be found that have unique successors 8059 // leading to the original header. 8060 for (std::pair<BasicBlock *, BasicBlock *> 8061 Pair(L->getLoopPredecessor(), L->getHeader()); 8062 Pair.first; 8063 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 8064 8065 if (isImpliedViaGuard(Pair.first, Pred, LHS, RHS)) 8066 return true; 8067 8068 BranchInst *LoopEntryPredicate = 8069 dyn_cast<BranchInst>(Pair.first->getTerminator()); 8070 if (!LoopEntryPredicate || 8071 LoopEntryPredicate->isUnconditional()) 8072 continue; 8073 8074 if (isImpliedCond(Pred, LHS, RHS, 8075 LoopEntryPredicate->getCondition(), 8076 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 8077 return true; 8078 } 8079 8080 // Check conditions due to any @llvm.assume intrinsics. 8081 for (auto &AssumeVH : AC.assumptions()) { 8082 if (!AssumeVH) 8083 continue; 8084 auto *CI = cast<CallInst>(AssumeVH); 8085 if (!DT.dominates(CI, L->getHeader())) 8086 continue; 8087 8088 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 8089 return true; 8090 } 8091 8092 return false; 8093 } 8094 8095 namespace { 8096 /// RAII wrapper to prevent recursive application of isImpliedCond. 8097 /// ScalarEvolution's PendingLoopPredicates set must be empty unless we are 8098 /// currently evaluating isImpliedCond. 8099 struct MarkPendingLoopPredicate { 8100 Value *Cond; 8101 DenseSet<Value*> &LoopPreds; 8102 bool Pending; 8103 8104 MarkPendingLoopPredicate(Value *C, DenseSet<Value*> &LP) 8105 : Cond(C), LoopPreds(LP) { 8106 Pending = !LoopPreds.insert(Cond).second; 8107 } 8108 ~MarkPendingLoopPredicate() { 8109 if (!Pending) 8110 LoopPreds.erase(Cond); 8111 } 8112 }; 8113 } // end anonymous namespace 8114 8115 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, 8116 const SCEV *LHS, const SCEV *RHS, 8117 Value *FoundCondValue, 8118 bool Inverse) { 8119 MarkPendingLoopPredicate Mark(FoundCondValue, PendingLoopPredicates); 8120 if (Mark.Pending) 8121 return false; 8122 8123 // Recursively handle And and Or conditions. 8124 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) { 8125 if (BO->getOpcode() == Instruction::And) { 8126 if (!Inverse) 8127 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 8128 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 8129 } else if (BO->getOpcode() == Instruction::Or) { 8130 if (Inverse) 8131 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 8132 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 8133 } 8134 } 8135 8136 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 8137 if (!ICI) return false; 8138 8139 // Now that we found a conditional branch that dominates the loop or controls 8140 // the loop latch. Check to see if it is the comparison we are looking for. 8141 ICmpInst::Predicate FoundPred; 8142 if (Inverse) 8143 FoundPred = ICI->getInversePredicate(); 8144 else 8145 FoundPred = ICI->getPredicate(); 8146 8147 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 8148 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 8149 8150 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS); 8151 } 8152 8153 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 8154 const SCEV *RHS, 8155 ICmpInst::Predicate FoundPred, 8156 const SCEV *FoundLHS, 8157 const SCEV *FoundRHS) { 8158 // Balance the types. 8159 if (getTypeSizeInBits(LHS->getType()) < 8160 getTypeSizeInBits(FoundLHS->getType())) { 8161 if (CmpInst::isSigned(Pred)) { 8162 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 8163 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 8164 } else { 8165 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 8166 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 8167 } 8168 } else if (getTypeSizeInBits(LHS->getType()) > 8169 getTypeSizeInBits(FoundLHS->getType())) { 8170 if (CmpInst::isSigned(FoundPred)) { 8171 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 8172 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 8173 } else { 8174 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 8175 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 8176 } 8177 } 8178 8179 // Canonicalize the query to match the way instcombine will have 8180 // canonicalized the comparison. 8181 if (SimplifyICmpOperands(Pred, LHS, RHS)) 8182 if (LHS == RHS) 8183 return CmpInst::isTrueWhenEqual(Pred); 8184 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 8185 if (FoundLHS == FoundRHS) 8186 return CmpInst::isFalseWhenEqual(FoundPred); 8187 8188 // Check to see if we can make the LHS or RHS match. 8189 if (LHS == FoundRHS || RHS == FoundLHS) { 8190 if (isa<SCEVConstant>(RHS)) { 8191 std::swap(FoundLHS, FoundRHS); 8192 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 8193 } else { 8194 std::swap(LHS, RHS); 8195 Pred = ICmpInst::getSwappedPredicate(Pred); 8196 } 8197 } 8198 8199 // Check whether the found predicate is the same as the desired predicate. 8200 if (FoundPred == Pred) 8201 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 8202 8203 // Check whether swapping the found predicate makes it the same as the 8204 // desired predicate. 8205 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 8206 if (isa<SCEVConstant>(RHS)) 8207 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS); 8208 else 8209 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), 8210 RHS, LHS, FoundLHS, FoundRHS); 8211 } 8212 8213 // Unsigned comparison is the same as signed comparison when both the operands 8214 // are non-negative. 8215 if (CmpInst::isUnsigned(FoundPred) && 8216 CmpInst::getSignedPredicate(FoundPred) == Pred && 8217 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) 8218 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 8219 8220 // Check if we can make progress by sharpening ranges. 8221 if (FoundPred == ICmpInst::ICMP_NE && 8222 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 8223 8224 const SCEVConstant *C = nullptr; 8225 const SCEV *V = nullptr; 8226 8227 if (isa<SCEVConstant>(FoundLHS)) { 8228 C = cast<SCEVConstant>(FoundLHS); 8229 V = FoundRHS; 8230 } else { 8231 C = cast<SCEVConstant>(FoundRHS); 8232 V = FoundLHS; 8233 } 8234 8235 // The guarding predicate tells us that C != V. If the known range 8236 // of V is [C, t), we can sharpen the range to [C + 1, t). The 8237 // range we consider has to correspond to same signedness as the 8238 // predicate we're interested in folding. 8239 8240 APInt Min = ICmpInst::isSigned(Pred) ? 8241 getSignedRange(V).getSignedMin() : getUnsignedRange(V).getUnsignedMin(); 8242 8243 if (Min == C->getAPInt()) { 8244 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 8245 // This is true even if (Min + 1) wraps around -- in case of 8246 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 8247 8248 APInt SharperMin = Min + 1; 8249 8250 switch (Pred) { 8251 case ICmpInst::ICMP_SGE: 8252 case ICmpInst::ICMP_UGE: 8253 // We know V `Pred` SharperMin. If this implies LHS `Pred` 8254 // RHS, we're done. 8255 if (isImpliedCondOperands(Pred, LHS, RHS, V, 8256 getConstant(SharperMin))) 8257 return true; 8258 8259 case ICmpInst::ICMP_SGT: 8260 case ICmpInst::ICMP_UGT: 8261 // We know from the range information that (V `Pred` Min || 8262 // V == Min). We know from the guarding condition that !(V 8263 // == Min). This gives us 8264 // 8265 // V `Pred` Min || V == Min && !(V == Min) 8266 // => V `Pred` Min 8267 // 8268 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 8269 8270 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min))) 8271 return true; 8272 8273 default: 8274 // No change 8275 break; 8276 } 8277 } 8278 } 8279 8280 // Check whether the actual condition is beyond sufficient. 8281 if (FoundPred == ICmpInst::ICMP_EQ) 8282 if (ICmpInst::isTrueWhenEqual(Pred)) 8283 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS)) 8284 return true; 8285 if (Pred == ICmpInst::ICMP_NE) 8286 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 8287 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS)) 8288 return true; 8289 8290 // Otherwise assume the worst. 8291 return false; 8292 } 8293 8294 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 8295 const SCEV *&L, const SCEV *&R, 8296 SCEV::NoWrapFlags &Flags) { 8297 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 8298 if (!AE || AE->getNumOperands() != 2) 8299 return false; 8300 8301 L = AE->getOperand(0); 8302 R = AE->getOperand(1); 8303 Flags = AE->getNoWrapFlags(); 8304 return true; 8305 } 8306 8307 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 8308 const SCEV *Less) { 8309 // We avoid subtracting expressions here because this function is usually 8310 // fairly deep in the call stack (i.e. is called many times). 8311 8312 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 8313 const auto *LAR = cast<SCEVAddRecExpr>(Less); 8314 const auto *MAR = cast<SCEVAddRecExpr>(More); 8315 8316 if (LAR->getLoop() != MAR->getLoop()) 8317 return None; 8318 8319 // We look at affine expressions only; not for correctness but to keep 8320 // getStepRecurrence cheap. 8321 if (!LAR->isAffine() || !MAR->isAffine()) 8322 return None; 8323 8324 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 8325 return None; 8326 8327 Less = LAR->getStart(); 8328 More = MAR->getStart(); 8329 8330 // fall through 8331 } 8332 8333 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 8334 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 8335 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 8336 return M - L; 8337 } 8338 8339 const SCEV *L, *R; 8340 SCEV::NoWrapFlags Flags; 8341 if (splitBinaryAdd(Less, L, R, Flags)) 8342 if (const auto *LC = dyn_cast<SCEVConstant>(L)) 8343 if (R == More) 8344 return -(LC->getAPInt()); 8345 8346 if (splitBinaryAdd(More, L, R, Flags)) 8347 if (const auto *LC = dyn_cast<SCEVConstant>(L)) 8348 if (R == Less) 8349 return LC->getAPInt(); 8350 8351 return None; 8352 } 8353 8354 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 8355 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 8356 const SCEV *FoundLHS, const SCEV *FoundRHS) { 8357 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 8358 return false; 8359 8360 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 8361 if (!AddRecLHS) 8362 return false; 8363 8364 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 8365 if (!AddRecFoundLHS) 8366 return false; 8367 8368 // We'd like to let SCEV reason about control dependencies, so we constrain 8369 // both the inequalities to be about add recurrences on the same loop. This 8370 // way we can use isLoopEntryGuardedByCond later. 8371 8372 const Loop *L = AddRecFoundLHS->getLoop(); 8373 if (L != AddRecLHS->getLoop()) 8374 return false; 8375 8376 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 8377 // 8378 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 8379 // ... (2) 8380 // 8381 // Informal proof for (2), assuming (1) [*]: 8382 // 8383 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 8384 // 8385 // Then 8386 // 8387 // FoundLHS s< FoundRHS s< INT_MIN - C 8388 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 8389 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 8390 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 8391 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 8392 // <=> FoundLHS + C s< FoundRHS + C 8393 // 8394 // [*]: (1) can be proved by ruling out overflow. 8395 // 8396 // [**]: This can be proved by analyzing all the four possibilities: 8397 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 8398 // (A s>= 0, B s>= 0). 8399 // 8400 // Note: 8401 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 8402 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 8403 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 8404 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 8405 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 8406 // C)". 8407 8408 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 8409 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 8410 if (!LDiff || !RDiff || *LDiff != *RDiff) 8411 return false; 8412 8413 if (LDiff->isMinValue()) 8414 return true; 8415 8416 APInt FoundRHSLimit; 8417 8418 if (Pred == CmpInst::ICMP_ULT) { 8419 FoundRHSLimit = -(*RDiff); 8420 } else { 8421 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 8422 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 8423 } 8424 8425 // Try to prove (1) or (2), as needed. 8426 return isLoopEntryGuardedByCond(L, Pred, FoundRHS, 8427 getConstant(FoundRHSLimit)); 8428 } 8429 8430 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 8431 const SCEV *LHS, const SCEV *RHS, 8432 const SCEV *FoundLHS, 8433 const SCEV *FoundRHS) { 8434 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 8435 return true; 8436 8437 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 8438 return true; 8439 8440 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 8441 FoundLHS, FoundRHS) || 8442 // ~x < ~y --> x > y 8443 isImpliedCondOperandsHelper(Pred, LHS, RHS, 8444 getNotSCEV(FoundRHS), 8445 getNotSCEV(FoundLHS)); 8446 } 8447 8448 8449 /// If Expr computes ~A, return A else return nullptr 8450 static const SCEV *MatchNotExpr(const SCEV *Expr) { 8451 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 8452 if (!Add || Add->getNumOperands() != 2 || 8453 !Add->getOperand(0)->isAllOnesValue()) 8454 return nullptr; 8455 8456 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 8457 if (!AddRHS || AddRHS->getNumOperands() != 2 || 8458 !AddRHS->getOperand(0)->isAllOnesValue()) 8459 return nullptr; 8460 8461 return AddRHS->getOperand(1); 8462 } 8463 8464 8465 /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values? 8466 template<typename MaxExprType> 8467 static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr, 8468 const SCEV *Candidate) { 8469 const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr); 8470 if (!MaxExpr) return false; 8471 8472 return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end(); 8473 } 8474 8475 8476 /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values? 8477 template<typename MaxExprType> 8478 static bool IsMinConsistingOf(ScalarEvolution &SE, 8479 const SCEV *MaybeMinExpr, 8480 const SCEV *Candidate) { 8481 const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr); 8482 if (!MaybeMaxExpr) 8483 return false; 8484 8485 return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate)); 8486 } 8487 8488 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 8489 ICmpInst::Predicate Pred, 8490 const SCEV *LHS, const SCEV *RHS) { 8491 8492 // If both sides are affine addrecs for the same loop, with equal 8493 // steps, and we know the recurrences don't wrap, then we only 8494 // need to check the predicate on the starting values. 8495 8496 if (!ICmpInst::isRelational(Pred)) 8497 return false; 8498 8499 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 8500 if (!LAR) 8501 return false; 8502 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 8503 if (!RAR) 8504 return false; 8505 if (LAR->getLoop() != RAR->getLoop()) 8506 return false; 8507 if (!LAR->isAffine() || !RAR->isAffine()) 8508 return false; 8509 8510 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 8511 return false; 8512 8513 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 8514 SCEV::FlagNSW : SCEV::FlagNUW; 8515 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 8516 return false; 8517 8518 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 8519 } 8520 8521 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 8522 /// expression? 8523 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 8524 ICmpInst::Predicate Pred, 8525 const SCEV *LHS, const SCEV *RHS) { 8526 switch (Pred) { 8527 default: 8528 return false; 8529 8530 case ICmpInst::ICMP_SGE: 8531 std::swap(LHS, RHS); 8532 LLVM_FALLTHROUGH; 8533 case ICmpInst::ICMP_SLE: 8534 return 8535 // min(A, ...) <= A 8536 IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) || 8537 // A <= max(A, ...) 8538 IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 8539 8540 case ICmpInst::ICMP_UGE: 8541 std::swap(LHS, RHS); 8542 LLVM_FALLTHROUGH; 8543 case ICmpInst::ICMP_ULE: 8544 return 8545 // min(A, ...) <= A 8546 IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) || 8547 // A <= max(A, ...) 8548 IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 8549 } 8550 8551 llvm_unreachable("covered switch fell through?!"); 8552 } 8553 8554 bool 8555 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 8556 const SCEV *LHS, const SCEV *RHS, 8557 const SCEV *FoundLHS, 8558 const SCEV *FoundRHS) { 8559 auto IsKnownPredicateFull = 8560 [this](ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 8561 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 8562 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 8563 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 8564 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 8565 }; 8566 8567 switch (Pred) { 8568 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 8569 case ICmpInst::ICMP_EQ: 8570 case ICmpInst::ICMP_NE: 8571 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 8572 return true; 8573 break; 8574 case ICmpInst::ICMP_SLT: 8575 case ICmpInst::ICMP_SLE: 8576 if (IsKnownPredicateFull(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 8577 IsKnownPredicateFull(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 8578 return true; 8579 break; 8580 case ICmpInst::ICMP_SGT: 8581 case ICmpInst::ICMP_SGE: 8582 if (IsKnownPredicateFull(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 8583 IsKnownPredicateFull(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 8584 return true; 8585 break; 8586 case ICmpInst::ICMP_ULT: 8587 case ICmpInst::ICMP_ULE: 8588 if (IsKnownPredicateFull(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 8589 IsKnownPredicateFull(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 8590 return true; 8591 break; 8592 case ICmpInst::ICMP_UGT: 8593 case ICmpInst::ICMP_UGE: 8594 if (IsKnownPredicateFull(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 8595 IsKnownPredicateFull(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 8596 return true; 8597 break; 8598 } 8599 8600 return false; 8601 } 8602 8603 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 8604 const SCEV *LHS, 8605 const SCEV *RHS, 8606 const SCEV *FoundLHS, 8607 const SCEV *FoundRHS) { 8608 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 8609 // The restriction on `FoundRHS` be lifted easily -- it exists only to 8610 // reduce the compile time impact of this optimization. 8611 return false; 8612 8613 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 8614 if (!Addend) 8615 return false; 8616 8617 APInt ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 8618 8619 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 8620 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 8621 ConstantRange FoundLHSRange = 8622 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); 8623 8624 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 8625 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 8626 8627 // We can also compute the range of values for `LHS` that satisfy the 8628 // consequent, "`LHS` `Pred` `RHS`": 8629 APInt ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 8630 ConstantRange SatisfyingLHSRange = 8631 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS); 8632 8633 // The antecedent implies the consequent if every value of `LHS` that 8634 // satisfies the antecedent also satisfies the consequent. 8635 return SatisfyingLHSRange.contains(LHSRange); 8636 } 8637 8638 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 8639 bool IsSigned, bool NoWrap) { 8640 assert(isKnownPositive(Stride) && "Positive stride expected!"); 8641 8642 if (NoWrap) return false; 8643 8644 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 8645 const SCEV *One = getOne(Stride->getType()); 8646 8647 if (IsSigned) { 8648 APInt MaxRHS = getSignedRange(RHS).getSignedMax(); 8649 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 8650 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One)) 8651 .getSignedMax(); 8652 8653 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 8654 return (MaxValue - MaxStrideMinusOne).slt(MaxRHS); 8655 } 8656 8657 APInt MaxRHS = getUnsignedRange(RHS).getUnsignedMax(); 8658 APInt MaxValue = APInt::getMaxValue(BitWidth); 8659 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One)) 8660 .getUnsignedMax(); 8661 8662 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 8663 return (MaxValue - MaxStrideMinusOne).ult(MaxRHS); 8664 } 8665 8666 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 8667 bool IsSigned, bool NoWrap) { 8668 if (NoWrap) return false; 8669 8670 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 8671 const SCEV *One = getOne(Stride->getType()); 8672 8673 if (IsSigned) { 8674 APInt MinRHS = getSignedRange(RHS).getSignedMin(); 8675 APInt MinValue = APInt::getSignedMinValue(BitWidth); 8676 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One)) 8677 .getSignedMax(); 8678 8679 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 8680 return (MinValue + MaxStrideMinusOne).sgt(MinRHS); 8681 } 8682 8683 APInt MinRHS = getUnsignedRange(RHS).getUnsignedMin(); 8684 APInt MinValue = APInt::getMinValue(BitWidth); 8685 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One)) 8686 .getUnsignedMax(); 8687 8688 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 8689 return (MinValue + MaxStrideMinusOne).ugt(MinRHS); 8690 } 8691 8692 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step, 8693 bool Equality) { 8694 const SCEV *One = getOne(Step->getType()); 8695 Delta = Equality ? getAddExpr(Delta, Step) 8696 : getAddExpr(Delta, getMinusSCEV(Step, One)); 8697 return getUDivExpr(Delta, Step); 8698 } 8699 8700 ScalarEvolution::ExitLimit 8701 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 8702 const Loop *L, bool IsSigned, 8703 bool ControlsExit, bool AllowPredicates) { 8704 SCEVUnionPredicate P; 8705 // We handle only IV < Invariant 8706 if (!isLoopInvariant(RHS, L)) 8707 return getCouldNotCompute(); 8708 8709 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 8710 bool PredicatedIV = false; 8711 8712 if (!IV && AllowPredicates) { 8713 // Try to make this an AddRec using runtime tests, in the first X 8714 // iterations of this loop, where X is the SCEV expression found by the 8715 // algorithm below. 8716 IV = convertSCEVToAddRecWithPredicates(LHS, L, P); 8717 PredicatedIV = true; 8718 } 8719 8720 // Avoid weird loops 8721 if (!IV || IV->getLoop() != L || !IV->isAffine()) 8722 return getCouldNotCompute(); 8723 8724 bool NoWrap = ControlsExit && 8725 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 8726 8727 const SCEV *Stride = IV->getStepRecurrence(*this); 8728 8729 bool PositiveStride = isKnownPositive(Stride); 8730 8731 // Avoid negative or zero stride values. 8732 if (!PositiveStride) { 8733 // We can compute the correct backedge taken count for loops with unknown 8734 // strides if we can prove that the loop is not an infinite loop with side 8735 // effects. Here's the loop structure we are trying to handle - 8736 // 8737 // i = start 8738 // do { 8739 // A[i] = i; 8740 // i += s; 8741 // } while (i < end); 8742 // 8743 // The backedge taken count for such loops is evaluated as - 8744 // (max(end, start + stride) - start - 1) /u stride 8745 // 8746 // The additional preconditions that we need to check to prove correctness 8747 // of the above formula is as follows - 8748 // 8749 // a) IV is either nuw or nsw depending upon signedness (indicated by the 8750 // NoWrap flag). 8751 // b) loop is single exit with no side effects. 8752 // 8753 // 8754 // Precondition a) implies that if the stride is negative, this is a single 8755 // trip loop. The backedge taken count formula reduces to zero in this case. 8756 // 8757 // Precondition b) implies that the unknown stride cannot be zero otherwise 8758 // we have UB. 8759 // 8760 // The positive stride case is the same as isKnownPositive(Stride) returning 8761 // true (original behavior of the function). 8762 // 8763 // We want to make sure that the stride is truly unknown as there are edge 8764 // cases where ScalarEvolution propagates no wrap flags to the 8765 // post-increment/decrement IV even though the increment/decrement operation 8766 // itself is wrapping. The computed backedge taken count may be wrong in 8767 // such cases. This is prevented by checking that the stride is not known to 8768 // be either positive or non-positive. For example, no wrap flags are 8769 // propagated to the post-increment IV of this loop with a trip count of 2 - 8770 // 8771 // unsigned char i; 8772 // for(i=127; i<128; i+=129) 8773 // A[i] = i; 8774 // 8775 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) || 8776 !loopHasNoSideEffects(L)) 8777 return getCouldNotCompute(); 8778 8779 } else if (!Stride->isOne() && 8780 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap)) 8781 // Avoid proven overflow cases: this will ensure that the backedge taken 8782 // count will not generate any unsigned overflow. Relaxed no-overflow 8783 // conditions exploit NoWrapFlags, allowing to optimize in presence of 8784 // undefined behaviors like the case of C language. 8785 return getCouldNotCompute(); 8786 8787 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT 8788 : ICmpInst::ICMP_ULT; 8789 const SCEV *Start = IV->getStart(); 8790 const SCEV *End = RHS; 8791 if (!isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) 8792 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 8793 8794 const SCEV *BECount = computeBECount(getMinusSCEV(End, Start), Stride, false); 8795 8796 APInt MinStart = IsSigned ? getSignedRange(Start).getSignedMin() 8797 : getUnsignedRange(Start).getUnsignedMin(); 8798 8799 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 8800 8801 APInt StrideForMaxBECount; 8802 8803 if (PositiveStride) 8804 StrideForMaxBECount = IsSigned ? getSignedRange(Stride).getSignedMin() 8805 : getUnsignedRange(Stride).getUnsignedMin(); 8806 else 8807 // Using a stride of 1 is safe when computing max backedge taken count for 8808 // a loop with unknown stride. 8809 StrideForMaxBECount = APInt(BitWidth, 1, IsSigned); 8810 8811 APInt Limit = 8812 IsSigned ? APInt::getSignedMaxValue(BitWidth) - (StrideForMaxBECount - 1) 8813 : APInt::getMaxValue(BitWidth) - (StrideForMaxBECount - 1); 8814 8815 // Although End can be a MAX expression we estimate MaxEnd considering only 8816 // the case End = RHS. This is safe because in the other case (End - Start) 8817 // is zero, leading to a zero maximum backedge taken count. 8818 APInt MaxEnd = 8819 IsSigned ? APIntOps::smin(getSignedRange(RHS).getSignedMax(), Limit) 8820 : APIntOps::umin(getUnsignedRange(RHS).getUnsignedMax(), Limit); 8821 8822 const SCEV *MaxBECount; 8823 if (isa<SCEVConstant>(BECount)) 8824 MaxBECount = BECount; 8825 else 8826 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart), 8827 getConstant(StrideForMaxBECount), false); 8828 8829 if (isa<SCEVCouldNotCompute>(MaxBECount)) 8830 MaxBECount = BECount; 8831 8832 return ExitLimit(BECount, MaxBECount, P); 8833 } 8834 8835 ScalarEvolution::ExitLimit 8836 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 8837 const Loop *L, bool IsSigned, 8838 bool ControlsExit, bool AllowPredicates) { 8839 SCEVUnionPredicate P; 8840 // We handle only IV > Invariant 8841 if (!isLoopInvariant(RHS, L)) 8842 return getCouldNotCompute(); 8843 8844 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 8845 if (!IV && AllowPredicates) 8846 // Try to make this an AddRec using runtime tests, in the first X 8847 // iterations of this loop, where X is the SCEV expression found by the 8848 // algorithm below. 8849 IV = convertSCEVToAddRecWithPredicates(LHS, L, P); 8850 8851 // Avoid weird loops 8852 if (!IV || IV->getLoop() != L || !IV->isAffine()) 8853 return getCouldNotCompute(); 8854 8855 bool NoWrap = ControlsExit && 8856 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 8857 8858 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 8859 8860 // Avoid negative or zero stride values 8861 if (!isKnownPositive(Stride)) 8862 return getCouldNotCompute(); 8863 8864 // Avoid proven overflow cases: this will ensure that the backedge taken count 8865 // will not generate any unsigned overflow. Relaxed no-overflow conditions 8866 // exploit NoWrapFlags, allowing to optimize in presence of undefined 8867 // behaviors like the case of C language. 8868 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap)) 8869 return getCouldNotCompute(); 8870 8871 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT 8872 : ICmpInst::ICMP_UGT; 8873 8874 const SCEV *Start = IV->getStart(); 8875 const SCEV *End = RHS; 8876 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) 8877 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 8878 8879 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false); 8880 8881 APInt MaxStart = IsSigned ? getSignedRange(Start).getSignedMax() 8882 : getUnsignedRange(Start).getUnsignedMax(); 8883 8884 APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin() 8885 : getUnsignedRange(Stride).getUnsignedMin(); 8886 8887 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 8888 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 8889 : APInt::getMinValue(BitWidth) + (MinStride - 1); 8890 8891 // Although End can be a MIN expression we estimate MinEnd considering only 8892 // the case End = RHS. This is safe because in the other case (Start - End) 8893 // is zero, leading to a zero maximum backedge taken count. 8894 APInt MinEnd = 8895 IsSigned ? APIntOps::smax(getSignedRange(RHS).getSignedMin(), Limit) 8896 : APIntOps::umax(getUnsignedRange(RHS).getUnsignedMin(), Limit); 8897 8898 8899 const SCEV *MaxBECount = getCouldNotCompute(); 8900 if (isa<SCEVConstant>(BECount)) 8901 MaxBECount = BECount; 8902 else 8903 MaxBECount = computeBECount(getConstant(MaxStart - MinEnd), 8904 getConstant(MinStride), false); 8905 8906 if (isa<SCEVCouldNotCompute>(MaxBECount)) 8907 MaxBECount = BECount; 8908 8909 return ExitLimit(BECount, MaxBECount, P); 8910 } 8911 8912 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 8913 ScalarEvolution &SE) const { 8914 if (Range.isFullSet()) // Infinite loop. 8915 return SE.getCouldNotCompute(); 8916 8917 // If the start is a non-zero constant, shift the range to simplify things. 8918 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 8919 if (!SC->getValue()->isZero()) { 8920 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end()); 8921 Operands[0] = SE.getZero(SC->getType()); 8922 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 8923 getNoWrapFlags(FlagNW)); 8924 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 8925 return ShiftedAddRec->getNumIterationsInRange( 8926 Range.subtract(SC->getAPInt()), SE); 8927 // This is strange and shouldn't happen. 8928 return SE.getCouldNotCompute(); 8929 } 8930 8931 // The only time we can solve this is when we have all constant indices. 8932 // Otherwise, we cannot determine the overflow conditions. 8933 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 8934 return SE.getCouldNotCompute(); 8935 8936 // Okay at this point we know that all elements of the chrec are constants and 8937 // that the start element is zero. 8938 8939 // First check to see if the range contains zero. If not, the first 8940 // iteration exits. 8941 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 8942 if (!Range.contains(APInt(BitWidth, 0))) 8943 return SE.getZero(getType()); 8944 8945 if (isAffine()) { 8946 // If this is an affine expression then we have this situation: 8947 // Solve {0,+,A} in Range === Ax in Range 8948 8949 // We know that zero is in the range. If A is positive then we know that 8950 // the upper value of the range must be the first possible exit value. 8951 // If A is negative then the lower of the range is the last possible loop 8952 // value. Also note that we already checked for a full range. 8953 APInt One(BitWidth,1); 8954 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 8955 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower(); 8956 8957 // The exit value should be (End+A)/A. 8958 APInt ExitVal = (End + A).udiv(A); 8959 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 8960 8961 // Evaluate at the exit value. If we really did fall out of the valid 8962 // range, then we computed our trip count, otherwise wrap around or other 8963 // things must have happened. 8964 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 8965 if (Range.contains(Val->getValue())) 8966 return SE.getCouldNotCompute(); // Something strange happened 8967 8968 // Ensure that the previous value is in the range. This is a sanity check. 8969 assert(Range.contains( 8970 EvaluateConstantChrecAtConstant(this, 8971 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) && 8972 "Linear scev computation is off in a bad way!"); 8973 return SE.getConstant(ExitValue); 8974 } else if (isQuadratic()) { 8975 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the 8976 // quadratic equation to solve it. To do this, we must frame our problem in 8977 // terms of figuring out when zero is crossed, instead of when 8978 // Range.getUpper() is crossed. 8979 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end()); 8980 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper())); 8981 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), 8982 // getNoWrapFlags(FlagNW) 8983 FlagAnyWrap); 8984 8985 // Next, solve the constructed addrec 8986 if (auto Roots = 8987 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE)) { 8988 const SCEVConstant *R1 = Roots->first; 8989 const SCEVConstant *R2 = Roots->second; 8990 // Pick the smallest positive root value. 8991 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp( 8992 ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) { 8993 if (!CB->getZExtValue()) 8994 std::swap(R1, R2); // R1 is the minimum root now. 8995 8996 // Make sure the root is not off by one. The returned iteration should 8997 // not be in the range, but the previous one should be. When solving 8998 // for "X*X < 5", for example, we should not return a root of 2. 8999 ConstantInt *R1Val = 9000 EvaluateConstantChrecAtConstant(this, R1->getValue(), SE); 9001 if (Range.contains(R1Val->getValue())) { 9002 // The next iteration must be out of the range... 9003 ConstantInt *NextVal = 9004 ConstantInt::get(SE.getContext(), R1->getAPInt() + 1); 9005 9006 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); 9007 if (!Range.contains(R1Val->getValue())) 9008 return SE.getConstant(NextVal); 9009 return SE.getCouldNotCompute(); // Something strange happened 9010 } 9011 9012 // If R1 was not in the range, then it is a good return value. Make 9013 // sure that R1-1 WAS in the range though, just in case. 9014 ConstantInt *NextVal = 9015 ConstantInt::get(SE.getContext(), R1->getAPInt() - 1); 9016 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); 9017 if (Range.contains(R1Val->getValue())) 9018 return R1; 9019 return SE.getCouldNotCompute(); // Something strange happened 9020 } 9021 } 9022 } 9023 9024 return SE.getCouldNotCompute(); 9025 } 9026 9027 namespace { 9028 struct FindUndefs { 9029 bool Found; 9030 FindUndefs() : Found(false) {} 9031 9032 bool follow(const SCEV *S) { 9033 if (const SCEVUnknown *C = dyn_cast<SCEVUnknown>(S)) { 9034 if (isa<UndefValue>(C->getValue())) 9035 Found = true; 9036 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) { 9037 if (isa<UndefValue>(C->getValue())) 9038 Found = true; 9039 } 9040 9041 // Keep looking if we haven't found it yet. 9042 return !Found; 9043 } 9044 bool isDone() const { 9045 // Stop recursion if we have found an undef. 9046 return Found; 9047 } 9048 }; 9049 } 9050 9051 // Return true when S contains at least an undef value. 9052 static inline bool 9053 containsUndefs(const SCEV *S) { 9054 FindUndefs F; 9055 SCEVTraversal<FindUndefs> ST(F); 9056 ST.visitAll(S); 9057 9058 return F.Found; 9059 } 9060 9061 namespace { 9062 // Collect all steps of SCEV expressions. 9063 struct SCEVCollectStrides { 9064 ScalarEvolution &SE; 9065 SmallVectorImpl<const SCEV *> &Strides; 9066 9067 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) 9068 : SE(SE), Strides(S) {} 9069 9070 bool follow(const SCEV *S) { 9071 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 9072 Strides.push_back(AR->getStepRecurrence(SE)); 9073 return true; 9074 } 9075 bool isDone() const { return false; } 9076 }; 9077 9078 // Collect all SCEVUnknown and SCEVMulExpr expressions. 9079 struct SCEVCollectTerms { 9080 SmallVectorImpl<const SCEV *> &Terms; 9081 9082 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) 9083 : Terms(T) {} 9084 9085 bool follow(const SCEV *S) { 9086 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S)) { 9087 if (!containsUndefs(S)) 9088 Terms.push_back(S); 9089 9090 // Stop recursion: once we collected a term, do not walk its operands. 9091 return false; 9092 } 9093 9094 // Keep looking. 9095 return true; 9096 } 9097 bool isDone() const { return false; } 9098 }; 9099 9100 // Check if a SCEV contains an AddRecExpr. 9101 struct SCEVHasAddRec { 9102 bool &ContainsAddRec; 9103 9104 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) { 9105 ContainsAddRec = false; 9106 } 9107 9108 bool follow(const SCEV *S) { 9109 if (isa<SCEVAddRecExpr>(S)) { 9110 ContainsAddRec = true; 9111 9112 // Stop recursion: once we collected a term, do not walk its operands. 9113 return false; 9114 } 9115 9116 // Keep looking. 9117 return true; 9118 } 9119 bool isDone() const { return false; } 9120 }; 9121 9122 // Find factors that are multiplied with an expression that (possibly as a 9123 // subexpression) contains an AddRecExpr. In the expression: 9124 // 9125 // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop)) 9126 // 9127 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)" 9128 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size 9129 // parameters as they form a product with an induction variable. 9130 // 9131 // This collector expects all array size parameters to be in the same MulExpr. 9132 // It might be necessary to later add support for collecting parameters that are 9133 // spread over different nested MulExpr. 9134 struct SCEVCollectAddRecMultiplies { 9135 SmallVectorImpl<const SCEV *> &Terms; 9136 ScalarEvolution &SE; 9137 9138 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE) 9139 : Terms(T), SE(SE) {} 9140 9141 bool follow(const SCEV *S) { 9142 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) { 9143 bool HasAddRec = false; 9144 SmallVector<const SCEV *, 0> Operands; 9145 for (auto Op : Mul->operands()) { 9146 if (isa<SCEVUnknown>(Op)) { 9147 Operands.push_back(Op); 9148 } else { 9149 bool ContainsAddRec; 9150 SCEVHasAddRec ContiansAddRec(ContainsAddRec); 9151 visitAll(Op, ContiansAddRec); 9152 HasAddRec |= ContainsAddRec; 9153 } 9154 } 9155 if (Operands.size() == 0) 9156 return true; 9157 9158 if (!HasAddRec) 9159 return false; 9160 9161 Terms.push_back(SE.getMulExpr(Operands)); 9162 // Stop recursion: once we collected a term, do not walk its operands. 9163 return false; 9164 } 9165 9166 // Keep looking. 9167 return true; 9168 } 9169 bool isDone() const { return false; } 9170 }; 9171 } 9172 9173 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in 9174 /// two places: 9175 /// 1) The strides of AddRec expressions. 9176 /// 2) Unknowns that are multiplied with AddRec expressions. 9177 void ScalarEvolution::collectParametricTerms(const SCEV *Expr, 9178 SmallVectorImpl<const SCEV *> &Terms) { 9179 SmallVector<const SCEV *, 4> Strides; 9180 SCEVCollectStrides StrideCollector(*this, Strides); 9181 visitAll(Expr, StrideCollector); 9182 9183 DEBUG({ 9184 dbgs() << "Strides:\n"; 9185 for (const SCEV *S : Strides) 9186 dbgs() << *S << "\n"; 9187 }); 9188 9189 for (const SCEV *S : Strides) { 9190 SCEVCollectTerms TermCollector(Terms); 9191 visitAll(S, TermCollector); 9192 } 9193 9194 DEBUG({ 9195 dbgs() << "Terms:\n"; 9196 for (const SCEV *T : Terms) 9197 dbgs() << *T << "\n"; 9198 }); 9199 9200 SCEVCollectAddRecMultiplies MulCollector(Terms, *this); 9201 visitAll(Expr, MulCollector); 9202 } 9203 9204 static bool findArrayDimensionsRec(ScalarEvolution &SE, 9205 SmallVectorImpl<const SCEV *> &Terms, 9206 SmallVectorImpl<const SCEV *> &Sizes) { 9207 int Last = Terms.size() - 1; 9208 const SCEV *Step = Terms[Last]; 9209 9210 // End of recursion. 9211 if (Last == 0) { 9212 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { 9213 SmallVector<const SCEV *, 2> Qs; 9214 for (const SCEV *Op : M->operands()) 9215 if (!isa<SCEVConstant>(Op)) 9216 Qs.push_back(Op); 9217 9218 Step = SE.getMulExpr(Qs); 9219 } 9220 9221 Sizes.push_back(Step); 9222 return true; 9223 } 9224 9225 for (const SCEV *&Term : Terms) { 9226 // Normalize the terms before the next call to findArrayDimensionsRec. 9227 const SCEV *Q, *R; 9228 SCEVDivision::divide(SE, Term, Step, &Q, &R); 9229 9230 // Bail out when GCD does not evenly divide one of the terms. 9231 if (!R->isZero()) 9232 return false; 9233 9234 Term = Q; 9235 } 9236 9237 // Remove all SCEVConstants. 9238 Terms.erase( 9239 remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }), 9240 Terms.end()); 9241 9242 if (Terms.size() > 0) 9243 if (!findArrayDimensionsRec(SE, Terms, Sizes)) 9244 return false; 9245 9246 Sizes.push_back(Step); 9247 return true; 9248 } 9249 9250 // Returns true when S contains at least a SCEVUnknown parameter. 9251 static inline bool 9252 containsParameters(const SCEV *S) { 9253 struct FindParameter { 9254 bool FoundParameter; 9255 FindParameter() : FoundParameter(false) {} 9256 9257 bool follow(const SCEV *S) { 9258 if (isa<SCEVUnknown>(S)) { 9259 FoundParameter = true; 9260 // Stop recursion: we found a parameter. 9261 return false; 9262 } 9263 // Keep looking. 9264 return true; 9265 } 9266 bool isDone() const { 9267 // Stop recursion if we have found a parameter. 9268 return FoundParameter; 9269 } 9270 }; 9271 9272 FindParameter F; 9273 SCEVTraversal<FindParameter> ST(F); 9274 ST.visitAll(S); 9275 9276 return F.FoundParameter; 9277 } 9278 9279 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. 9280 static inline bool 9281 containsParameters(SmallVectorImpl<const SCEV *> &Terms) { 9282 for (const SCEV *T : Terms) 9283 if (containsParameters(T)) 9284 return true; 9285 return false; 9286 } 9287 9288 // Return the number of product terms in S. 9289 static inline int numberOfTerms(const SCEV *S) { 9290 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) 9291 return Expr->getNumOperands(); 9292 return 1; 9293 } 9294 9295 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { 9296 if (isa<SCEVConstant>(T)) 9297 return nullptr; 9298 9299 if (isa<SCEVUnknown>(T)) 9300 return T; 9301 9302 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { 9303 SmallVector<const SCEV *, 2> Factors; 9304 for (const SCEV *Op : M->operands()) 9305 if (!isa<SCEVConstant>(Op)) 9306 Factors.push_back(Op); 9307 9308 return SE.getMulExpr(Factors); 9309 } 9310 9311 return T; 9312 } 9313 9314 /// Return the size of an element read or written by Inst. 9315 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 9316 Type *Ty; 9317 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 9318 Ty = Store->getValueOperand()->getType(); 9319 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 9320 Ty = Load->getType(); 9321 else 9322 return nullptr; 9323 9324 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 9325 return getSizeOfExpr(ETy, Ty); 9326 } 9327 9328 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, 9329 SmallVectorImpl<const SCEV *> &Sizes, 9330 const SCEV *ElementSize) const { 9331 if (Terms.size() < 1 || !ElementSize) 9332 return; 9333 9334 // Early return when Terms do not contain parameters: we do not delinearize 9335 // non parametric SCEVs. 9336 if (!containsParameters(Terms)) 9337 return; 9338 9339 DEBUG({ 9340 dbgs() << "Terms:\n"; 9341 for (const SCEV *T : Terms) 9342 dbgs() << *T << "\n"; 9343 }); 9344 9345 // Remove duplicates. 9346 std::sort(Terms.begin(), Terms.end()); 9347 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); 9348 9349 // Put larger terms first. 9350 std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) { 9351 return numberOfTerms(LHS) > numberOfTerms(RHS); 9352 }); 9353 9354 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 9355 9356 // Try to divide all terms by the element size. If term is not divisible by 9357 // element size, proceed with the original term. 9358 for (const SCEV *&Term : Terms) { 9359 const SCEV *Q, *R; 9360 SCEVDivision::divide(SE, Term, ElementSize, &Q, &R); 9361 if (!Q->isZero()) 9362 Term = Q; 9363 } 9364 9365 SmallVector<const SCEV *, 4> NewTerms; 9366 9367 // Remove constant factors. 9368 for (const SCEV *T : Terms) 9369 if (const SCEV *NewT = removeConstantFactors(SE, T)) 9370 NewTerms.push_back(NewT); 9371 9372 DEBUG({ 9373 dbgs() << "Terms after sorting:\n"; 9374 for (const SCEV *T : NewTerms) 9375 dbgs() << *T << "\n"; 9376 }); 9377 9378 if (NewTerms.empty() || 9379 !findArrayDimensionsRec(SE, NewTerms, Sizes)) { 9380 Sizes.clear(); 9381 return; 9382 } 9383 9384 // The last element to be pushed into Sizes is the size of an element. 9385 Sizes.push_back(ElementSize); 9386 9387 DEBUG({ 9388 dbgs() << "Sizes:\n"; 9389 for (const SCEV *S : Sizes) 9390 dbgs() << *S << "\n"; 9391 }); 9392 } 9393 9394 void ScalarEvolution::computeAccessFunctions( 9395 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, 9396 SmallVectorImpl<const SCEV *> &Sizes) { 9397 9398 // Early exit in case this SCEV is not an affine multivariate function. 9399 if (Sizes.empty()) 9400 return; 9401 9402 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr)) 9403 if (!AR->isAffine()) 9404 return; 9405 9406 const SCEV *Res = Expr; 9407 int Last = Sizes.size() - 1; 9408 for (int i = Last; i >= 0; i--) { 9409 const SCEV *Q, *R; 9410 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); 9411 9412 DEBUG({ 9413 dbgs() << "Res: " << *Res << "\n"; 9414 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; 9415 dbgs() << "Res divided by Sizes[i]:\n"; 9416 dbgs() << "Quotient: " << *Q << "\n"; 9417 dbgs() << "Remainder: " << *R << "\n"; 9418 }); 9419 9420 Res = Q; 9421 9422 // Do not record the last subscript corresponding to the size of elements in 9423 // the array. 9424 if (i == Last) { 9425 9426 // Bail out if the remainder is too complex. 9427 if (isa<SCEVAddRecExpr>(R)) { 9428 Subscripts.clear(); 9429 Sizes.clear(); 9430 return; 9431 } 9432 9433 continue; 9434 } 9435 9436 // Record the access function for the current subscript. 9437 Subscripts.push_back(R); 9438 } 9439 9440 // Also push in last position the remainder of the last division: it will be 9441 // the access function of the innermost dimension. 9442 Subscripts.push_back(Res); 9443 9444 std::reverse(Subscripts.begin(), Subscripts.end()); 9445 9446 DEBUG({ 9447 dbgs() << "Subscripts:\n"; 9448 for (const SCEV *S : Subscripts) 9449 dbgs() << *S << "\n"; 9450 }); 9451 } 9452 9453 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and 9454 /// sizes of an array access. Returns the remainder of the delinearization that 9455 /// is the offset start of the array. The SCEV->delinearize algorithm computes 9456 /// the multiples of SCEV coefficients: that is a pattern matching of sub 9457 /// expressions in the stride and base of a SCEV corresponding to the 9458 /// computation of a GCD (greatest common divisor) of base and stride. When 9459 /// SCEV->delinearize fails, it returns the SCEV unchanged. 9460 /// 9461 /// For example: when analyzing the memory access A[i][j][k] in this loop nest 9462 /// 9463 /// void foo(long n, long m, long o, double A[n][m][o]) { 9464 /// 9465 /// for (long i = 0; i < n; i++) 9466 /// for (long j = 0; j < m; j++) 9467 /// for (long k = 0; k < o; k++) 9468 /// A[i][j][k] = 1.0; 9469 /// } 9470 /// 9471 /// the delinearization input is the following AddRec SCEV: 9472 /// 9473 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> 9474 /// 9475 /// From this SCEV, we are able to say that the base offset of the access is %A 9476 /// because it appears as an offset that does not divide any of the strides in 9477 /// the loops: 9478 /// 9479 /// CHECK: Base offset: %A 9480 /// 9481 /// and then SCEV->delinearize determines the size of some of the dimensions of 9482 /// the array as these are the multiples by which the strides are happening: 9483 /// 9484 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. 9485 /// 9486 /// Note that the outermost dimension remains of UnknownSize because there are 9487 /// no strides that would help identifying the size of the last dimension: when 9488 /// the array has been statically allocated, one could compute the size of that 9489 /// dimension by dividing the overall size of the array by the size of the known 9490 /// dimensions: %m * %o * 8. 9491 /// 9492 /// Finally delinearize provides the access functions for the array reference 9493 /// that does correspond to A[i][j][k] of the above C testcase: 9494 /// 9495 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] 9496 /// 9497 /// The testcases are checking the output of a function pass: 9498 /// DelinearizationPass that walks through all loads and stores of a function 9499 /// asking for the SCEV of the memory access with respect to all enclosing 9500 /// loops, calling SCEV->delinearize on that and printing the results. 9501 9502 void ScalarEvolution::delinearize(const SCEV *Expr, 9503 SmallVectorImpl<const SCEV *> &Subscripts, 9504 SmallVectorImpl<const SCEV *> &Sizes, 9505 const SCEV *ElementSize) { 9506 // First step: collect parametric terms. 9507 SmallVector<const SCEV *, 4> Terms; 9508 collectParametricTerms(Expr, Terms); 9509 9510 if (Terms.empty()) 9511 return; 9512 9513 // Second step: find subscript sizes. 9514 findArrayDimensions(Terms, Sizes, ElementSize); 9515 9516 if (Sizes.empty()) 9517 return; 9518 9519 // Third step: compute the access functions for each subscript. 9520 computeAccessFunctions(Expr, Subscripts, Sizes); 9521 9522 if (Subscripts.empty()) 9523 return; 9524 9525 DEBUG({ 9526 dbgs() << "succeeded to delinearize " << *Expr << "\n"; 9527 dbgs() << "ArrayDecl[UnknownSize]"; 9528 for (const SCEV *S : Sizes) 9529 dbgs() << "[" << *S << "]"; 9530 9531 dbgs() << "\nArrayRef"; 9532 for (const SCEV *S : Subscripts) 9533 dbgs() << "[" << *S << "]"; 9534 dbgs() << "\n"; 9535 }); 9536 } 9537 9538 //===----------------------------------------------------------------------===// 9539 // SCEVCallbackVH Class Implementation 9540 //===----------------------------------------------------------------------===// 9541 9542 void ScalarEvolution::SCEVCallbackVH::deleted() { 9543 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 9544 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 9545 SE->ConstantEvolutionLoopExitValue.erase(PN); 9546 SE->eraseValueFromMap(getValPtr()); 9547 // this now dangles! 9548 } 9549 9550 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 9551 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 9552 9553 // Forget all the expressions associated with users of the old value, 9554 // so that future queries will recompute the expressions using the new 9555 // value. 9556 Value *Old = getValPtr(); 9557 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end()); 9558 SmallPtrSet<User *, 8> Visited; 9559 while (!Worklist.empty()) { 9560 User *U = Worklist.pop_back_val(); 9561 // Deleting the Old value will cause this to dangle. Postpone 9562 // that until everything else is done. 9563 if (U == Old) 9564 continue; 9565 if (!Visited.insert(U).second) 9566 continue; 9567 if (PHINode *PN = dyn_cast<PHINode>(U)) 9568 SE->ConstantEvolutionLoopExitValue.erase(PN); 9569 SE->eraseValueFromMap(U); 9570 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end()); 9571 } 9572 // Delete the Old value. 9573 if (PHINode *PN = dyn_cast<PHINode>(Old)) 9574 SE->ConstantEvolutionLoopExitValue.erase(PN); 9575 SE->eraseValueFromMap(Old); 9576 // this now dangles! 9577 } 9578 9579 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 9580 : CallbackVH(V), SE(se) {} 9581 9582 //===----------------------------------------------------------------------===// 9583 // ScalarEvolution Class Implementation 9584 //===----------------------------------------------------------------------===// 9585 9586 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 9587 AssumptionCache &AC, DominatorTree &DT, 9588 LoopInfo &LI) 9589 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 9590 CouldNotCompute(new SCEVCouldNotCompute()), 9591 WalkingBEDominatingConds(false), ProvingSplitPredicate(false), 9592 ValuesAtScopes(64), LoopDispositions(64), BlockDispositions(64), 9593 FirstUnknown(nullptr) { 9594 9595 // To use guards for proving predicates, we need to scan every instruction in 9596 // relevant basic blocks, and not just terminators. Doing this is a waste of 9597 // time if the IR does not actually contain any calls to 9598 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 9599 // 9600 // This pessimizes the case where a pass that preserves ScalarEvolution wants 9601 // to _add_ guards to the module when there weren't any before, and wants 9602 // ScalarEvolution to optimize based on those guards. For now we prefer to be 9603 // efficient in lieu of being smart in that rather obscure case. 9604 9605 auto *GuardDecl = F.getParent()->getFunction( 9606 Intrinsic::getName(Intrinsic::experimental_guard)); 9607 HasGuards = GuardDecl && !GuardDecl->use_empty(); 9608 } 9609 9610 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 9611 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 9612 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 9613 ValueExprMap(std::move(Arg.ValueExprMap)), 9614 WalkingBEDominatingConds(false), ProvingSplitPredicate(false), 9615 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 9616 PredicatedBackedgeTakenCounts( 9617 std::move(Arg.PredicatedBackedgeTakenCounts)), 9618 ConstantEvolutionLoopExitValue( 9619 std::move(Arg.ConstantEvolutionLoopExitValue)), 9620 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 9621 LoopDispositions(std::move(Arg.LoopDispositions)), 9622 BlockDispositions(std::move(Arg.BlockDispositions)), 9623 UnsignedRanges(std::move(Arg.UnsignedRanges)), 9624 SignedRanges(std::move(Arg.SignedRanges)), 9625 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 9626 UniquePreds(std::move(Arg.UniquePreds)), 9627 SCEVAllocator(std::move(Arg.SCEVAllocator)), 9628 FirstUnknown(Arg.FirstUnknown) { 9629 Arg.FirstUnknown = nullptr; 9630 } 9631 9632 ScalarEvolution::~ScalarEvolution() { 9633 // Iterate through all the SCEVUnknown instances and call their 9634 // destructors, so that they release their references to their values. 9635 for (SCEVUnknown *U = FirstUnknown; U;) { 9636 SCEVUnknown *Tmp = U; 9637 U = U->Next; 9638 Tmp->~SCEVUnknown(); 9639 } 9640 FirstUnknown = nullptr; 9641 9642 ExprValueMap.clear(); 9643 ValueExprMap.clear(); 9644 HasRecMap.clear(); 9645 9646 // Free any extra memory created for ExitNotTakenInfo in the unlikely event 9647 // that a loop had multiple computable exits. 9648 for (auto &BTCI : BackedgeTakenCounts) 9649 BTCI.second.clear(); 9650 for (auto &BTCI : PredicatedBackedgeTakenCounts) 9651 BTCI.second.clear(); 9652 9653 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 9654 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 9655 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 9656 } 9657 9658 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 9659 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 9660 } 9661 9662 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 9663 const Loop *L) { 9664 // Print all inner loops first 9665 for (Loop *I : *L) 9666 PrintLoopInfo(OS, SE, I); 9667 9668 OS << "Loop "; 9669 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 9670 OS << ": "; 9671 9672 SmallVector<BasicBlock *, 8> ExitBlocks; 9673 L->getExitBlocks(ExitBlocks); 9674 if (ExitBlocks.size() != 1) 9675 OS << "<multiple exits> "; 9676 9677 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 9678 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L); 9679 } else { 9680 OS << "Unpredictable backedge-taken count. "; 9681 } 9682 9683 OS << "\n" 9684 "Loop "; 9685 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 9686 OS << ": "; 9687 9688 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) { 9689 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L); 9690 } else { 9691 OS << "Unpredictable max backedge-taken count. "; 9692 } 9693 9694 OS << "\n" 9695 "Loop "; 9696 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 9697 OS << ": "; 9698 9699 SCEVUnionPredicate Pred; 9700 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); 9701 if (!isa<SCEVCouldNotCompute>(PBT)) { 9702 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 9703 OS << " Predicates:\n"; 9704 Pred.print(OS, 4); 9705 } else { 9706 OS << "Unpredictable predicated backedge-taken count. "; 9707 } 9708 OS << "\n"; 9709 } 9710 9711 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 9712 switch (LD) { 9713 case ScalarEvolution::LoopVariant: 9714 return "Variant"; 9715 case ScalarEvolution::LoopInvariant: 9716 return "Invariant"; 9717 case ScalarEvolution::LoopComputable: 9718 return "Computable"; 9719 } 9720 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 9721 } 9722 9723 void ScalarEvolution::print(raw_ostream &OS) const { 9724 // ScalarEvolution's implementation of the print method is to print 9725 // out SCEV values of all instructions that are interesting. Doing 9726 // this potentially causes it to create new SCEV objects though, 9727 // which technically conflicts with the const qualifier. This isn't 9728 // observable from outside the class though, so casting away the 9729 // const isn't dangerous. 9730 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 9731 9732 OS << "Classifying expressions for: "; 9733 F.printAsOperand(OS, /*PrintType=*/false); 9734 OS << "\n"; 9735 for (Instruction &I : instructions(F)) 9736 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 9737 OS << I << '\n'; 9738 OS << " --> "; 9739 const SCEV *SV = SE.getSCEV(&I); 9740 SV->print(OS); 9741 if (!isa<SCEVCouldNotCompute>(SV)) { 9742 OS << " U: "; 9743 SE.getUnsignedRange(SV).print(OS); 9744 OS << " S: "; 9745 SE.getSignedRange(SV).print(OS); 9746 } 9747 9748 const Loop *L = LI.getLoopFor(I.getParent()); 9749 9750 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 9751 if (AtUse != SV) { 9752 OS << " --> "; 9753 AtUse->print(OS); 9754 if (!isa<SCEVCouldNotCompute>(AtUse)) { 9755 OS << " U: "; 9756 SE.getUnsignedRange(AtUse).print(OS); 9757 OS << " S: "; 9758 SE.getSignedRange(AtUse).print(OS); 9759 } 9760 } 9761 9762 if (L) { 9763 OS << "\t\t" "Exits: "; 9764 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 9765 if (!SE.isLoopInvariant(ExitValue, L)) { 9766 OS << "<<Unknown>>"; 9767 } else { 9768 OS << *ExitValue; 9769 } 9770 9771 bool First = true; 9772 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 9773 if (First) { 9774 OS << "\t\t" "LoopDispositions: { "; 9775 First = false; 9776 } else { 9777 OS << ", "; 9778 } 9779 9780 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 9781 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 9782 } 9783 9784 for (auto *InnerL : depth_first(L)) { 9785 if (InnerL == L) 9786 continue; 9787 if (First) { 9788 OS << "\t\t" "LoopDispositions: { "; 9789 First = false; 9790 } else { 9791 OS << ", "; 9792 } 9793 9794 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 9795 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 9796 } 9797 9798 OS << " }"; 9799 } 9800 9801 OS << "\n"; 9802 } 9803 9804 OS << "Determining loop execution counts for: "; 9805 F.printAsOperand(OS, /*PrintType=*/false); 9806 OS << "\n"; 9807 for (Loop *I : LI) 9808 PrintLoopInfo(OS, &SE, I); 9809 } 9810 9811 ScalarEvolution::LoopDisposition 9812 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 9813 auto &Values = LoopDispositions[S]; 9814 for (auto &V : Values) { 9815 if (V.getPointer() == L) 9816 return V.getInt(); 9817 } 9818 Values.emplace_back(L, LoopVariant); 9819 LoopDisposition D = computeLoopDisposition(S, L); 9820 auto &Values2 = LoopDispositions[S]; 9821 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 9822 if (V.getPointer() == L) { 9823 V.setInt(D); 9824 break; 9825 } 9826 } 9827 return D; 9828 } 9829 9830 ScalarEvolution::LoopDisposition 9831 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 9832 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 9833 case scConstant: 9834 return LoopInvariant; 9835 case scTruncate: 9836 case scZeroExtend: 9837 case scSignExtend: 9838 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 9839 case scAddRecExpr: { 9840 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 9841 9842 // If L is the addrec's loop, it's computable. 9843 if (AR->getLoop() == L) 9844 return LoopComputable; 9845 9846 // Add recurrences are never invariant in the function-body (null loop). 9847 if (!L) 9848 return LoopVariant; 9849 9850 // This recurrence is variant w.r.t. L if L contains AR's loop. 9851 if (L->contains(AR->getLoop())) 9852 return LoopVariant; 9853 9854 // This recurrence is invariant w.r.t. L if AR's loop contains L. 9855 if (AR->getLoop()->contains(L)) 9856 return LoopInvariant; 9857 9858 // This recurrence is variant w.r.t. L if any of its operands 9859 // are variant. 9860 for (auto *Op : AR->operands()) 9861 if (!isLoopInvariant(Op, L)) 9862 return LoopVariant; 9863 9864 // Otherwise it's loop-invariant. 9865 return LoopInvariant; 9866 } 9867 case scAddExpr: 9868 case scMulExpr: 9869 case scUMaxExpr: 9870 case scSMaxExpr: { 9871 bool HasVarying = false; 9872 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 9873 LoopDisposition D = getLoopDisposition(Op, L); 9874 if (D == LoopVariant) 9875 return LoopVariant; 9876 if (D == LoopComputable) 9877 HasVarying = true; 9878 } 9879 return HasVarying ? LoopComputable : LoopInvariant; 9880 } 9881 case scUDivExpr: { 9882 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 9883 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 9884 if (LD == LoopVariant) 9885 return LoopVariant; 9886 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 9887 if (RD == LoopVariant) 9888 return LoopVariant; 9889 return (LD == LoopInvariant && RD == LoopInvariant) ? 9890 LoopInvariant : LoopComputable; 9891 } 9892 case scUnknown: 9893 // All non-instruction values are loop invariant. All instructions are loop 9894 // invariant if they are not contained in the specified loop. 9895 // Instructions are never considered invariant in the function body 9896 // (null loop) because they are defined within the "loop". 9897 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 9898 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 9899 return LoopInvariant; 9900 case scCouldNotCompute: 9901 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 9902 } 9903 llvm_unreachable("Unknown SCEV kind!"); 9904 } 9905 9906 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 9907 return getLoopDisposition(S, L) == LoopInvariant; 9908 } 9909 9910 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 9911 return getLoopDisposition(S, L) == LoopComputable; 9912 } 9913 9914 ScalarEvolution::BlockDisposition 9915 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 9916 auto &Values = BlockDispositions[S]; 9917 for (auto &V : Values) { 9918 if (V.getPointer() == BB) 9919 return V.getInt(); 9920 } 9921 Values.emplace_back(BB, DoesNotDominateBlock); 9922 BlockDisposition D = computeBlockDisposition(S, BB); 9923 auto &Values2 = BlockDispositions[S]; 9924 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 9925 if (V.getPointer() == BB) { 9926 V.setInt(D); 9927 break; 9928 } 9929 } 9930 return D; 9931 } 9932 9933 ScalarEvolution::BlockDisposition 9934 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 9935 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 9936 case scConstant: 9937 return ProperlyDominatesBlock; 9938 case scTruncate: 9939 case scZeroExtend: 9940 case scSignExtend: 9941 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 9942 case scAddRecExpr: { 9943 // This uses a "dominates" query instead of "properly dominates" query 9944 // to test for proper dominance too, because the instruction which 9945 // produces the addrec's value is a PHI, and a PHI effectively properly 9946 // dominates its entire containing block. 9947 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 9948 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 9949 return DoesNotDominateBlock; 9950 9951 // Fall through into SCEVNAryExpr handling. 9952 LLVM_FALLTHROUGH; 9953 } 9954 case scAddExpr: 9955 case scMulExpr: 9956 case scUMaxExpr: 9957 case scSMaxExpr: { 9958 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 9959 bool Proper = true; 9960 for (const SCEV *NAryOp : NAry->operands()) { 9961 BlockDisposition D = getBlockDisposition(NAryOp, BB); 9962 if (D == DoesNotDominateBlock) 9963 return DoesNotDominateBlock; 9964 if (D == DominatesBlock) 9965 Proper = false; 9966 } 9967 return Proper ? ProperlyDominatesBlock : DominatesBlock; 9968 } 9969 case scUDivExpr: { 9970 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 9971 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 9972 BlockDisposition LD = getBlockDisposition(LHS, BB); 9973 if (LD == DoesNotDominateBlock) 9974 return DoesNotDominateBlock; 9975 BlockDisposition RD = getBlockDisposition(RHS, BB); 9976 if (RD == DoesNotDominateBlock) 9977 return DoesNotDominateBlock; 9978 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 9979 ProperlyDominatesBlock : DominatesBlock; 9980 } 9981 case scUnknown: 9982 if (Instruction *I = 9983 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 9984 if (I->getParent() == BB) 9985 return DominatesBlock; 9986 if (DT.properlyDominates(I->getParent(), BB)) 9987 return ProperlyDominatesBlock; 9988 return DoesNotDominateBlock; 9989 } 9990 return ProperlyDominatesBlock; 9991 case scCouldNotCompute: 9992 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 9993 } 9994 llvm_unreachable("Unknown SCEV kind!"); 9995 } 9996 9997 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 9998 return getBlockDisposition(S, BB) >= DominatesBlock; 9999 } 10000 10001 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 10002 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 10003 } 10004 10005 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 10006 // Search for a SCEV expression node within an expression tree. 10007 // Implements SCEVTraversal::Visitor. 10008 struct SCEVSearch { 10009 const SCEV *Node; 10010 bool IsFound; 10011 10012 SCEVSearch(const SCEV *N): Node(N), IsFound(false) {} 10013 10014 bool follow(const SCEV *S) { 10015 IsFound |= (S == Node); 10016 return !IsFound; 10017 } 10018 bool isDone() const { return IsFound; } 10019 }; 10020 10021 SCEVSearch Search(Op); 10022 visitAll(S, Search); 10023 return Search.IsFound; 10024 } 10025 10026 void ScalarEvolution::forgetMemoizedResults(const SCEV *S) { 10027 ValuesAtScopes.erase(S); 10028 LoopDispositions.erase(S); 10029 BlockDispositions.erase(S); 10030 UnsignedRanges.erase(S); 10031 SignedRanges.erase(S); 10032 ExprValueMap.erase(S); 10033 HasRecMap.erase(S); 10034 10035 auto RemoveSCEVFromBackedgeMap = 10036 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 10037 for (auto I = Map.begin(), E = Map.end(); I != E;) { 10038 BackedgeTakenInfo &BEInfo = I->second; 10039 if (BEInfo.hasOperand(S, this)) { 10040 BEInfo.clear(); 10041 Map.erase(I++); 10042 } else 10043 ++I; 10044 } 10045 }; 10046 10047 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); 10048 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); 10049 } 10050 10051 typedef DenseMap<const Loop *, std::string> VerifyMap; 10052 10053 /// replaceSubString - Replaces all occurrences of From in Str with To. 10054 static void replaceSubString(std::string &Str, StringRef From, StringRef To) { 10055 size_t Pos = 0; 10056 while ((Pos = Str.find(From, Pos)) != std::string::npos) { 10057 Str.replace(Pos, From.size(), To.data(), To.size()); 10058 Pos += To.size(); 10059 } 10060 } 10061 10062 /// getLoopBackedgeTakenCounts - Helper method for verifyAnalysis. 10063 static void 10064 getLoopBackedgeTakenCounts(Loop *L, VerifyMap &Map, ScalarEvolution &SE) { 10065 std::string &S = Map[L]; 10066 if (S.empty()) { 10067 raw_string_ostream OS(S); 10068 SE.getBackedgeTakenCount(L)->print(OS); 10069 10070 // false and 0 are semantically equivalent. This can happen in dead loops. 10071 replaceSubString(OS.str(), "false", "0"); 10072 // Remove wrap flags, their use in SCEV is highly fragile. 10073 // FIXME: Remove this when SCEV gets smarter about them. 10074 replaceSubString(OS.str(), "<nw>", ""); 10075 replaceSubString(OS.str(), "<nsw>", ""); 10076 replaceSubString(OS.str(), "<nuw>", ""); 10077 } 10078 10079 for (auto *R : reverse(*L)) 10080 getLoopBackedgeTakenCounts(R, Map, SE); // recurse. 10081 } 10082 10083 void ScalarEvolution::verify() const { 10084 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 10085 10086 // Gather stringified backedge taken counts for all loops using SCEV's caches. 10087 // FIXME: It would be much better to store actual values instead of strings, 10088 // but SCEV pointers will change if we drop the caches. 10089 VerifyMap BackedgeDumpsOld, BackedgeDumpsNew; 10090 for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I) 10091 getLoopBackedgeTakenCounts(*I, BackedgeDumpsOld, SE); 10092 10093 // Gather stringified backedge taken counts for all loops using a fresh 10094 // ScalarEvolution object. 10095 ScalarEvolution SE2(F, TLI, AC, DT, LI); 10096 for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I) 10097 getLoopBackedgeTakenCounts(*I, BackedgeDumpsNew, SE2); 10098 10099 // Now compare whether they're the same with and without caches. This allows 10100 // verifying that no pass changed the cache. 10101 assert(BackedgeDumpsOld.size() == BackedgeDumpsNew.size() && 10102 "New loops suddenly appeared!"); 10103 10104 for (VerifyMap::iterator OldI = BackedgeDumpsOld.begin(), 10105 OldE = BackedgeDumpsOld.end(), 10106 NewI = BackedgeDumpsNew.begin(); 10107 OldI != OldE; ++OldI, ++NewI) { 10108 assert(OldI->first == NewI->first && "Loop order changed!"); 10109 10110 // Compare the stringified SCEVs. We don't care if undef backedgetaken count 10111 // changes. 10112 // FIXME: We currently ignore SCEV changes from/to CouldNotCompute. This 10113 // means that a pass is buggy or SCEV has to learn a new pattern but is 10114 // usually not harmful. 10115 if (OldI->second != NewI->second && 10116 OldI->second.find("undef") == std::string::npos && 10117 NewI->second.find("undef") == std::string::npos && 10118 OldI->second != "***COULDNOTCOMPUTE***" && 10119 NewI->second != "***COULDNOTCOMPUTE***") { 10120 dbgs() << "SCEVValidator: SCEV for loop '" 10121 << OldI->first->getHeader()->getName() 10122 << "' changed from '" << OldI->second 10123 << "' to '" << NewI->second << "'!\n"; 10124 std::abort(); 10125 } 10126 } 10127 10128 // TODO: Verify more things. 10129 } 10130 10131 char ScalarEvolutionAnalysis::PassID; 10132 10133 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 10134 FunctionAnalysisManager &AM) { 10135 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 10136 AM.getResult<AssumptionAnalysis>(F), 10137 AM.getResult<DominatorTreeAnalysis>(F), 10138 AM.getResult<LoopAnalysis>(F)); 10139 } 10140 10141 PreservedAnalyses 10142 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 10143 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 10144 return PreservedAnalyses::all(); 10145 } 10146 10147 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 10148 "Scalar Evolution Analysis", false, true) 10149 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 10150 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 10151 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 10152 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 10153 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 10154 "Scalar Evolution Analysis", false, true) 10155 char ScalarEvolutionWrapperPass::ID = 0; 10156 10157 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 10158 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 10159 } 10160 10161 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 10162 SE.reset(new ScalarEvolution( 10163 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(), 10164 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 10165 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 10166 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 10167 return false; 10168 } 10169 10170 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 10171 10172 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 10173 SE->print(OS); 10174 } 10175 10176 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 10177 if (!VerifySCEV) 10178 return; 10179 10180 SE->verify(); 10181 } 10182 10183 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 10184 AU.setPreservesAll(); 10185 AU.addRequiredTransitive<AssumptionCacheTracker>(); 10186 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 10187 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 10188 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 10189 } 10190 10191 const SCEVPredicate * 10192 ScalarEvolution::getEqualPredicate(const SCEVUnknown *LHS, 10193 const SCEVConstant *RHS) { 10194 FoldingSetNodeID ID; 10195 // Unique this node based on the arguments 10196 ID.AddInteger(SCEVPredicate::P_Equal); 10197 ID.AddPointer(LHS); 10198 ID.AddPointer(RHS); 10199 void *IP = nullptr; 10200 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 10201 return S; 10202 SCEVEqualPredicate *Eq = new (SCEVAllocator) 10203 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 10204 UniquePreds.InsertNode(Eq, IP); 10205 return Eq; 10206 } 10207 10208 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 10209 const SCEVAddRecExpr *AR, 10210 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 10211 FoldingSetNodeID ID; 10212 // Unique this node based on the arguments 10213 ID.AddInteger(SCEVPredicate::P_Wrap); 10214 ID.AddPointer(AR); 10215 ID.AddInteger(AddedFlags); 10216 void *IP = nullptr; 10217 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 10218 return S; 10219 auto *OF = new (SCEVAllocator) 10220 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 10221 UniquePreds.InsertNode(OF, IP); 10222 return OF; 10223 } 10224 10225 namespace { 10226 10227 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 10228 public: 10229 // Rewrites \p S in the context of a loop L and the predicate A. 10230 // If Assume is true, rewrite is free to add further predicates to A 10231 // such that the result will be an AddRecExpr. 10232 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 10233 SCEVUnionPredicate &A, bool Assume) { 10234 SCEVPredicateRewriter Rewriter(L, SE, A, Assume); 10235 return Rewriter.visit(S); 10236 } 10237 10238 SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 10239 SCEVUnionPredicate &P, bool Assume) 10240 : SCEVRewriteVisitor(SE), P(P), L(L), Assume(Assume) {} 10241 10242 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 10243 auto ExprPreds = P.getPredicatesForExpr(Expr); 10244 for (auto *Pred : ExprPreds) 10245 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) 10246 if (IPred->getLHS() == Expr) 10247 return IPred->getRHS(); 10248 10249 return Expr; 10250 } 10251 10252 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 10253 const SCEV *Operand = visit(Expr->getOperand()); 10254 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 10255 if (AR && AR->getLoop() == L && AR->isAffine()) { 10256 // This couldn't be folded because the operand didn't have the nuw 10257 // flag. Add the nusw flag as an assumption that we could make. 10258 const SCEV *Step = AR->getStepRecurrence(SE); 10259 Type *Ty = Expr->getType(); 10260 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 10261 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 10262 SE.getSignExtendExpr(Step, Ty), L, 10263 AR->getNoWrapFlags()); 10264 } 10265 return SE.getZeroExtendExpr(Operand, Expr->getType()); 10266 } 10267 10268 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 10269 const SCEV *Operand = visit(Expr->getOperand()); 10270 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 10271 if (AR && AR->getLoop() == L && AR->isAffine()) { 10272 // This couldn't be folded because the operand didn't have the nsw 10273 // flag. Add the nssw flag as an assumption that we could make. 10274 const SCEV *Step = AR->getStepRecurrence(SE); 10275 Type *Ty = Expr->getType(); 10276 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 10277 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 10278 SE.getSignExtendExpr(Step, Ty), L, 10279 AR->getNoWrapFlags()); 10280 } 10281 return SE.getSignExtendExpr(Operand, Expr->getType()); 10282 } 10283 10284 private: 10285 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 10286 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 10287 auto *A = SE.getWrapPredicate(AR, AddedFlags); 10288 if (!Assume) { 10289 // Check if we've already made this assumption. 10290 if (P.implies(A)) 10291 return true; 10292 return false; 10293 } 10294 P.add(A); 10295 return true; 10296 } 10297 10298 SCEVUnionPredicate &P; 10299 const Loop *L; 10300 bool Assume; 10301 }; 10302 } // end anonymous namespace 10303 10304 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 10305 SCEVUnionPredicate &Preds) { 10306 return SCEVPredicateRewriter::rewrite(S, L, *this, Preds, false); 10307 } 10308 10309 const SCEVAddRecExpr * 10310 ScalarEvolution::convertSCEVToAddRecWithPredicates(const SCEV *S, const Loop *L, 10311 SCEVUnionPredicate &Preds) { 10312 SCEVUnionPredicate TransformPreds; 10313 S = SCEVPredicateRewriter::rewrite(S, L, *this, TransformPreds, true); 10314 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 10315 10316 if (!AddRec) 10317 return nullptr; 10318 10319 // Since the transformation was successful, we can now transfer the SCEV 10320 // predicates. 10321 Preds.add(&TransformPreds); 10322 return AddRec; 10323 } 10324 10325 /// SCEV predicates 10326 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 10327 SCEVPredicateKind Kind) 10328 : FastID(ID), Kind(Kind) {} 10329 10330 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 10331 const SCEVUnknown *LHS, 10332 const SCEVConstant *RHS) 10333 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {} 10334 10335 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 10336 const auto *Op = dyn_cast<SCEVEqualPredicate>(N); 10337 10338 if (!Op) 10339 return false; 10340 10341 return Op->LHS == LHS && Op->RHS == RHS; 10342 } 10343 10344 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 10345 10346 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 10347 10348 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 10349 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 10350 } 10351 10352 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 10353 const SCEVAddRecExpr *AR, 10354 IncrementWrapFlags Flags) 10355 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 10356 10357 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 10358 10359 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 10360 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 10361 10362 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 10363 } 10364 10365 bool SCEVWrapPredicate::isAlwaysTrue() const { 10366 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 10367 IncrementWrapFlags IFlags = Flags; 10368 10369 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 10370 IFlags = clearFlags(IFlags, IncrementNSSW); 10371 10372 return IFlags == IncrementAnyWrap; 10373 } 10374 10375 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 10376 OS.indent(Depth) << *getExpr() << " Added Flags: "; 10377 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 10378 OS << "<nusw>"; 10379 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 10380 OS << "<nssw>"; 10381 OS << "\n"; 10382 } 10383 10384 SCEVWrapPredicate::IncrementWrapFlags 10385 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 10386 ScalarEvolution &SE) { 10387 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 10388 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 10389 10390 // We can safely transfer the NSW flag as NSSW. 10391 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 10392 ImpliedFlags = IncrementNSSW; 10393 10394 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 10395 // If the increment is positive, the SCEV NUW flag will also imply the 10396 // WrapPredicate NUSW flag. 10397 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 10398 if (Step->getValue()->getValue().isNonNegative()) 10399 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 10400 } 10401 10402 return ImpliedFlags; 10403 } 10404 10405 /// Union predicates don't get cached so create a dummy set ID for it. 10406 SCEVUnionPredicate::SCEVUnionPredicate() 10407 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 10408 10409 bool SCEVUnionPredicate::isAlwaysTrue() const { 10410 return all_of(Preds, 10411 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 10412 } 10413 10414 ArrayRef<const SCEVPredicate *> 10415 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 10416 auto I = SCEVToPreds.find(Expr); 10417 if (I == SCEVToPreds.end()) 10418 return ArrayRef<const SCEVPredicate *>(); 10419 return I->second; 10420 } 10421 10422 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 10423 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 10424 return all_of(Set->Preds, 10425 [this](const SCEVPredicate *I) { return this->implies(I); }); 10426 10427 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 10428 if (ScevPredsIt == SCEVToPreds.end()) 10429 return false; 10430 auto &SCEVPreds = ScevPredsIt->second; 10431 10432 return any_of(SCEVPreds, 10433 [N](const SCEVPredicate *I) { return I->implies(N); }); 10434 } 10435 10436 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 10437 10438 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 10439 for (auto Pred : Preds) 10440 Pred->print(OS, Depth); 10441 } 10442 10443 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 10444 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 10445 for (auto Pred : Set->Preds) 10446 add(Pred); 10447 return; 10448 } 10449 10450 if (implies(N)) 10451 return; 10452 10453 const SCEV *Key = N->getExpr(); 10454 assert(Key && "Only SCEVUnionPredicate doesn't have an " 10455 " associated expression!"); 10456 10457 SCEVToPreds[Key].push_back(N); 10458 Preds.push_back(N); 10459 } 10460 10461 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 10462 Loop &L) 10463 : SE(SE), L(L), Generation(0), BackedgeCount(nullptr) {} 10464 10465 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 10466 const SCEV *Expr = SE.getSCEV(V); 10467 RewriteEntry &Entry = RewriteMap[Expr]; 10468 10469 // If we already have an entry and the version matches, return it. 10470 if (Entry.second && Generation == Entry.first) 10471 return Entry.second; 10472 10473 // We found an entry but it's stale. Rewrite the stale entry 10474 // acording to the current predicate. 10475 if (Entry.second) 10476 Expr = Entry.second; 10477 10478 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 10479 Entry = {Generation, NewSCEV}; 10480 10481 return NewSCEV; 10482 } 10483 10484 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 10485 if (!BackedgeCount) { 10486 SCEVUnionPredicate BackedgePred; 10487 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); 10488 addPredicate(BackedgePred); 10489 } 10490 return BackedgeCount; 10491 } 10492 10493 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 10494 if (Preds.implies(&Pred)) 10495 return; 10496 Preds.add(&Pred); 10497 updateGeneration(); 10498 } 10499 10500 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 10501 return Preds; 10502 } 10503 10504 void PredicatedScalarEvolution::updateGeneration() { 10505 // If the generation number wrapped recompute everything. 10506 if (++Generation == 0) { 10507 for (auto &II : RewriteMap) { 10508 const SCEV *Rewritten = II.second.second; 10509 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 10510 } 10511 } 10512 } 10513 10514 void PredicatedScalarEvolution::setNoOverflow( 10515 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 10516 const SCEV *Expr = getSCEV(V); 10517 const auto *AR = cast<SCEVAddRecExpr>(Expr); 10518 10519 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 10520 10521 // Clear the statically implied flags. 10522 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 10523 addPredicate(*SE.getWrapPredicate(AR, Flags)); 10524 10525 auto II = FlagsMap.insert({V, Flags}); 10526 if (!II.second) 10527 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 10528 } 10529 10530 bool PredicatedScalarEvolution::hasNoOverflow( 10531 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 10532 const SCEV *Expr = getSCEV(V); 10533 const auto *AR = cast<SCEVAddRecExpr>(Expr); 10534 10535 Flags = SCEVWrapPredicate::clearFlags( 10536 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 10537 10538 auto II = FlagsMap.find(V); 10539 10540 if (II != FlagsMap.end()) 10541 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 10542 10543 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 10544 } 10545 10546 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 10547 const SCEV *Expr = this->getSCEV(V); 10548 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, Preds); 10549 10550 if (!New) 10551 return nullptr; 10552 10553 updateGeneration(); 10554 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 10555 return New; 10556 } 10557 10558 PredicatedScalarEvolution::PredicatedScalarEvolution( 10559 const PredicatedScalarEvolution &Init) 10560 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 10561 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 10562 for (const auto &I : Init.FlagsMap) 10563 FlagsMap.insert(I); 10564 } 10565 10566 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 10567 // For each block. 10568 for (auto *BB : L.getBlocks()) 10569 for (auto &I : *BB) { 10570 if (!SE.isSCEVable(I.getType())) 10571 continue; 10572 10573 auto *Expr = SE.getSCEV(&I); 10574 auto II = RewriteMap.find(Expr); 10575 10576 if (II == RewriteMap.end()) 10577 continue; 10578 10579 // Don't print things that are not interesting. 10580 if (II->second.second == Expr) 10581 continue; 10582 10583 OS.indent(Depth) << "[PSE]" << I << ":\n"; 10584 OS.indent(Depth + 2) << *Expr << "\n"; 10585 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 10586 } 10587 } 10588