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/Support/CommandLine.h" 87 #include "llvm/Support/Debug.h" 88 #include "llvm/Support/ErrorHandling.h" 89 #include "llvm/Support/MathExtras.h" 90 #include "llvm/Support/raw_ostream.h" 91 #include <algorithm> 92 using namespace llvm; 93 94 #define DEBUG_TYPE "scalar-evolution" 95 96 STATISTIC(NumArrayLenItCounts, 97 "Number of trip counts computed with array length"); 98 STATISTIC(NumTripCountsComputed, 99 "Number of loops with predictable loop counts"); 100 STATISTIC(NumTripCountsNotComputed, 101 "Number of loops without predictable loop counts"); 102 STATISTIC(NumBruteForceTripCountsComputed, 103 "Number of loops with trip counts computed by force"); 104 105 static cl::opt<unsigned> 106 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, 107 cl::desc("Maximum number of iterations SCEV will " 108 "symbolically execute a constant " 109 "derived loop"), 110 cl::init(100)); 111 112 // FIXME: Enable this with XDEBUG when the test suite is clean. 113 static cl::opt<bool> 114 VerifySCEV("verify-scev", 115 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)")); 116 117 //===----------------------------------------------------------------------===// 118 // SCEV class definitions 119 //===----------------------------------------------------------------------===// 120 121 //===----------------------------------------------------------------------===// 122 // Implementation of the SCEV class. 123 // 124 125 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 126 void SCEV::dump() const { 127 print(dbgs()); 128 dbgs() << '\n'; 129 } 130 #endif 131 132 void SCEV::print(raw_ostream &OS) const { 133 switch (static_cast<SCEVTypes>(getSCEVType())) { 134 case scConstant: 135 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false); 136 return; 137 case scTruncate: { 138 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this); 139 const SCEV *Op = Trunc->getOperand(); 140 OS << "(trunc " << *Op->getType() << " " << *Op << " to " 141 << *Trunc->getType() << ")"; 142 return; 143 } 144 case scZeroExtend: { 145 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this); 146 const SCEV *Op = ZExt->getOperand(); 147 OS << "(zext " << *Op->getType() << " " << *Op << " to " 148 << *ZExt->getType() << ")"; 149 return; 150 } 151 case scSignExtend: { 152 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this); 153 const SCEV *Op = SExt->getOperand(); 154 OS << "(sext " << *Op->getType() << " " << *Op << " to " 155 << *SExt->getType() << ")"; 156 return; 157 } 158 case scAddRecExpr: { 159 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this); 160 OS << "{" << *AR->getOperand(0); 161 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i) 162 OS << ",+," << *AR->getOperand(i); 163 OS << "}<"; 164 if (AR->getNoWrapFlags(FlagNUW)) 165 OS << "nuw><"; 166 if (AR->getNoWrapFlags(FlagNSW)) 167 OS << "nsw><"; 168 if (AR->getNoWrapFlags(FlagNW) && 169 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW))) 170 OS << "nw><"; 171 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false); 172 OS << ">"; 173 return; 174 } 175 case scAddExpr: 176 case scMulExpr: 177 case scUMaxExpr: 178 case scSMaxExpr: { 179 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this); 180 const char *OpStr = nullptr; 181 switch (NAry->getSCEVType()) { 182 case scAddExpr: OpStr = " + "; break; 183 case scMulExpr: OpStr = " * "; break; 184 case scUMaxExpr: OpStr = " umax "; break; 185 case scSMaxExpr: OpStr = " smax "; break; 186 } 187 OS << "("; 188 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end(); 189 I != E; ++I) { 190 OS << **I; 191 if (std::next(I) != E) 192 OS << OpStr; 193 } 194 OS << ")"; 195 switch (NAry->getSCEVType()) { 196 case scAddExpr: 197 case scMulExpr: 198 if (NAry->getNoWrapFlags(FlagNUW)) 199 OS << "<nuw>"; 200 if (NAry->getNoWrapFlags(FlagNSW)) 201 OS << "<nsw>"; 202 } 203 return; 204 } 205 case scUDivExpr: { 206 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this); 207 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")"; 208 return; 209 } 210 case scUnknown: { 211 const SCEVUnknown *U = cast<SCEVUnknown>(this); 212 Type *AllocTy; 213 if (U->isSizeOf(AllocTy)) { 214 OS << "sizeof(" << *AllocTy << ")"; 215 return; 216 } 217 if (U->isAlignOf(AllocTy)) { 218 OS << "alignof(" << *AllocTy << ")"; 219 return; 220 } 221 222 Type *CTy; 223 Constant *FieldNo; 224 if (U->isOffsetOf(CTy, FieldNo)) { 225 OS << "offsetof(" << *CTy << ", "; 226 FieldNo->printAsOperand(OS, false); 227 OS << ")"; 228 return; 229 } 230 231 // Otherwise just print it normally. 232 U->getValue()->printAsOperand(OS, false); 233 return; 234 } 235 case scCouldNotCompute: 236 OS << "***COULDNOTCOMPUTE***"; 237 return; 238 } 239 llvm_unreachable("Unknown SCEV kind!"); 240 } 241 242 Type *SCEV::getType() const { 243 switch (static_cast<SCEVTypes>(getSCEVType())) { 244 case scConstant: 245 return cast<SCEVConstant>(this)->getType(); 246 case scTruncate: 247 case scZeroExtend: 248 case scSignExtend: 249 return cast<SCEVCastExpr>(this)->getType(); 250 case scAddRecExpr: 251 case scMulExpr: 252 case scUMaxExpr: 253 case scSMaxExpr: 254 return cast<SCEVNAryExpr>(this)->getType(); 255 case scAddExpr: 256 return cast<SCEVAddExpr>(this)->getType(); 257 case scUDivExpr: 258 return cast<SCEVUDivExpr>(this)->getType(); 259 case scUnknown: 260 return cast<SCEVUnknown>(this)->getType(); 261 case scCouldNotCompute: 262 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 263 } 264 llvm_unreachable("Unknown SCEV kind!"); 265 } 266 267 bool SCEV::isZero() const { 268 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 269 return SC->getValue()->isZero(); 270 return false; 271 } 272 273 bool SCEV::isOne() const { 274 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 275 return SC->getValue()->isOne(); 276 return false; 277 } 278 279 bool SCEV::isAllOnesValue() const { 280 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 281 return SC->getValue()->isAllOnesValue(); 282 return false; 283 } 284 285 /// isNonConstantNegative - Return true if the specified scev is negated, but 286 /// not a constant. 287 bool SCEV::isNonConstantNegative() const { 288 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this); 289 if (!Mul) return false; 290 291 // If there is a constant factor, it will be first. 292 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); 293 if (!SC) return false; 294 295 // Return true if the value is negative, this matches things like (-42 * V). 296 return SC->getValue()->getValue().isNegative(); 297 } 298 299 SCEVCouldNotCompute::SCEVCouldNotCompute() : 300 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {} 301 302 bool SCEVCouldNotCompute::classof(const SCEV *S) { 303 return S->getSCEVType() == scCouldNotCompute; 304 } 305 306 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) { 307 FoldingSetNodeID ID; 308 ID.AddInteger(scConstant); 309 ID.AddPointer(V); 310 void *IP = nullptr; 311 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 312 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V); 313 UniqueSCEVs.InsertNode(S, IP); 314 return S; 315 } 316 317 const SCEV *ScalarEvolution::getConstant(const APInt &Val) { 318 return getConstant(ConstantInt::get(getContext(), Val)); 319 } 320 321 const SCEV * 322 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) { 323 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty)); 324 return getConstant(ConstantInt::get(ITy, V, isSigned)); 325 } 326 327 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, 328 unsigned SCEVTy, const SCEV *op, Type *ty) 329 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {} 330 331 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, 332 const SCEV *op, Type *ty) 333 : SCEVCastExpr(ID, scTruncate, op, ty) { 334 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && 335 (Ty->isIntegerTy() || Ty->isPointerTy()) && 336 "Cannot truncate non-integer value!"); 337 } 338 339 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, 340 const SCEV *op, Type *ty) 341 : SCEVCastExpr(ID, scZeroExtend, op, ty) { 342 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && 343 (Ty->isIntegerTy() || Ty->isPointerTy()) && 344 "Cannot zero extend non-integer value!"); 345 } 346 347 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, 348 const SCEV *op, Type *ty) 349 : SCEVCastExpr(ID, scSignExtend, op, ty) { 350 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && 351 (Ty->isIntegerTy() || Ty->isPointerTy()) && 352 "Cannot sign extend non-integer value!"); 353 } 354 355 void SCEVUnknown::deleted() { 356 // Clear this SCEVUnknown from various maps. 357 SE->forgetMemoizedResults(this); 358 359 // Remove this SCEVUnknown from the uniquing map. 360 SE->UniqueSCEVs.RemoveNode(this); 361 362 // Release the value. 363 setValPtr(nullptr); 364 } 365 366 void SCEVUnknown::allUsesReplacedWith(Value *New) { 367 // Clear this SCEVUnknown from various maps. 368 SE->forgetMemoizedResults(this); 369 370 // Remove this SCEVUnknown from the uniquing map. 371 SE->UniqueSCEVs.RemoveNode(this); 372 373 // Update this SCEVUnknown to point to the new value. This is needed 374 // because there may still be outstanding SCEVs which still point to 375 // this SCEVUnknown. 376 setValPtr(New); 377 } 378 379 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const { 380 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 381 if (VCE->getOpcode() == Instruction::PtrToInt) 382 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 383 if (CE->getOpcode() == Instruction::GetElementPtr && 384 CE->getOperand(0)->isNullValue() && 385 CE->getNumOperands() == 2) 386 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1))) 387 if (CI->isOne()) { 388 AllocTy = cast<PointerType>(CE->getOperand(0)->getType()) 389 ->getElementType(); 390 return true; 391 } 392 393 return false; 394 } 395 396 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const { 397 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 398 if (VCE->getOpcode() == Instruction::PtrToInt) 399 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 400 if (CE->getOpcode() == Instruction::GetElementPtr && 401 CE->getOperand(0)->isNullValue()) { 402 Type *Ty = 403 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 404 if (StructType *STy = dyn_cast<StructType>(Ty)) 405 if (!STy->isPacked() && 406 CE->getNumOperands() == 3 && 407 CE->getOperand(1)->isNullValue()) { 408 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2))) 409 if (CI->isOne() && 410 STy->getNumElements() == 2 && 411 STy->getElementType(0)->isIntegerTy(1)) { 412 AllocTy = STy->getElementType(1); 413 return true; 414 } 415 } 416 } 417 418 return false; 419 } 420 421 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const { 422 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 423 if (VCE->getOpcode() == Instruction::PtrToInt) 424 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 425 if (CE->getOpcode() == Instruction::GetElementPtr && 426 CE->getNumOperands() == 3 && 427 CE->getOperand(0)->isNullValue() && 428 CE->getOperand(1)->isNullValue()) { 429 Type *Ty = 430 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 431 // Ignore vector types here so that ScalarEvolutionExpander doesn't 432 // emit getelementptrs that index into vectors. 433 if (Ty->isStructTy() || Ty->isArrayTy()) { 434 CTy = Ty; 435 FieldNo = CE->getOperand(2); 436 return true; 437 } 438 } 439 440 return false; 441 } 442 443 //===----------------------------------------------------------------------===// 444 // SCEV Utilities 445 //===----------------------------------------------------------------------===// 446 447 namespace { 448 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less 449 /// than the complexity of the RHS. This comparator is used to canonicalize 450 /// expressions. 451 class SCEVComplexityCompare { 452 const LoopInfo *const LI; 453 public: 454 explicit SCEVComplexityCompare(const LoopInfo *li) : LI(li) {} 455 456 // Return true or false if LHS is less than, or at least RHS, respectively. 457 bool operator()(const SCEV *LHS, const SCEV *RHS) const { 458 return compare(LHS, RHS) < 0; 459 } 460 461 // Return negative, zero, or positive, if LHS is less than, equal to, or 462 // greater than RHS, respectively. A three-way result allows recursive 463 // comparisons to be more efficient. 464 int compare(const SCEV *LHS, const SCEV *RHS) const { 465 // Fast-path: SCEVs are uniqued so we can do a quick equality check. 466 if (LHS == RHS) 467 return 0; 468 469 // Primarily, sort the SCEVs by their getSCEVType(). 470 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType(); 471 if (LType != RType) 472 return (int)LType - (int)RType; 473 474 // Aside from the getSCEVType() ordering, the particular ordering 475 // isn't very important except that it's beneficial to be consistent, 476 // so that (a + b) and (b + a) don't end up as different expressions. 477 switch (static_cast<SCEVTypes>(LType)) { 478 case scUnknown: { 479 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS); 480 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); 481 482 // Sort SCEVUnknown values with some loose heuristics. TODO: This is 483 // not as complete as it could be. 484 const Value *LV = LU->getValue(), *RV = RU->getValue(); 485 486 // Order pointer values after integer values. This helps SCEVExpander 487 // form GEPs. 488 bool LIsPointer = LV->getType()->isPointerTy(), 489 RIsPointer = RV->getType()->isPointerTy(); 490 if (LIsPointer != RIsPointer) 491 return (int)LIsPointer - (int)RIsPointer; 492 493 // Compare getValueID values. 494 unsigned LID = LV->getValueID(), 495 RID = RV->getValueID(); 496 if (LID != RID) 497 return (int)LID - (int)RID; 498 499 // Sort arguments by their position. 500 if (const Argument *LA = dyn_cast<Argument>(LV)) { 501 const Argument *RA = cast<Argument>(RV); 502 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo(); 503 return (int)LArgNo - (int)RArgNo; 504 } 505 506 // For instructions, compare their loop depth, and their operand 507 // count. This is pretty loose. 508 if (const Instruction *LInst = dyn_cast<Instruction>(LV)) { 509 const Instruction *RInst = cast<Instruction>(RV); 510 511 // Compare loop depths. 512 const BasicBlock *LParent = LInst->getParent(), 513 *RParent = RInst->getParent(); 514 if (LParent != RParent) { 515 unsigned LDepth = LI->getLoopDepth(LParent), 516 RDepth = LI->getLoopDepth(RParent); 517 if (LDepth != RDepth) 518 return (int)LDepth - (int)RDepth; 519 } 520 521 // Compare the number of operands. 522 unsigned LNumOps = LInst->getNumOperands(), 523 RNumOps = RInst->getNumOperands(); 524 return (int)LNumOps - (int)RNumOps; 525 } 526 527 return 0; 528 } 529 530 case scConstant: { 531 const SCEVConstant *LC = cast<SCEVConstant>(LHS); 532 const SCEVConstant *RC = cast<SCEVConstant>(RHS); 533 534 // Compare constant values. 535 const APInt &LA = LC->getValue()->getValue(); 536 const APInt &RA = RC->getValue()->getValue(); 537 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth(); 538 if (LBitWidth != RBitWidth) 539 return (int)LBitWidth - (int)RBitWidth; 540 return LA.ult(RA) ? -1 : 1; 541 } 542 543 case scAddRecExpr: { 544 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); 545 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); 546 547 // Compare addrec loop depths. 548 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); 549 if (LLoop != RLoop) { 550 unsigned LDepth = LLoop->getLoopDepth(), 551 RDepth = RLoop->getLoopDepth(); 552 if (LDepth != RDepth) 553 return (int)LDepth - (int)RDepth; 554 } 555 556 // Addrec complexity grows with operand count. 557 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands(); 558 if (LNumOps != RNumOps) 559 return (int)LNumOps - (int)RNumOps; 560 561 // Lexicographically compare. 562 for (unsigned i = 0; i != LNumOps; ++i) { 563 long X = compare(LA->getOperand(i), RA->getOperand(i)); 564 if (X != 0) 565 return X; 566 } 567 568 return 0; 569 } 570 571 case scAddExpr: 572 case scMulExpr: 573 case scSMaxExpr: 574 case scUMaxExpr: { 575 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); 576 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); 577 578 // Lexicographically compare n-ary expressions. 579 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); 580 if (LNumOps != RNumOps) 581 return (int)LNumOps - (int)RNumOps; 582 583 for (unsigned i = 0; i != LNumOps; ++i) { 584 if (i >= RNumOps) 585 return 1; 586 long X = compare(LC->getOperand(i), RC->getOperand(i)); 587 if (X != 0) 588 return X; 589 } 590 return (int)LNumOps - (int)RNumOps; 591 } 592 593 case scUDivExpr: { 594 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); 595 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); 596 597 // Lexicographically compare udiv expressions. 598 long X = compare(LC->getLHS(), RC->getLHS()); 599 if (X != 0) 600 return X; 601 return compare(LC->getRHS(), RC->getRHS()); 602 } 603 604 case scTruncate: 605 case scZeroExtend: 606 case scSignExtend: { 607 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS); 608 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS); 609 610 // Compare cast expressions by operand. 611 return compare(LC->getOperand(), RC->getOperand()); 612 } 613 614 case scCouldNotCompute: 615 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 616 } 617 llvm_unreachable("Unknown SCEV kind!"); 618 } 619 }; 620 } 621 622 /// GroupByComplexity - Given a list of SCEV objects, order them by their 623 /// complexity, and group objects of the same complexity together by value. 624 /// When this routine is finished, we know that any duplicates in the vector are 625 /// consecutive and that complexity is monotonically increasing. 626 /// 627 /// Note that we go take special precautions to ensure that we get deterministic 628 /// results from this routine. In other words, we don't want the results of 629 /// this to depend on where the addresses of various SCEV objects happened to 630 /// land in memory. 631 /// 632 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, 633 LoopInfo *LI) { 634 if (Ops.size() < 2) return; // Noop 635 if (Ops.size() == 2) { 636 // This is the common case, which also happens to be trivially simple. 637 // Special case it. 638 const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; 639 if (SCEVComplexityCompare(LI)(RHS, LHS)) 640 std::swap(LHS, RHS); 641 return; 642 } 643 644 // Do the rough sort by complexity. 645 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI)); 646 647 // Now that we are sorted by complexity, group elements of the same 648 // complexity. Note that this is, at worst, N^2, but the vector is likely to 649 // be extremely short in practice. Note that we take this approach because we 650 // do not want to depend on the addresses of the objects we are grouping. 651 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { 652 const SCEV *S = Ops[i]; 653 unsigned Complexity = S->getSCEVType(); 654 655 // If there are any objects of the same complexity and same value as this 656 // one, group them. 657 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { 658 if (Ops[j] == S) { // Found a duplicate. 659 // Move it to immediately after i'th element. 660 std::swap(Ops[i+1], Ops[j]); 661 ++i; // no need to rescan it. 662 if (i == e-2) return; // Done! 663 } 664 } 665 } 666 } 667 668 namespace { 669 struct FindSCEVSize { 670 int Size; 671 FindSCEVSize() : Size(0) {} 672 673 bool follow(const SCEV *S) { 674 ++Size; 675 // Keep looking at all operands of S. 676 return true; 677 } 678 bool isDone() const { 679 return false; 680 } 681 }; 682 } 683 684 // Returns the size of the SCEV S. 685 static inline int sizeOfSCEV(const SCEV *S) { 686 FindSCEVSize F; 687 SCEVTraversal<FindSCEVSize> ST(F); 688 ST.visitAll(S); 689 return F.Size; 690 } 691 692 namespace { 693 694 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> { 695 public: 696 // Computes the Quotient and Remainder of the division of Numerator by 697 // Denominator. 698 static void divide(ScalarEvolution &SE, const SCEV *Numerator, 699 const SCEV *Denominator, const SCEV **Quotient, 700 const SCEV **Remainder) { 701 assert(Numerator && Denominator && "Uninitialized SCEV"); 702 703 SCEVDivision D(SE, Numerator, Denominator); 704 705 // Check for the trivial case here to avoid having to check for it in the 706 // rest of the code. 707 if (Numerator == Denominator) { 708 *Quotient = D.One; 709 *Remainder = D.Zero; 710 return; 711 } 712 713 if (Numerator->isZero()) { 714 *Quotient = D.Zero; 715 *Remainder = D.Zero; 716 return; 717 } 718 719 // A simple case when N/1. The quotient is N. 720 if (Denominator->isOne()) { 721 *Quotient = Numerator; 722 *Remainder = D.Zero; 723 return; 724 } 725 726 // Split the Denominator when it is a product. 727 if (const SCEVMulExpr *T = dyn_cast<const SCEVMulExpr>(Denominator)) { 728 const SCEV *Q, *R; 729 *Quotient = Numerator; 730 for (const SCEV *Op : T->operands()) { 731 divide(SE, *Quotient, Op, &Q, &R); 732 *Quotient = Q; 733 734 // Bail out when the Numerator is not divisible by one of the terms of 735 // the Denominator. 736 if (!R->isZero()) { 737 *Quotient = D.Zero; 738 *Remainder = Numerator; 739 return; 740 } 741 } 742 *Remainder = D.Zero; 743 return; 744 } 745 746 D.visit(Numerator); 747 *Quotient = D.Quotient; 748 *Remainder = D.Remainder; 749 } 750 751 // Except in the trivial case described above, we do not know how to divide 752 // Expr by Denominator for the following functions with empty implementation. 753 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {} 754 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {} 755 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {} 756 void visitUDivExpr(const SCEVUDivExpr *Numerator) {} 757 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {} 758 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {} 759 void visitUnknown(const SCEVUnknown *Numerator) {} 760 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {} 761 762 void visitConstant(const SCEVConstant *Numerator) { 763 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) { 764 APInt NumeratorVal = Numerator->getValue()->getValue(); 765 APInt DenominatorVal = D->getValue()->getValue(); 766 uint32_t NumeratorBW = NumeratorVal.getBitWidth(); 767 uint32_t DenominatorBW = DenominatorVal.getBitWidth(); 768 769 if (NumeratorBW > DenominatorBW) 770 DenominatorVal = DenominatorVal.sext(NumeratorBW); 771 else if (NumeratorBW < DenominatorBW) 772 NumeratorVal = NumeratorVal.sext(DenominatorBW); 773 774 APInt QuotientVal(NumeratorVal.getBitWidth(), 0); 775 APInt RemainderVal(NumeratorVal.getBitWidth(), 0); 776 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal); 777 Quotient = SE.getConstant(QuotientVal); 778 Remainder = SE.getConstant(RemainderVal); 779 return; 780 } 781 } 782 783 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) { 784 const SCEV *StartQ, *StartR, *StepQ, *StepR; 785 if (!Numerator->isAffine()) 786 return cannotDivide(Numerator); 787 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR); 788 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR); 789 // Bail out if the types do not match. 790 Type *Ty = Denominator->getType(); 791 if (Ty != StartQ->getType() || Ty != StartR->getType() || 792 Ty != StepQ->getType() || Ty != StepR->getType()) 793 return cannotDivide(Numerator); 794 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(), 795 Numerator->getNoWrapFlags()); 796 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(), 797 Numerator->getNoWrapFlags()); 798 } 799 800 void visitAddExpr(const SCEVAddExpr *Numerator) { 801 SmallVector<const SCEV *, 2> Qs, Rs; 802 Type *Ty = Denominator->getType(); 803 804 for (const SCEV *Op : Numerator->operands()) { 805 const SCEV *Q, *R; 806 divide(SE, Op, Denominator, &Q, &R); 807 808 // Bail out if types do not match. 809 if (Ty != Q->getType() || Ty != R->getType()) 810 return cannotDivide(Numerator); 811 812 Qs.push_back(Q); 813 Rs.push_back(R); 814 } 815 816 if (Qs.size() == 1) { 817 Quotient = Qs[0]; 818 Remainder = Rs[0]; 819 return; 820 } 821 822 Quotient = SE.getAddExpr(Qs); 823 Remainder = SE.getAddExpr(Rs); 824 } 825 826 void visitMulExpr(const SCEVMulExpr *Numerator) { 827 SmallVector<const SCEV *, 2> Qs; 828 Type *Ty = Denominator->getType(); 829 830 bool FoundDenominatorTerm = false; 831 for (const SCEV *Op : Numerator->operands()) { 832 // Bail out if types do not match. 833 if (Ty != Op->getType()) 834 return cannotDivide(Numerator); 835 836 if (FoundDenominatorTerm) { 837 Qs.push_back(Op); 838 continue; 839 } 840 841 // Check whether Denominator divides one of the product operands. 842 const SCEV *Q, *R; 843 divide(SE, Op, Denominator, &Q, &R); 844 if (!R->isZero()) { 845 Qs.push_back(Op); 846 continue; 847 } 848 849 // Bail out if types do not match. 850 if (Ty != Q->getType()) 851 return cannotDivide(Numerator); 852 853 FoundDenominatorTerm = true; 854 Qs.push_back(Q); 855 } 856 857 if (FoundDenominatorTerm) { 858 Remainder = Zero; 859 if (Qs.size() == 1) 860 Quotient = Qs[0]; 861 else 862 Quotient = SE.getMulExpr(Qs); 863 return; 864 } 865 866 if (!isa<SCEVUnknown>(Denominator)) 867 return cannotDivide(Numerator); 868 869 // The Remainder is obtained by replacing Denominator by 0 in Numerator. 870 ValueToValueMap RewriteMap; 871 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 872 cast<SCEVConstant>(Zero)->getValue(); 873 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 874 875 if (Remainder->isZero()) { 876 // The Quotient is obtained by replacing Denominator by 1 in Numerator. 877 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 878 cast<SCEVConstant>(One)->getValue(); 879 Quotient = 880 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 881 return; 882 } 883 884 // Quotient is (Numerator - Remainder) divided by Denominator. 885 const SCEV *Q, *R; 886 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder); 887 // This SCEV does not seem to simplify: fail the division here. 888 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator)) 889 return cannotDivide(Numerator); 890 divide(SE, Diff, Denominator, &Q, &R); 891 if (R != Zero) 892 return cannotDivide(Numerator); 893 Quotient = Q; 894 } 895 896 private: 897 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator, 898 const SCEV *Denominator) 899 : SE(S), Denominator(Denominator) { 900 Zero = SE.getConstant(Denominator->getType(), 0); 901 One = SE.getConstant(Denominator->getType(), 1); 902 903 // We generally do not know how to divide Expr by Denominator. We 904 // initialize the division to a "cannot divide" state to simplify the rest 905 // of the code. 906 cannotDivide(Numerator); 907 } 908 909 // Convenience function for giving up on the division. We set the quotient to 910 // be equal to zero and the remainder to be equal to the numerator. 911 void cannotDivide(const SCEV *Numerator) { 912 Quotient = Zero; 913 Remainder = Numerator; 914 } 915 916 ScalarEvolution &SE; 917 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One; 918 }; 919 920 } 921 922 //===----------------------------------------------------------------------===// 923 // Simple SCEV method implementations 924 //===----------------------------------------------------------------------===// 925 926 /// BinomialCoefficient - Compute BC(It, K). The result has width W. 927 /// 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 /// evaluateAtIteration - Return the value of this chain of recurrences at 1039 /// the specified iteration number. We can evaluate this recurrence by 1040 /// multiplying each element in the chain by the binomial coefficient 1041 /// corresponding to it. In other words, we 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 (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 1135 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), 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 const SCEV *PreStart = SE->getAddExpr(DiffOps, SA->getNoWrapFlags()); 1271 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( 1272 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); 1273 1274 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies 1275 // "S+X does not sign/unsign-overflow". 1276 // 1277 1278 const SCEV *BECount = SE->getBackedgeTakenCount(L); 1279 if (PreAR && PreAR->getNoWrapFlags(WrapType) && 1280 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) 1281 return PreStart; 1282 1283 // 2. Direct overflow check on the step operation's expression. 1284 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); 1285 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); 1286 const SCEV *OperandExtendedStart = 1287 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy), 1288 (SE->*GetExtendExpr)(Step, WideTy)); 1289 if ((SE->*GetExtendExpr)(Start, WideTy) == OperandExtendedStart) { 1290 if (PreAR && AR->getNoWrapFlags(WrapType)) { 1291 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW 1292 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then 1293 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. 1294 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType); 1295 } 1296 return PreStart; 1297 } 1298 1299 // 3. Loop precondition. 1300 ICmpInst::Predicate Pred; 1301 const SCEV *OverflowLimit = 1302 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); 1303 1304 if (OverflowLimit && 1305 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) { 1306 return PreStart; 1307 } 1308 return nullptr; 1309 } 1310 1311 // Get the normalized zero or sign extended expression for this AddRec's Start. 1312 template <typename ExtendOpTy> 1313 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, 1314 ScalarEvolution *SE) { 1315 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1316 1317 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE); 1318 if (!PreStart) 1319 return (SE->*GetExtendExpr)(AR->getStart(), Ty); 1320 1321 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty), 1322 (SE->*GetExtendExpr)(PreStart, Ty)); 1323 } 1324 1325 // Try to prove away overflow by looking at "nearby" add recurrences. A 1326 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it 1327 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. 1328 // 1329 // Formally: 1330 // 1331 // {S,+,X} == {S-T,+,X} + T 1332 // => Ext({S,+,X}) == Ext({S-T,+,X} + T) 1333 // 1334 // If ({S-T,+,X} + T) does not overflow ... (1) 1335 // 1336 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) 1337 // 1338 // If {S-T,+,X} does not overflow ... (2) 1339 // 1340 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) 1341 // == {Ext(S-T)+Ext(T),+,Ext(X)} 1342 // 1343 // If (S-T)+T does not overflow ... (3) 1344 // 1345 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} 1346 // == {Ext(S),+,Ext(X)} == LHS 1347 // 1348 // Thus, if (1), (2) and (3) are true for some T, then 1349 // Ext({S,+,X}) == {Ext(S),+,Ext(X)} 1350 // 1351 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) 1352 // does not overflow" restricted to the 0th iteration. Therefore we only need 1353 // to check for (1) and (2). 1354 // 1355 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T 1356 // is `Delta` (defined below). 1357 // 1358 template <typename ExtendOpTy> 1359 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, 1360 const SCEV *Step, 1361 const Loop *L) { 1362 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1363 1364 // We restrict `Start` to a constant to prevent SCEV from spending too much 1365 // time here. It is correct (but more expensive) to continue with a 1366 // non-constant `Start` and do a general SCEV subtraction to compute 1367 // `PreStart` below. 1368 // 1369 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); 1370 if (!StartC) 1371 return false; 1372 1373 APInt StartAI = StartC->getValue()->getValue(); 1374 1375 for (unsigned Delta : {-2, -1, 1, 2}) { 1376 const SCEV *PreStart = getConstant(StartAI - Delta); 1377 1378 // Give up if we don't already have the add recurrence we need because 1379 // actually constructing an add recurrence is relatively expensive. 1380 const SCEVAddRecExpr *PreAR = [&]() { 1381 FoldingSetNodeID ID; 1382 ID.AddInteger(scAddRecExpr); 1383 ID.AddPointer(PreStart); 1384 ID.AddPointer(Step); 1385 ID.AddPointer(L); 1386 void *IP = nullptr; 1387 return static_cast<SCEVAddRecExpr *>( 1388 this->UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 1389 }(); 1390 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 we have special knowledge that this addrec won't overflow, 1455 // we don't need to do any further analysis. 1456 if (AR->getNoWrapFlags(SCEV::FlagNUW)) 1457 return getAddRecExpr( 1458 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), 1459 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1460 1461 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1462 // Note that this serves two purposes: It filters out loops that are 1463 // simply not analyzable, and it covers the case where this code is 1464 // being called from within backedge-taken count analysis, such that 1465 // attempting to ask for the backedge-taken count would likely result 1466 // in infinite recursion. In the later case, the analysis code will 1467 // cope with a conservative value, and it will take care to purge 1468 // that value once it has finished. 1469 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); 1470 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1471 // Manually compute the final value for AR, checking for 1472 // overflow. 1473 1474 // Check whether the backedge-taken count can be losslessly casted to 1475 // the addrec's type. The count is always unsigned. 1476 const SCEV *CastedMaxBECount = 1477 getTruncateOrZeroExtend(MaxBECount, Start->getType()); 1478 const SCEV *RecastedMaxBECount = 1479 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); 1480 if (MaxBECount == RecastedMaxBECount) { 1481 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1482 // Check whether Start+Step*MaxBECount has no unsigned overflow. 1483 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step); 1484 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul), WideTy); 1485 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy); 1486 const SCEV *WideMaxBECount = 1487 getZeroExtendExpr(CastedMaxBECount, WideTy); 1488 const SCEV *OperandExtendedAdd = 1489 getAddExpr(WideStart, 1490 getMulExpr(WideMaxBECount, 1491 getZeroExtendExpr(Step, WideTy))); 1492 if (ZAdd == OperandExtendedAdd) { 1493 // Cache knowledge of AR NUW, which is propagated to this AddRec. 1494 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1495 // Return the expression with the addrec on the outside. 1496 return getAddRecExpr( 1497 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), 1498 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1499 } 1500 // Similar to above, only this time treat the step value as signed. 1501 // This covers loops that count down. 1502 OperandExtendedAdd = 1503 getAddExpr(WideStart, 1504 getMulExpr(WideMaxBECount, 1505 getSignExtendExpr(Step, WideTy))); 1506 if (ZAdd == OperandExtendedAdd) { 1507 // Cache knowledge of AR NW, which is propagated to this AddRec. 1508 // Negative step causes unsigned wrap, but it still can't self-wrap. 1509 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1510 // Return the expression with the addrec on the outside. 1511 return getAddRecExpr( 1512 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), 1513 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1514 } 1515 } 1516 1517 // If the backedge is guarded by a comparison with the pre-inc value 1518 // the addrec is safe. Also, if the entry is guarded by a comparison 1519 // with the start value and the backedge is guarded by a comparison 1520 // with the post-inc value, the addrec is safe. 1521 if (isKnownPositive(Step)) { 1522 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 1523 getUnsignedRange(Step).getUnsignedMax()); 1524 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 1525 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) && 1526 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, 1527 AR->getPostIncExpr(*this), N))) { 1528 // Cache knowledge of AR NUW, which is propagated to this AddRec. 1529 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1530 // Return the expression with the addrec on the outside. 1531 return getAddRecExpr( 1532 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), 1533 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1534 } 1535 } else if (isKnownNegative(Step)) { 1536 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - 1537 getSignedRange(Step).getSignedMin()); 1538 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || 1539 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) && 1540 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, 1541 AR->getPostIncExpr(*this), N))) { 1542 // Cache knowledge of AR NW, which is propagated to this AddRec. 1543 // Negative step causes unsigned wrap, but it still can't self-wrap. 1544 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1545 // Return the expression with the addrec on the outside. 1546 return getAddRecExpr( 1547 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), 1548 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1549 } 1550 } 1551 } 1552 1553 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { 1554 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1555 return getAddRecExpr( 1556 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), 1557 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1558 } 1559 } 1560 1561 // The cast wasn't folded; create an explicit cast node. 1562 // Recompute the insert position, as it may have been invalidated. 1563 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1564 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1565 Op, Ty); 1566 UniqueSCEVs.InsertNode(S, IP); 1567 return S; 1568 } 1569 1570 const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op, 1571 Type *Ty) { 1572 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1573 "This is not an extending conversion!"); 1574 assert(isSCEVable(Ty) && 1575 "This is not a conversion to a SCEVable type!"); 1576 Ty = getEffectiveSCEVType(Ty); 1577 1578 // Fold if the operand is constant. 1579 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1580 return getConstant( 1581 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); 1582 1583 // sext(sext(x)) --> sext(x) 1584 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1585 return getSignExtendExpr(SS->getOperand(), Ty); 1586 1587 // sext(zext(x)) --> zext(x) 1588 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1589 return getZeroExtendExpr(SZ->getOperand(), Ty); 1590 1591 // Before doing any expensive analysis, check to see if we've already 1592 // computed a SCEV for this Op and Ty. 1593 FoldingSetNodeID ID; 1594 ID.AddInteger(scSignExtend); 1595 ID.AddPointer(Op); 1596 ID.AddPointer(Ty); 1597 void *IP = nullptr; 1598 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1599 1600 // If the input value is provably positive, build a zext instead. 1601 if (isKnownNonNegative(Op)) 1602 return getZeroExtendExpr(Op, Ty); 1603 1604 // sext(trunc(x)) --> sext(x) or x or trunc(x) 1605 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1606 // It's possible the bits taken off by the truncate were all sign bits. If 1607 // so, we should be able to simplify this further. 1608 const SCEV *X = ST->getOperand(); 1609 ConstantRange CR = getSignedRange(X); 1610 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1611 unsigned NewBits = getTypeSizeInBits(Ty); 1612 if (CR.truncate(TruncBits).signExtend(NewBits).contains( 1613 CR.sextOrTrunc(NewBits))) 1614 return getTruncateOrSignExtend(X, Ty); 1615 } 1616 1617 // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2 1618 if (auto SA = dyn_cast<SCEVAddExpr>(Op)) { 1619 if (SA->getNumOperands() == 2) { 1620 auto SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0)); 1621 auto SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1)); 1622 if (SMul && SC1) { 1623 if (auto SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) { 1624 const APInt &C1 = SC1->getValue()->getValue(); 1625 const APInt &C2 = SC2->getValue()->getValue(); 1626 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && 1627 C2.ugt(C1) && C2.isPowerOf2()) 1628 return getAddExpr(getSignExtendExpr(SC1, Ty), 1629 getSignExtendExpr(SMul, Ty)); 1630 } 1631 } 1632 } 1633 } 1634 // If the input value is a chrec scev, and we can prove that the value 1635 // did not overflow the old, smaller, value, we can sign extend all of the 1636 // operands (often constants). This allows analysis of something like 1637 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 1638 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1639 if (AR->isAffine()) { 1640 const SCEV *Start = AR->getStart(); 1641 const SCEV *Step = AR->getStepRecurrence(*this); 1642 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1643 const Loop *L = AR->getLoop(); 1644 1645 // If we have special knowledge that this addrec won't overflow, 1646 // we don't need to do any further analysis. 1647 if (AR->getNoWrapFlags(SCEV::FlagNSW)) 1648 return getAddRecExpr( 1649 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), 1650 getSignExtendExpr(Step, Ty), L, SCEV::FlagNSW); 1651 1652 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1653 // Note that this serves two purposes: It filters out loops that are 1654 // simply not analyzable, and it covers the case where this code is 1655 // being called from within backedge-taken count analysis, such that 1656 // attempting to ask for the backedge-taken count would likely result 1657 // in infinite recursion. In the later case, the analysis code will 1658 // cope with a conservative value, and it will take care to purge 1659 // that value once it has finished. 1660 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); 1661 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1662 // Manually compute the final value for AR, checking for 1663 // overflow. 1664 1665 // Check whether the backedge-taken count can be losslessly casted to 1666 // the addrec's type. The count is always unsigned. 1667 const SCEV *CastedMaxBECount = 1668 getTruncateOrZeroExtend(MaxBECount, Start->getType()); 1669 const SCEV *RecastedMaxBECount = 1670 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); 1671 if (MaxBECount == RecastedMaxBECount) { 1672 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1673 // Check whether Start+Step*MaxBECount has no signed overflow. 1674 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step); 1675 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul), WideTy); 1676 const SCEV *WideStart = getSignExtendExpr(Start, WideTy); 1677 const SCEV *WideMaxBECount = 1678 getZeroExtendExpr(CastedMaxBECount, WideTy); 1679 const SCEV *OperandExtendedAdd = 1680 getAddExpr(WideStart, 1681 getMulExpr(WideMaxBECount, 1682 getSignExtendExpr(Step, WideTy))); 1683 if (SAdd == OperandExtendedAdd) { 1684 // Cache knowledge of AR NSW, which is propagated to this AddRec. 1685 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1686 // Return the expression with the addrec on the outside. 1687 return getAddRecExpr( 1688 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), 1689 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1690 } 1691 // Similar to above, only this time treat the step value as unsigned. 1692 // This covers loops that count up with an unsigned step. 1693 OperandExtendedAdd = 1694 getAddExpr(WideStart, 1695 getMulExpr(WideMaxBECount, 1696 getZeroExtendExpr(Step, WideTy))); 1697 if (SAdd == OperandExtendedAdd) { 1698 // If AR wraps around then 1699 // 1700 // abs(Step) * MaxBECount > unsigned-max(AR->getType()) 1701 // => SAdd != OperandExtendedAdd 1702 // 1703 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> 1704 // (SAdd == OperandExtendedAdd => AR is NW) 1705 1706 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1707 1708 // Return the expression with the addrec on the outside. 1709 return getAddRecExpr( 1710 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), 1711 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1712 } 1713 } 1714 1715 // If the backedge is guarded by a comparison with the pre-inc value 1716 // the addrec is safe. Also, if the entry is guarded by a comparison 1717 // with the start value and the backedge is guarded by a comparison 1718 // with the post-inc value, the addrec is safe. 1719 ICmpInst::Predicate Pred; 1720 const SCEV *OverflowLimit = 1721 getSignedOverflowLimitForStep(Step, &Pred, this); 1722 if (OverflowLimit && 1723 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 1724 (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) && 1725 isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this), 1726 OverflowLimit)))) { 1727 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec. 1728 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1729 return getAddRecExpr( 1730 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), 1731 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1732 } 1733 } 1734 // If Start and Step are constants, check if we can apply this 1735 // transformation: 1736 // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2 1737 auto SC1 = dyn_cast<SCEVConstant>(Start); 1738 auto SC2 = dyn_cast<SCEVConstant>(Step); 1739 if (SC1 && SC2) { 1740 const APInt &C1 = SC1->getValue()->getValue(); 1741 const APInt &C2 = SC2->getValue()->getValue(); 1742 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) && 1743 C2.isPowerOf2()) { 1744 Start = getSignExtendExpr(Start, Ty); 1745 const SCEV *NewAR = getAddRecExpr(getConstant(AR->getType(), 0), Step, 1746 L, AR->getNoWrapFlags()); 1747 return getAddExpr(Start, getSignExtendExpr(NewAR, Ty)); 1748 } 1749 } 1750 1751 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { 1752 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1753 return getAddRecExpr( 1754 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), 1755 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); 1756 } 1757 } 1758 1759 // The cast wasn't folded; create an explicit cast node. 1760 // Recompute the insert position, as it may have been invalidated. 1761 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1762 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1763 Op, Ty); 1764 UniqueSCEVs.InsertNode(S, IP); 1765 return S; 1766 } 1767 1768 /// getAnyExtendExpr - Return a SCEV for the given operand extended with 1769 /// unspecified bits out to the given type. 1770 /// 1771 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, 1772 Type *Ty) { 1773 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1774 "This is not an extending conversion!"); 1775 assert(isSCEVable(Ty) && 1776 "This is not a conversion to a SCEVable type!"); 1777 Ty = getEffectiveSCEVType(Ty); 1778 1779 // Sign-extend negative constants. 1780 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1781 if (SC->getValue()->getValue().isNegative()) 1782 return getSignExtendExpr(Op, Ty); 1783 1784 // Peel off a truncate cast. 1785 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { 1786 const SCEV *NewOp = T->getOperand(); 1787 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) 1788 return getAnyExtendExpr(NewOp, Ty); 1789 return getTruncateOrNoop(NewOp, Ty); 1790 } 1791 1792 // Next try a zext cast. If the cast is folded, use it. 1793 const SCEV *ZExt = getZeroExtendExpr(Op, Ty); 1794 if (!isa<SCEVZeroExtendExpr>(ZExt)) 1795 return ZExt; 1796 1797 // Next try a sext cast. If the cast is folded, use it. 1798 const SCEV *SExt = getSignExtendExpr(Op, Ty); 1799 if (!isa<SCEVSignExtendExpr>(SExt)) 1800 return SExt; 1801 1802 // Force the cast to be folded into the operands of an addrec. 1803 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { 1804 SmallVector<const SCEV *, 4> Ops; 1805 for (const SCEV *Op : AR->operands()) 1806 Ops.push_back(getAnyExtendExpr(Op, Ty)); 1807 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); 1808 } 1809 1810 // If the expression is obviously signed, use the sext cast value. 1811 if (isa<SCEVSMaxExpr>(Op)) 1812 return SExt; 1813 1814 // Absent any other information, use the zext cast value. 1815 return ZExt; 1816 } 1817 1818 /// CollectAddOperandsWithScales - Process the given Ops list, which is 1819 /// a list of operands to be added under the given scale, update the given 1820 /// map. This is a helper function for getAddRecExpr. As an example of 1821 /// what it does, given a sequence of operands that would form an add 1822 /// expression like this: 1823 /// 1824 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r) 1825 /// 1826 /// where A and B are constants, update the map with these values: 1827 /// 1828 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) 1829 /// 1830 /// and add 13 + A*B*29 to AccumulatedConstant. 1831 /// This will allow getAddRecExpr to produce this: 1832 /// 1833 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) 1834 /// 1835 /// This form often exposes folding opportunities that are hidden in 1836 /// the original operand list. 1837 /// 1838 /// Return true iff it appears that any interesting folding opportunities 1839 /// may be exposed. This helps getAddRecExpr short-circuit extra work in 1840 /// the common case where no interesting opportunities are present, and 1841 /// is also used as a check to avoid infinite recursion. 1842 /// 1843 static bool 1844 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, 1845 SmallVectorImpl<const SCEV *> &NewOps, 1846 APInt &AccumulatedConstant, 1847 const SCEV *const *Ops, size_t NumOperands, 1848 const APInt &Scale, 1849 ScalarEvolution &SE) { 1850 bool Interesting = false; 1851 1852 // Iterate over the add operands. They are sorted, with constants first. 1853 unsigned i = 0; 1854 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 1855 ++i; 1856 // Pull a buried constant out to the outside. 1857 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) 1858 Interesting = true; 1859 AccumulatedConstant += Scale * C->getValue()->getValue(); 1860 } 1861 1862 // Next comes everything else. We're especially interested in multiplies 1863 // here, but they're in the middle, so just visit the rest with one loop. 1864 for (; i != NumOperands; ++i) { 1865 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); 1866 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { 1867 APInt NewScale = 1868 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue(); 1869 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { 1870 // A multiplication of a constant with another add; recurse. 1871 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); 1872 Interesting |= 1873 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 1874 Add->op_begin(), Add->getNumOperands(), 1875 NewScale, SE); 1876 } else { 1877 // A multiplication of a constant with some other value. Update 1878 // the map. 1879 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end()); 1880 const SCEV *Key = SE.getMulExpr(MulOps); 1881 auto Pair = M.insert(std::make_pair(Key, NewScale)); 1882 if (Pair.second) { 1883 NewOps.push_back(Pair.first->first); 1884 } else { 1885 Pair.first->second += NewScale; 1886 // The map already had an entry for this value, which may indicate 1887 // a folding opportunity. 1888 Interesting = true; 1889 } 1890 } 1891 } else { 1892 // An ordinary operand. Update the map. 1893 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = 1894 M.insert(std::make_pair(Ops[i], Scale)); 1895 if (Pair.second) { 1896 NewOps.push_back(Pair.first->first); 1897 } else { 1898 Pair.first->second += Scale; 1899 // The map already had an entry for this value, which may indicate 1900 // a folding opportunity. 1901 Interesting = true; 1902 } 1903 } 1904 } 1905 1906 return Interesting; 1907 } 1908 1909 namespace { 1910 struct APIntCompare { 1911 bool operator()(const APInt &LHS, const APInt &RHS) const { 1912 return LHS.ult(RHS); 1913 } 1914 }; 1915 } 1916 1917 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and 1918 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of 1919 // can't-overflow flags for the operation if possible. 1920 static SCEV::NoWrapFlags 1921 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, 1922 const SmallVectorImpl<const SCEV *> &Ops, 1923 SCEV::NoWrapFlags OldFlags) { 1924 using namespace std::placeholders; 1925 1926 bool CanAnalyze = 1927 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; 1928 (void)CanAnalyze; 1929 assert(CanAnalyze && "don't call from other places!"); 1930 1931 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 1932 SCEV::NoWrapFlags SignOrUnsignWrap = 1933 ScalarEvolution::maskFlags(OldFlags, SignOrUnsignMask); 1934 1935 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 1936 auto IsKnownNonNegative = 1937 std::bind(std::mem_fn(&ScalarEvolution::isKnownNonNegative), SE, _1); 1938 1939 if (SignOrUnsignWrap == SCEV::FlagNSW && 1940 std::all_of(Ops.begin(), Ops.end(), IsKnownNonNegative)) 1941 return ScalarEvolution::setFlags(OldFlags, 1942 (SCEV::NoWrapFlags)SignOrUnsignMask); 1943 1944 return OldFlags; 1945 } 1946 1947 /// getAddExpr - Get a canonical add expression, or something simpler if 1948 /// possible. 1949 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 1950 SCEV::NoWrapFlags Flags) { 1951 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && 1952 "only nuw or nsw allowed"); 1953 assert(!Ops.empty() && "Cannot get empty add!"); 1954 if (Ops.size() == 1) return Ops[0]; 1955 #ifndef NDEBUG 1956 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 1957 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 1958 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 1959 "SCEVAddExpr operand types don't match!"); 1960 #endif 1961 1962 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags); 1963 1964 // Sort by complexity, this groups all similar expression types together. 1965 GroupByComplexity(Ops, &LI); 1966 1967 // If there are any constants, fold them together. 1968 unsigned Idx = 0; 1969 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 1970 ++Idx; 1971 assert(Idx < Ops.size()); 1972 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 1973 // We found two constants, fold them together! 1974 Ops[0] = getConstant(LHSC->getValue()->getValue() + 1975 RHSC->getValue()->getValue()); 1976 if (Ops.size() == 2) return Ops[0]; 1977 Ops.erase(Ops.begin()+1); // Erase the folded element 1978 LHSC = cast<SCEVConstant>(Ops[0]); 1979 } 1980 1981 // If we are left with a constant zero being added, strip it off. 1982 if (LHSC->getValue()->isZero()) { 1983 Ops.erase(Ops.begin()); 1984 --Idx; 1985 } 1986 1987 if (Ops.size() == 1) return Ops[0]; 1988 } 1989 1990 // Okay, check to see if the same value occurs in the operand list more than 1991 // once. If so, merge them together into an multiply expression. Since we 1992 // sorted the list, these values are required to be adjacent. 1993 Type *Ty = Ops[0]->getType(); 1994 bool FoundMatch = false; 1995 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 1996 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 1997 // Scan ahead to count how many equal operands there are. 1998 unsigned Count = 2; 1999 while (i+Count != e && Ops[i+Count] == Ops[i]) 2000 ++Count; 2001 // Merge the values into a multiply. 2002 const SCEV *Scale = getConstant(Ty, Count); 2003 const SCEV *Mul = getMulExpr(Scale, Ops[i]); 2004 if (Ops.size() == Count) 2005 return Mul; 2006 Ops[i] = Mul; 2007 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 2008 --i; e -= Count - 1; 2009 FoundMatch = true; 2010 } 2011 if (FoundMatch) 2012 return getAddExpr(Ops, Flags); 2013 2014 // Check for truncates. If all the operands are truncated from the same 2015 // type, see if factoring out the truncate would permit the result to be 2016 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n) 2017 // if the contents of the resulting outer trunc fold to something simple. 2018 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) { 2019 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]); 2020 Type *DstType = Trunc->getType(); 2021 Type *SrcType = Trunc->getOperand()->getType(); 2022 SmallVector<const SCEV *, 8> LargeOps; 2023 bool Ok = true; 2024 // Check all the operands to see if they can be represented in the 2025 // source type of the truncate. 2026 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 2027 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 2028 if (T->getOperand()->getType() != SrcType) { 2029 Ok = false; 2030 break; 2031 } 2032 LargeOps.push_back(T->getOperand()); 2033 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2034 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 2035 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 2036 SmallVector<const SCEV *, 8> LargeMulOps; 2037 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 2038 if (const SCEVTruncateExpr *T = 2039 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 2040 if (T->getOperand()->getType() != SrcType) { 2041 Ok = false; 2042 break; 2043 } 2044 LargeMulOps.push_back(T->getOperand()); 2045 } else if (const SCEVConstant *C = 2046 dyn_cast<SCEVConstant>(M->getOperand(j))) { 2047 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 2048 } else { 2049 Ok = false; 2050 break; 2051 } 2052 } 2053 if (Ok) 2054 LargeOps.push_back(getMulExpr(LargeMulOps)); 2055 } else { 2056 Ok = false; 2057 break; 2058 } 2059 } 2060 if (Ok) { 2061 // Evaluate the expression in the larger type. 2062 const SCEV *Fold = getAddExpr(LargeOps, Flags); 2063 // If it folds to something simple, use it. Otherwise, don't. 2064 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 2065 return getTruncateExpr(Fold, DstType); 2066 } 2067 } 2068 2069 // Skip past any other cast SCEVs. 2070 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 2071 ++Idx; 2072 2073 // If there are add operands they would be next. 2074 if (Idx < Ops.size()) { 2075 bool DeletedAdd = false; 2076 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2077 // If we have an add, expand the add operands onto the end of the operands 2078 // list. 2079 Ops.erase(Ops.begin()+Idx); 2080 Ops.append(Add->op_begin(), Add->op_end()); 2081 DeletedAdd = true; 2082 } 2083 2084 // If we deleted at least one add, we added operands to the end of the list, 2085 // and they are not necessarily sorted. Recurse to resort and resimplify 2086 // any operands we just acquired. 2087 if (DeletedAdd) 2088 return getAddExpr(Ops); 2089 } 2090 2091 // Skip over the add expression until we get to a multiply. 2092 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2093 ++Idx; 2094 2095 // Check to see if there are any folding opportunities present with 2096 // operands multiplied by constant values. 2097 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2098 uint64_t BitWidth = getTypeSizeInBits(Ty); 2099 DenseMap<const SCEV *, APInt> M; 2100 SmallVector<const SCEV *, 8> NewOps; 2101 APInt AccumulatedConstant(BitWidth, 0); 2102 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2103 Ops.data(), Ops.size(), 2104 APInt(BitWidth, 1), *this)) { 2105 // Some interesting folding opportunity is present, so its worthwhile to 2106 // re-generate the operands list. Group the operands by constant scale, 2107 // to avoid multiplying by the same constant scale multiple times. 2108 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2109 for (SmallVectorImpl<const SCEV *>::const_iterator I = NewOps.begin(), 2110 E = NewOps.end(); I != E; ++I) 2111 MulOpLists[M.find(*I)->second].push_back(*I); 2112 // Re-generate the operands list. 2113 Ops.clear(); 2114 if (AccumulatedConstant != 0) 2115 Ops.push_back(getConstant(AccumulatedConstant)); 2116 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator 2117 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I) 2118 if (I->first != 0) 2119 Ops.push_back(getMulExpr(getConstant(I->first), 2120 getAddExpr(I->second))); 2121 if (Ops.empty()) 2122 return getConstant(Ty, 0); 2123 if (Ops.size() == 1) 2124 return Ops[0]; 2125 return getAddExpr(Ops); 2126 } 2127 } 2128 2129 // If we are adding something to a multiply expression, make sure the 2130 // something is not already an operand of the multiply. If so, merge it into 2131 // the multiply. 2132 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2133 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2134 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2135 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2136 if (isa<SCEVConstant>(MulOpSCEV)) 2137 continue; 2138 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2139 if (MulOpSCEV == Ops[AddOp]) { 2140 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2141 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2142 if (Mul->getNumOperands() != 2) { 2143 // If the multiply has more than two operands, we must get the 2144 // Y*Z term. 2145 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2146 Mul->op_begin()+MulOp); 2147 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2148 InnerMul = getMulExpr(MulOps); 2149 } 2150 const SCEV *One = getConstant(Ty, 1); 2151 const SCEV *AddOne = getAddExpr(One, InnerMul); 2152 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV); 2153 if (Ops.size() == 2) return OuterMul; 2154 if (AddOp < Idx) { 2155 Ops.erase(Ops.begin()+AddOp); 2156 Ops.erase(Ops.begin()+Idx-1); 2157 } else { 2158 Ops.erase(Ops.begin()+Idx); 2159 Ops.erase(Ops.begin()+AddOp-1); 2160 } 2161 Ops.push_back(OuterMul); 2162 return getAddExpr(Ops); 2163 } 2164 2165 // Check this multiply against other multiplies being added together. 2166 for (unsigned OtherMulIdx = Idx+1; 2167 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2168 ++OtherMulIdx) { 2169 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2170 // If MulOp occurs in OtherMul, we can fold the two multiplies 2171 // together. 2172 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2173 OMulOp != e; ++OMulOp) 2174 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2175 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2176 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2177 if (Mul->getNumOperands() != 2) { 2178 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2179 Mul->op_begin()+MulOp); 2180 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2181 InnerMul1 = getMulExpr(MulOps); 2182 } 2183 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2184 if (OtherMul->getNumOperands() != 2) { 2185 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2186 OtherMul->op_begin()+OMulOp); 2187 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2188 InnerMul2 = getMulExpr(MulOps); 2189 } 2190 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2); 2191 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum); 2192 if (Ops.size() == 2) return OuterMul; 2193 Ops.erase(Ops.begin()+Idx); 2194 Ops.erase(Ops.begin()+OtherMulIdx-1); 2195 Ops.push_back(OuterMul); 2196 return getAddExpr(Ops); 2197 } 2198 } 2199 } 2200 } 2201 2202 // If there are any add recurrences in the operands list, see if any other 2203 // added values are loop invariant. If so, we can fold them into the 2204 // recurrence. 2205 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2206 ++Idx; 2207 2208 // Scan over all recurrences, trying to fold loop invariants into them. 2209 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2210 // Scan all of the other operands to this add and add them to the vector if 2211 // they are loop invariant w.r.t. the recurrence. 2212 SmallVector<const SCEV *, 8> LIOps; 2213 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2214 const Loop *AddRecLoop = AddRec->getLoop(); 2215 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2216 if (isLoopInvariant(Ops[i], AddRecLoop)) { 2217 LIOps.push_back(Ops[i]); 2218 Ops.erase(Ops.begin()+i); 2219 --i; --e; 2220 } 2221 2222 // If we found some loop invariants, fold them into the recurrence. 2223 if (!LIOps.empty()) { 2224 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2225 LIOps.push_back(AddRec->getStart()); 2226 2227 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2228 AddRec->op_end()); 2229 AddRecOps[0] = getAddExpr(LIOps); 2230 2231 // Build the new addrec. Propagate the NUW and NSW flags if both the 2232 // outer add and the inner addrec are guaranteed to have no overflow. 2233 // Always propagate NW. 2234 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2235 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2236 2237 // If all of the other operands were loop invariant, we are done. 2238 if (Ops.size() == 1) return NewRec; 2239 2240 // Otherwise, add the folded AddRec by the non-invariant parts. 2241 for (unsigned i = 0;; ++i) 2242 if (Ops[i] == AddRec) { 2243 Ops[i] = NewRec; 2244 break; 2245 } 2246 return getAddExpr(Ops); 2247 } 2248 2249 // Okay, if there weren't any loop invariants to be folded, check to see if 2250 // there are multiple AddRec's with the same loop induction variable being 2251 // added together. If so, we can fold them. 2252 for (unsigned OtherIdx = Idx+1; 2253 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2254 ++OtherIdx) 2255 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2256 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2257 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2258 AddRec->op_end()); 2259 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2260 ++OtherIdx) 2261 if (const SCEVAddRecExpr *OtherAddRec = 2262 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx])) 2263 if (OtherAddRec->getLoop() == AddRecLoop) { 2264 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2265 i != e; ++i) { 2266 if (i >= AddRecOps.size()) { 2267 AddRecOps.append(OtherAddRec->op_begin()+i, 2268 OtherAddRec->op_end()); 2269 break; 2270 } 2271 AddRecOps[i] = getAddExpr(AddRecOps[i], 2272 OtherAddRec->getOperand(i)); 2273 } 2274 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2275 } 2276 // Step size has changed, so we cannot guarantee no self-wraparound. 2277 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2278 return getAddExpr(Ops); 2279 } 2280 2281 // Otherwise couldn't fold anything into this recurrence. Move onto the 2282 // next one. 2283 } 2284 2285 // Okay, it looks like we really DO need an add expr. Check to see if we 2286 // already have one, otherwise create a new one. 2287 FoldingSetNodeID ID; 2288 ID.AddInteger(scAddExpr); 2289 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2290 ID.AddPointer(Ops[i]); 2291 void *IP = nullptr; 2292 SCEVAddExpr *S = 2293 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2294 if (!S) { 2295 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2296 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2297 S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator), 2298 O, Ops.size()); 2299 UniqueSCEVs.InsertNode(S, IP); 2300 } 2301 S->setNoWrapFlags(Flags); 2302 return S; 2303 } 2304 2305 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2306 uint64_t k = i*j; 2307 if (j > 1 && k / j != i) Overflow = true; 2308 return k; 2309 } 2310 2311 /// Compute the result of "n choose k", the binomial coefficient. If an 2312 /// intermediate computation overflows, Overflow will be set and the return will 2313 /// be garbage. Overflow is not cleared on absence of overflow. 2314 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 2315 // We use the multiplicative formula: 2316 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 2317 // At each iteration, we take the n-th term of the numeral and divide by the 2318 // (k-n)th term of the denominator. This division will always produce an 2319 // integral result, and helps reduce the chance of overflow in the 2320 // intermediate computations. However, we can still overflow even when the 2321 // final result would fit. 2322 2323 if (n == 0 || n == k) return 1; 2324 if (k > n) return 0; 2325 2326 if (k > n/2) 2327 k = n-k; 2328 2329 uint64_t r = 1; 2330 for (uint64_t i = 1; i <= k; ++i) { 2331 r = umul_ov(r, n-(i-1), Overflow); 2332 r /= i; 2333 } 2334 return r; 2335 } 2336 2337 /// Determine if any of the operands in this SCEV are a constant or if 2338 /// any of the add or multiply expressions in this SCEV contain a constant. 2339 static bool containsConstantSomewhere(const SCEV *StartExpr) { 2340 SmallVector<const SCEV *, 4> Ops; 2341 Ops.push_back(StartExpr); 2342 while (!Ops.empty()) { 2343 const SCEV *CurrentExpr = Ops.pop_back_val(); 2344 if (isa<SCEVConstant>(*CurrentExpr)) 2345 return true; 2346 2347 if (isa<SCEVAddExpr>(*CurrentExpr) || isa<SCEVMulExpr>(*CurrentExpr)) { 2348 const auto *CurrentNAry = cast<SCEVNAryExpr>(CurrentExpr); 2349 Ops.append(CurrentNAry->op_begin(), CurrentNAry->op_end()); 2350 } 2351 } 2352 return false; 2353 } 2354 2355 /// getMulExpr - Get a canonical multiply expression, or something simpler if 2356 /// possible. 2357 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2358 SCEV::NoWrapFlags Flags) { 2359 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && 2360 "only nuw or nsw allowed"); 2361 assert(!Ops.empty() && "Cannot get empty mul!"); 2362 if (Ops.size() == 1) return Ops[0]; 2363 #ifndef NDEBUG 2364 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2365 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2366 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2367 "SCEVMulExpr operand types don't match!"); 2368 #endif 2369 2370 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags); 2371 2372 // Sort by complexity, this groups all similar expression types together. 2373 GroupByComplexity(Ops, &LI); 2374 2375 // If there are any constants, fold them together. 2376 unsigned Idx = 0; 2377 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2378 2379 // C1*(C2+V) -> C1*C2 + C1*V 2380 if (Ops.size() == 2) 2381 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 2382 // If any of Add's ops are Adds or Muls with a constant, 2383 // apply this transformation as well. 2384 if (Add->getNumOperands() == 2) 2385 if (containsConstantSomewhere(Add)) 2386 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)), 2387 getMulExpr(LHSC, Add->getOperand(1))); 2388 2389 ++Idx; 2390 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2391 // We found two constants, fold them together! 2392 ConstantInt *Fold = ConstantInt::get(getContext(), 2393 LHSC->getValue()->getValue() * 2394 RHSC->getValue()->getValue()); 2395 Ops[0] = getConstant(Fold); 2396 Ops.erase(Ops.begin()+1); // Erase the folded element 2397 if (Ops.size() == 1) return Ops[0]; 2398 LHSC = cast<SCEVConstant>(Ops[0]); 2399 } 2400 2401 // If we are left with a constant one being multiplied, strip it off. 2402 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) { 2403 Ops.erase(Ops.begin()); 2404 --Idx; 2405 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) { 2406 // If we have a multiply of zero, it will always be zero. 2407 return Ops[0]; 2408 } else if (Ops[0]->isAllOnesValue()) { 2409 // If we have a mul by -1 of an add, try distributing the -1 among the 2410 // add operands. 2411 if (Ops.size() == 2) { 2412 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 2413 SmallVector<const SCEV *, 4> NewOps; 2414 bool AnyFolded = false; 2415 for (SCEVAddRecExpr::op_iterator I = Add->op_begin(), 2416 E = Add->op_end(); I != E; ++I) { 2417 const SCEV *Mul = getMulExpr(Ops[0], *I); 2418 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 2419 NewOps.push_back(Mul); 2420 } 2421 if (AnyFolded) 2422 return getAddExpr(NewOps); 2423 } 2424 else if (const SCEVAddRecExpr * 2425 AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 2426 // Negation preserves a recurrence's no self-wrap property. 2427 SmallVector<const SCEV *, 4> Operands; 2428 for (SCEVAddRecExpr::op_iterator I = AddRec->op_begin(), 2429 E = AddRec->op_end(); I != E; ++I) { 2430 Operands.push_back(getMulExpr(Ops[0], *I)); 2431 } 2432 return getAddRecExpr(Operands, AddRec->getLoop(), 2433 AddRec->getNoWrapFlags(SCEV::FlagNW)); 2434 } 2435 } 2436 } 2437 2438 if (Ops.size() == 1) 2439 return Ops[0]; 2440 } 2441 2442 // Skip over the add expression until we get to a multiply. 2443 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2444 ++Idx; 2445 2446 // If there are mul operands inline them all into this expression. 2447 if (Idx < Ops.size()) { 2448 bool DeletedMul = false; 2449 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2450 // If we have an mul, expand the mul operands onto the end of the operands 2451 // list. 2452 Ops.erase(Ops.begin()+Idx); 2453 Ops.append(Mul->op_begin(), Mul->op_end()); 2454 DeletedMul = true; 2455 } 2456 2457 // If we deleted at least one mul, we added operands to the end of the list, 2458 // and they are not necessarily sorted. Recurse to resort and resimplify 2459 // any operands we just acquired. 2460 if (DeletedMul) 2461 return getMulExpr(Ops); 2462 } 2463 2464 // If there are any add recurrences in the operands list, see if any other 2465 // added values are loop invariant. If so, we can fold them into the 2466 // recurrence. 2467 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2468 ++Idx; 2469 2470 // Scan over all recurrences, trying to fold loop invariants into them. 2471 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2472 // Scan all of the other operands to this mul and add them to the vector if 2473 // they are loop invariant w.r.t. the recurrence. 2474 SmallVector<const SCEV *, 8> LIOps; 2475 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2476 const Loop *AddRecLoop = AddRec->getLoop(); 2477 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2478 if (isLoopInvariant(Ops[i], AddRecLoop)) { 2479 LIOps.push_back(Ops[i]); 2480 Ops.erase(Ops.begin()+i); 2481 --i; --e; 2482 } 2483 2484 // If we found some loop invariants, fold them into the recurrence. 2485 if (!LIOps.empty()) { 2486 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 2487 SmallVector<const SCEV *, 4> NewOps; 2488 NewOps.reserve(AddRec->getNumOperands()); 2489 const SCEV *Scale = getMulExpr(LIOps); 2490 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 2491 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i))); 2492 2493 // Build the new addrec. Propagate the NUW and NSW flags if both the 2494 // outer mul and the inner addrec are guaranteed to have no overflow. 2495 // 2496 // No self-wrap cannot be guaranteed after changing the step size, but 2497 // will be inferred if either NUW or NSW is true. 2498 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW)); 2499 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags); 2500 2501 // If all of the other operands were loop invariant, we are done. 2502 if (Ops.size() == 1) return NewRec; 2503 2504 // Otherwise, multiply the folded AddRec by the non-invariant parts. 2505 for (unsigned i = 0;; ++i) 2506 if (Ops[i] == AddRec) { 2507 Ops[i] = NewRec; 2508 break; 2509 } 2510 return getMulExpr(Ops); 2511 } 2512 2513 // Okay, if there weren't any loop invariants to be folded, check to see if 2514 // there are multiple AddRec's with the same loop induction variable being 2515 // multiplied together. If so, we can fold them. 2516 2517 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 2518 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 2519 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 2520 // ]]],+,...up to x=2n}. 2521 // Note that the arguments to choose() are always integers with values 2522 // known at compile time, never SCEV objects. 2523 // 2524 // The implementation avoids pointless extra computations when the two 2525 // addrec's are of different length (mathematically, it's equivalent to 2526 // an infinite stream of zeros on the right). 2527 bool OpsModified = false; 2528 for (unsigned OtherIdx = Idx+1; 2529 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2530 ++OtherIdx) { 2531 const SCEVAddRecExpr *OtherAddRec = 2532 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2533 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 2534 continue; 2535 2536 bool Overflow = false; 2537 Type *Ty = AddRec->getType(); 2538 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 2539 SmallVector<const SCEV*, 7> AddRecOps; 2540 for (int x = 0, xe = AddRec->getNumOperands() + 2541 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 2542 const SCEV *Term = getConstant(Ty, 0); 2543 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 2544 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 2545 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 2546 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 2547 z < ze && !Overflow; ++z) { 2548 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 2549 uint64_t Coeff; 2550 if (LargerThan64Bits) 2551 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 2552 else 2553 Coeff = Coeff1*Coeff2; 2554 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 2555 const SCEV *Term1 = AddRec->getOperand(y-z); 2556 const SCEV *Term2 = OtherAddRec->getOperand(z); 2557 Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1,Term2)); 2558 } 2559 } 2560 AddRecOps.push_back(Term); 2561 } 2562 if (!Overflow) { 2563 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(), 2564 SCEV::FlagAnyWrap); 2565 if (Ops.size() == 2) return NewAddRec; 2566 Ops[Idx] = NewAddRec; 2567 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2568 OpsModified = true; 2569 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 2570 if (!AddRec) 2571 break; 2572 } 2573 } 2574 if (OpsModified) 2575 return getMulExpr(Ops); 2576 2577 // Otherwise couldn't fold anything into this recurrence. Move onto the 2578 // next one. 2579 } 2580 2581 // Okay, it looks like we really DO need an mul expr. Check to see if we 2582 // already have one, otherwise create a new one. 2583 FoldingSetNodeID ID; 2584 ID.AddInteger(scMulExpr); 2585 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2586 ID.AddPointer(Ops[i]); 2587 void *IP = nullptr; 2588 SCEVMulExpr *S = 2589 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2590 if (!S) { 2591 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2592 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2593 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2594 O, Ops.size()); 2595 UniqueSCEVs.InsertNode(S, IP); 2596 } 2597 S->setNoWrapFlags(Flags); 2598 return S; 2599 } 2600 2601 /// getUDivExpr - Get a canonical unsigned division expression, or something 2602 /// simpler if possible. 2603 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 2604 const SCEV *RHS) { 2605 assert(getEffectiveSCEVType(LHS->getType()) == 2606 getEffectiveSCEVType(RHS->getType()) && 2607 "SCEVUDivExpr operand types don't match!"); 2608 2609 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 2610 if (RHSC->getValue()->equalsInt(1)) 2611 return LHS; // X udiv 1 --> x 2612 // If the denominator is zero, the result of the udiv is undefined. Don't 2613 // try to analyze it, because the resolution chosen here may differ from 2614 // the resolution chosen in other parts of the compiler. 2615 if (!RHSC->getValue()->isZero()) { 2616 // Determine if the division can be folded into the operands of 2617 // its operands. 2618 // TODO: Generalize this to non-constants by using known-bits information. 2619 Type *Ty = LHS->getType(); 2620 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros(); 2621 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 2622 // For non-power-of-two values, effectively round the value up to the 2623 // nearest power of two. 2624 if (!RHSC->getValue()->getValue().isPowerOf2()) 2625 ++MaxShiftAmt; 2626 IntegerType *ExtTy = 2627 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 2628 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 2629 if (const SCEVConstant *Step = 2630 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 2631 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 2632 const APInt &StepInt = Step->getValue()->getValue(); 2633 const APInt &DivInt = RHSC->getValue()->getValue(); 2634 if (!StepInt.urem(DivInt) && 2635 getZeroExtendExpr(AR, ExtTy) == 2636 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 2637 getZeroExtendExpr(Step, ExtTy), 2638 AR->getLoop(), SCEV::FlagAnyWrap)) { 2639 SmallVector<const SCEV *, 4> Operands; 2640 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i) 2641 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS)); 2642 return getAddRecExpr(Operands, AR->getLoop(), 2643 SCEV::FlagNW); 2644 } 2645 /// Get a canonical UDivExpr for a recurrence. 2646 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 2647 // We can currently only fold X%N if X is constant. 2648 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 2649 if (StartC && !DivInt.urem(StepInt) && 2650 getZeroExtendExpr(AR, ExtTy) == 2651 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 2652 getZeroExtendExpr(Step, ExtTy), 2653 AR->getLoop(), SCEV::FlagAnyWrap)) { 2654 const APInt &StartInt = StartC->getValue()->getValue(); 2655 const APInt &StartRem = StartInt.urem(StepInt); 2656 if (StartRem != 0) 2657 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step, 2658 AR->getLoop(), SCEV::FlagNW); 2659 } 2660 } 2661 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 2662 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 2663 SmallVector<const SCEV *, 4> Operands; 2664 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) 2665 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy)); 2666 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 2667 // Find an operand that's safely divisible. 2668 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 2669 const SCEV *Op = M->getOperand(i); 2670 const SCEV *Div = getUDivExpr(Op, RHSC); 2671 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 2672 Operands = SmallVector<const SCEV *, 4>(M->op_begin(), 2673 M->op_end()); 2674 Operands[i] = Div; 2675 return getMulExpr(Operands); 2676 } 2677 } 2678 } 2679 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 2680 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 2681 SmallVector<const SCEV *, 4> Operands; 2682 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) 2683 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy)); 2684 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 2685 Operands.clear(); 2686 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 2687 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 2688 if (isa<SCEVUDivExpr>(Op) || 2689 getMulExpr(Op, RHS) != A->getOperand(i)) 2690 break; 2691 Operands.push_back(Op); 2692 } 2693 if (Operands.size() == A->getNumOperands()) 2694 return getAddExpr(Operands); 2695 } 2696 } 2697 2698 // Fold if both operands are constant. 2699 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 2700 Constant *LHSCV = LHSC->getValue(); 2701 Constant *RHSCV = RHSC->getValue(); 2702 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 2703 RHSCV))); 2704 } 2705 } 2706 } 2707 2708 FoldingSetNodeID ID; 2709 ID.AddInteger(scUDivExpr); 2710 ID.AddPointer(LHS); 2711 ID.AddPointer(RHS); 2712 void *IP = nullptr; 2713 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 2714 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 2715 LHS, RHS); 2716 UniqueSCEVs.InsertNode(S, IP); 2717 return S; 2718 } 2719 2720 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 2721 APInt A = C1->getValue()->getValue().abs(); 2722 APInt B = C2->getValue()->getValue().abs(); 2723 uint32_t ABW = A.getBitWidth(); 2724 uint32_t BBW = B.getBitWidth(); 2725 2726 if (ABW > BBW) 2727 B = B.zext(ABW); 2728 else if (ABW < BBW) 2729 A = A.zext(BBW); 2730 2731 return APIntOps::GreatestCommonDivisor(A, B); 2732 } 2733 2734 /// getUDivExactExpr - Get a canonical unsigned division expression, or 2735 /// something simpler if possible. There is no representation for an exact udiv 2736 /// in SCEV IR, but we can attempt to remove factors from the LHS and RHS. 2737 /// We can't do this when it's not exact because the udiv may be clearing bits. 2738 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 2739 const SCEV *RHS) { 2740 // TODO: we could try to find factors in all sorts of things, but for now we 2741 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 2742 // end of this file for inspiration. 2743 2744 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 2745 if (!Mul) 2746 return getUDivExpr(LHS, RHS); 2747 2748 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 2749 // If the mulexpr multiplies by a constant, then that constant must be the 2750 // first element of the mulexpr. 2751 if (const SCEVConstant *LHSCst = 2752 dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 2753 if (LHSCst == RHSCst) { 2754 SmallVector<const SCEV *, 2> Operands; 2755 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 2756 return getMulExpr(Operands); 2757 } 2758 2759 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 2760 // that there's a factor provided by one of the other terms. We need to 2761 // check. 2762 APInt Factor = gcd(LHSCst, RHSCst); 2763 if (!Factor.isIntN(1)) { 2764 LHSCst = cast<SCEVConstant>( 2765 getConstant(LHSCst->getValue()->getValue().udiv(Factor))); 2766 RHSCst = cast<SCEVConstant>( 2767 getConstant(RHSCst->getValue()->getValue().udiv(Factor))); 2768 SmallVector<const SCEV *, 2> Operands; 2769 Operands.push_back(LHSCst); 2770 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 2771 LHS = getMulExpr(Operands); 2772 RHS = RHSCst; 2773 Mul = dyn_cast<SCEVMulExpr>(LHS); 2774 if (!Mul) 2775 return getUDivExactExpr(LHS, RHS); 2776 } 2777 } 2778 } 2779 2780 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 2781 if (Mul->getOperand(i) == RHS) { 2782 SmallVector<const SCEV *, 2> Operands; 2783 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 2784 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 2785 return getMulExpr(Operands); 2786 } 2787 } 2788 2789 return getUDivExpr(LHS, RHS); 2790 } 2791 2792 /// getAddRecExpr - Get an add recurrence expression for the specified loop. 2793 /// Simplify the expression as much as possible. 2794 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 2795 const Loop *L, 2796 SCEV::NoWrapFlags Flags) { 2797 SmallVector<const SCEV *, 4> Operands; 2798 Operands.push_back(Start); 2799 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 2800 if (StepChrec->getLoop() == L) { 2801 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 2802 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 2803 } 2804 2805 Operands.push_back(Step); 2806 return getAddRecExpr(Operands, L, Flags); 2807 } 2808 2809 /// getAddRecExpr - Get an add recurrence expression for the specified loop. 2810 /// Simplify the expression as much as possible. 2811 const SCEV * 2812 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 2813 const Loop *L, SCEV::NoWrapFlags Flags) { 2814 if (Operands.size() == 1) return Operands[0]; 2815 #ifndef NDEBUG 2816 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 2817 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 2818 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 2819 "SCEVAddRecExpr operand types don't match!"); 2820 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 2821 assert(isLoopInvariant(Operands[i], L) && 2822 "SCEVAddRecExpr operand is not loop-invariant!"); 2823 #endif 2824 2825 if (Operands.back()->isZero()) { 2826 Operands.pop_back(); 2827 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 2828 } 2829 2830 // It's tempting to want to call getMaxBackedgeTakenCount count here and 2831 // use that information to infer NUW and NSW flags. However, computing a 2832 // BE count requires calling getAddRecExpr, so we may not yet have a 2833 // meaningful BE count at this point (and if we don't, we'd be stuck 2834 // with a SCEVCouldNotCompute as the cached BE count). 2835 2836 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 2837 2838 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 2839 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 2840 const Loop *NestedLoop = NestedAR->getLoop(); 2841 if (L->contains(NestedLoop) 2842 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 2843 : (!NestedLoop->contains(L) && 2844 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 2845 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(), 2846 NestedAR->op_end()); 2847 Operands[0] = NestedAR->getStart(); 2848 // AddRecs require their operands be loop-invariant with respect to their 2849 // loops. Don't perform this transformation if it would break this 2850 // requirement. 2851 bool AllInvariant = true; 2852 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 2853 if (!isLoopInvariant(Operands[i], L)) { 2854 AllInvariant = false; 2855 break; 2856 } 2857 if (AllInvariant) { 2858 // Create a recurrence for the outer loop with the same step size. 2859 // 2860 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 2861 // inner recurrence has the same property. 2862 SCEV::NoWrapFlags OuterFlags = 2863 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 2864 2865 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 2866 AllInvariant = true; 2867 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i) 2868 if (!isLoopInvariant(NestedOperands[i], NestedLoop)) { 2869 AllInvariant = false; 2870 break; 2871 } 2872 if (AllInvariant) { 2873 // Ok, both add recurrences are valid after the transformation. 2874 // 2875 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 2876 // the outer recurrence has the same property. 2877 SCEV::NoWrapFlags InnerFlags = 2878 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 2879 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 2880 } 2881 } 2882 // Reset Operands to its original state. 2883 Operands[0] = NestedAR; 2884 } 2885 } 2886 2887 // Okay, it looks like we really DO need an addrec expr. Check to see if we 2888 // already have one, otherwise create a new one. 2889 FoldingSetNodeID ID; 2890 ID.AddInteger(scAddRecExpr); 2891 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 2892 ID.AddPointer(Operands[i]); 2893 ID.AddPointer(L); 2894 void *IP = nullptr; 2895 SCEVAddRecExpr *S = 2896 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2897 if (!S) { 2898 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size()); 2899 std::uninitialized_copy(Operands.begin(), Operands.end(), O); 2900 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator), 2901 O, Operands.size(), L); 2902 UniqueSCEVs.InsertNode(S, IP); 2903 } 2904 S->setNoWrapFlags(Flags); 2905 return S; 2906 } 2907 2908 const SCEV * 2909 ScalarEvolution::getGEPExpr(Type *PointeeType, const SCEV *BaseExpr, 2910 const SmallVectorImpl<const SCEV *> &IndexExprs, 2911 bool InBounds) { 2912 // getSCEV(Base)->getType() has the same address space as Base->getType() 2913 // because SCEV::getType() preserves the address space. 2914 Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType()); 2915 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP 2916 // instruction to its SCEV, because the Instruction may be guarded by control 2917 // flow and the no-overflow bits may not be valid for the expression in any 2918 // context. This can be fixed similarly to how these flags are handled for 2919 // adds. 2920 SCEV::NoWrapFlags Wrap = InBounds ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 2921 2922 const SCEV *TotalOffset = getConstant(IntPtrTy, 0); 2923 // The address space is unimportant. The first thing we do on CurTy is getting 2924 // its element type. 2925 Type *CurTy = PointerType::getUnqual(PointeeType); 2926 for (const SCEV *IndexExpr : IndexExprs) { 2927 // Compute the (potentially symbolic) offset in bytes for this index. 2928 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 2929 // For a struct, add the member offset. 2930 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 2931 unsigned FieldNo = Index->getZExtValue(); 2932 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo); 2933 2934 // Add the field offset to the running total offset. 2935 TotalOffset = getAddExpr(TotalOffset, FieldOffset); 2936 2937 // Update CurTy to the type of the field at Index. 2938 CurTy = STy->getTypeAtIndex(Index); 2939 } else { 2940 // Update CurTy to its element type. 2941 CurTy = cast<SequentialType>(CurTy)->getElementType(); 2942 // For an array, add the element offset, explicitly scaled. 2943 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy); 2944 // Getelementptr indices are signed. 2945 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy); 2946 2947 // Multiply the index by the element size to compute the element offset. 2948 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap); 2949 2950 // Add the element offset to the running total offset. 2951 TotalOffset = getAddExpr(TotalOffset, LocalOffset); 2952 } 2953 } 2954 2955 // Add the total offset from all the GEP indices to the base. 2956 return getAddExpr(BaseExpr, TotalOffset, Wrap); 2957 } 2958 2959 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, 2960 const SCEV *RHS) { 2961 SmallVector<const SCEV *, 2> Ops; 2962 Ops.push_back(LHS); 2963 Ops.push_back(RHS); 2964 return getSMaxExpr(Ops); 2965 } 2966 2967 const SCEV * 2968 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 2969 assert(!Ops.empty() && "Cannot get empty smax!"); 2970 if (Ops.size() == 1) return Ops[0]; 2971 #ifndef NDEBUG 2972 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2973 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2974 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2975 "SCEVSMaxExpr operand types don't match!"); 2976 #endif 2977 2978 // Sort by complexity, this groups all similar expression types together. 2979 GroupByComplexity(Ops, &LI); 2980 2981 // If there are any constants, fold them together. 2982 unsigned Idx = 0; 2983 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2984 ++Idx; 2985 assert(Idx < Ops.size()); 2986 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2987 // We found two constants, fold them together! 2988 ConstantInt *Fold = ConstantInt::get(getContext(), 2989 APIntOps::smax(LHSC->getValue()->getValue(), 2990 RHSC->getValue()->getValue())); 2991 Ops[0] = getConstant(Fold); 2992 Ops.erase(Ops.begin()+1); // Erase the folded element 2993 if (Ops.size() == 1) return Ops[0]; 2994 LHSC = cast<SCEVConstant>(Ops[0]); 2995 } 2996 2997 // If we are left with a constant minimum-int, strip it off. 2998 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) { 2999 Ops.erase(Ops.begin()); 3000 --Idx; 3001 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) { 3002 // If we have an smax with a constant maximum-int, it will always be 3003 // maximum-int. 3004 return Ops[0]; 3005 } 3006 3007 if (Ops.size() == 1) return Ops[0]; 3008 } 3009 3010 // Find the first SMax 3011 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr) 3012 ++Idx; 3013 3014 // Check to see if one of the operands is an SMax. If so, expand its operands 3015 // onto our operand list, and recurse to simplify. 3016 if (Idx < Ops.size()) { 3017 bool DeletedSMax = false; 3018 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) { 3019 Ops.erase(Ops.begin()+Idx); 3020 Ops.append(SMax->op_begin(), SMax->op_end()); 3021 DeletedSMax = true; 3022 } 3023 3024 if (DeletedSMax) 3025 return getSMaxExpr(Ops); 3026 } 3027 3028 // Okay, check to see if the same value occurs in the operand list twice. If 3029 // so, delete one. Since we sorted the list, these values are required to 3030 // be adjacent. 3031 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 3032 // X smax Y smax Y --> X smax Y 3033 // X smax Y --> X, if X is always greater than Y 3034 if (Ops[i] == Ops[i+1] || 3035 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) { 3036 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); 3037 --i; --e; 3038 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) { 3039 Ops.erase(Ops.begin()+i, Ops.begin()+i+1); 3040 --i; --e; 3041 } 3042 3043 if (Ops.size() == 1) return Ops[0]; 3044 3045 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3046 3047 // Okay, it looks like we really DO need an smax expr. Check to see if we 3048 // already have one, otherwise create a new one. 3049 FoldingSetNodeID ID; 3050 ID.AddInteger(scSMaxExpr); 3051 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3052 ID.AddPointer(Ops[i]); 3053 void *IP = nullptr; 3054 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3055 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3056 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3057 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator), 3058 O, Ops.size()); 3059 UniqueSCEVs.InsertNode(S, IP); 3060 return S; 3061 } 3062 3063 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, 3064 const SCEV *RHS) { 3065 SmallVector<const SCEV *, 2> Ops; 3066 Ops.push_back(LHS); 3067 Ops.push_back(RHS); 3068 return getUMaxExpr(Ops); 3069 } 3070 3071 const SCEV * 3072 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3073 assert(!Ops.empty() && "Cannot get empty umax!"); 3074 if (Ops.size() == 1) return Ops[0]; 3075 #ifndef NDEBUG 3076 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3077 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3078 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3079 "SCEVUMaxExpr operand types don't match!"); 3080 #endif 3081 3082 // Sort by complexity, this groups all similar expression types together. 3083 GroupByComplexity(Ops, &LI); 3084 3085 // If there are any constants, fold them together. 3086 unsigned Idx = 0; 3087 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3088 ++Idx; 3089 assert(Idx < Ops.size()); 3090 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3091 // We found two constants, fold them together! 3092 ConstantInt *Fold = ConstantInt::get(getContext(), 3093 APIntOps::umax(LHSC->getValue()->getValue(), 3094 RHSC->getValue()->getValue())); 3095 Ops[0] = getConstant(Fold); 3096 Ops.erase(Ops.begin()+1); // Erase the folded element 3097 if (Ops.size() == 1) return Ops[0]; 3098 LHSC = cast<SCEVConstant>(Ops[0]); 3099 } 3100 3101 // If we are left with a constant minimum-int, strip it off. 3102 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) { 3103 Ops.erase(Ops.begin()); 3104 --Idx; 3105 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) { 3106 // If we have an umax with a constant maximum-int, it will always be 3107 // maximum-int. 3108 return Ops[0]; 3109 } 3110 3111 if (Ops.size() == 1) return Ops[0]; 3112 } 3113 3114 // Find the first UMax 3115 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr) 3116 ++Idx; 3117 3118 // Check to see if one of the operands is a UMax. If so, expand its operands 3119 // onto our operand list, and recurse to simplify. 3120 if (Idx < Ops.size()) { 3121 bool DeletedUMax = false; 3122 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) { 3123 Ops.erase(Ops.begin()+Idx); 3124 Ops.append(UMax->op_begin(), UMax->op_end()); 3125 DeletedUMax = true; 3126 } 3127 3128 if (DeletedUMax) 3129 return getUMaxExpr(Ops); 3130 } 3131 3132 // Okay, check to see if the same value occurs in the operand list twice. If 3133 // so, delete one. Since we sorted the list, these values are required to 3134 // be adjacent. 3135 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 3136 // X umax Y umax Y --> X umax Y 3137 // X umax Y --> X, if X is always greater than Y 3138 if (Ops[i] == Ops[i+1] || 3139 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) { 3140 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); 3141 --i; --e; 3142 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) { 3143 Ops.erase(Ops.begin()+i, Ops.begin()+i+1); 3144 --i; --e; 3145 } 3146 3147 if (Ops.size() == 1) return Ops[0]; 3148 3149 assert(!Ops.empty() && "Reduced umax down to nothing!"); 3150 3151 // Okay, it looks like we really DO need a umax expr. Check to see if we 3152 // already have one, otherwise create a new one. 3153 FoldingSetNodeID ID; 3154 ID.AddInteger(scUMaxExpr); 3155 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3156 ID.AddPointer(Ops[i]); 3157 void *IP = nullptr; 3158 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3159 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3160 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3161 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator), 3162 O, Ops.size()); 3163 UniqueSCEVs.InsertNode(S, IP); 3164 return S; 3165 } 3166 3167 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 3168 const SCEV *RHS) { 3169 // ~smax(~x, ~y) == smin(x, y). 3170 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS))); 3171 } 3172 3173 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, 3174 const SCEV *RHS) { 3175 // ~umax(~x, ~y) == umin(x, y) 3176 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS))); 3177 } 3178 3179 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 3180 // We can bypass creating a target-independent 3181 // constant expression and then folding it back into a ConstantInt. 3182 // This is just a compile-time optimization. 3183 return getConstant(IntTy, 3184 F.getParent()->getDataLayout().getTypeAllocSize(AllocTy)); 3185 } 3186 3187 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 3188 StructType *STy, 3189 unsigned FieldNo) { 3190 // We can bypass creating a target-independent 3191 // constant expression and then folding it back into a ConstantInt. 3192 // This is just a compile-time optimization. 3193 return getConstant( 3194 IntTy, 3195 F.getParent()->getDataLayout().getStructLayout(STy)->getElementOffset( 3196 FieldNo)); 3197 } 3198 3199 const SCEV *ScalarEvolution::getUnknown(Value *V) { 3200 // Don't attempt to do anything other than create a SCEVUnknown object 3201 // here. createSCEV only calls getUnknown after checking for all other 3202 // interesting possibilities, and any other code that calls getUnknown 3203 // is doing so in order to hide a value from SCEV canonicalization. 3204 3205 FoldingSetNodeID ID; 3206 ID.AddInteger(scUnknown); 3207 ID.AddPointer(V); 3208 void *IP = nullptr; 3209 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 3210 assert(cast<SCEVUnknown>(S)->getValue() == V && 3211 "Stale SCEVUnknown in uniquing map!"); 3212 return S; 3213 } 3214 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 3215 FirstUnknown); 3216 FirstUnknown = cast<SCEVUnknown>(S); 3217 UniqueSCEVs.InsertNode(S, IP); 3218 return S; 3219 } 3220 3221 //===----------------------------------------------------------------------===// 3222 // Basic SCEV Analysis and PHI Idiom Recognition Code 3223 // 3224 3225 /// isSCEVable - Test if values of the given type are analyzable within 3226 /// the SCEV framework. This primarily includes integer types, and it 3227 /// can optionally include pointer types if the ScalarEvolution class 3228 /// has access to target-specific information. 3229 bool ScalarEvolution::isSCEVable(Type *Ty) const { 3230 // Integers and pointers are always SCEVable. 3231 return Ty->isIntegerTy() || Ty->isPointerTy(); 3232 } 3233 3234 /// getTypeSizeInBits - Return the size in bits of the specified type, 3235 /// for which isSCEVable must return true. 3236 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 3237 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3238 return F.getParent()->getDataLayout().getTypeSizeInBits(Ty); 3239 } 3240 3241 /// getEffectiveSCEVType - Return a type with the same bitwidth as 3242 /// the given type and which represents how SCEV will treat the given 3243 /// type, for which isSCEVable must return true. For pointer types, 3244 /// this is the pointer-sized integer type. 3245 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 3246 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3247 3248 if (Ty->isIntegerTy()) { 3249 return Ty; 3250 } 3251 3252 // The only other support type is pointer. 3253 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 3254 return F.getParent()->getDataLayout().getIntPtrType(Ty); 3255 } 3256 3257 const SCEV *ScalarEvolution::getCouldNotCompute() { 3258 return CouldNotCompute.get(); 3259 } 3260 3261 namespace { 3262 // Helper class working with SCEVTraversal to figure out if a SCEV contains 3263 // a SCEVUnknown with null value-pointer. FindInvalidSCEVUnknown::FindOne 3264 // is set iff if find such SCEVUnknown. 3265 // 3266 struct FindInvalidSCEVUnknown { 3267 bool FindOne; 3268 FindInvalidSCEVUnknown() { FindOne = false; } 3269 bool follow(const SCEV *S) { 3270 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 3271 case scConstant: 3272 return false; 3273 case scUnknown: 3274 if (!cast<SCEVUnknown>(S)->getValue()) 3275 FindOne = true; 3276 return false; 3277 default: 3278 return true; 3279 } 3280 } 3281 bool isDone() const { return FindOne; } 3282 }; 3283 } 3284 3285 bool ScalarEvolution::checkValidity(const SCEV *S) const { 3286 FindInvalidSCEVUnknown F; 3287 SCEVTraversal<FindInvalidSCEVUnknown> ST(F); 3288 ST.visitAll(S); 3289 3290 return !F.FindOne; 3291 } 3292 3293 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the 3294 /// expression and create a new one. 3295 const SCEV *ScalarEvolution::getSCEV(Value *V) { 3296 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3297 3298 const SCEV *S = getExistingSCEV(V); 3299 if (S == nullptr) { 3300 S = createSCEV(V); 3301 ValueExprMap.insert(std::make_pair(SCEVCallbackVH(V, this), S)); 3302 } 3303 return S; 3304 } 3305 3306 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 3307 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3308 3309 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3310 if (I != ValueExprMap.end()) { 3311 const SCEV *S = I->second; 3312 if (checkValidity(S)) 3313 return S; 3314 ValueExprMap.erase(I); 3315 } 3316 return nullptr; 3317 } 3318 3319 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V 3320 /// 3321 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 3322 SCEV::NoWrapFlags Flags) { 3323 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3324 return getConstant( 3325 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 3326 3327 Type *Ty = V->getType(); 3328 Ty = getEffectiveSCEVType(Ty); 3329 return getMulExpr( 3330 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags); 3331 } 3332 3333 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V 3334 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 3335 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3336 return getConstant( 3337 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 3338 3339 Type *Ty = V->getType(); 3340 Ty = getEffectiveSCEVType(Ty); 3341 const SCEV *AllOnes = 3342 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))); 3343 return getMinusSCEV(AllOnes, V); 3344 } 3345 3346 /// getMinusSCEV - Return LHS-RHS. Minus is represented in SCEV as A+B*-1. 3347 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 3348 SCEV::NoWrapFlags Flags) { 3349 // Fast path: X - X --> 0. 3350 if (LHS == RHS) 3351 return getConstant(LHS->getType(), 0); 3352 3353 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 3354 // makes it so that we cannot make much use of NUW. 3355 auto AddFlags = SCEV::FlagAnyWrap; 3356 const bool RHSIsNotMinSigned = 3357 !getSignedRange(RHS).getSignedMin().isMinSignedValue(); 3358 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) { 3359 // Let M be the minimum representable signed value. Then (-1)*RHS 3360 // signed-wraps if and only if RHS is M. That can happen even for 3361 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 3362 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 3363 // (-1)*RHS, we need to prove that RHS != M. 3364 // 3365 // If LHS is non-negative and we know that LHS - RHS does not 3366 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 3367 // either by proving that RHS > M or that LHS >= 0. 3368 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 3369 AddFlags = SCEV::FlagNSW; 3370 } 3371 } 3372 3373 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 3374 // RHS is NSW and LHS >= 0. 3375 // 3376 // The difficulty here is that the NSW flag may have been proven 3377 // relative to a loop that is to be found in a recurrence in LHS and 3378 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 3379 // larger scope than intended. 3380 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3381 3382 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags); 3383 } 3384 3385 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the 3386 /// input value to the specified type. If the type must be extended, it is zero 3387 /// extended. 3388 const SCEV * 3389 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) { 3390 Type *SrcTy = V->getType(); 3391 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3392 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3393 "Cannot truncate or zero extend with non-integer arguments!"); 3394 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3395 return V; // No conversion 3396 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 3397 return getTruncateExpr(V, Ty); 3398 return getZeroExtendExpr(V, Ty); 3399 } 3400 3401 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the 3402 /// input value to the specified type. If the type must be extended, it is sign 3403 /// extended. 3404 const SCEV * 3405 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, 3406 Type *Ty) { 3407 Type *SrcTy = V->getType(); 3408 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3409 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3410 "Cannot truncate or zero extend with non-integer arguments!"); 3411 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3412 return V; // No conversion 3413 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 3414 return getTruncateExpr(V, Ty); 3415 return getSignExtendExpr(V, Ty); 3416 } 3417 3418 /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the 3419 /// input value to the specified type. If the type must be extended, it is zero 3420 /// extended. The conversion must not be narrowing. 3421 const SCEV * 3422 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 3423 Type *SrcTy = V->getType(); 3424 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3425 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3426 "Cannot noop or zero extend with non-integer arguments!"); 3427 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3428 "getNoopOrZeroExtend cannot truncate!"); 3429 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3430 return V; // No conversion 3431 return getZeroExtendExpr(V, Ty); 3432 } 3433 3434 /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the 3435 /// input value to the specified type. If the type must be extended, it is sign 3436 /// extended. The conversion must not be narrowing. 3437 const SCEV * 3438 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 3439 Type *SrcTy = V->getType(); 3440 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3441 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3442 "Cannot noop or sign extend with non-integer arguments!"); 3443 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3444 "getNoopOrSignExtend cannot truncate!"); 3445 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3446 return V; // No conversion 3447 return getSignExtendExpr(V, Ty); 3448 } 3449 3450 /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of 3451 /// the input value to the specified type. If the type must be extended, 3452 /// it is extended with unspecified bits. The conversion must not be 3453 /// narrowing. 3454 const SCEV * 3455 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 3456 Type *SrcTy = V->getType(); 3457 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3458 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3459 "Cannot noop or any extend with non-integer arguments!"); 3460 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3461 "getNoopOrAnyExtend cannot truncate!"); 3462 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3463 return V; // No conversion 3464 return getAnyExtendExpr(V, Ty); 3465 } 3466 3467 /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the 3468 /// input value to the specified type. The conversion must not be widening. 3469 const SCEV * 3470 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 3471 Type *SrcTy = V->getType(); 3472 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 3473 (Ty->isIntegerTy() || Ty->isPointerTy()) && 3474 "Cannot truncate or noop with non-integer arguments!"); 3475 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 3476 "getTruncateOrNoop cannot extend!"); 3477 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3478 return V; // No conversion 3479 return getTruncateExpr(V, Ty); 3480 } 3481 3482 /// getUMaxFromMismatchedTypes - Promote the operands to the wider of 3483 /// the types using zero-extension, and then perform a umax operation 3484 /// with them. 3485 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 3486 const SCEV *RHS) { 3487 const SCEV *PromotedLHS = LHS; 3488 const SCEV *PromotedRHS = RHS; 3489 3490 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 3491 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 3492 else 3493 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 3494 3495 return getUMaxExpr(PromotedLHS, PromotedRHS); 3496 } 3497 3498 /// getUMinFromMismatchedTypes - Promote the operands to the wider of 3499 /// the types using zero-extension, and then perform a umin operation 3500 /// with them. 3501 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 3502 const SCEV *RHS) { 3503 const SCEV *PromotedLHS = LHS; 3504 const SCEV *PromotedRHS = RHS; 3505 3506 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 3507 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 3508 else 3509 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 3510 3511 return getUMinExpr(PromotedLHS, PromotedRHS); 3512 } 3513 3514 /// getPointerBase - Transitively follow the chain of pointer-type operands 3515 /// until reaching a SCEV that does not have a single pointer operand. This 3516 /// returns a SCEVUnknown pointer for well-formed pointer-type expressions, 3517 /// but corner cases do exist. 3518 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 3519 // A pointer operand may evaluate to a nonpointer expression, such as null. 3520 if (!V->getType()->isPointerTy()) 3521 return V; 3522 3523 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) { 3524 return getPointerBase(Cast->getOperand()); 3525 } 3526 else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) { 3527 const SCEV *PtrOp = nullptr; 3528 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end(); 3529 I != E; ++I) { 3530 if ((*I)->getType()->isPointerTy()) { 3531 // Cannot find the base of an expression with multiple pointer operands. 3532 if (PtrOp) 3533 return V; 3534 PtrOp = *I; 3535 } 3536 } 3537 if (!PtrOp) 3538 return V; 3539 return getPointerBase(PtrOp); 3540 } 3541 return V; 3542 } 3543 3544 /// PushDefUseChildren - Push users of the given Instruction 3545 /// onto the given Worklist. 3546 static void 3547 PushDefUseChildren(Instruction *I, 3548 SmallVectorImpl<Instruction *> &Worklist) { 3549 // Push the def-use children onto the Worklist stack. 3550 for (User *U : I->users()) 3551 Worklist.push_back(cast<Instruction>(U)); 3552 } 3553 3554 /// ForgetSymbolicValue - This looks up computed SCEV values for all 3555 /// instructions that depend on the given instruction and removes them from 3556 /// the ValueExprMapType map if they reference SymName. This is used during PHI 3557 /// resolution. 3558 void 3559 ScalarEvolution::ForgetSymbolicName(Instruction *PN, const SCEV *SymName) { 3560 SmallVector<Instruction *, 16> Worklist; 3561 PushDefUseChildren(PN, Worklist); 3562 3563 SmallPtrSet<Instruction *, 8> Visited; 3564 Visited.insert(PN); 3565 while (!Worklist.empty()) { 3566 Instruction *I = Worklist.pop_back_val(); 3567 if (!Visited.insert(I).second) 3568 continue; 3569 3570 ValueExprMapType::iterator It = 3571 ValueExprMap.find_as(static_cast<Value *>(I)); 3572 if (It != ValueExprMap.end()) { 3573 const SCEV *Old = It->second; 3574 3575 // Short-circuit the def-use traversal if the symbolic name 3576 // ceases to appear in expressions. 3577 if (Old != SymName && !hasOperand(Old, SymName)) 3578 continue; 3579 3580 // SCEVUnknown for a PHI either means that it has an unrecognized 3581 // structure, it's a PHI that's in the progress of being computed 3582 // by createNodeForPHI, or it's a single-value PHI. In the first case, 3583 // additional loop trip count information isn't going to change anything. 3584 // In the second case, createNodeForPHI will perform the necessary 3585 // updates on its own when it gets to that point. In the third, we do 3586 // want to forget the SCEVUnknown. 3587 if (!isa<PHINode>(I) || 3588 !isa<SCEVUnknown>(Old) || 3589 (I != PN && Old == SymName)) { 3590 forgetMemoizedResults(Old); 3591 ValueExprMap.erase(It); 3592 } 3593 } 3594 3595 PushDefUseChildren(I, Worklist); 3596 } 3597 } 3598 3599 /// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in 3600 /// a loop header, making it a potential recurrence, or it doesn't. 3601 /// 3602 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 3603 if (const Loop *L = LI.getLoopFor(PN->getParent())) 3604 if (L->getHeader() == PN->getParent()) { 3605 // The loop may have multiple entrances or multiple exits; we can analyze 3606 // this phi as an addrec if it has a unique entry value and a unique 3607 // backedge value. 3608 Value *BEValueV = nullptr, *StartValueV = nullptr; 3609 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 3610 Value *V = PN->getIncomingValue(i); 3611 if (L->contains(PN->getIncomingBlock(i))) { 3612 if (!BEValueV) { 3613 BEValueV = V; 3614 } else if (BEValueV != V) { 3615 BEValueV = nullptr; 3616 break; 3617 } 3618 } else if (!StartValueV) { 3619 StartValueV = V; 3620 } else if (StartValueV != V) { 3621 StartValueV = nullptr; 3622 break; 3623 } 3624 } 3625 if (BEValueV && StartValueV) { 3626 // While we are analyzing this PHI node, handle its value symbolically. 3627 const SCEV *SymbolicName = getUnknown(PN); 3628 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 3629 "PHI node already processed?"); 3630 ValueExprMap.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName)); 3631 3632 // Using this symbolic name for the PHI, analyze the value coming around 3633 // the back-edge. 3634 const SCEV *BEValue = getSCEV(BEValueV); 3635 3636 // NOTE: If BEValue is loop invariant, we know that the PHI node just 3637 // has a special value for the first iteration of the loop. 3638 3639 // If the value coming around the backedge is an add with the symbolic 3640 // value we just inserted, then we found a simple induction variable! 3641 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 3642 // If there is a single occurrence of the symbolic value, replace it 3643 // with a recurrence. 3644 unsigned FoundIndex = Add->getNumOperands(); 3645 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 3646 if (Add->getOperand(i) == SymbolicName) 3647 if (FoundIndex == e) { 3648 FoundIndex = i; 3649 break; 3650 } 3651 3652 if (FoundIndex != Add->getNumOperands()) { 3653 // Create an add with everything but the specified operand. 3654 SmallVector<const SCEV *, 8> Ops; 3655 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 3656 if (i != FoundIndex) 3657 Ops.push_back(Add->getOperand(i)); 3658 const SCEV *Accum = getAddExpr(Ops); 3659 3660 // This is not a valid addrec if the step amount is varying each 3661 // loop iteration, but is not itself an addrec in this loop. 3662 if (isLoopInvariant(Accum, L) || 3663 (isa<SCEVAddRecExpr>(Accum) && 3664 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 3665 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 3666 3667 // If the increment doesn't overflow, then neither the addrec nor 3668 // the post-increment will overflow. 3669 if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV)) { 3670 if (OBO->getOperand(0) == PN) { 3671 if (OBO->hasNoUnsignedWrap()) 3672 Flags = setFlags(Flags, SCEV::FlagNUW); 3673 if (OBO->hasNoSignedWrap()) 3674 Flags = setFlags(Flags, SCEV::FlagNSW); 3675 } 3676 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 3677 // If the increment is an inbounds GEP, then we know the address 3678 // space cannot be wrapped around. We cannot make any guarantee 3679 // about signed or unsigned overflow because pointers are 3680 // unsigned but we may have a negative index from the base 3681 // pointer. We can guarantee that no unsigned wrap occurs if the 3682 // indices form a positive value. 3683 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 3684 Flags = setFlags(Flags, SCEV::FlagNW); 3685 3686 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 3687 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 3688 Flags = setFlags(Flags, SCEV::FlagNUW); 3689 } 3690 3691 // We cannot transfer nuw and nsw flags from subtraction 3692 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 3693 // for instance. 3694 } 3695 3696 const SCEV *StartVal = getSCEV(StartValueV); 3697 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 3698 3699 // Since the no-wrap flags are on the increment, they apply to the 3700 // post-incremented value as well. 3701 if (isLoopInvariant(Accum, L)) 3702 (void)getAddRecExpr(getAddExpr(StartVal, Accum), 3703 Accum, L, Flags); 3704 3705 // Okay, for the entire analysis of this edge we assumed the PHI 3706 // to be symbolic. We now need to go back and purge all of the 3707 // entries for the scalars that use the symbolic expression. 3708 ForgetSymbolicName(PN, SymbolicName); 3709 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 3710 return PHISCEV; 3711 } 3712 } 3713 } else if (const SCEVAddRecExpr *AddRec = 3714 dyn_cast<SCEVAddRecExpr>(BEValue)) { 3715 // Otherwise, this could be a loop like this: 3716 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 3717 // In this case, j = {1,+,1} and BEValue is j. 3718 // Because the other in-value of i (0) fits the evolution of BEValue 3719 // i really is an addrec evolution. 3720 if (AddRec->getLoop() == L && AddRec->isAffine()) { 3721 const SCEV *StartVal = getSCEV(StartValueV); 3722 3723 // If StartVal = j.start - j.stride, we can use StartVal as the 3724 // initial step of the addrec evolution. 3725 if (StartVal == getMinusSCEV(AddRec->getOperand(0), 3726 AddRec->getOperand(1))) { 3727 // FIXME: For constant StartVal, we should be able to infer 3728 // no-wrap flags. 3729 const SCEV *PHISCEV = 3730 getAddRecExpr(StartVal, AddRec->getOperand(1), L, 3731 SCEV::FlagAnyWrap); 3732 3733 // Okay, for the entire analysis of this edge we assumed the PHI 3734 // to be symbolic. We now need to go back and purge all of the 3735 // entries for the scalars that use the symbolic expression. 3736 ForgetSymbolicName(PN, SymbolicName); 3737 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 3738 return PHISCEV; 3739 } 3740 } 3741 } 3742 } 3743 } 3744 3745 // If the PHI has a single incoming value, follow that value, unless the 3746 // PHI's incoming blocks are in a different loop, in which case doing so 3747 // risks breaking LCSSA form. Instcombine would normally zap these, but 3748 // it doesn't have DominatorTree information, so it may miss cases. 3749 if (Value *V = SimplifyInstruction(PN, F.getParent()->getDataLayout(), &TLI, 3750 &DT, &AC)) 3751 if (LI.replacementPreservesLCSSAForm(PN, V)) 3752 return getSCEV(V); 3753 3754 // If it's not a loop phi, we can't handle it yet. 3755 return getUnknown(PN); 3756 } 3757 3758 /// createNodeForGEP - Expand GEP instructions into add and multiply 3759 /// operations. This allows them to be analyzed by regular SCEV code. 3760 /// 3761 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 3762 Value *Base = GEP->getOperand(0); 3763 // Don't attempt to analyze GEPs over unsized objects. 3764 if (!Base->getType()->getPointerElementType()->isSized()) 3765 return getUnknown(GEP); 3766 3767 SmallVector<const SCEV *, 4> IndexExprs; 3768 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) 3769 IndexExprs.push_back(getSCEV(*Index)); 3770 return getGEPExpr(GEP->getSourceElementType(), getSCEV(Base), IndexExprs, 3771 GEP->isInBounds()); 3772 } 3773 3774 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S is 3775 /// guaranteed to end in (at every loop iteration). It is, at the same time, 3776 /// the minimum number of times S is divisible by 2. For example, given {4,+,8} 3777 /// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S. 3778 uint32_t 3779 ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 3780 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 3781 return C->getValue()->getValue().countTrailingZeros(); 3782 3783 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 3784 return std::min(GetMinTrailingZeros(T->getOperand()), 3785 (uint32_t)getTypeSizeInBits(T->getType())); 3786 3787 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 3788 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 3789 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ? 3790 getTypeSizeInBits(E->getType()) : OpRes; 3791 } 3792 3793 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 3794 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 3795 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ? 3796 getTypeSizeInBits(E->getType()) : OpRes; 3797 } 3798 3799 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 3800 // The result is the min of all operands results. 3801 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 3802 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 3803 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 3804 return MinOpRes; 3805 } 3806 3807 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 3808 // The result is the sum of all operands results. 3809 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 3810 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 3811 for (unsigned i = 1, e = M->getNumOperands(); 3812 SumOpRes != BitWidth && i != e; ++i) 3813 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), 3814 BitWidth); 3815 return SumOpRes; 3816 } 3817 3818 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 3819 // The result is the min of all operands results. 3820 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 3821 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 3822 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 3823 return MinOpRes; 3824 } 3825 3826 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 3827 // The result is the min of all operands results. 3828 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 3829 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 3830 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 3831 return MinOpRes; 3832 } 3833 3834 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 3835 // The result is the min of all operands results. 3836 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 3837 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 3838 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 3839 return MinOpRes; 3840 } 3841 3842 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 3843 // For a SCEVUnknown, ask ValueTracking. 3844 unsigned BitWidth = getTypeSizeInBits(U->getType()); 3845 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0); 3846 computeKnownBits(U->getValue(), Zeros, Ones, F.getParent()->getDataLayout(), 3847 0, &AC, nullptr, &DT); 3848 return Zeros.countTrailingOnes(); 3849 } 3850 3851 // SCEVUDivExpr 3852 return 0; 3853 } 3854 3855 /// GetRangeFromMetadata - Helper method to assign a range to V from 3856 /// metadata present in the IR. 3857 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 3858 if (Instruction *I = dyn_cast<Instruction>(V)) { 3859 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) { 3860 ConstantRange TotalRange( 3861 cast<IntegerType>(I->getType())->getBitWidth(), false); 3862 3863 unsigned NumRanges = MD->getNumOperands() / 2; 3864 assert(NumRanges >= 1); 3865 3866 for (unsigned i = 0; i < NumRanges; ++i) { 3867 ConstantInt *Lower = 3868 mdconst::extract<ConstantInt>(MD->getOperand(2 * i + 0)); 3869 ConstantInt *Upper = 3870 mdconst::extract<ConstantInt>(MD->getOperand(2 * i + 1)); 3871 ConstantRange Range(Lower->getValue(), Upper->getValue()); 3872 TotalRange = TotalRange.unionWith(Range); 3873 } 3874 3875 return TotalRange; 3876 } 3877 } 3878 3879 return None; 3880 } 3881 3882 /// getRange - Determine the range for a particular SCEV. If SignHint is 3883 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 3884 /// with a "cleaner" unsigned (resp. signed) representation. 3885 /// 3886 ConstantRange 3887 ScalarEvolution::getRange(const SCEV *S, 3888 ScalarEvolution::RangeSignHint SignHint) { 3889 DenseMap<const SCEV *, ConstantRange> &Cache = 3890 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 3891 : SignedRanges; 3892 3893 // See if we've computed this range already. 3894 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 3895 if (I != Cache.end()) 3896 return I->second; 3897 3898 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 3899 return setRange(C, SignHint, ConstantRange(C->getValue()->getValue())); 3900 3901 unsigned BitWidth = getTypeSizeInBits(S->getType()); 3902 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 3903 3904 // If the value has known zeros, the maximum value will have those known zeros 3905 // as well. 3906 uint32_t TZ = GetMinTrailingZeros(S); 3907 if (TZ != 0) { 3908 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 3909 ConservativeResult = 3910 ConstantRange(APInt::getMinValue(BitWidth), 3911 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 3912 else 3913 ConservativeResult = ConstantRange( 3914 APInt::getSignedMinValue(BitWidth), 3915 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 3916 } 3917 3918 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 3919 ConstantRange X = getRange(Add->getOperand(0), SignHint); 3920 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 3921 X = X.add(getRange(Add->getOperand(i), SignHint)); 3922 return setRange(Add, SignHint, ConservativeResult.intersectWith(X)); 3923 } 3924 3925 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 3926 ConstantRange X = getRange(Mul->getOperand(0), SignHint); 3927 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 3928 X = X.multiply(getRange(Mul->getOperand(i), SignHint)); 3929 return setRange(Mul, SignHint, ConservativeResult.intersectWith(X)); 3930 } 3931 3932 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 3933 ConstantRange X = getRange(SMax->getOperand(0), SignHint); 3934 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 3935 X = X.smax(getRange(SMax->getOperand(i), SignHint)); 3936 return setRange(SMax, SignHint, ConservativeResult.intersectWith(X)); 3937 } 3938 3939 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 3940 ConstantRange X = getRange(UMax->getOperand(0), SignHint); 3941 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 3942 X = X.umax(getRange(UMax->getOperand(i), SignHint)); 3943 return setRange(UMax, SignHint, ConservativeResult.intersectWith(X)); 3944 } 3945 3946 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 3947 ConstantRange X = getRange(UDiv->getLHS(), SignHint); 3948 ConstantRange Y = getRange(UDiv->getRHS(), SignHint); 3949 return setRange(UDiv, SignHint, 3950 ConservativeResult.intersectWith(X.udiv(Y))); 3951 } 3952 3953 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 3954 ConstantRange X = getRange(ZExt->getOperand(), SignHint); 3955 return setRange(ZExt, SignHint, 3956 ConservativeResult.intersectWith(X.zeroExtend(BitWidth))); 3957 } 3958 3959 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 3960 ConstantRange X = getRange(SExt->getOperand(), SignHint); 3961 return setRange(SExt, SignHint, 3962 ConservativeResult.intersectWith(X.signExtend(BitWidth))); 3963 } 3964 3965 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 3966 ConstantRange X = getRange(Trunc->getOperand(), SignHint); 3967 return setRange(Trunc, SignHint, 3968 ConservativeResult.intersectWith(X.truncate(BitWidth))); 3969 } 3970 3971 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 3972 // If there's no unsigned wrap, the value will never be less than its 3973 // initial value. 3974 if (AddRec->getNoWrapFlags(SCEV::FlagNUW)) 3975 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart())) 3976 if (!C->getValue()->isZero()) 3977 ConservativeResult = 3978 ConservativeResult.intersectWith( 3979 ConstantRange(C->getValue()->getValue(), APInt(BitWidth, 0))); 3980 3981 // If there's no signed wrap, and all the operands have the same sign or 3982 // zero, the value won't ever change sign. 3983 if (AddRec->getNoWrapFlags(SCEV::FlagNSW)) { 3984 bool AllNonNeg = true; 3985 bool AllNonPos = true; 3986 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 3987 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false; 3988 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false; 3989 } 3990 if (AllNonNeg) 3991 ConservativeResult = ConservativeResult.intersectWith( 3992 ConstantRange(APInt(BitWidth, 0), 3993 APInt::getSignedMinValue(BitWidth))); 3994 else if (AllNonPos) 3995 ConservativeResult = ConservativeResult.intersectWith( 3996 ConstantRange(APInt::getSignedMinValue(BitWidth), 3997 APInt(BitWidth, 1))); 3998 } 3999 4000 // TODO: non-affine addrec 4001 if (AddRec->isAffine()) { 4002 Type *Ty = AddRec->getType(); 4003 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop()); 4004 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 4005 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 4006 4007 // Check for overflow. This must be done with ConstantRange arithmetic 4008 // because we could be called from within the ScalarEvolution overflow 4009 // checking code. 4010 4011 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty); 4012 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount); 4013 ConstantRange ZExtMaxBECountRange = 4014 MaxBECountRange.zextOrTrunc(BitWidth * 2 + 1); 4015 4016 const SCEV *Start = AddRec->getStart(); 4017 const SCEV *Step = AddRec->getStepRecurrence(*this); 4018 ConstantRange StepSRange = getSignedRange(Step); 4019 ConstantRange SExtStepSRange = StepSRange.sextOrTrunc(BitWidth * 2 + 1); 4020 4021 ConstantRange StartURange = getUnsignedRange(Start); 4022 ConstantRange EndURange = 4023 StartURange.add(MaxBECountRange.multiply(StepSRange)); 4024 4025 // Check for unsigned overflow. 4026 ConstantRange ZExtStartURange = 4027 StartURange.zextOrTrunc(BitWidth * 2 + 1); 4028 ConstantRange ZExtEndURange = EndURange.zextOrTrunc(BitWidth * 2 + 1); 4029 if (ZExtStartURange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) == 4030 ZExtEndURange) { 4031 APInt Min = APIntOps::umin(StartURange.getUnsignedMin(), 4032 EndURange.getUnsignedMin()); 4033 APInt Max = APIntOps::umax(StartURange.getUnsignedMax(), 4034 EndURange.getUnsignedMax()); 4035 bool IsFullRange = Min.isMinValue() && Max.isMaxValue(); 4036 if (!IsFullRange) 4037 ConservativeResult = 4038 ConservativeResult.intersectWith(ConstantRange(Min, Max + 1)); 4039 } 4040 4041 ConstantRange StartSRange = getSignedRange(Start); 4042 ConstantRange EndSRange = 4043 StartSRange.add(MaxBECountRange.multiply(StepSRange)); 4044 4045 // Check for signed overflow. This must be done with ConstantRange 4046 // arithmetic because we could be called from within the ScalarEvolution 4047 // overflow checking code. 4048 ConstantRange SExtStartSRange = 4049 StartSRange.sextOrTrunc(BitWidth * 2 + 1); 4050 ConstantRange SExtEndSRange = EndSRange.sextOrTrunc(BitWidth * 2 + 1); 4051 if (SExtStartSRange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) == 4052 SExtEndSRange) { 4053 APInt Min = APIntOps::smin(StartSRange.getSignedMin(), 4054 EndSRange.getSignedMin()); 4055 APInt Max = APIntOps::smax(StartSRange.getSignedMax(), 4056 EndSRange.getSignedMax()); 4057 bool IsFullRange = Min.isMinSignedValue() && Max.isMaxSignedValue(); 4058 if (!IsFullRange) 4059 ConservativeResult = 4060 ConservativeResult.intersectWith(ConstantRange(Min, Max + 1)); 4061 } 4062 } 4063 } 4064 4065 return setRange(AddRec, SignHint, ConservativeResult); 4066 } 4067 4068 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 4069 // Check if the IR explicitly contains !range metadata. 4070 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 4071 if (MDRange.hasValue()) 4072 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue()); 4073 4074 // Split here to avoid paying the compile-time cost of calling both 4075 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted 4076 // if needed. 4077 const DataLayout &DL = F.getParent()->getDataLayout(); 4078 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) { 4079 // For a SCEVUnknown, ask ValueTracking. 4080 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0); 4081 computeKnownBits(U->getValue(), Zeros, Ones, DL, 0, &AC, nullptr, &DT); 4082 if (Ones != ~Zeros + 1) 4083 ConservativeResult = 4084 ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1)); 4085 } else { 4086 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED && 4087 "generalize as needed!"); 4088 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 4089 if (NS > 1) 4090 ConservativeResult = ConservativeResult.intersectWith( 4091 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 4092 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1)); 4093 } 4094 4095 return setRange(U, SignHint, ConservativeResult); 4096 } 4097 4098 return setRange(S, SignHint, ConservativeResult); 4099 } 4100 4101 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 4102 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 4103 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 4104 4105 // Return early if there are no flags to propagate to the SCEV. 4106 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 4107 if (BinOp->hasNoUnsignedWrap()) 4108 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 4109 if (BinOp->hasNoSignedWrap()) 4110 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 4111 if (Flags == SCEV::FlagAnyWrap) { 4112 return SCEV::FlagAnyWrap; 4113 } 4114 4115 // Here we check that BinOp is in the header of the innermost loop 4116 // containing BinOp, since we only deal with instructions in the loop 4117 // header. The actual loop we need to check later will come from an add 4118 // recurrence, but getting that requires computing the SCEV of the operands, 4119 // which can be expensive. This check we can do cheaply to rule out some 4120 // cases early. 4121 Loop *innermostContainingLoop = LI.getLoopFor(BinOp->getParent()); 4122 if (innermostContainingLoop == nullptr || 4123 innermostContainingLoop->getHeader() != BinOp->getParent()) 4124 return SCEV::FlagAnyWrap; 4125 4126 // Only proceed if we can prove that BinOp does not yield poison. 4127 if (!isKnownNotFullPoison(BinOp)) return SCEV::FlagAnyWrap; 4128 4129 // At this point we know that if V is executed, then it does not wrap 4130 // according to at least one of NSW or NUW. If V is not executed, then we do 4131 // not know if the calculation that V represents would wrap. Multiple 4132 // instructions can map to the same SCEV. If we apply NSW or NUW from V to 4133 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 4134 // derived from other instructions that map to the same SCEV. We cannot make 4135 // that guarantee for cases where V is not executed. So we need to find the 4136 // loop that V is considered in relation to and prove that V is executed for 4137 // every iteration of that loop. That implies that the value that V 4138 // calculates does not wrap anywhere in the loop, so then we can apply the 4139 // flags to the SCEV. 4140 // 4141 // We check isLoopInvariant to disambiguate in case we are adding two 4142 // recurrences from different loops, so that we know which loop to prove 4143 // that V is executed in. 4144 for (int OpIndex = 0; OpIndex < 2; ++OpIndex) { 4145 const SCEV *Op = getSCEV(BinOp->getOperand(OpIndex)); 4146 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 4147 const int OtherOpIndex = 1 - OpIndex; 4148 const SCEV *OtherOp = getSCEV(BinOp->getOperand(OtherOpIndex)); 4149 if (isLoopInvariant(OtherOp, AddRec->getLoop()) && 4150 isGuaranteedToExecuteForEveryIteration(BinOp, AddRec->getLoop())) 4151 return Flags; 4152 } 4153 } 4154 return SCEV::FlagAnyWrap; 4155 } 4156 4157 /// createSCEV - We know that there is no SCEV for the specified value. Analyze 4158 /// the expression. 4159 /// 4160 const SCEV *ScalarEvolution::createSCEV(Value *V) { 4161 if (!isSCEVable(V->getType())) 4162 return getUnknown(V); 4163 4164 unsigned Opcode = Instruction::UserOp1; 4165 if (Instruction *I = dyn_cast<Instruction>(V)) { 4166 Opcode = I->getOpcode(); 4167 4168 // Don't attempt to analyze instructions in blocks that aren't 4169 // reachable. Such instructions don't matter, and they aren't required 4170 // to obey basic rules for definitions dominating uses which this 4171 // analysis depends on. 4172 if (!DT.isReachableFromEntry(I->getParent())) 4173 return getUnknown(V); 4174 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) 4175 Opcode = CE->getOpcode(); 4176 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 4177 return getConstant(CI); 4178 else if (isa<ConstantPointerNull>(V)) 4179 return getConstant(V->getType(), 0); 4180 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 4181 return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee()); 4182 else 4183 return getUnknown(V); 4184 4185 Operator *U = cast<Operator>(V); 4186 switch (Opcode) { 4187 case Instruction::Add: { 4188 // The simple thing to do would be to just call getSCEV on both operands 4189 // and call getAddExpr with the result. However if we're looking at a 4190 // bunch of things all added together, this can be quite inefficient, 4191 // because it leads to N-1 getAddExpr calls for N ultimate operands. 4192 // Instead, gather up all the operands and make a single getAddExpr call. 4193 // LLVM IR canonical form means we need only traverse the left operands. 4194 SmallVector<const SCEV *, 4> AddOps; 4195 for (Value *Op = U;; Op = U->getOperand(0)) { 4196 U = dyn_cast<Operator>(Op); 4197 unsigned Opcode = U ? U->getOpcode() : 0; 4198 if (!U || (Opcode != Instruction::Add && Opcode != Instruction::Sub)) { 4199 assert(Op != V && "V should be an add"); 4200 AddOps.push_back(getSCEV(Op)); 4201 break; 4202 } 4203 4204 if (auto *OpSCEV = getExistingSCEV(U)) { 4205 AddOps.push_back(OpSCEV); 4206 break; 4207 } 4208 4209 // If a NUW or NSW flag can be applied to the SCEV for this 4210 // addition, then compute the SCEV for this addition by itself 4211 // with a separate call to getAddExpr. We need to do that 4212 // instead of pushing the operands of the addition onto AddOps, 4213 // since the flags are only known to apply to this particular 4214 // addition - they may not apply to other additions that can be 4215 // formed with operands from AddOps. 4216 const SCEV *RHS = getSCEV(U->getOperand(1)); 4217 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(U); 4218 if (Flags != SCEV::FlagAnyWrap) { 4219 const SCEV *LHS = getSCEV(U->getOperand(0)); 4220 if (Opcode == Instruction::Sub) 4221 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 4222 else 4223 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 4224 break; 4225 } 4226 4227 if (Opcode == Instruction::Sub) 4228 AddOps.push_back(getNegativeSCEV(RHS)); 4229 else 4230 AddOps.push_back(RHS); 4231 } 4232 return getAddExpr(AddOps); 4233 } 4234 4235 case Instruction::Mul: { 4236 SmallVector<const SCEV *, 4> MulOps; 4237 for (Value *Op = U;; Op = U->getOperand(0)) { 4238 U = dyn_cast<Operator>(Op); 4239 if (!U || U->getOpcode() != Instruction::Mul) { 4240 assert(Op != V && "V should be a mul"); 4241 MulOps.push_back(getSCEV(Op)); 4242 break; 4243 } 4244 4245 if (auto *OpSCEV = getExistingSCEV(U)) { 4246 MulOps.push_back(OpSCEV); 4247 break; 4248 } 4249 4250 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(U); 4251 if (Flags != SCEV::FlagAnyWrap) { 4252 MulOps.push_back(getMulExpr(getSCEV(U->getOperand(0)), 4253 getSCEV(U->getOperand(1)), Flags)); 4254 break; 4255 } 4256 4257 MulOps.push_back(getSCEV(U->getOperand(1))); 4258 } 4259 return getMulExpr(MulOps); 4260 } 4261 case Instruction::UDiv: 4262 return getUDivExpr(getSCEV(U->getOperand(0)), 4263 getSCEV(U->getOperand(1))); 4264 case Instruction::Sub: 4265 return getMinusSCEV(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)), 4266 getNoWrapFlagsFromUB(U)); 4267 case Instruction::And: 4268 // For an expression like x&255 that merely masks off the high bits, 4269 // use zext(trunc(x)) as the SCEV expression. 4270 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) { 4271 if (CI->isNullValue()) 4272 return getSCEV(U->getOperand(1)); 4273 if (CI->isAllOnesValue()) 4274 return getSCEV(U->getOperand(0)); 4275 const APInt &A = CI->getValue(); 4276 4277 // Instcombine's ShrinkDemandedConstant may strip bits out of 4278 // constants, obscuring what would otherwise be a low-bits mask. 4279 // Use computeKnownBits to compute what ShrinkDemandedConstant 4280 // knew about to reconstruct a low-bits mask value. 4281 unsigned LZ = A.countLeadingZeros(); 4282 unsigned TZ = A.countTrailingZeros(); 4283 unsigned BitWidth = A.getBitWidth(); 4284 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0); 4285 computeKnownBits(U->getOperand(0), KnownZero, KnownOne, 4286 F.getParent()->getDataLayout(), 0, &AC, nullptr, &DT); 4287 4288 APInt EffectiveMask = 4289 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 4290 if ((LZ != 0 || TZ != 0) && !((~A & ~KnownZero) & EffectiveMask)) { 4291 const SCEV *MulCount = getConstant( 4292 ConstantInt::get(getContext(), APInt::getOneBitSet(BitWidth, TZ))); 4293 return getMulExpr( 4294 getZeroExtendExpr( 4295 getTruncateExpr( 4296 getUDivExactExpr(getSCEV(U->getOperand(0)), MulCount), 4297 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 4298 U->getType()), 4299 MulCount); 4300 } 4301 } 4302 break; 4303 4304 case Instruction::Or: 4305 // If the RHS of the Or is a constant, we may have something like: 4306 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 4307 // optimizations will transparently handle this case. 4308 // 4309 // In order for this transformation to be safe, the LHS must be of the 4310 // form X*(2^n) and the Or constant must be less than 2^n. 4311 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) { 4312 const SCEV *LHS = getSCEV(U->getOperand(0)); 4313 const APInt &CIVal = CI->getValue(); 4314 if (GetMinTrailingZeros(LHS) >= 4315 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 4316 // Build a plain add SCEV. 4317 const SCEV *S = getAddExpr(LHS, getSCEV(CI)); 4318 // If the LHS of the add was an addrec and it has no-wrap flags, 4319 // transfer the no-wrap flags, since an or won't introduce a wrap. 4320 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) { 4321 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS); 4322 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags( 4323 OldAR->getNoWrapFlags()); 4324 } 4325 return S; 4326 } 4327 } 4328 break; 4329 case Instruction::Xor: 4330 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) { 4331 // If the RHS of the xor is a signbit, then this is just an add. 4332 // Instcombine turns add of signbit into xor as a strength reduction step. 4333 if (CI->getValue().isSignBit()) 4334 return getAddExpr(getSCEV(U->getOperand(0)), 4335 getSCEV(U->getOperand(1))); 4336 4337 // If the RHS of xor is -1, then this is a not operation. 4338 if (CI->isAllOnesValue()) 4339 return getNotSCEV(getSCEV(U->getOperand(0))); 4340 4341 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 4342 // This is a variant of the check for xor with -1, and it handles 4343 // the case where instcombine has trimmed non-demanded bits out 4344 // of an xor with -1. 4345 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0))) 4346 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1))) 4347 if (BO->getOpcode() == Instruction::And && 4348 LCI->getValue() == CI->getValue()) 4349 if (const SCEVZeroExtendExpr *Z = 4350 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) { 4351 Type *UTy = U->getType(); 4352 const SCEV *Z0 = Z->getOperand(); 4353 Type *Z0Ty = Z0->getType(); 4354 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 4355 4356 // If C is a low-bits mask, the zero extend is serving to 4357 // mask off the high bits. Complement the operand and 4358 // re-apply the zext. 4359 if (APIntOps::isMask(Z0TySize, CI->getValue())) 4360 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 4361 4362 // If C is a single bit, it may be in the sign-bit position 4363 // before the zero-extend. In this case, represent the xor 4364 // using an add, which is equivalent, and re-apply the zext. 4365 APInt Trunc = CI->getValue().trunc(Z0TySize); 4366 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 4367 Trunc.isSignBit()) 4368 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 4369 UTy); 4370 } 4371 } 4372 break; 4373 4374 case Instruction::Shl: 4375 // Turn shift left of a constant amount into a multiply. 4376 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) { 4377 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth(); 4378 4379 // If the shift count is not less than the bitwidth, the result of 4380 // the shift is undefined. Don't try to analyze it, because the 4381 // resolution chosen here may differ from the resolution chosen in 4382 // other parts of the compiler. 4383 if (SA->getValue().uge(BitWidth)) 4384 break; 4385 4386 // It is currently not resolved how to interpret NSW for left 4387 // shift by BitWidth - 1, so we avoid applying flags in that 4388 // case. Remove this check (or this comment) once the situation 4389 // is resolved. See 4390 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html 4391 // and http://reviews.llvm.org/D8890 . 4392 auto Flags = SCEV::FlagAnyWrap; 4393 if (SA->getValue().ult(BitWidth - 1)) Flags = getNoWrapFlagsFromUB(U); 4394 4395 Constant *X = ConstantInt::get(getContext(), 4396 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 4397 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X), Flags); 4398 } 4399 break; 4400 4401 case Instruction::LShr: 4402 // Turn logical shift right of a constant into a unsigned divide. 4403 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) { 4404 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth(); 4405 4406 // If the shift count is not less than the bitwidth, the result of 4407 // the shift is undefined. Don't try to analyze it, because the 4408 // resolution chosen here may differ from the resolution chosen in 4409 // other parts of the compiler. 4410 if (SA->getValue().uge(BitWidth)) 4411 break; 4412 4413 Constant *X = ConstantInt::get(getContext(), 4414 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 4415 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X)); 4416 } 4417 break; 4418 4419 case Instruction::AShr: 4420 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression. 4421 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) 4422 if (Operator *L = dyn_cast<Operator>(U->getOperand(0))) 4423 if (L->getOpcode() == Instruction::Shl && 4424 L->getOperand(1) == U->getOperand(1)) { 4425 uint64_t BitWidth = getTypeSizeInBits(U->getType()); 4426 4427 // If the shift count is not less than the bitwidth, the result of 4428 // the shift is undefined. Don't try to analyze it, because the 4429 // resolution chosen here may differ from the resolution chosen in 4430 // other parts of the compiler. 4431 if (CI->getValue().uge(BitWidth)) 4432 break; 4433 4434 uint64_t Amt = BitWidth - CI->getZExtValue(); 4435 if (Amt == BitWidth) 4436 return getSCEV(L->getOperand(0)); // shift by zero --> noop 4437 return 4438 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)), 4439 IntegerType::get(getContext(), 4440 Amt)), 4441 U->getType()); 4442 } 4443 break; 4444 4445 case Instruction::Trunc: 4446 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 4447 4448 case Instruction::ZExt: 4449 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 4450 4451 case Instruction::SExt: 4452 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 4453 4454 case Instruction::BitCast: 4455 // BitCasts are no-op casts so we just eliminate the cast. 4456 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 4457 return getSCEV(U->getOperand(0)); 4458 break; 4459 4460 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can 4461 // lead to pointer expressions which cannot safely be expanded to GEPs, 4462 // because ScalarEvolution doesn't respect the GEP aliasing rules when 4463 // simplifying integer expressions. 4464 4465 case Instruction::GetElementPtr: 4466 return createNodeForGEP(cast<GEPOperator>(U)); 4467 4468 case Instruction::PHI: 4469 return createNodeForPHI(cast<PHINode>(U)); 4470 4471 case Instruction::Select: 4472 // This could be a smax or umax that was lowered earlier. 4473 // Try to recover it. 4474 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) { 4475 Value *LHS = ICI->getOperand(0); 4476 Value *RHS = ICI->getOperand(1); 4477 switch (ICI->getPredicate()) { 4478 case ICmpInst::ICMP_SLT: 4479 case ICmpInst::ICMP_SLE: 4480 std::swap(LHS, RHS); 4481 // fall through 4482 case ICmpInst::ICMP_SGT: 4483 case ICmpInst::ICMP_SGE: 4484 // a >s b ? a+x : b+x -> smax(a, b)+x 4485 // a >s b ? b+x : a+x -> smin(a, b)+x 4486 if (getTypeSizeInBits(LHS->getType()) <= 4487 getTypeSizeInBits(U->getType())) { 4488 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), U->getType()); 4489 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), U->getType()); 4490 const SCEV *LA = getSCEV(U->getOperand(1)); 4491 const SCEV *RA = getSCEV(U->getOperand(2)); 4492 const SCEV *LDiff = getMinusSCEV(LA, LS); 4493 const SCEV *RDiff = getMinusSCEV(RA, RS); 4494 if (LDiff == RDiff) 4495 return getAddExpr(getSMaxExpr(LS, RS), LDiff); 4496 LDiff = getMinusSCEV(LA, RS); 4497 RDiff = getMinusSCEV(RA, LS); 4498 if (LDiff == RDiff) 4499 return getAddExpr(getSMinExpr(LS, RS), LDiff); 4500 } 4501 break; 4502 case ICmpInst::ICMP_ULT: 4503 case ICmpInst::ICMP_ULE: 4504 std::swap(LHS, RHS); 4505 // fall through 4506 case ICmpInst::ICMP_UGT: 4507 case ICmpInst::ICMP_UGE: 4508 // a >u b ? a+x : b+x -> umax(a, b)+x 4509 // a >u b ? b+x : a+x -> umin(a, b)+x 4510 if (getTypeSizeInBits(LHS->getType()) <= 4511 getTypeSizeInBits(U->getType())) { 4512 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), U->getType()); 4513 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), U->getType()); 4514 const SCEV *LA = getSCEV(U->getOperand(1)); 4515 const SCEV *RA = getSCEV(U->getOperand(2)); 4516 const SCEV *LDiff = getMinusSCEV(LA, LS); 4517 const SCEV *RDiff = getMinusSCEV(RA, RS); 4518 if (LDiff == RDiff) 4519 return getAddExpr(getUMaxExpr(LS, RS), LDiff); 4520 LDiff = getMinusSCEV(LA, RS); 4521 RDiff = getMinusSCEV(RA, LS); 4522 if (LDiff == RDiff) 4523 return getAddExpr(getUMinExpr(LS, RS), LDiff); 4524 } 4525 break; 4526 case ICmpInst::ICMP_NE: 4527 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 4528 if (getTypeSizeInBits(LHS->getType()) <= 4529 getTypeSizeInBits(U->getType()) && 4530 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 4531 const SCEV *One = getConstant(U->getType(), 1); 4532 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), U->getType()); 4533 const SCEV *LA = getSCEV(U->getOperand(1)); 4534 const SCEV *RA = getSCEV(U->getOperand(2)); 4535 const SCEV *LDiff = getMinusSCEV(LA, LS); 4536 const SCEV *RDiff = getMinusSCEV(RA, One); 4537 if (LDiff == RDiff) 4538 return getAddExpr(getUMaxExpr(One, LS), LDiff); 4539 } 4540 break; 4541 case ICmpInst::ICMP_EQ: 4542 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 4543 if (getTypeSizeInBits(LHS->getType()) <= 4544 getTypeSizeInBits(U->getType()) && 4545 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 4546 const SCEV *One = getConstant(U->getType(), 1); 4547 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), U->getType()); 4548 const SCEV *LA = getSCEV(U->getOperand(1)); 4549 const SCEV *RA = getSCEV(U->getOperand(2)); 4550 const SCEV *LDiff = getMinusSCEV(LA, One); 4551 const SCEV *RDiff = getMinusSCEV(RA, LS); 4552 if (LDiff == RDiff) 4553 return getAddExpr(getUMaxExpr(One, LS), LDiff); 4554 } 4555 break; 4556 default: 4557 break; 4558 } 4559 } 4560 4561 default: // We cannot analyze this expression. 4562 break; 4563 } 4564 4565 return getUnknown(V); 4566 } 4567 4568 4569 4570 //===----------------------------------------------------------------------===// 4571 // Iteration Count Computation Code 4572 // 4573 4574 unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L) { 4575 if (BasicBlock *ExitingBB = L->getExitingBlock()) 4576 return getSmallConstantTripCount(L, ExitingBB); 4577 4578 // No trip count information for multiple exits. 4579 return 0; 4580 } 4581 4582 /// getSmallConstantTripCount - Returns the maximum trip count of this loop as a 4583 /// normal unsigned value. Returns 0 if the trip count is unknown or not 4584 /// constant. Will also return 0 if the maximum trip count is very large (>= 4585 /// 2^32). 4586 /// 4587 /// This "trip count" assumes that control exits via ExitingBlock. More 4588 /// precisely, it is the number of times that control may reach ExitingBlock 4589 /// before taking the branch. For loops with multiple exits, it may not be the 4590 /// number times that the loop header executes because the loop may exit 4591 /// prematurely via another branch. 4592 unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L, 4593 BasicBlock *ExitingBlock) { 4594 assert(ExitingBlock && "Must pass a non-null exiting block!"); 4595 assert(L->isLoopExiting(ExitingBlock) && 4596 "Exiting block must actually branch out of the loop!"); 4597 const SCEVConstant *ExitCount = 4598 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 4599 if (!ExitCount) 4600 return 0; 4601 4602 ConstantInt *ExitConst = ExitCount->getValue(); 4603 4604 // Guard against huge trip counts. 4605 if (ExitConst->getValue().getActiveBits() > 32) 4606 return 0; 4607 4608 // In case of integer overflow, this returns 0, which is correct. 4609 return ((unsigned)ExitConst->getZExtValue()) + 1; 4610 } 4611 4612 unsigned ScalarEvolution::getSmallConstantTripMultiple(Loop *L) { 4613 if (BasicBlock *ExitingBB = L->getExitingBlock()) 4614 return getSmallConstantTripMultiple(L, ExitingBB); 4615 4616 // No trip multiple information for multiple exits. 4617 return 0; 4618 } 4619 4620 /// getSmallConstantTripMultiple - Returns the largest constant divisor of the 4621 /// trip count of this loop as a normal unsigned value, if possible. This 4622 /// means that the actual trip count is always a multiple of the returned 4623 /// value (don't forget the trip count could very well be zero as well!). 4624 /// 4625 /// Returns 1 if the trip count is unknown or not guaranteed to be the 4626 /// multiple of a constant (which is also the case if the trip count is simply 4627 /// constant, use getSmallConstantTripCount for that case), Will also return 1 4628 /// if the trip count is very large (>= 2^32). 4629 /// 4630 /// As explained in the comments for getSmallConstantTripCount, this assumes 4631 /// that control exits the loop via ExitingBlock. 4632 unsigned 4633 ScalarEvolution::getSmallConstantTripMultiple(Loop *L, 4634 BasicBlock *ExitingBlock) { 4635 assert(ExitingBlock && "Must pass a non-null exiting block!"); 4636 assert(L->isLoopExiting(ExitingBlock) && 4637 "Exiting block must actually branch out of the loop!"); 4638 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 4639 if (ExitCount == getCouldNotCompute()) 4640 return 1; 4641 4642 // Get the trip count from the BE count by adding 1. 4643 const SCEV *TCMul = getAddExpr(ExitCount, 4644 getConstant(ExitCount->getType(), 1)); 4645 // FIXME: SCEV distributes multiplication as V1*C1 + V2*C1. We could attempt 4646 // to factor simple cases. 4647 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(TCMul)) 4648 TCMul = Mul->getOperand(0); 4649 4650 const SCEVConstant *MulC = dyn_cast<SCEVConstant>(TCMul); 4651 if (!MulC) 4652 return 1; 4653 4654 ConstantInt *Result = MulC->getValue(); 4655 4656 // Guard against huge trip counts (this requires checking 4657 // for zero to handle the case where the trip count == -1 and the 4658 // addition wraps). 4659 if (!Result || Result->getValue().getActiveBits() > 32 || 4660 Result->getValue().getActiveBits() == 0) 4661 return 1; 4662 4663 return (unsigned)Result->getZExtValue(); 4664 } 4665 4666 // getExitCount - Get the expression for the number of loop iterations for which 4667 // this loop is guaranteed not to exit via ExitingBlock. Otherwise return 4668 // SCEVCouldNotCompute. 4669 const SCEV *ScalarEvolution::getExitCount(Loop *L, BasicBlock *ExitingBlock) { 4670 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 4671 } 4672 4673 /// getBackedgeTakenCount - If the specified loop has a predictable 4674 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute 4675 /// object. The backedge-taken count is the number of times the loop header 4676 /// will be branched to from within the loop. This is one less than the 4677 /// trip count of the loop, since it doesn't count the first iteration, 4678 /// when the header is branched to from outside the loop. 4679 /// 4680 /// Note that it is not valid to call this method on a loop without a 4681 /// loop-invariant backedge-taken count (see 4682 /// hasLoopInvariantBackedgeTakenCount). 4683 /// 4684 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) { 4685 return getBackedgeTakenInfo(L).getExact(this); 4686 } 4687 4688 /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except 4689 /// return the least SCEV value that is known never to be less than the 4690 /// actual backedge taken count. 4691 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) { 4692 return getBackedgeTakenInfo(L).getMax(this); 4693 } 4694 4695 /// PushLoopPHIs - Push PHI nodes in the header of the given loop 4696 /// onto the given Worklist. 4697 static void 4698 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { 4699 BasicBlock *Header = L->getHeader(); 4700 4701 // Push all Loop-header PHIs onto the Worklist stack. 4702 for (BasicBlock::iterator I = Header->begin(); 4703 PHINode *PN = dyn_cast<PHINode>(I); ++I) 4704 Worklist.push_back(PN); 4705 } 4706 4707 const ScalarEvolution::BackedgeTakenInfo & 4708 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 4709 // Initially insert an invalid entry for this loop. If the insertion 4710 // succeeds, proceed to actually compute a backedge-taken count and 4711 // update the value. The temporary CouldNotCompute value tells SCEV 4712 // code elsewhere that it shouldn't attempt to request a new 4713 // backedge-taken count, which could result in infinite recursion. 4714 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 4715 BackedgeTakenCounts.insert(std::make_pair(L, BackedgeTakenInfo())); 4716 if (!Pair.second) 4717 return Pair.first->second; 4718 4719 // ComputeBackedgeTakenCount may allocate memory for its result. Inserting it 4720 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 4721 // must be cleared in this scope. 4722 BackedgeTakenInfo Result = ComputeBackedgeTakenCount(L); 4723 4724 if (Result.getExact(this) != getCouldNotCompute()) { 4725 assert(isLoopInvariant(Result.getExact(this), L) && 4726 isLoopInvariant(Result.getMax(this), L) && 4727 "Computed backedge-taken count isn't loop invariant for loop!"); 4728 ++NumTripCountsComputed; 4729 } 4730 else if (Result.getMax(this) == getCouldNotCompute() && 4731 isa<PHINode>(L->getHeader()->begin())) { 4732 // Only count loops that have phi nodes as not being computable. 4733 ++NumTripCountsNotComputed; 4734 } 4735 4736 // Now that we know more about the trip count for this loop, forget any 4737 // existing SCEV values for PHI nodes in this loop since they are only 4738 // conservative estimates made without the benefit of trip count 4739 // information. This is similar to the code in forgetLoop, except that 4740 // it handles SCEVUnknown PHI nodes specially. 4741 if (Result.hasAnyInfo()) { 4742 SmallVector<Instruction *, 16> Worklist; 4743 PushLoopPHIs(L, Worklist); 4744 4745 SmallPtrSet<Instruction *, 8> Visited; 4746 while (!Worklist.empty()) { 4747 Instruction *I = Worklist.pop_back_val(); 4748 if (!Visited.insert(I).second) 4749 continue; 4750 4751 ValueExprMapType::iterator It = 4752 ValueExprMap.find_as(static_cast<Value *>(I)); 4753 if (It != ValueExprMap.end()) { 4754 const SCEV *Old = It->second; 4755 4756 // SCEVUnknown for a PHI either means that it has an unrecognized 4757 // structure, or it's a PHI that's in the progress of being computed 4758 // by createNodeForPHI. In the former case, additional loop trip 4759 // count information isn't going to change anything. In the later 4760 // case, createNodeForPHI will perform the necessary updates on its 4761 // own when it gets to that point. 4762 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 4763 forgetMemoizedResults(Old); 4764 ValueExprMap.erase(It); 4765 } 4766 if (PHINode *PN = dyn_cast<PHINode>(I)) 4767 ConstantEvolutionLoopExitValue.erase(PN); 4768 } 4769 4770 PushDefUseChildren(I, Worklist); 4771 } 4772 } 4773 4774 // Re-lookup the insert position, since the call to 4775 // ComputeBackedgeTakenCount above could result in a 4776 // recusive call to getBackedgeTakenInfo (on a different 4777 // loop), which would invalidate the iterator computed 4778 // earlier. 4779 return BackedgeTakenCounts.find(L)->second = Result; 4780 } 4781 4782 /// forgetLoop - This method should be called by the client when it has 4783 /// changed a loop in a way that may effect ScalarEvolution's ability to 4784 /// compute a trip count, or if the loop is deleted. 4785 void ScalarEvolution::forgetLoop(const Loop *L) { 4786 // Drop any stored trip count value. 4787 DenseMap<const Loop*, BackedgeTakenInfo>::iterator BTCPos = 4788 BackedgeTakenCounts.find(L); 4789 if (BTCPos != BackedgeTakenCounts.end()) { 4790 BTCPos->second.clear(); 4791 BackedgeTakenCounts.erase(BTCPos); 4792 } 4793 4794 // Drop information about expressions based on loop-header PHIs. 4795 SmallVector<Instruction *, 16> Worklist; 4796 PushLoopPHIs(L, Worklist); 4797 4798 SmallPtrSet<Instruction *, 8> Visited; 4799 while (!Worklist.empty()) { 4800 Instruction *I = Worklist.pop_back_val(); 4801 if (!Visited.insert(I).second) 4802 continue; 4803 4804 ValueExprMapType::iterator It = 4805 ValueExprMap.find_as(static_cast<Value *>(I)); 4806 if (It != ValueExprMap.end()) { 4807 forgetMemoizedResults(It->second); 4808 ValueExprMap.erase(It); 4809 if (PHINode *PN = dyn_cast<PHINode>(I)) 4810 ConstantEvolutionLoopExitValue.erase(PN); 4811 } 4812 4813 PushDefUseChildren(I, Worklist); 4814 } 4815 4816 // Forget all contained loops too, to avoid dangling entries in the 4817 // ValuesAtScopes map. 4818 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I) 4819 forgetLoop(*I); 4820 } 4821 4822 /// forgetValue - This method should be called by the client when it has 4823 /// changed a value in a way that may effect its value, or which may 4824 /// disconnect it from a def-use chain linking it to a loop. 4825 void ScalarEvolution::forgetValue(Value *V) { 4826 Instruction *I = dyn_cast<Instruction>(V); 4827 if (!I) return; 4828 4829 // Drop information about expressions based on loop-header PHIs. 4830 SmallVector<Instruction *, 16> Worklist; 4831 Worklist.push_back(I); 4832 4833 SmallPtrSet<Instruction *, 8> Visited; 4834 while (!Worklist.empty()) { 4835 I = Worklist.pop_back_val(); 4836 if (!Visited.insert(I).second) 4837 continue; 4838 4839 ValueExprMapType::iterator It = 4840 ValueExprMap.find_as(static_cast<Value *>(I)); 4841 if (It != ValueExprMap.end()) { 4842 forgetMemoizedResults(It->second); 4843 ValueExprMap.erase(It); 4844 if (PHINode *PN = dyn_cast<PHINode>(I)) 4845 ConstantEvolutionLoopExitValue.erase(PN); 4846 } 4847 4848 PushDefUseChildren(I, Worklist); 4849 } 4850 } 4851 4852 /// getExact - Get the exact loop backedge taken count considering all loop 4853 /// exits. A computable result can only be returned for loops with a single 4854 /// exit. Returning the minimum taken count among all exits is incorrect 4855 /// because one of the loop's exit limit's may have been skipped. HowFarToZero 4856 /// assumes that the limit of each loop test is never skipped. This is a valid 4857 /// assumption as long as the loop exits via that test. For precise results, it 4858 /// is the caller's responsibility to specify the relevant loop exit using 4859 /// getExact(ExitingBlock, SE). 4860 const SCEV * 4861 ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE) const { 4862 // If any exits were not computable, the loop is not computable. 4863 if (!ExitNotTaken.isCompleteList()) return SE->getCouldNotCompute(); 4864 4865 // We need exactly one computable exit. 4866 if (!ExitNotTaken.ExitingBlock) return SE->getCouldNotCompute(); 4867 assert(ExitNotTaken.ExactNotTaken && "uninitialized not-taken info"); 4868 4869 const SCEV *BECount = nullptr; 4870 for (const ExitNotTakenInfo *ENT = &ExitNotTaken; 4871 ENT != nullptr; ENT = ENT->getNextExit()) { 4872 4873 assert(ENT->ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV"); 4874 4875 if (!BECount) 4876 BECount = ENT->ExactNotTaken; 4877 else if (BECount != ENT->ExactNotTaken) 4878 return SE->getCouldNotCompute(); 4879 } 4880 assert(BECount && "Invalid not taken count for loop exit"); 4881 return BECount; 4882 } 4883 4884 /// getExact - Get the exact not taken count for this loop exit. 4885 const SCEV * 4886 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock, 4887 ScalarEvolution *SE) const { 4888 for (const ExitNotTakenInfo *ENT = &ExitNotTaken; 4889 ENT != nullptr; ENT = ENT->getNextExit()) { 4890 4891 if (ENT->ExitingBlock == ExitingBlock) 4892 return ENT->ExactNotTaken; 4893 } 4894 return SE->getCouldNotCompute(); 4895 } 4896 4897 /// getMax - Get the max backedge taken count for the loop. 4898 const SCEV * 4899 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const { 4900 return Max ? Max : SE->getCouldNotCompute(); 4901 } 4902 4903 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S, 4904 ScalarEvolution *SE) const { 4905 if (Max && Max != SE->getCouldNotCompute() && SE->hasOperand(Max, S)) 4906 return true; 4907 4908 if (!ExitNotTaken.ExitingBlock) 4909 return false; 4910 4911 for (const ExitNotTakenInfo *ENT = &ExitNotTaken; 4912 ENT != nullptr; ENT = ENT->getNextExit()) { 4913 4914 if (ENT->ExactNotTaken != SE->getCouldNotCompute() 4915 && SE->hasOperand(ENT->ExactNotTaken, S)) { 4916 return true; 4917 } 4918 } 4919 return false; 4920 } 4921 4922 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 4923 /// computable exit into a persistent ExitNotTakenInfo array. 4924 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 4925 SmallVectorImpl< std::pair<BasicBlock *, const SCEV *> > &ExitCounts, 4926 bool Complete, const SCEV *MaxCount) : Max(MaxCount) { 4927 4928 if (!Complete) 4929 ExitNotTaken.setIncomplete(); 4930 4931 unsigned NumExits = ExitCounts.size(); 4932 if (NumExits == 0) return; 4933 4934 ExitNotTaken.ExitingBlock = ExitCounts[0].first; 4935 ExitNotTaken.ExactNotTaken = ExitCounts[0].second; 4936 if (NumExits == 1) return; 4937 4938 // Handle the rare case of multiple computable exits. 4939 ExitNotTakenInfo *ENT = new ExitNotTakenInfo[NumExits-1]; 4940 4941 ExitNotTakenInfo *PrevENT = &ExitNotTaken; 4942 for (unsigned i = 1; i < NumExits; ++i, PrevENT = ENT, ++ENT) { 4943 PrevENT->setNextExit(ENT); 4944 ENT->ExitingBlock = ExitCounts[i].first; 4945 ENT->ExactNotTaken = ExitCounts[i].second; 4946 } 4947 } 4948 4949 /// clear - Invalidate this result and free the ExitNotTakenInfo array. 4950 void ScalarEvolution::BackedgeTakenInfo::clear() { 4951 ExitNotTaken.ExitingBlock = nullptr; 4952 ExitNotTaken.ExactNotTaken = nullptr; 4953 delete[] ExitNotTaken.getNextExit(); 4954 } 4955 4956 /// ComputeBackedgeTakenCount - Compute the number of times the backedge 4957 /// of the specified loop will execute. 4958 ScalarEvolution::BackedgeTakenInfo 4959 ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) { 4960 SmallVector<BasicBlock *, 8> ExitingBlocks; 4961 L->getExitingBlocks(ExitingBlocks); 4962 4963 SmallVector<std::pair<BasicBlock *, const SCEV *>, 4> ExitCounts; 4964 bool CouldComputeBECount = true; 4965 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 4966 const SCEV *MustExitMaxBECount = nullptr; 4967 const SCEV *MayExitMaxBECount = nullptr; 4968 4969 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 4970 // and compute maxBECount. 4971 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 4972 BasicBlock *ExitBB = ExitingBlocks[i]; 4973 ExitLimit EL = ComputeExitLimit(L, ExitBB); 4974 4975 // 1. For each exit that can be computed, add an entry to ExitCounts. 4976 // CouldComputeBECount is true only if all exits can be computed. 4977 if (EL.Exact == getCouldNotCompute()) 4978 // We couldn't compute an exact value for this exit, so 4979 // we won't be able to compute an exact value for the loop. 4980 CouldComputeBECount = false; 4981 else 4982 ExitCounts.push_back(std::make_pair(ExitBB, EL.Exact)); 4983 4984 // 2. Derive the loop's MaxBECount from each exit's max number of 4985 // non-exiting iterations. Partition the loop exits into two kinds: 4986 // LoopMustExits and LoopMayExits. 4987 // 4988 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 4989 // is a LoopMayExit. If any computable LoopMustExit is found, then 4990 // MaxBECount is the minimum EL.Max of computable LoopMustExits. Otherwise, 4991 // MaxBECount is conservatively the maximum EL.Max, where CouldNotCompute is 4992 // considered greater than any computable EL.Max. 4993 if (EL.Max != getCouldNotCompute() && Latch && 4994 DT.dominates(ExitBB, Latch)) { 4995 if (!MustExitMaxBECount) 4996 MustExitMaxBECount = EL.Max; 4997 else { 4998 MustExitMaxBECount = 4999 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.Max); 5000 } 5001 } else if (MayExitMaxBECount != getCouldNotCompute()) { 5002 if (!MayExitMaxBECount || EL.Max == getCouldNotCompute()) 5003 MayExitMaxBECount = EL.Max; 5004 else { 5005 MayExitMaxBECount = 5006 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.Max); 5007 } 5008 } 5009 } 5010 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 5011 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 5012 return BackedgeTakenInfo(ExitCounts, CouldComputeBECount, MaxBECount); 5013 } 5014 5015 /// ComputeExitLimit - Compute the number of times the backedge of the specified 5016 /// loop will execute if it exits via the specified block. 5017 ScalarEvolution::ExitLimit 5018 ScalarEvolution::ComputeExitLimit(const Loop *L, BasicBlock *ExitingBlock) { 5019 5020 // Okay, we've chosen an exiting block. See what condition causes us to 5021 // exit at this block and remember the exit block and whether all other targets 5022 // lead to the loop header. 5023 bool MustExecuteLoopHeader = true; 5024 BasicBlock *Exit = nullptr; 5025 for (succ_iterator SI = succ_begin(ExitingBlock), SE = succ_end(ExitingBlock); 5026 SI != SE; ++SI) 5027 if (!L->contains(*SI)) { 5028 if (Exit) // Multiple exit successors. 5029 return getCouldNotCompute(); 5030 Exit = *SI; 5031 } else if (*SI != L->getHeader()) { 5032 MustExecuteLoopHeader = false; 5033 } 5034 5035 // At this point, we know we have a conditional branch that determines whether 5036 // the loop is exited. However, we don't know if the branch is executed each 5037 // time through the loop. If not, then the execution count of the branch will 5038 // not be equal to the trip count of the loop. 5039 // 5040 // Currently we check for this by checking to see if the Exit branch goes to 5041 // the loop header. If so, we know it will always execute the same number of 5042 // times as the loop. We also handle the case where the exit block *is* the 5043 // loop header. This is common for un-rotated loops. 5044 // 5045 // If both of those tests fail, walk up the unique predecessor chain to the 5046 // header, stopping if there is an edge that doesn't exit the loop. If the 5047 // header is reached, the execution count of the branch will be equal to the 5048 // trip count of the loop. 5049 // 5050 // More extensive analysis could be done to handle more cases here. 5051 // 5052 if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) { 5053 // The simple checks failed, try climbing the unique predecessor chain 5054 // up to the header. 5055 bool Ok = false; 5056 for (BasicBlock *BB = ExitingBlock; BB; ) { 5057 BasicBlock *Pred = BB->getUniquePredecessor(); 5058 if (!Pred) 5059 return getCouldNotCompute(); 5060 TerminatorInst *PredTerm = Pred->getTerminator(); 5061 for (const BasicBlock *PredSucc : PredTerm->successors()) { 5062 if (PredSucc == BB) 5063 continue; 5064 // If the predecessor has a successor that isn't BB and isn't 5065 // outside the loop, assume the worst. 5066 if (L->contains(PredSucc)) 5067 return getCouldNotCompute(); 5068 } 5069 if (Pred == L->getHeader()) { 5070 Ok = true; 5071 break; 5072 } 5073 BB = Pred; 5074 } 5075 if (!Ok) 5076 return getCouldNotCompute(); 5077 } 5078 5079 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 5080 TerminatorInst *Term = ExitingBlock->getTerminator(); 5081 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 5082 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 5083 // Proceed to the next level to examine the exit condition expression. 5084 return ComputeExitLimitFromCond(L, BI->getCondition(), BI->getSuccessor(0), 5085 BI->getSuccessor(1), 5086 /*ControlsExit=*/IsOnlyExit); 5087 } 5088 5089 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) 5090 return ComputeExitLimitFromSingleExitSwitch(L, SI, Exit, 5091 /*ControlsExit=*/IsOnlyExit); 5092 5093 return getCouldNotCompute(); 5094 } 5095 5096 /// ComputeExitLimitFromCond - Compute the number of times the 5097 /// backedge of the specified loop will execute if its exit condition 5098 /// were a conditional branch of ExitCond, TBB, and FBB. 5099 /// 5100 /// @param ControlsExit is true if ExitCond directly controls the exit 5101 /// branch. In this case, we can assume that the loop exits only if the 5102 /// condition is true and can infer that failing to meet the condition prior to 5103 /// integer wraparound results in undefined behavior. 5104 ScalarEvolution::ExitLimit 5105 ScalarEvolution::ComputeExitLimitFromCond(const Loop *L, 5106 Value *ExitCond, 5107 BasicBlock *TBB, 5108 BasicBlock *FBB, 5109 bool ControlsExit) { 5110 // Check if the controlling expression for this loop is an And or Or. 5111 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) { 5112 if (BO->getOpcode() == Instruction::And) { 5113 // Recurse on the operands of the and. 5114 bool EitherMayExit = L->contains(TBB); 5115 ExitLimit EL0 = ComputeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB, 5116 ControlsExit && !EitherMayExit); 5117 ExitLimit EL1 = ComputeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB, 5118 ControlsExit && !EitherMayExit); 5119 const SCEV *BECount = getCouldNotCompute(); 5120 const SCEV *MaxBECount = getCouldNotCompute(); 5121 if (EitherMayExit) { 5122 // Both conditions must be true for the loop to continue executing. 5123 // Choose the less conservative count. 5124 if (EL0.Exact == getCouldNotCompute() || 5125 EL1.Exact == getCouldNotCompute()) 5126 BECount = getCouldNotCompute(); 5127 else 5128 BECount = getUMinFromMismatchedTypes(EL0.Exact, EL1.Exact); 5129 if (EL0.Max == getCouldNotCompute()) 5130 MaxBECount = EL1.Max; 5131 else if (EL1.Max == getCouldNotCompute()) 5132 MaxBECount = EL0.Max; 5133 else 5134 MaxBECount = getUMinFromMismatchedTypes(EL0.Max, EL1.Max); 5135 } else { 5136 // Both conditions must be true at the same time for the loop to exit. 5137 // For now, be conservative. 5138 assert(L->contains(FBB) && "Loop block has no successor in loop!"); 5139 if (EL0.Max == EL1.Max) 5140 MaxBECount = EL0.Max; 5141 if (EL0.Exact == EL1.Exact) 5142 BECount = EL0.Exact; 5143 } 5144 5145 return ExitLimit(BECount, MaxBECount); 5146 } 5147 if (BO->getOpcode() == Instruction::Or) { 5148 // Recurse on the operands of the or. 5149 bool EitherMayExit = L->contains(FBB); 5150 ExitLimit EL0 = ComputeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB, 5151 ControlsExit && !EitherMayExit); 5152 ExitLimit EL1 = ComputeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB, 5153 ControlsExit && !EitherMayExit); 5154 const SCEV *BECount = getCouldNotCompute(); 5155 const SCEV *MaxBECount = getCouldNotCompute(); 5156 if (EitherMayExit) { 5157 // Both conditions must be false for the loop to continue executing. 5158 // Choose the less conservative count. 5159 if (EL0.Exact == getCouldNotCompute() || 5160 EL1.Exact == getCouldNotCompute()) 5161 BECount = getCouldNotCompute(); 5162 else 5163 BECount = getUMinFromMismatchedTypes(EL0.Exact, EL1.Exact); 5164 if (EL0.Max == getCouldNotCompute()) 5165 MaxBECount = EL1.Max; 5166 else if (EL1.Max == getCouldNotCompute()) 5167 MaxBECount = EL0.Max; 5168 else 5169 MaxBECount = getUMinFromMismatchedTypes(EL0.Max, EL1.Max); 5170 } else { 5171 // Both conditions must be false at the same time for the loop to exit. 5172 // For now, be conservative. 5173 assert(L->contains(TBB) && "Loop block has no successor in loop!"); 5174 if (EL0.Max == EL1.Max) 5175 MaxBECount = EL0.Max; 5176 if (EL0.Exact == EL1.Exact) 5177 BECount = EL0.Exact; 5178 } 5179 5180 return ExitLimit(BECount, MaxBECount); 5181 } 5182 } 5183 5184 // With an icmp, it may be feasible to compute an exact backedge-taken count. 5185 // Proceed to the next level to examine the icmp. 5186 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) 5187 return ComputeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit); 5188 5189 // Check for a constant condition. These are normally stripped out by 5190 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 5191 // preserve the CFG and is temporarily leaving constant conditions 5192 // in place. 5193 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 5194 if (L->contains(FBB) == !CI->getZExtValue()) 5195 // The backedge is always taken. 5196 return getCouldNotCompute(); 5197 else 5198 // The backedge is never taken. 5199 return getConstant(CI->getType(), 0); 5200 } 5201 5202 // If it's not an integer or pointer comparison then compute it the hard way. 5203 return ComputeExitCountExhaustively(L, ExitCond, !L->contains(TBB)); 5204 } 5205 5206 /// ComputeExitLimitFromICmp - Compute the number of times the 5207 /// backedge of the specified loop will execute if its exit condition 5208 /// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB. 5209 ScalarEvolution::ExitLimit 5210 ScalarEvolution::ComputeExitLimitFromICmp(const Loop *L, 5211 ICmpInst *ExitCond, 5212 BasicBlock *TBB, 5213 BasicBlock *FBB, 5214 bool ControlsExit) { 5215 5216 // If the condition was exit on true, convert the condition to exit on false 5217 ICmpInst::Predicate Cond; 5218 if (!L->contains(FBB)) 5219 Cond = ExitCond->getPredicate(); 5220 else 5221 Cond = ExitCond->getInversePredicate(); 5222 5223 // Handle common loops like: for (X = "string"; *X; ++X) 5224 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 5225 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 5226 ExitLimit ItCnt = 5227 ComputeLoadConstantCompareExitLimit(LI, RHS, L, Cond); 5228 if (ItCnt.hasAnyInfo()) 5229 return ItCnt; 5230 } 5231 5232 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 5233 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 5234 5235 // Try to evaluate any dependencies out of the loop. 5236 LHS = getSCEVAtScope(LHS, L); 5237 RHS = getSCEVAtScope(RHS, L); 5238 5239 // At this point, we would like to compute how many iterations of the 5240 // loop the predicate will return true for these inputs. 5241 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 5242 // If there is a loop-invariant, force it into the RHS. 5243 std::swap(LHS, RHS); 5244 Cond = ICmpInst::getSwappedPredicate(Cond); 5245 } 5246 5247 // Simplify the operands before analyzing them. 5248 (void)SimplifyICmpOperands(Cond, LHS, RHS); 5249 5250 // If we have a comparison of a chrec against a constant, try to use value 5251 // ranges to answer this query. 5252 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 5253 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 5254 if (AddRec->getLoop() == L) { 5255 // Form the constant range. 5256 ConstantRange CompRange( 5257 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue())); 5258 5259 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 5260 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 5261 } 5262 5263 switch (Cond) { 5264 case ICmpInst::ICMP_NE: { // while (X != Y) 5265 // Convert to: while (X-Y != 0) 5266 ExitLimit EL = HowFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 5267 if (EL.hasAnyInfo()) return EL; 5268 break; 5269 } 5270 case ICmpInst::ICMP_EQ: { // while (X == Y) 5271 // Convert to: while (X-Y == 0) 5272 ExitLimit EL = HowFarToNonZero(getMinusSCEV(LHS, RHS), L); 5273 if (EL.hasAnyInfo()) return EL; 5274 break; 5275 } 5276 case ICmpInst::ICMP_SLT: 5277 case ICmpInst::ICMP_ULT: { // while (X < Y) 5278 bool IsSigned = Cond == ICmpInst::ICMP_SLT; 5279 ExitLimit EL = HowManyLessThans(LHS, RHS, L, IsSigned, ControlsExit); 5280 if (EL.hasAnyInfo()) return EL; 5281 break; 5282 } 5283 case ICmpInst::ICMP_SGT: 5284 case ICmpInst::ICMP_UGT: { // while (X > Y) 5285 bool IsSigned = Cond == ICmpInst::ICMP_SGT; 5286 ExitLimit EL = HowManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit); 5287 if (EL.hasAnyInfo()) return EL; 5288 break; 5289 } 5290 default: 5291 #if 0 5292 dbgs() << "ComputeBackedgeTakenCount "; 5293 if (ExitCond->getOperand(0)->getType()->isUnsigned()) 5294 dbgs() << "[unsigned] "; 5295 dbgs() << *LHS << " " 5296 << Instruction::getOpcodeName(Instruction::ICmp) 5297 << " " << *RHS << "\n"; 5298 #endif 5299 break; 5300 } 5301 return ComputeExitCountExhaustively(L, ExitCond, !L->contains(TBB)); 5302 } 5303 5304 ScalarEvolution::ExitLimit 5305 ScalarEvolution::ComputeExitLimitFromSingleExitSwitch(const Loop *L, 5306 SwitchInst *Switch, 5307 BasicBlock *ExitingBlock, 5308 bool ControlsExit) { 5309 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 5310 5311 // Give up if the exit is the default dest of a switch. 5312 if (Switch->getDefaultDest() == ExitingBlock) 5313 return getCouldNotCompute(); 5314 5315 assert(L->contains(Switch->getDefaultDest()) && 5316 "Default case must not exit the loop!"); 5317 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 5318 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 5319 5320 // while (X != Y) --> while (X-Y != 0) 5321 ExitLimit EL = HowFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 5322 if (EL.hasAnyInfo()) 5323 return EL; 5324 5325 return getCouldNotCompute(); 5326 } 5327 5328 static ConstantInt * 5329 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 5330 ScalarEvolution &SE) { 5331 const SCEV *InVal = SE.getConstant(C); 5332 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 5333 assert(isa<SCEVConstant>(Val) && 5334 "Evaluation of SCEV at constant didn't fold correctly?"); 5335 return cast<SCEVConstant>(Val)->getValue(); 5336 } 5337 5338 /// ComputeLoadConstantCompareExitLimit - Given an exit condition of 5339 /// 'icmp op load X, cst', try to see if we can compute the backedge 5340 /// execution count. 5341 ScalarEvolution::ExitLimit 5342 ScalarEvolution::ComputeLoadConstantCompareExitLimit( 5343 LoadInst *LI, 5344 Constant *RHS, 5345 const Loop *L, 5346 ICmpInst::Predicate predicate) { 5347 5348 if (LI->isVolatile()) return getCouldNotCompute(); 5349 5350 // Check to see if the loaded pointer is a getelementptr of a global. 5351 // TODO: Use SCEV instead of manually grubbing with GEPs. 5352 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 5353 if (!GEP) return getCouldNotCompute(); 5354 5355 // Make sure that it is really a constant global we are gepping, with an 5356 // initializer, and make sure the first IDX is really 0. 5357 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 5358 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || 5359 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 5360 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 5361 return getCouldNotCompute(); 5362 5363 // Okay, we allow one non-constant index into the GEP instruction. 5364 Value *VarIdx = nullptr; 5365 std::vector<Constant*> Indexes; 5366 unsigned VarIdxNum = 0; 5367 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 5368 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 5369 Indexes.push_back(CI); 5370 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 5371 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. 5372 VarIdx = GEP->getOperand(i); 5373 VarIdxNum = i-2; 5374 Indexes.push_back(nullptr); 5375 } 5376 5377 // Loop-invariant loads may be a byproduct of loop optimization. Skip them. 5378 if (!VarIdx) 5379 return getCouldNotCompute(); 5380 5381 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 5382 // Check to see if X is a loop variant variable value now. 5383 const SCEV *Idx = getSCEV(VarIdx); 5384 Idx = getSCEVAtScope(Idx, L); 5385 5386 // We can only recognize very limited forms of loop index expressions, in 5387 // particular, only affine AddRec's like {C1,+,C2}. 5388 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 5389 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) || 5390 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 5391 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 5392 return getCouldNotCompute(); 5393 5394 unsigned MaxSteps = MaxBruteForceIterations; 5395 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 5396 ConstantInt *ItCst = ConstantInt::get( 5397 cast<IntegerType>(IdxExpr->getType()), IterationNum); 5398 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 5399 5400 // Form the GEP offset. 5401 Indexes[VarIdxNum] = Val; 5402 5403 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), 5404 Indexes); 5405 if (!Result) break; // Cannot compute! 5406 5407 // Evaluate the condition for this iteration. 5408 Result = ConstantExpr::getICmp(predicate, Result, RHS); 5409 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 5410 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 5411 #if 0 5412 dbgs() << "\n***\n*** Computed loop count " << *ItCst 5413 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader() 5414 << "***\n"; 5415 #endif 5416 ++NumArrayLenItCounts; 5417 return getConstant(ItCst); // Found terminating iteration! 5418 } 5419 } 5420 return getCouldNotCompute(); 5421 } 5422 5423 5424 /// CanConstantFold - Return true if we can constant fold an instruction of the 5425 /// specified type, assuming that all operands were constants. 5426 static bool CanConstantFold(const Instruction *I) { 5427 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 5428 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 5429 isa<LoadInst>(I)) 5430 return true; 5431 5432 if (const CallInst *CI = dyn_cast<CallInst>(I)) 5433 if (const Function *F = CI->getCalledFunction()) 5434 return canConstantFoldCallTo(F); 5435 return false; 5436 } 5437 5438 /// Determine whether this instruction can constant evolve within this loop 5439 /// assuming its operands can all constant evolve. 5440 static bool canConstantEvolve(Instruction *I, const Loop *L) { 5441 // An instruction outside of the loop can't be derived from a loop PHI. 5442 if (!L->contains(I)) return false; 5443 5444 if (isa<PHINode>(I)) { 5445 // We don't currently keep track of the control flow needed to evaluate 5446 // PHIs, so we cannot handle PHIs inside of loops. 5447 return L->getHeader() == I->getParent(); 5448 } 5449 5450 // If we won't be able to constant fold this expression even if the operands 5451 // are constants, bail early. 5452 return CanConstantFold(I); 5453 } 5454 5455 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 5456 /// recursing through each instruction operand until reaching a loop header phi. 5457 static PHINode * 5458 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 5459 DenseMap<Instruction *, PHINode *> &PHIMap) { 5460 5461 // Otherwise, we can evaluate this instruction if all of its operands are 5462 // constant or derived from a PHI node themselves. 5463 PHINode *PHI = nullptr; 5464 for (Instruction::op_iterator OpI = UseInst->op_begin(), 5465 OpE = UseInst->op_end(); OpI != OpE; ++OpI) { 5466 5467 if (isa<Constant>(*OpI)) continue; 5468 5469 Instruction *OpInst = dyn_cast<Instruction>(*OpI); 5470 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 5471 5472 PHINode *P = dyn_cast<PHINode>(OpInst); 5473 if (!P) 5474 // If this operand is already visited, reuse the prior result. 5475 // We may have P != PHI if this is the deepest point at which the 5476 // inconsistent paths meet. 5477 P = PHIMap.lookup(OpInst); 5478 if (!P) { 5479 // Recurse and memoize the results, whether a phi is found or not. 5480 // This recursive call invalidates pointers into PHIMap. 5481 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap); 5482 PHIMap[OpInst] = P; 5483 } 5484 if (!P) 5485 return nullptr; // Not evolving from PHI 5486 if (PHI && PHI != P) 5487 return nullptr; // Evolving from multiple different PHIs. 5488 PHI = P; 5489 } 5490 // This is a expression evolving from a constant PHI! 5491 return PHI; 5492 } 5493 5494 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 5495 /// in the loop that V is derived from. We allow arbitrary operations along the 5496 /// way, but the operands of an operation must either be constants or a value 5497 /// derived from a constant PHI. If this expression does not fit with these 5498 /// constraints, return null. 5499 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 5500 Instruction *I = dyn_cast<Instruction>(V); 5501 if (!I || !canConstantEvolve(I, L)) return nullptr; 5502 5503 if (PHINode *PN = dyn_cast<PHINode>(I)) { 5504 return PN; 5505 } 5506 5507 // Record non-constant instructions contained by the loop. 5508 DenseMap<Instruction *, PHINode *> PHIMap; 5509 return getConstantEvolvingPHIOperands(I, L, PHIMap); 5510 } 5511 5512 /// EvaluateExpression - Given an expression that passes the 5513 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 5514 /// in the loop has the value PHIVal. If we can't fold this expression for some 5515 /// reason, return null. 5516 static Constant *EvaluateExpression(Value *V, const Loop *L, 5517 DenseMap<Instruction *, Constant *> &Vals, 5518 const DataLayout &DL, 5519 const TargetLibraryInfo *TLI) { 5520 // Convenient constant check, but redundant for recursive calls. 5521 if (Constant *C = dyn_cast<Constant>(V)) return C; 5522 Instruction *I = dyn_cast<Instruction>(V); 5523 if (!I) return nullptr; 5524 5525 if (Constant *C = Vals.lookup(I)) return C; 5526 5527 // An instruction inside the loop depends on a value outside the loop that we 5528 // weren't given a mapping for, or a value such as a call inside the loop. 5529 if (!canConstantEvolve(I, L)) return nullptr; 5530 5531 // An unmapped PHI can be due to a branch or another loop inside this loop, 5532 // or due to this not being the initial iteration through a loop where we 5533 // couldn't compute the evolution of this particular PHI last time. 5534 if (isa<PHINode>(I)) return nullptr; 5535 5536 std::vector<Constant*> Operands(I->getNumOperands()); 5537 5538 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 5539 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 5540 if (!Operand) { 5541 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 5542 if (!Operands[i]) return nullptr; 5543 continue; 5544 } 5545 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 5546 Vals[Operand] = C; 5547 if (!C) return nullptr; 5548 Operands[i] = C; 5549 } 5550 5551 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 5552 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 5553 Operands[1], DL, TLI); 5554 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 5555 if (!LI->isVolatile()) 5556 return ConstantFoldLoadFromConstPtr(Operands[0], DL); 5557 } 5558 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), Operands, DL, 5559 TLI); 5560 } 5561 5562 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 5563 /// in the header of its containing loop, we know the loop executes a 5564 /// constant number of times, and the PHI node is just a recurrence 5565 /// involving constants, fold it. 5566 Constant * 5567 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 5568 const APInt &BEs, 5569 const Loop *L) { 5570 DenseMap<PHINode*, Constant*>::const_iterator I = 5571 ConstantEvolutionLoopExitValue.find(PN); 5572 if (I != ConstantEvolutionLoopExitValue.end()) 5573 return I->second; 5574 5575 if (BEs.ugt(MaxBruteForceIterations)) 5576 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 5577 5578 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 5579 5580 DenseMap<Instruction *, Constant *> CurrentIterVals; 5581 BasicBlock *Header = L->getHeader(); 5582 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 5583 5584 // Since the loop is canonicalized, the PHI node must have two entries. One 5585 // entry must be a constant (coming in from outside of the loop), and the 5586 // second must be derived from the same PHI. 5587 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1)); 5588 PHINode *PHI = nullptr; 5589 for (BasicBlock::iterator I = Header->begin(); 5590 (PHI = dyn_cast<PHINode>(I)); ++I) { 5591 Constant *StartCST = 5592 dyn_cast<Constant>(PHI->getIncomingValue(!SecondIsBackedge)); 5593 if (!StartCST) continue; 5594 CurrentIterVals[PHI] = StartCST; 5595 } 5596 if (!CurrentIterVals.count(PN)) 5597 return RetVal = nullptr; 5598 5599 Value *BEValue = PN->getIncomingValue(SecondIsBackedge); 5600 5601 // Execute the loop symbolically to determine the exit value. 5602 if (BEs.getActiveBits() >= 32) 5603 return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it! 5604 5605 unsigned NumIterations = BEs.getZExtValue(); // must be in range 5606 unsigned IterationNum = 0; 5607 const DataLayout &DL = F.getParent()->getDataLayout(); 5608 for (; ; ++IterationNum) { 5609 if (IterationNum == NumIterations) 5610 return RetVal = CurrentIterVals[PN]; // Got exit value! 5611 5612 // Compute the value of the PHIs for the next iteration. 5613 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 5614 DenseMap<Instruction *, Constant *> NextIterVals; 5615 Constant *NextPHI = 5616 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 5617 if (!NextPHI) 5618 return nullptr; // Couldn't evaluate! 5619 NextIterVals[PN] = NextPHI; 5620 5621 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 5622 5623 // Also evaluate the other PHI nodes. However, we don't get to stop if we 5624 // cease to be able to evaluate one of them or if they stop evolving, 5625 // because that doesn't necessarily prevent us from computing PN. 5626 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 5627 for (DenseMap<Instruction *, Constant *>::const_iterator 5628 I = CurrentIterVals.begin(), E = CurrentIterVals.end(); I != E; ++I){ 5629 PHINode *PHI = dyn_cast<PHINode>(I->first); 5630 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 5631 PHIsToCompute.push_back(std::make_pair(PHI, I->second)); 5632 } 5633 // We use two distinct loops because EvaluateExpression may invalidate any 5634 // iterators into CurrentIterVals. 5635 for (SmallVectorImpl<std::pair<PHINode *, Constant*> >::const_iterator 5636 I = PHIsToCompute.begin(), E = PHIsToCompute.end(); I != E; ++I) { 5637 PHINode *PHI = I->first; 5638 Constant *&NextPHI = NextIterVals[PHI]; 5639 if (!NextPHI) { // Not already computed. 5640 Value *BEValue = PHI->getIncomingValue(SecondIsBackedge); 5641 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 5642 } 5643 if (NextPHI != I->second) 5644 StoppedEvolving = false; 5645 } 5646 5647 // If all entries in CurrentIterVals == NextIterVals then we can stop 5648 // iterating, the loop can't continue to change. 5649 if (StoppedEvolving) 5650 return RetVal = CurrentIterVals[PN]; 5651 5652 CurrentIterVals.swap(NextIterVals); 5653 } 5654 } 5655 5656 /// ComputeExitCountExhaustively - If the loop is known to execute a 5657 /// constant number of times (the condition evolves only from constants), 5658 /// try to evaluate a few iterations of the loop until we get the exit 5659 /// condition gets a value of ExitWhen (true or false). If we cannot 5660 /// evaluate the trip count of the loop, return getCouldNotCompute(). 5661 const SCEV *ScalarEvolution::ComputeExitCountExhaustively(const Loop *L, 5662 Value *Cond, 5663 bool ExitWhen) { 5664 PHINode *PN = getConstantEvolvingPHI(Cond, L); 5665 if (!PN) return getCouldNotCompute(); 5666 5667 // If the loop is canonicalized, the PHI will have exactly two entries. 5668 // That's the only form we support here. 5669 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 5670 5671 DenseMap<Instruction *, Constant *> CurrentIterVals; 5672 BasicBlock *Header = L->getHeader(); 5673 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 5674 5675 // One entry must be a constant (coming in from outside of the loop), and the 5676 // second must be derived from the same PHI. 5677 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1)); 5678 PHINode *PHI = nullptr; 5679 for (BasicBlock::iterator I = Header->begin(); 5680 (PHI = dyn_cast<PHINode>(I)); ++I) { 5681 Constant *StartCST = 5682 dyn_cast<Constant>(PHI->getIncomingValue(!SecondIsBackedge)); 5683 if (!StartCST) continue; 5684 CurrentIterVals[PHI] = StartCST; 5685 } 5686 if (!CurrentIterVals.count(PN)) 5687 return getCouldNotCompute(); 5688 5689 // Okay, we find a PHI node that defines the trip count of this loop. Execute 5690 // the loop symbolically to determine when the condition gets a value of 5691 // "ExitWhen". 5692 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 5693 const DataLayout &DL = F.getParent()->getDataLayout(); 5694 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 5695 ConstantInt *CondVal = dyn_cast_or_null<ConstantInt>( 5696 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 5697 5698 // Couldn't symbolically evaluate. 5699 if (!CondVal) return getCouldNotCompute(); 5700 5701 if (CondVal->getValue() == uint64_t(ExitWhen)) { 5702 ++NumBruteForceTripCountsComputed; 5703 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 5704 } 5705 5706 // Update all the PHI nodes for the next iteration. 5707 DenseMap<Instruction *, Constant *> NextIterVals; 5708 5709 // Create a list of which PHIs we need to compute. We want to do this before 5710 // calling EvaluateExpression on them because that may invalidate iterators 5711 // into CurrentIterVals. 5712 SmallVector<PHINode *, 8> PHIsToCompute; 5713 for (DenseMap<Instruction *, Constant *>::const_iterator 5714 I = CurrentIterVals.begin(), E = CurrentIterVals.end(); I != E; ++I){ 5715 PHINode *PHI = dyn_cast<PHINode>(I->first); 5716 if (!PHI || PHI->getParent() != Header) continue; 5717 PHIsToCompute.push_back(PHI); 5718 } 5719 for (SmallVectorImpl<PHINode *>::const_iterator I = PHIsToCompute.begin(), 5720 E = PHIsToCompute.end(); I != E; ++I) { 5721 PHINode *PHI = *I; 5722 Constant *&NextPHI = NextIterVals[PHI]; 5723 if (NextPHI) continue; // Already computed! 5724 5725 Value *BEValue = PHI->getIncomingValue(SecondIsBackedge); 5726 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 5727 } 5728 CurrentIterVals.swap(NextIterVals); 5729 } 5730 5731 // Too many iterations were needed to evaluate. 5732 return getCouldNotCompute(); 5733 } 5734 5735 /// getSCEVAtScope - Return a SCEV expression for the specified value 5736 /// at the specified scope in the program. The L value specifies a loop 5737 /// nest to evaluate the expression at, where null is the top-level or a 5738 /// specified loop is immediately inside of the loop. 5739 /// 5740 /// This method can be used to compute the exit value for a variable defined 5741 /// in a loop by querying what the value will hold in the parent loop. 5742 /// 5743 /// In the case that a relevant loop exit value cannot be computed, the 5744 /// original value V is returned. 5745 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 5746 // Check to see if we've folded this expression at this loop before. 5747 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = ValuesAtScopes[V]; 5748 for (unsigned u = 0; u < Values.size(); u++) { 5749 if (Values[u].first == L) 5750 return Values[u].second ? Values[u].second : V; 5751 } 5752 Values.push_back(std::make_pair(L, static_cast<const SCEV *>(nullptr))); 5753 // Otherwise compute it. 5754 const SCEV *C = computeSCEVAtScope(V, L); 5755 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values2 = ValuesAtScopes[V]; 5756 for (unsigned u = Values2.size(); u > 0; u--) { 5757 if (Values2[u - 1].first == L) { 5758 Values2[u - 1].second = C; 5759 break; 5760 } 5761 } 5762 return C; 5763 } 5764 5765 /// This builds up a Constant using the ConstantExpr interface. That way, we 5766 /// will return Constants for objects which aren't represented by a 5767 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 5768 /// Returns NULL if the SCEV isn't representable as a Constant. 5769 static Constant *BuildConstantFromSCEV(const SCEV *V) { 5770 switch (static_cast<SCEVTypes>(V->getSCEVType())) { 5771 case scCouldNotCompute: 5772 case scAddRecExpr: 5773 break; 5774 case scConstant: 5775 return cast<SCEVConstant>(V)->getValue(); 5776 case scUnknown: 5777 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 5778 case scSignExtend: { 5779 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 5780 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 5781 return ConstantExpr::getSExt(CastOp, SS->getType()); 5782 break; 5783 } 5784 case scZeroExtend: { 5785 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 5786 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 5787 return ConstantExpr::getZExt(CastOp, SZ->getType()); 5788 break; 5789 } 5790 case scTruncate: { 5791 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 5792 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 5793 return ConstantExpr::getTrunc(CastOp, ST->getType()); 5794 break; 5795 } 5796 case scAddExpr: { 5797 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 5798 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 5799 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 5800 unsigned AS = PTy->getAddressSpace(); 5801 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 5802 C = ConstantExpr::getBitCast(C, DestPtrTy); 5803 } 5804 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 5805 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 5806 if (!C2) return nullptr; 5807 5808 // First pointer! 5809 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 5810 unsigned AS = C2->getType()->getPointerAddressSpace(); 5811 std::swap(C, C2); 5812 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 5813 // The offsets have been converted to bytes. We can add bytes to an 5814 // i8* by GEP with the byte count in the first index. 5815 C = ConstantExpr::getBitCast(C, DestPtrTy); 5816 } 5817 5818 // Don't bother trying to sum two pointers. We probably can't 5819 // statically compute a load that results from it anyway. 5820 if (C2->getType()->isPointerTy()) 5821 return nullptr; 5822 5823 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 5824 if (PTy->getElementType()->isStructTy()) 5825 C2 = ConstantExpr::getIntegerCast( 5826 C2, Type::getInt32Ty(C->getContext()), true); 5827 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); 5828 } else 5829 C = ConstantExpr::getAdd(C, C2); 5830 } 5831 return C; 5832 } 5833 break; 5834 } 5835 case scMulExpr: { 5836 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 5837 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 5838 // Don't bother with pointers at all. 5839 if (C->getType()->isPointerTy()) return nullptr; 5840 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 5841 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 5842 if (!C2 || C2->getType()->isPointerTy()) return nullptr; 5843 C = ConstantExpr::getMul(C, C2); 5844 } 5845 return C; 5846 } 5847 break; 5848 } 5849 case scUDivExpr: { 5850 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 5851 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 5852 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 5853 if (LHS->getType() == RHS->getType()) 5854 return ConstantExpr::getUDiv(LHS, RHS); 5855 break; 5856 } 5857 case scSMaxExpr: 5858 case scUMaxExpr: 5859 break; // TODO: smax, umax. 5860 } 5861 return nullptr; 5862 } 5863 5864 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 5865 if (isa<SCEVConstant>(V)) return V; 5866 5867 // If this instruction is evolved from a constant-evolving PHI, compute the 5868 // exit value from the loop without using SCEVs. 5869 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 5870 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 5871 const Loop *LI = this->LI[I->getParent()]; 5872 if (LI && LI->getParentLoop() == L) // Looking for loop exit value. 5873 if (PHINode *PN = dyn_cast<PHINode>(I)) 5874 if (PN->getParent() == LI->getHeader()) { 5875 // Okay, there is no closed form solution for the PHI node. Check 5876 // to see if the loop that contains it has a known backedge-taken 5877 // count. If so, we may be able to force computation of the exit 5878 // value. 5879 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI); 5880 if (const SCEVConstant *BTCC = 5881 dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 5882 // Okay, we know how many times the containing loop executes. If 5883 // this is a constant evolving PHI node, get the final value at 5884 // the specified iteration number. 5885 Constant *RV = getConstantEvolutionLoopExitValue(PN, 5886 BTCC->getValue()->getValue(), 5887 LI); 5888 if (RV) return getSCEV(RV); 5889 } 5890 } 5891 5892 // Okay, this is an expression that we cannot symbolically evaluate 5893 // into a SCEV. Check to see if it's possible to symbolically evaluate 5894 // the arguments into constants, and if so, try to constant propagate the 5895 // result. This is particularly useful for computing loop exit values. 5896 if (CanConstantFold(I)) { 5897 SmallVector<Constant *, 4> Operands; 5898 bool MadeImprovement = false; 5899 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 5900 Value *Op = I->getOperand(i); 5901 if (Constant *C = dyn_cast<Constant>(Op)) { 5902 Operands.push_back(C); 5903 continue; 5904 } 5905 5906 // If any of the operands is non-constant and if they are 5907 // non-integer and non-pointer, don't even try to analyze them 5908 // with scev techniques. 5909 if (!isSCEVable(Op->getType())) 5910 return V; 5911 5912 const SCEV *OrigV = getSCEV(Op); 5913 const SCEV *OpV = getSCEVAtScope(OrigV, L); 5914 MadeImprovement |= OrigV != OpV; 5915 5916 Constant *C = BuildConstantFromSCEV(OpV); 5917 if (!C) return V; 5918 if (C->getType() != Op->getType()) 5919 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 5920 Op->getType(), 5921 false), 5922 C, Op->getType()); 5923 Operands.push_back(C); 5924 } 5925 5926 // Check to see if getSCEVAtScope actually made an improvement. 5927 if (MadeImprovement) { 5928 Constant *C = nullptr; 5929 const DataLayout &DL = F.getParent()->getDataLayout(); 5930 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 5931 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 5932 Operands[1], DL, &TLI); 5933 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) { 5934 if (!LI->isVolatile()) 5935 C = ConstantFoldLoadFromConstPtr(Operands[0], DL); 5936 } else 5937 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(), Operands, 5938 DL, &TLI); 5939 if (!C) return V; 5940 return getSCEV(C); 5941 } 5942 } 5943 } 5944 5945 // This is some other type of SCEVUnknown, just return it. 5946 return V; 5947 } 5948 5949 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 5950 // Avoid performing the look-up in the common case where the specified 5951 // expression has no loop-variant portions. 5952 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 5953 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 5954 if (OpAtScope != Comm->getOperand(i)) { 5955 // Okay, at least one of these operands is loop variant but might be 5956 // foldable. Build a new instance of the folded commutative expression. 5957 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 5958 Comm->op_begin()+i); 5959 NewOps.push_back(OpAtScope); 5960 5961 for (++i; i != e; ++i) { 5962 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 5963 NewOps.push_back(OpAtScope); 5964 } 5965 if (isa<SCEVAddExpr>(Comm)) 5966 return getAddExpr(NewOps); 5967 if (isa<SCEVMulExpr>(Comm)) 5968 return getMulExpr(NewOps); 5969 if (isa<SCEVSMaxExpr>(Comm)) 5970 return getSMaxExpr(NewOps); 5971 if (isa<SCEVUMaxExpr>(Comm)) 5972 return getUMaxExpr(NewOps); 5973 llvm_unreachable("Unknown commutative SCEV type!"); 5974 } 5975 } 5976 // If we got here, all operands are loop invariant. 5977 return Comm; 5978 } 5979 5980 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 5981 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 5982 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 5983 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 5984 return Div; // must be loop invariant 5985 return getUDivExpr(LHS, RHS); 5986 } 5987 5988 // If this is a loop recurrence for a loop that does not contain L, then we 5989 // are dealing with the final value computed by the loop. 5990 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 5991 // First, attempt to evaluate each operand. 5992 // Avoid performing the look-up in the common case where the specified 5993 // expression has no loop-variant portions. 5994 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 5995 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 5996 if (OpAtScope == AddRec->getOperand(i)) 5997 continue; 5998 5999 // Okay, at least one of these operands is loop variant but might be 6000 // foldable. Build a new instance of the folded commutative expression. 6001 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 6002 AddRec->op_begin()+i); 6003 NewOps.push_back(OpAtScope); 6004 for (++i; i != e; ++i) 6005 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 6006 6007 const SCEV *FoldedRec = 6008 getAddRecExpr(NewOps, AddRec->getLoop(), 6009 AddRec->getNoWrapFlags(SCEV::FlagNW)); 6010 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 6011 // The addrec may be folded to a nonrecurrence, for example, if the 6012 // induction variable is multiplied by zero after constant folding. Go 6013 // ahead and return the folded value. 6014 if (!AddRec) 6015 return FoldedRec; 6016 break; 6017 } 6018 6019 // If the scope is outside the addrec's loop, evaluate it by using the 6020 // loop exit value of the addrec. 6021 if (!AddRec->getLoop()->contains(L)) { 6022 // To evaluate this recurrence, we need to know how many times the AddRec 6023 // loop iterates. Compute this now. 6024 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 6025 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 6026 6027 // Then, evaluate the AddRec. 6028 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 6029 } 6030 6031 return AddRec; 6032 } 6033 6034 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 6035 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 6036 if (Op == Cast->getOperand()) 6037 return Cast; // must be loop invariant 6038 return getZeroExtendExpr(Op, Cast->getType()); 6039 } 6040 6041 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 6042 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 6043 if (Op == Cast->getOperand()) 6044 return Cast; // must be loop invariant 6045 return getSignExtendExpr(Op, Cast->getType()); 6046 } 6047 6048 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 6049 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 6050 if (Op == Cast->getOperand()) 6051 return Cast; // must be loop invariant 6052 return getTruncateExpr(Op, Cast->getType()); 6053 } 6054 6055 llvm_unreachable("Unknown SCEV type!"); 6056 } 6057 6058 /// getSCEVAtScope - This is a convenience function which does 6059 /// getSCEVAtScope(getSCEV(V), L). 6060 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 6061 return getSCEVAtScope(getSCEV(V), L); 6062 } 6063 6064 /// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the 6065 /// following equation: 6066 /// 6067 /// A * X = B (mod N) 6068 /// 6069 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 6070 /// A and B isn't important. 6071 /// 6072 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 6073 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B, 6074 ScalarEvolution &SE) { 6075 uint32_t BW = A.getBitWidth(); 6076 assert(BW == B.getBitWidth() && "Bit widths must be the same."); 6077 assert(A != 0 && "A must be non-zero."); 6078 6079 // 1. D = gcd(A, N) 6080 // 6081 // The gcd of A and N may have only one prime factor: 2. The number of 6082 // trailing zeros in A is its multiplicity 6083 uint32_t Mult2 = A.countTrailingZeros(); 6084 // D = 2^Mult2 6085 6086 // 2. Check if B is divisible by D. 6087 // 6088 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 6089 // is not less than multiplicity of this prime factor for D. 6090 if (B.countTrailingZeros() < Mult2) 6091 return SE.getCouldNotCompute(); 6092 6093 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 6094 // modulo (N / D). 6095 // 6096 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this 6097 // bit width during computations. 6098 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 6099 APInt Mod(BW + 1, 0); 6100 Mod.setBit(BW - Mult2); // Mod = N / D 6101 APInt I = AD.multiplicativeInverse(Mod); 6102 6103 // 4. Compute the minimum unsigned root of the equation: 6104 // I * (B / D) mod (N / D) 6105 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod); 6106 6107 // The result is guaranteed to be less than 2^BW so we may truncate it to BW 6108 // bits. 6109 return SE.getConstant(Result.trunc(BW)); 6110 } 6111 6112 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the 6113 /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which 6114 /// might be the same) or two SCEVCouldNotCompute objects. 6115 /// 6116 static std::pair<const SCEV *,const SCEV *> 6117 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 6118 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 6119 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 6120 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 6121 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 6122 6123 // We currently can only solve this if the coefficients are constants. 6124 if (!LC || !MC || !NC) { 6125 const SCEV *CNC = SE.getCouldNotCompute(); 6126 return std::make_pair(CNC, CNC); 6127 } 6128 6129 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth(); 6130 const APInt &L = LC->getValue()->getValue(); 6131 const APInt &M = MC->getValue()->getValue(); 6132 const APInt &N = NC->getValue()->getValue(); 6133 APInt Two(BitWidth, 2); 6134 APInt Four(BitWidth, 4); 6135 6136 { 6137 using namespace APIntOps; 6138 const APInt& C = L; 6139 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C 6140 // The B coefficient is M-N/2 6141 APInt B(M); 6142 B -= sdiv(N,Two); 6143 6144 // The A coefficient is N/2 6145 APInt A(N.sdiv(Two)); 6146 6147 // Compute the B^2-4ac term. 6148 APInt SqrtTerm(B); 6149 SqrtTerm *= B; 6150 SqrtTerm -= Four * (A * C); 6151 6152 if (SqrtTerm.isNegative()) { 6153 // The loop is provably infinite. 6154 const SCEV *CNC = SE.getCouldNotCompute(); 6155 return std::make_pair(CNC, CNC); 6156 } 6157 6158 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest 6159 // integer value or else APInt::sqrt() will assert. 6160 APInt SqrtVal(SqrtTerm.sqrt()); 6161 6162 // Compute the two solutions for the quadratic formula. 6163 // The divisions must be performed as signed divisions. 6164 APInt NegB(-B); 6165 APInt TwoA(A << 1); 6166 if (TwoA.isMinValue()) { 6167 const SCEV *CNC = SE.getCouldNotCompute(); 6168 return std::make_pair(CNC, CNC); 6169 } 6170 6171 LLVMContext &Context = SE.getContext(); 6172 6173 ConstantInt *Solution1 = 6174 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA)); 6175 ConstantInt *Solution2 = 6176 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA)); 6177 6178 return std::make_pair(SE.getConstant(Solution1), 6179 SE.getConstant(Solution2)); 6180 } // end APIntOps namespace 6181 } 6182 6183 /// HowFarToZero - Return the number of times a backedge comparing the specified 6184 /// value to zero will execute. If not computable, return CouldNotCompute. 6185 /// 6186 /// This is only used for loops with a "x != y" exit test. The exit condition is 6187 /// now expressed as a single expression, V = x-y. So the exit test is 6188 /// effectively V != 0. We know and take advantage of the fact that this 6189 /// expression only being used in a comparison by zero context. 6190 ScalarEvolution::ExitLimit 6191 ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L, bool ControlsExit) { 6192 // If the value is a constant 6193 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 6194 // If the value is already zero, the branch will execute zero times. 6195 if (C->getValue()->isZero()) return C; 6196 return getCouldNotCompute(); // Otherwise it will loop infinitely. 6197 } 6198 6199 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V); 6200 if (!AddRec || AddRec->getLoop() != L) 6201 return getCouldNotCompute(); 6202 6203 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 6204 // the quadratic equation to solve it. 6205 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 6206 std::pair<const SCEV *,const SCEV *> Roots = 6207 SolveQuadraticEquation(AddRec, *this); 6208 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first); 6209 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second); 6210 if (R1 && R2) { 6211 #if 0 6212 dbgs() << "HFTZ: " << *V << " - sol#1: " << *R1 6213 << " sol#2: " << *R2 << "\n"; 6214 #endif 6215 // Pick the smallest positive root value. 6216 if (ConstantInt *CB = 6217 dyn_cast<ConstantInt>(ConstantExpr::getICmp(CmpInst::ICMP_ULT, 6218 R1->getValue(), 6219 R2->getValue()))) { 6220 if (!CB->getZExtValue()) 6221 std::swap(R1, R2); // R1 is the minimum root now. 6222 6223 // We can only use this value if the chrec ends up with an exact zero 6224 // value at this index. When solving for "X*X != 5", for example, we 6225 // should not accept a root of 2. 6226 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this); 6227 if (Val->isZero()) 6228 return R1; // We found a quadratic root! 6229 } 6230 } 6231 return getCouldNotCompute(); 6232 } 6233 6234 // Otherwise we can only handle this if it is affine. 6235 if (!AddRec->isAffine()) 6236 return getCouldNotCompute(); 6237 6238 // If this is an affine expression, the execution count of this branch is 6239 // the minimum unsigned root of the following equation: 6240 // 6241 // Start + Step*N = 0 (mod 2^BW) 6242 // 6243 // equivalent to: 6244 // 6245 // Step*N = -Start (mod 2^BW) 6246 // 6247 // where BW is the common bit width of Start and Step. 6248 6249 // Get the initial value for the loop. 6250 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 6251 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 6252 6253 // For now we handle only constant steps. 6254 // 6255 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 6256 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 6257 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 6258 // We have not yet seen any such cases. 6259 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 6260 if (!StepC || StepC->getValue()->equalsInt(0)) 6261 return getCouldNotCompute(); 6262 6263 // For positive steps (counting up until unsigned overflow): 6264 // N = -Start/Step (as unsigned) 6265 // For negative steps (counting down to zero): 6266 // N = Start/-Step 6267 // First compute the unsigned distance from zero in the direction of Step. 6268 bool CountDown = StepC->getValue()->getValue().isNegative(); 6269 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 6270 6271 // Handle unitary steps, which cannot wraparound. 6272 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 6273 // N = Distance (as unsigned) 6274 if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) { 6275 ConstantRange CR = getUnsignedRange(Start); 6276 const SCEV *MaxBECount; 6277 if (!CountDown && CR.getUnsignedMin().isMinValue()) 6278 // When counting up, the worst starting value is 1, not 0. 6279 MaxBECount = CR.getUnsignedMax().isMinValue() 6280 ? getConstant(APInt::getMinValue(CR.getBitWidth())) 6281 : getConstant(APInt::getMaxValue(CR.getBitWidth())); 6282 else 6283 MaxBECount = getConstant(CountDown ? CR.getUnsignedMax() 6284 : -CR.getUnsignedMin()); 6285 return ExitLimit(Distance, MaxBECount); 6286 } 6287 6288 // As a special case, handle the instance where Step is a positive power of 6289 // two. In this case, determining whether Step divides Distance evenly can be 6290 // done by counting and comparing the number of trailing zeros of Step and 6291 // Distance. 6292 if (!CountDown) { 6293 const APInt &StepV = StepC->getValue()->getValue(); 6294 // StepV.isPowerOf2() returns true if StepV is an positive power of two. It 6295 // also returns true if StepV is maximally negative (eg, INT_MIN), but that 6296 // case is not handled as this code is guarded by !CountDown. 6297 if (StepV.isPowerOf2() && 6298 GetMinTrailingZeros(Distance) >= StepV.countTrailingZeros()) { 6299 // Here we've constrained the equation to be of the form 6300 // 6301 // 2^(N + k) * Distance' = (StepV == 2^N) * X (mod 2^W) ... (0) 6302 // 6303 // where we're operating on a W bit wide integer domain and k is 6304 // non-negative. The smallest unsigned solution for X is the trip count. 6305 // 6306 // (0) is equivalent to: 6307 // 6308 // 2^(N + k) * Distance' - 2^N * X = L * 2^W 6309 // <=> 2^N(2^k * Distance' - X) = L * 2^(W - N) * 2^N 6310 // <=> 2^k * Distance' - X = L * 2^(W - N) 6311 // <=> 2^k * Distance' = L * 2^(W - N) + X ... (1) 6312 // 6313 // The smallest X satisfying (1) is unsigned remainder of dividing the LHS 6314 // by 2^(W - N). 6315 // 6316 // <=> X = 2^k * Distance' URem 2^(W - N) ... (2) 6317 // 6318 // E.g. say we're solving 6319 // 6320 // 2 * Val = 2 * X (in i8) ... (3) 6321 // 6322 // then from (2), we get X = Val URem i8 128 (k = 0 in this case). 6323 // 6324 // Note: It is tempting to solve (3) by setting X = Val, but Val is not 6325 // necessarily the smallest unsigned value of X that satisfies (3). 6326 // E.g. if Val is i8 -127 then the smallest value of X that satisfies (3) 6327 // is i8 1, not i8 -127 6328 6329 const auto *ModuloResult = getUDivExactExpr(Distance, Step); 6330 6331 // Since SCEV does not have a URem node, we construct one using a truncate 6332 // and a zero extend. 6333 6334 unsigned NarrowWidth = StepV.getBitWidth() - StepV.countTrailingZeros(); 6335 auto *NarrowTy = IntegerType::get(getContext(), NarrowWidth); 6336 auto *WideTy = Distance->getType(); 6337 6338 return getZeroExtendExpr(getTruncateExpr(ModuloResult, NarrowTy), WideTy); 6339 } 6340 } 6341 6342 // If the condition controls loop exit (the loop exits only if the expression 6343 // is true) and the addition is no-wrap we can use unsigned divide to 6344 // compute the backedge count. In this case, the step may not divide the 6345 // distance, but we don't care because if the condition is "missed" the loop 6346 // will have undefined behavior due to wrapping. 6347 if (ControlsExit && AddRec->getNoWrapFlags(SCEV::FlagNW)) { 6348 const SCEV *Exact = 6349 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 6350 return ExitLimit(Exact, Exact); 6351 } 6352 6353 // Then, try to solve the above equation provided that Start is constant. 6354 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) 6355 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(), 6356 -StartC->getValue()->getValue(), 6357 *this); 6358 return getCouldNotCompute(); 6359 } 6360 6361 /// HowFarToNonZero - Return the number of times a backedge checking the 6362 /// specified value for nonzero will execute. If not computable, return 6363 /// CouldNotCompute 6364 ScalarEvolution::ExitLimit 6365 ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) { 6366 // Loops that look like: while (X == 0) are very strange indeed. We don't 6367 // handle them yet except for the trivial case. This could be expanded in the 6368 // future as needed. 6369 6370 // If the value is a constant, check to see if it is known to be non-zero 6371 // already. If so, the backedge will execute zero times. 6372 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 6373 if (!C->getValue()->isNullValue()) 6374 return getConstant(C->getType(), 0); 6375 return getCouldNotCompute(); // Otherwise it will loop infinitely. 6376 } 6377 6378 // We could implement others, but I really doubt anyone writes loops like 6379 // this, and if they did, they would already be constant folded. 6380 return getCouldNotCompute(); 6381 } 6382 6383 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB 6384 /// (which may not be an immediate predecessor) which has exactly one 6385 /// successor from which BB is reachable, or null if no such block is 6386 /// found. 6387 /// 6388 std::pair<BasicBlock *, BasicBlock *> 6389 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) { 6390 // If the block has a unique predecessor, then there is no path from the 6391 // predecessor to the block that does not go through the direct edge 6392 // from the predecessor to the block. 6393 if (BasicBlock *Pred = BB->getSinglePredecessor()) 6394 return std::make_pair(Pred, BB); 6395 6396 // A loop's header is defined to be a block that dominates the loop. 6397 // If the header has a unique predecessor outside the loop, it must be 6398 // a block that has exactly one successor that can reach the loop. 6399 if (Loop *L = LI.getLoopFor(BB)) 6400 return std::make_pair(L->getLoopPredecessor(), L->getHeader()); 6401 6402 return std::pair<BasicBlock *, BasicBlock *>(); 6403 } 6404 6405 /// HasSameValue - SCEV structural equivalence is usually sufficient for 6406 /// testing whether two expressions are equal, however for the purposes of 6407 /// looking for a condition guarding a loop, it can be useful to be a little 6408 /// more general, since a front-end may have replicated the controlling 6409 /// expression. 6410 /// 6411 static bool HasSameValue(const SCEV *A, const SCEV *B) { 6412 // Quick check to see if they are the same SCEV. 6413 if (A == B) return true; 6414 6415 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 6416 // two different instructions with the same value. Check for this case. 6417 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 6418 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 6419 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 6420 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 6421 if (AI->isIdenticalTo(BI) && !AI->mayReadFromMemory()) 6422 return true; 6423 6424 // Otherwise assume they may have a different value. 6425 return false; 6426 } 6427 6428 /// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with 6429 /// predicate Pred. Return true iff any changes were made. 6430 /// 6431 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 6432 const SCEV *&LHS, const SCEV *&RHS, 6433 unsigned Depth) { 6434 bool Changed = false; 6435 6436 // If we hit the max recursion limit bail out. 6437 if (Depth >= 3) 6438 return false; 6439 6440 // Canonicalize a constant to the right side. 6441 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 6442 // Check for both operands constant. 6443 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 6444 if (ConstantExpr::getICmp(Pred, 6445 LHSC->getValue(), 6446 RHSC->getValue())->isNullValue()) 6447 goto trivially_false; 6448 else 6449 goto trivially_true; 6450 } 6451 // Otherwise swap the operands to put the constant on the right. 6452 std::swap(LHS, RHS); 6453 Pred = ICmpInst::getSwappedPredicate(Pred); 6454 Changed = true; 6455 } 6456 6457 // If we're comparing an addrec with a value which is loop-invariant in the 6458 // addrec's loop, put the addrec on the left. Also make a dominance check, 6459 // as both operands could be addrecs loop-invariant in each other's loop. 6460 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 6461 const Loop *L = AR->getLoop(); 6462 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 6463 std::swap(LHS, RHS); 6464 Pred = ICmpInst::getSwappedPredicate(Pred); 6465 Changed = true; 6466 } 6467 } 6468 6469 // If there's a constant operand, canonicalize comparisons with boundary 6470 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 6471 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 6472 const APInt &RA = RC->getValue()->getValue(); 6473 switch (Pred) { 6474 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 6475 case ICmpInst::ICMP_EQ: 6476 case ICmpInst::ICMP_NE: 6477 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 6478 if (!RA) 6479 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 6480 if (const SCEVMulExpr *ME = dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 6481 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 6482 ME->getOperand(0)->isAllOnesValue()) { 6483 RHS = AE->getOperand(1); 6484 LHS = ME->getOperand(1); 6485 Changed = true; 6486 } 6487 break; 6488 case ICmpInst::ICMP_UGE: 6489 if ((RA - 1).isMinValue()) { 6490 Pred = ICmpInst::ICMP_NE; 6491 RHS = getConstant(RA - 1); 6492 Changed = true; 6493 break; 6494 } 6495 if (RA.isMaxValue()) { 6496 Pred = ICmpInst::ICMP_EQ; 6497 Changed = true; 6498 break; 6499 } 6500 if (RA.isMinValue()) goto trivially_true; 6501 6502 Pred = ICmpInst::ICMP_UGT; 6503 RHS = getConstant(RA - 1); 6504 Changed = true; 6505 break; 6506 case ICmpInst::ICMP_ULE: 6507 if ((RA + 1).isMaxValue()) { 6508 Pred = ICmpInst::ICMP_NE; 6509 RHS = getConstant(RA + 1); 6510 Changed = true; 6511 break; 6512 } 6513 if (RA.isMinValue()) { 6514 Pred = ICmpInst::ICMP_EQ; 6515 Changed = true; 6516 break; 6517 } 6518 if (RA.isMaxValue()) goto trivially_true; 6519 6520 Pred = ICmpInst::ICMP_ULT; 6521 RHS = getConstant(RA + 1); 6522 Changed = true; 6523 break; 6524 case ICmpInst::ICMP_SGE: 6525 if ((RA - 1).isMinSignedValue()) { 6526 Pred = ICmpInst::ICMP_NE; 6527 RHS = getConstant(RA - 1); 6528 Changed = true; 6529 break; 6530 } 6531 if (RA.isMaxSignedValue()) { 6532 Pred = ICmpInst::ICMP_EQ; 6533 Changed = true; 6534 break; 6535 } 6536 if (RA.isMinSignedValue()) goto trivially_true; 6537 6538 Pred = ICmpInst::ICMP_SGT; 6539 RHS = getConstant(RA - 1); 6540 Changed = true; 6541 break; 6542 case ICmpInst::ICMP_SLE: 6543 if ((RA + 1).isMaxSignedValue()) { 6544 Pred = ICmpInst::ICMP_NE; 6545 RHS = getConstant(RA + 1); 6546 Changed = true; 6547 break; 6548 } 6549 if (RA.isMinSignedValue()) { 6550 Pred = ICmpInst::ICMP_EQ; 6551 Changed = true; 6552 break; 6553 } 6554 if (RA.isMaxSignedValue()) goto trivially_true; 6555 6556 Pred = ICmpInst::ICMP_SLT; 6557 RHS = getConstant(RA + 1); 6558 Changed = true; 6559 break; 6560 case ICmpInst::ICMP_UGT: 6561 if (RA.isMinValue()) { 6562 Pred = ICmpInst::ICMP_NE; 6563 Changed = true; 6564 break; 6565 } 6566 if ((RA + 1).isMaxValue()) { 6567 Pred = ICmpInst::ICMP_EQ; 6568 RHS = getConstant(RA + 1); 6569 Changed = true; 6570 break; 6571 } 6572 if (RA.isMaxValue()) goto trivially_false; 6573 break; 6574 case ICmpInst::ICMP_ULT: 6575 if (RA.isMaxValue()) { 6576 Pred = ICmpInst::ICMP_NE; 6577 Changed = true; 6578 break; 6579 } 6580 if ((RA - 1).isMinValue()) { 6581 Pred = ICmpInst::ICMP_EQ; 6582 RHS = getConstant(RA - 1); 6583 Changed = true; 6584 break; 6585 } 6586 if (RA.isMinValue()) goto trivially_false; 6587 break; 6588 case ICmpInst::ICMP_SGT: 6589 if (RA.isMinSignedValue()) { 6590 Pred = ICmpInst::ICMP_NE; 6591 Changed = true; 6592 break; 6593 } 6594 if ((RA + 1).isMaxSignedValue()) { 6595 Pred = ICmpInst::ICMP_EQ; 6596 RHS = getConstant(RA + 1); 6597 Changed = true; 6598 break; 6599 } 6600 if (RA.isMaxSignedValue()) goto trivially_false; 6601 break; 6602 case ICmpInst::ICMP_SLT: 6603 if (RA.isMaxSignedValue()) { 6604 Pred = ICmpInst::ICMP_NE; 6605 Changed = true; 6606 break; 6607 } 6608 if ((RA - 1).isMinSignedValue()) { 6609 Pred = ICmpInst::ICMP_EQ; 6610 RHS = getConstant(RA - 1); 6611 Changed = true; 6612 break; 6613 } 6614 if (RA.isMinSignedValue()) goto trivially_false; 6615 break; 6616 } 6617 } 6618 6619 // Check for obvious equality. 6620 if (HasSameValue(LHS, RHS)) { 6621 if (ICmpInst::isTrueWhenEqual(Pred)) 6622 goto trivially_true; 6623 if (ICmpInst::isFalseWhenEqual(Pred)) 6624 goto trivially_false; 6625 } 6626 6627 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 6628 // adding or subtracting 1 from one of the operands. 6629 switch (Pred) { 6630 case ICmpInst::ICMP_SLE: 6631 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) { 6632 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 6633 SCEV::FlagNSW); 6634 Pred = ICmpInst::ICMP_SLT; 6635 Changed = true; 6636 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) { 6637 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 6638 SCEV::FlagNSW); 6639 Pred = ICmpInst::ICMP_SLT; 6640 Changed = true; 6641 } 6642 break; 6643 case ICmpInst::ICMP_SGE: 6644 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) { 6645 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 6646 SCEV::FlagNSW); 6647 Pred = ICmpInst::ICMP_SGT; 6648 Changed = true; 6649 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) { 6650 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 6651 SCEV::FlagNSW); 6652 Pred = ICmpInst::ICMP_SGT; 6653 Changed = true; 6654 } 6655 break; 6656 case ICmpInst::ICMP_ULE: 6657 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) { 6658 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 6659 SCEV::FlagNUW); 6660 Pred = ICmpInst::ICMP_ULT; 6661 Changed = true; 6662 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) { 6663 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 6664 SCEV::FlagNUW); 6665 Pred = ICmpInst::ICMP_ULT; 6666 Changed = true; 6667 } 6668 break; 6669 case ICmpInst::ICMP_UGE: 6670 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) { 6671 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 6672 SCEV::FlagNUW); 6673 Pred = ICmpInst::ICMP_UGT; 6674 Changed = true; 6675 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) { 6676 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 6677 SCEV::FlagNUW); 6678 Pred = ICmpInst::ICMP_UGT; 6679 Changed = true; 6680 } 6681 break; 6682 default: 6683 break; 6684 } 6685 6686 // TODO: More simplifications are possible here. 6687 6688 // Recursively simplify until we either hit a recursion limit or nothing 6689 // changes. 6690 if (Changed) 6691 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 6692 6693 return Changed; 6694 6695 trivially_true: 6696 // Return 0 == 0. 6697 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 6698 Pred = ICmpInst::ICMP_EQ; 6699 return true; 6700 6701 trivially_false: 6702 // Return 0 != 0. 6703 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 6704 Pred = ICmpInst::ICMP_NE; 6705 return true; 6706 } 6707 6708 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 6709 return getSignedRange(S).getSignedMax().isNegative(); 6710 } 6711 6712 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 6713 return getSignedRange(S).getSignedMin().isStrictlyPositive(); 6714 } 6715 6716 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 6717 return !getSignedRange(S).getSignedMin().isNegative(); 6718 } 6719 6720 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 6721 return !getSignedRange(S).getSignedMax().isStrictlyPositive(); 6722 } 6723 6724 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 6725 return isKnownNegative(S) || isKnownPositive(S); 6726 } 6727 6728 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 6729 const SCEV *LHS, const SCEV *RHS) { 6730 // Canonicalize the inputs first. 6731 (void)SimplifyICmpOperands(Pred, LHS, RHS); 6732 6733 // If LHS or RHS is an addrec, check to see if the condition is true in 6734 // every iteration of the loop. 6735 // If LHS and RHS are both addrec, both conditions must be true in 6736 // every iteration of the loop. 6737 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 6738 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 6739 bool LeftGuarded = false; 6740 bool RightGuarded = false; 6741 if (LAR) { 6742 const Loop *L = LAR->getLoop(); 6743 if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) && 6744 isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) { 6745 if (!RAR) return true; 6746 LeftGuarded = true; 6747 } 6748 } 6749 if (RAR) { 6750 const Loop *L = RAR->getLoop(); 6751 if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) && 6752 isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) { 6753 if (!LAR) return true; 6754 RightGuarded = true; 6755 } 6756 } 6757 if (LeftGuarded && RightGuarded) 6758 return true; 6759 6760 // Otherwise see what can be done with known constant ranges. 6761 return isKnownPredicateWithRanges(Pred, LHS, RHS); 6762 } 6763 6764 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS, 6765 ICmpInst::Predicate Pred, 6766 bool &Increasing) { 6767 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing); 6768 6769 #ifndef NDEBUG 6770 // Verify an invariant: inverting the predicate should turn a monotonically 6771 // increasing change to a monotonically decreasing one, and vice versa. 6772 bool IncreasingSwapped; 6773 bool ResultSwapped = isMonotonicPredicateImpl( 6774 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped); 6775 6776 assert(Result == ResultSwapped && "should be able to analyze both!"); 6777 if (ResultSwapped) 6778 assert(Increasing == !IncreasingSwapped && 6779 "monotonicity should flip as we flip the predicate"); 6780 #endif 6781 6782 return Result; 6783 } 6784 6785 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS, 6786 ICmpInst::Predicate Pred, 6787 bool &Increasing) { 6788 6789 // A zero step value for LHS means the induction variable is essentially a 6790 // loop invariant value. We don't really depend on the predicate actually 6791 // flipping from false to true (for increasing predicates, and the other way 6792 // around for decreasing predicates), all we care about is that *if* the 6793 // predicate changes then it only changes from false to true. 6794 // 6795 // A zero step value in itself is not very useful, but there may be places 6796 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 6797 // as general as possible. 6798 6799 switch (Pred) { 6800 default: 6801 return false; // Conservative answer 6802 6803 case ICmpInst::ICMP_UGT: 6804 case ICmpInst::ICMP_UGE: 6805 case ICmpInst::ICMP_ULT: 6806 case ICmpInst::ICMP_ULE: 6807 if (!LHS->getNoWrapFlags(SCEV::FlagNUW)) 6808 return false; 6809 6810 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE; 6811 return true; 6812 6813 case ICmpInst::ICMP_SGT: 6814 case ICmpInst::ICMP_SGE: 6815 case ICmpInst::ICMP_SLT: 6816 case ICmpInst::ICMP_SLE: { 6817 if (!LHS->getNoWrapFlags(SCEV::FlagNSW)) 6818 return false; 6819 6820 const SCEV *Step = LHS->getStepRecurrence(*this); 6821 6822 if (isKnownNonNegative(Step)) { 6823 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE; 6824 return true; 6825 } 6826 6827 if (isKnownNonPositive(Step)) { 6828 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE; 6829 return true; 6830 } 6831 6832 return false; 6833 } 6834 6835 } 6836 6837 llvm_unreachable("switch has default clause!"); 6838 } 6839 6840 bool ScalarEvolution::isLoopInvariantPredicate( 6841 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 6842 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS, 6843 const SCEV *&InvariantRHS) { 6844 6845 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 6846 if (!isLoopInvariant(RHS, L)) { 6847 if (!isLoopInvariant(LHS, L)) 6848 return false; 6849 6850 std::swap(LHS, RHS); 6851 Pred = ICmpInst::getSwappedPredicate(Pred); 6852 } 6853 6854 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 6855 if (!ArLHS || ArLHS->getLoop() != L) 6856 return false; 6857 6858 bool Increasing; 6859 if (!isMonotonicPredicate(ArLHS, Pred, Increasing)) 6860 return false; 6861 6862 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 6863 // true as the loop iterates, and the backedge is control dependent on 6864 // "ArLHS `Pred` RHS" == true then we can reason as follows: 6865 // 6866 // * if the predicate was false in the first iteration then the predicate 6867 // is never evaluated again, since the loop exits without taking the 6868 // backedge. 6869 // * if the predicate was true in the first iteration then it will 6870 // continue to be true for all future iterations since it is 6871 // monotonically increasing. 6872 // 6873 // For both the above possibilities, we can replace the loop varying 6874 // predicate with its value on the first iteration of the loop (which is 6875 // loop invariant). 6876 // 6877 // A similar reasoning applies for a monotonically decreasing predicate, by 6878 // replacing true with false and false with true in the above two bullets. 6879 6880 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 6881 6882 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 6883 return false; 6884 6885 InvariantPred = Pred; 6886 InvariantLHS = ArLHS->getStart(); 6887 InvariantRHS = RHS; 6888 return true; 6889 } 6890 6891 bool 6892 ScalarEvolution::isKnownPredicateWithRanges(ICmpInst::Predicate Pred, 6893 const SCEV *LHS, const SCEV *RHS) { 6894 if (HasSameValue(LHS, RHS)) 6895 return ICmpInst::isTrueWhenEqual(Pred); 6896 6897 // This code is split out from isKnownPredicate because it is called from 6898 // within isLoopEntryGuardedByCond. 6899 switch (Pred) { 6900 default: 6901 llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 6902 case ICmpInst::ICMP_SGT: 6903 std::swap(LHS, RHS); 6904 case ICmpInst::ICMP_SLT: { 6905 ConstantRange LHSRange = getSignedRange(LHS); 6906 ConstantRange RHSRange = getSignedRange(RHS); 6907 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin())) 6908 return true; 6909 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax())) 6910 return false; 6911 break; 6912 } 6913 case ICmpInst::ICMP_SGE: 6914 std::swap(LHS, RHS); 6915 case ICmpInst::ICMP_SLE: { 6916 ConstantRange LHSRange = getSignedRange(LHS); 6917 ConstantRange RHSRange = getSignedRange(RHS); 6918 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin())) 6919 return true; 6920 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax())) 6921 return false; 6922 break; 6923 } 6924 case ICmpInst::ICMP_UGT: 6925 std::swap(LHS, RHS); 6926 case ICmpInst::ICMP_ULT: { 6927 ConstantRange LHSRange = getUnsignedRange(LHS); 6928 ConstantRange RHSRange = getUnsignedRange(RHS); 6929 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin())) 6930 return true; 6931 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax())) 6932 return false; 6933 break; 6934 } 6935 case ICmpInst::ICMP_UGE: 6936 std::swap(LHS, RHS); 6937 case ICmpInst::ICMP_ULE: { 6938 ConstantRange LHSRange = getUnsignedRange(LHS); 6939 ConstantRange RHSRange = getUnsignedRange(RHS); 6940 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin())) 6941 return true; 6942 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax())) 6943 return false; 6944 break; 6945 } 6946 case ICmpInst::ICMP_NE: { 6947 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet()) 6948 return true; 6949 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet()) 6950 return true; 6951 6952 const SCEV *Diff = getMinusSCEV(LHS, RHS); 6953 if (isKnownNonZero(Diff)) 6954 return true; 6955 break; 6956 } 6957 case ICmpInst::ICMP_EQ: 6958 // The check at the top of the function catches the case where 6959 // the values are known to be equal. 6960 break; 6961 } 6962 return false; 6963 } 6964 6965 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 6966 /// protected by a conditional between LHS and RHS. This is used to 6967 /// to eliminate casts. 6968 bool 6969 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 6970 ICmpInst::Predicate Pred, 6971 const SCEV *LHS, const SCEV *RHS) { 6972 // Interpret a null as meaning no loop, where there is obviously no guard 6973 // (interprocedural conditions notwithstanding). 6974 if (!L) return true; 6975 6976 if (isKnownPredicateWithRanges(Pred, LHS, RHS)) return true; 6977 6978 BasicBlock *Latch = L->getLoopLatch(); 6979 if (!Latch) 6980 return false; 6981 6982 BranchInst *LoopContinuePredicate = 6983 dyn_cast<BranchInst>(Latch->getTerminator()); 6984 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 6985 isImpliedCond(Pred, LHS, RHS, 6986 LoopContinuePredicate->getCondition(), 6987 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 6988 return true; 6989 6990 struct ClearWalkingBEDominatingCondsOnExit { 6991 ScalarEvolution &SE; 6992 6993 explicit ClearWalkingBEDominatingCondsOnExit(ScalarEvolution &SE) 6994 : SE(SE){} 6995 6996 ~ClearWalkingBEDominatingCondsOnExit() { 6997 SE.WalkingBEDominatingConds = false; 6998 } 6999 }; 7000 7001 // We don't want more than one activation of the following loops on the stack 7002 // -- that can lead to O(n!) time complexity. 7003 if (WalkingBEDominatingConds) 7004 return false; 7005 7006 WalkingBEDominatingConds = true; 7007 ClearWalkingBEDominatingCondsOnExit ClearOnExit(*this); 7008 7009 // Check conditions due to any @llvm.assume intrinsics. 7010 for (auto &AssumeVH : AC.assumptions()) { 7011 if (!AssumeVH) 7012 continue; 7013 auto *CI = cast<CallInst>(AssumeVH); 7014 if (!DT.dominates(CI, Latch->getTerminator())) 7015 continue; 7016 7017 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 7018 return true; 7019 } 7020 7021 // If the loop is not reachable from the entry block, we risk running into an 7022 // infinite loop as we walk up into the dom tree. These loops do not matter 7023 // anyway, so we just return a conservative answer when we see them. 7024 if (!DT.isReachableFromEntry(L->getHeader())) 7025 return false; 7026 7027 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 7028 DTN != HeaderDTN; DTN = DTN->getIDom()) { 7029 7030 assert(DTN && "should reach the loop header before reaching the root!"); 7031 7032 BasicBlock *BB = DTN->getBlock(); 7033 BasicBlock *PBB = BB->getSinglePredecessor(); 7034 if (!PBB) 7035 continue; 7036 7037 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 7038 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 7039 continue; 7040 7041 Value *Condition = ContinuePredicate->getCondition(); 7042 7043 // If we have an edge `E` within the loop body that dominates the only 7044 // latch, the condition guarding `E` also guards the backedge. This 7045 // reasoning works only for loops with a single latch. 7046 7047 BasicBlockEdge DominatingEdge(PBB, BB); 7048 if (DominatingEdge.isSingleEdge()) { 7049 // We're constructively (and conservatively) enumerating edges within the 7050 // loop body that dominate the latch. The dominator tree better agree 7051 // with us on this: 7052 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 7053 7054 if (isImpliedCond(Pred, LHS, RHS, Condition, 7055 BB != ContinuePredicate->getSuccessor(0))) 7056 return true; 7057 } 7058 } 7059 7060 return false; 7061 } 7062 7063 /// isLoopEntryGuardedByCond - Test whether entry to the loop is protected 7064 /// by a conditional between LHS and RHS. This is used to help avoid max 7065 /// expressions in loop trip counts, and to eliminate casts. 7066 bool 7067 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 7068 ICmpInst::Predicate Pred, 7069 const SCEV *LHS, const SCEV *RHS) { 7070 // Interpret a null as meaning no loop, where there is obviously no guard 7071 // (interprocedural conditions notwithstanding). 7072 if (!L) return false; 7073 7074 if (isKnownPredicateWithRanges(Pred, LHS, RHS)) return true; 7075 7076 // Starting at the loop predecessor, climb up the predecessor chain, as long 7077 // as there are predecessors that can be found that have unique successors 7078 // leading to the original header. 7079 for (std::pair<BasicBlock *, BasicBlock *> 7080 Pair(L->getLoopPredecessor(), L->getHeader()); 7081 Pair.first; 7082 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 7083 7084 BranchInst *LoopEntryPredicate = 7085 dyn_cast<BranchInst>(Pair.first->getTerminator()); 7086 if (!LoopEntryPredicate || 7087 LoopEntryPredicate->isUnconditional()) 7088 continue; 7089 7090 if (isImpliedCond(Pred, LHS, RHS, 7091 LoopEntryPredicate->getCondition(), 7092 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 7093 return true; 7094 } 7095 7096 // Check conditions due to any @llvm.assume intrinsics. 7097 for (auto &AssumeVH : AC.assumptions()) { 7098 if (!AssumeVH) 7099 continue; 7100 auto *CI = cast<CallInst>(AssumeVH); 7101 if (!DT.dominates(CI, L->getHeader())) 7102 continue; 7103 7104 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 7105 return true; 7106 } 7107 7108 return false; 7109 } 7110 7111 /// RAII wrapper to prevent recursive application of isImpliedCond. 7112 /// ScalarEvolution's PendingLoopPredicates set must be empty unless we are 7113 /// currently evaluating isImpliedCond. 7114 struct MarkPendingLoopPredicate { 7115 Value *Cond; 7116 DenseSet<Value*> &LoopPreds; 7117 bool Pending; 7118 7119 MarkPendingLoopPredicate(Value *C, DenseSet<Value*> &LP) 7120 : Cond(C), LoopPreds(LP) { 7121 Pending = !LoopPreds.insert(Cond).second; 7122 } 7123 ~MarkPendingLoopPredicate() { 7124 if (!Pending) 7125 LoopPreds.erase(Cond); 7126 } 7127 }; 7128 7129 /// isImpliedCond - Test whether the condition described by Pred, LHS, 7130 /// and RHS is true whenever the given Cond value evaluates to true. 7131 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, 7132 const SCEV *LHS, const SCEV *RHS, 7133 Value *FoundCondValue, 7134 bool Inverse) { 7135 MarkPendingLoopPredicate Mark(FoundCondValue, PendingLoopPredicates); 7136 if (Mark.Pending) 7137 return false; 7138 7139 // Recursively handle And and Or conditions. 7140 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) { 7141 if (BO->getOpcode() == Instruction::And) { 7142 if (!Inverse) 7143 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 7144 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 7145 } else if (BO->getOpcode() == Instruction::Or) { 7146 if (Inverse) 7147 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 7148 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 7149 } 7150 } 7151 7152 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 7153 if (!ICI) return false; 7154 7155 // Now that we found a conditional branch that dominates the loop or controls 7156 // the loop latch. Check to see if it is the comparison we are looking for. 7157 ICmpInst::Predicate FoundPred; 7158 if (Inverse) 7159 FoundPred = ICI->getInversePredicate(); 7160 else 7161 FoundPred = ICI->getPredicate(); 7162 7163 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 7164 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 7165 7166 // Balance the types. 7167 if (getTypeSizeInBits(LHS->getType()) < 7168 getTypeSizeInBits(FoundLHS->getType())) { 7169 if (CmpInst::isSigned(Pred)) { 7170 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 7171 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 7172 } else { 7173 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 7174 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 7175 } 7176 } else if (getTypeSizeInBits(LHS->getType()) > 7177 getTypeSizeInBits(FoundLHS->getType())) { 7178 if (CmpInst::isSigned(FoundPred)) { 7179 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 7180 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 7181 } else { 7182 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 7183 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 7184 } 7185 } 7186 7187 // Canonicalize the query to match the way instcombine will have 7188 // canonicalized the comparison. 7189 if (SimplifyICmpOperands(Pred, LHS, RHS)) 7190 if (LHS == RHS) 7191 return CmpInst::isTrueWhenEqual(Pred); 7192 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 7193 if (FoundLHS == FoundRHS) 7194 return CmpInst::isFalseWhenEqual(FoundPred); 7195 7196 // Check to see if we can make the LHS or RHS match. 7197 if (LHS == FoundRHS || RHS == FoundLHS) { 7198 if (isa<SCEVConstant>(RHS)) { 7199 std::swap(FoundLHS, FoundRHS); 7200 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 7201 } else { 7202 std::swap(LHS, RHS); 7203 Pred = ICmpInst::getSwappedPredicate(Pred); 7204 } 7205 } 7206 7207 // Check whether the found predicate is the same as the desired predicate. 7208 if (FoundPred == Pred) 7209 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 7210 7211 // Check whether swapping the found predicate makes it the same as the 7212 // desired predicate. 7213 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 7214 if (isa<SCEVConstant>(RHS)) 7215 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS); 7216 else 7217 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), 7218 RHS, LHS, FoundLHS, FoundRHS); 7219 } 7220 7221 // Check if we can make progress by sharpening ranges. 7222 if (FoundPred == ICmpInst::ICMP_NE && 7223 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 7224 7225 const SCEVConstant *C = nullptr; 7226 const SCEV *V = nullptr; 7227 7228 if (isa<SCEVConstant>(FoundLHS)) { 7229 C = cast<SCEVConstant>(FoundLHS); 7230 V = FoundRHS; 7231 } else { 7232 C = cast<SCEVConstant>(FoundRHS); 7233 V = FoundLHS; 7234 } 7235 7236 // The guarding predicate tells us that C != V. If the known range 7237 // of V is [C, t), we can sharpen the range to [C + 1, t). The 7238 // range we consider has to correspond to same signedness as the 7239 // predicate we're interested in folding. 7240 7241 APInt Min = ICmpInst::isSigned(Pred) ? 7242 getSignedRange(V).getSignedMin() : getUnsignedRange(V).getUnsignedMin(); 7243 7244 if (Min == C->getValue()->getValue()) { 7245 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 7246 // This is true even if (Min + 1) wraps around -- in case of 7247 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 7248 7249 APInt SharperMin = Min + 1; 7250 7251 switch (Pred) { 7252 case ICmpInst::ICMP_SGE: 7253 case ICmpInst::ICMP_UGE: 7254 // We know V `Pred` SharperMin. If this implies LHS `Pred` 7255 // RHS, we're done. 7256 if (isImpliedCondOperands(Pred, LHS, RHS, V, 7257 getConstant(SharperMin))) 7258 return true; 7259 7260 case ICmpInst::ICMP_SGT: 7261 case ICmpInst::ICMP_UGT: 7262 // We know from the range information that (V `Pred` Min || 7263 // V == Min). We know from the guarding condition that !(V 7264 // == Min). This gives us 7265 // 7266 // V `Pred` Min || V == Min && !(V == Min) 7267 // => V `Pred` Min 7268 // 7269 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 7270 7271 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min))) 7272 return true; 7273 7274 default: 7275 // No change 7276 break; 7277 } 7278 } 7279 } 7280 7281 // Check whether the actual condition is beyond sufficient. 7282 if (FoundPred == ICmpInst::ICMP_EQ) 7283 if (ICmpInst::isTrueWhenEqual(Pred)) 7284 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS)) 7285 return true; 7286 if (Pred == ICmpInst::ICMP_NE) 7287 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 7288 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS)) 7289 return true; 7290 7291 // Otherwise assume the worst. 7292 return false; 7293 } 7294 7295 /// isImpliedCondOperands - Test whether the condition described by Pred, 7296 /// LHS, and RHS is true whenever the condition described by Pred, FoundLHS, 7297 /// and FoundRHS is true. 7298 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 7299 const SCEV *LHS, const SCEV *RHS, 7300 const SCEV *FoundLHS, 7301 const SCEV *FoundRHS) { 7302 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 7303 return true; 7304 7305 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 7306 FoundLHS, FoundRHS) || 7307 // ~x < ~y --> x > y 7308 isImpliedCondOperandsHelper(Pred, LHS, RHS, 7309 getNotSCEV(FoundRHS), 7310 getNotSCEV(FoundLHS)); 7311 } 7312 7313 7314 /// If Expr computes ~A, return A else return nullptr 7315 static const SCEV *MatchNotExpr(const SCEV *Expr) { 7316 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 7317 if (!Add || Add->getNumOperands() != 2) return nullptr; 7318 7319 const SCEVConstant *AddLHS = dyn_cast<SCEVConstant>(Add->getOperand(0)); 7320 if (!(AddLHS && AddLHS->getValue()->getValue().isAllOnesValue())) 7321 return nullptr; 7322 7323 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 7324 if (!AddRHS || AddRHS->getNumOperands() != 2) return nullptr; 7325 7326 const SCEVConstant *MulLHS = dyn_cast<SCEVConstant>(AddRHS->getOperand(0)); 7327 if (!(MulLHS && MulLHS->getValue()->getValue().isAllOnesValue())) 7328 return nullptr; 7329 7330 return AddRHS->getOperand(1); 7331 } 7332 7333 7334 /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values? 7335 template<typename MaxExprType> 7336 static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr, 7337 const SCEV *Candidate) { 7338 const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr); 7339 if (!MaxExpr) return false; 7340 7341 auto It = std::find(MaxExpr->op_begin(), MaxExpr->op_end(), Candidate); 7342 return It != MaxExpr->op_end(); 7343 } 7344 7345 7346 /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values? 7347 template<typename MaxExprType> 7348 static bool IsMinConsistingOf(ScalarEvolution &SE, 7349 const SCEV *MaybeMinExpr, 7350 const SCEV *Candidate) { 7351 const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr); 7352 if (!MaybeMaxExpr) 7353 return false; 7354 7355 return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate)); 7356 } 7357 7358 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 7359 ICmpInst::Predicate Pred, 7360 const SCEV *LHS, const SCEV *RHS) { 7361 7362 // If both sides are affine addrecs for the same loop, with equal 7363 // steps, and we know the recurrences don't wrap, then we only 7364 // need to check the predicate on the starting values. 7365 7366 if (!ICmpInst::isRelational(Pred)) 7367 return false; 7368 7369 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 7370 if (!LAR) 7371 return false; 7372 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 7373 if (!RAR) 7374 return false; 7375 if (LAR->getLoop() != RAR->getLoop()) 7376 return false; 7377 if (!LAR->isAffine() || !RAR->isAffine()) 7378 return false; 7379 7380 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 7381 return false; 7382 7383 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 7384 SCEV::FlagNSW : SCEV::FlagNUW; 7385 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 7386 return false; 7387 7388 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 7389 } 7390 7391 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 7392 /// expression? 7393 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 7394 ICmpInst::Predicate Pred, 7395 const SCEV *LHS, const SCEV *RHS) { 7396 switch (Pred) { 7397 default: 7398 return false; 7399 7400 case ICmpInst::ICMP_SGE: 7401 std::swap(LHS, RHS); 7402 // fall through 7403 case ICmpInst::ICMP_SLE: 7404 return 7405 // min(A, ...) <= A 7406 IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) || 7407 // A <= max(A, ...) 7408 IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 7409 7410 case ICmpInst::ICMP_UGE: 7411 std::swap(LHS, RHS); 7412 // fall through 7413 case ICmpInst::ICMP_ULE: 7414 return 7415 // min(A, ...) <= A 7416 IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) || 7417 // A <= max(A, ...) 7418 IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 7419 } 7420 7421 llvm_unreachable("covered switch fell through?!"); 7422 } 7423 7424 /// isImpliedCondOperandsHelper - Test whether the condition described by 7425 /// Pred, LHS, and RHS is true whenever the condition described by Pred, 7426 /// FoundLHS, and FoundRHS is true. 7427 bool 7428 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 7429 const SCEV *LHS, const SCEV *RHS, 7430 const SCEV *FoundLHS, 7431 const SCEV *FoundRHS) { 7432 auto IsKnownPredicateFull = 7433 [this](ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 7434 return isKnownPredicateWithRanges(Pred, LHS, RHS) || 7435 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 7436 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS); 7437 }; 7438 7439 switch (Pred) { 7440 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 7441 case ICmpInst::ICMP_EQ: 7442 case ICmpInst::ICMP_NE: 7443 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 7444 return true; 7445 break; 7446 case ICmpInst::ICMP_SLT: 7447 case ICmpInst::ICMP_SLE: 7448 if (IsKnownPredicateFull(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 7449 IsKnownPredicateFull(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 7450 return true; 7451 break; 7452 case ICmpInst::ICMP_SGT: 7453 case ICmpInst::ICMP_SGE: 7454 if (IsKnownPredicateFull(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 7455 IsKnownPredicateFull(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 7456 return true; 7457 break; 7458 case ICmpInst::ICMP_ULT: 7459 case ICmpInst::ICMP_ULE: 7460 if (IsKnownPredicateFull(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 7461 IsKnownPredicateFull(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 7462 return true; 7463 break; 7464 case ICmpInst::ICMP_UGT: 7465 case ICmpInst::ICMP_UGE: 7466 if (IsKnownPredicateFull(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 7467 IsKnownPredicateFull(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 7468 return true; 7469 break; 7470 } 7471 7472 return false; 7473 } 7474 7475 /// isImpliedCondOperandsViaRanges - helper function for isImpliedCondOperands. 7476 /// Tries to get cases like "X `sgt` 0 => X - 1 `sgt` -1". 7477 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 7478 const SCEV *LHS, 7479 const SCEV *RHS, 7480 const SCEV *FoundLHS, 7481 const SCEV *FoundRHS) { 7482 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 7483 // The restriction on `FoundRHS` be lifted easily -- it exists only to 7484 // reduce the compile time impact of this optimization. 7485 return false; 7486 7487 const SCEVAddExpr *AddLHS = dyn_cast<SCEVAddExpr>(LHS); 7488 if (!AddLHS || AddLHS->getOperand(1) != FoundLHS || 7489 !isa<SCEVConstant>(AddLHS->getOperand(0))) 7490 return false; 7491 7492 APInt ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getValue()->getValue(); 7493 7494 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 7495 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 7496 ConstantRange FoundLHSRange = 7497 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); 7498 7499 // Since `LHS` is `FoundLHS` + `AddLHS->getOperand(0)`, we can compute a range 7500 // for `LHS`: 7501 APInt Addend = 7502 cast<SCEVConstant>(AddLHS->getOperand(0))->getValue()->getValue(); 7503 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(Addend)); 7504 7505 // We can also compute the range of values for `LHS` that satisfy the 7506 // consequent, "`LHS` `Pred` `RHS`": 7507 APInt ConstRHS = cast<SCEVConstant>(RHS)->getValue()->getValue(); 7508 ConstantRange SatisfyingLHSRange = 7509 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS); 7510 7511 // The antecedent implies the consequent if every value of `LHS` that 7512 // satisfies the antecedent also satisfies the consequent. 7513 return SatisfyingLHSRange.contains(LHSRange); 7514 } 7515 7516 // Verify if an linear IV with positive stride can overflow when in a 7517 // less-than comparison, knowing the invariant term of the comparison, the 7518 // stride and the knowledge of NSW/NUW flags on the recurrence. 7519 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 7520 bool IsSigned, bool NoWrap) { 7521 if (NoWrap) return false; 7522 7523 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 7524 const SCEV *One = getConstant(Stride->getType(), 1); 7525 7526 if (IsSigned) { 7527 APInt MaxRHS = getSignedRange(RHS).getSignedMax(); 7528 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 7529 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One)) 7530 .getSignedMax(); 7531 7532 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 7533 return (MaxValue - MaxStrideMinusOne).slt(MaxRHS); 7534 } 7535 7536 APInt MaxRHS = getUnsignedRange(RHS).getUnsignedMax(); 7537 APInt MaxValue = APInt::getMaxValue(BitWidth); 7538 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One)) 7539 .getUnsignedMax(); 7540 7541 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 7542 return (MaxValue - MaxStrideMinusOne).ult(MaxRHS); 7543 } 7544 7545 // Verify if an linear IV with negative stride can overflow when in a 7546 // greater-than comparison, knowing the invariant term of the comparison, 7547 // the stride and the knowledge of NSW/NUW flags on the recurrence. 7548 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 7549 bool IsSigned, bool NoWrap) { 7550 if (NoWrap) return false; 7551 7552 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 7553 const SCEV *One = getConstant(Stride->getType(), 1); 7554 7555 if (IsSigned) { 7556 APInt MinRHS = getSignedRange(RHS).getSignedMin(); 7557 APInt MinValue = APInt::getSignedMinValue(BitWidth); 7558 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One)) 7559 .getSignedMax(); 7560 7561 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 7562 return (MinValue + MaxStrideMinusOne).sgt(MinRHS); 7563 } 7564 7565 APInt MinRHS = getUnsignedRange(RHS).getUnsignedMin(); 7566 APInt MinValue = APInt::getMinValue(BitWidth); 7567 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One)) 7568 .getUnsignedMax(); 7569 7570 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 7571 return (MinValue + MaxStrideMinusOne).ugt(MinRHS); 7572 } 7573 7574 // Compute the backedge taken count knowing the interval difference, the 7575 // stride and presence of the equality in the comparison. 7576 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step, 7577 bool Equality) { 7578 const SCEV *One = getConstant(Step->getType(), 1); 7579 Delta = Equality ? getAddExpr(Delta, Step) 7580 : getAddExpr(Delta, getMinusSCEV(Step, One)); 7581 return getUDivExpr(Delta, Step); 7582 } 7583 7584 /// HowManyLessThans - Return the number of times a backedge containing the 7585 /// specified less-than comparison will execute. If not computable, return 7586 /// CouldNotCompute. 7587 /// 7588 /// @param ControlsExit is true when the LHS < RHS condition directly controls 7589 /// the branch (loops exits only if condition is true). In this case, we can use 7590 /// NoWrapFlags to skip overflow checks. 7591 ScalarEvolution::ExitLimit 7592 ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS, 7593 const Loop *L, bool IsSigned, 7594 bool ControlsExit) { 7595 // We handle only IV < Invariant 7596 if (!isLoopInvariant(RHS, L)) 7597 return getCouldNotCompute(); 7598 7599 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 7600 7601 // Avoid weird loops 7602 if (!IV || IV->getLoop() != L || !IV->isAffine()) 7603 return getCouldNotCompute(); 7604 7605 bool NoWrap = ControlsExit && 7606 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 7607 7608 const SCEV *Stride = IV->getStepRecurrence(*this); 7609 7610 // Avoid negative or zero stride values 7611 if (!isKnownPositive(Stride)) 7612 return getCouldNotCompute(); 7613 7614 // Avoid proven overflow cases: this will ensure that the backedge taken count 7615 // will not generate any unsigned overflow. Relaxed no-overflow conditions 7616 // exploit NoWrapFlags, allowing to optimize in presence of undefined 7617 // behaviors like the case of C language. 7618 if (!Stride->isOne() && doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap)) 7619 return getCouldNotCompute(); 7620 7621 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT 7622 : ICmpInst::ICMP_ULT; 7623 const SCEV *Start = IV->getStart(); 7624 const SCEV *End = RHS; 7625 if (!isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) { 7626 const SCEV *Diff = getMinusSCEV(RHS, Start); 7627 // If we have NoWrap set, then we can assume that the increment won't 7628 // overflow, in which case if RHS - Start is a constant, we don't need to 7629 // do a max operation since we can just figure it out statically 7630 if (NoWrap && isa<SCEVConstant>(Diff)) { 7631 APInt D = dyn_cast<const SCEVConstant>(Diff)->getValue()->getValue(); 7632 if (D.isNegative()) 7633 End = Start; 7634 } else 7635 End = IsSigned ? getSMaxExpr(RHS, Start) 7636 : getUMaxExpr(RHS, Start); 7637 } 7638 7639 const SCEV *BECount = computeBECount(getMinusSCEV(End, Start), Stride, false); 7640 7641 APInt MinStart = IsSigned ? getSignedRange(Start).getSignedMin() 7642 : getUnsignedRange(Start).getUnsignedMin(); 7643 7644 APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin() 7645 : getUnsignedRange(Stride).getUnsignedMin(); 7646 7647 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 7648 APInt Limit = IsSigned ? APInt::getSignedMaxValue(BitWidth) - (MinStride - 1) 7649 : APInt::getMaxValue(BitWidth) - (MinStride - 1); 7650 7651 // Although End can be a MAX expression we estimate MaxEnd considering only 7652 // the case End = RHS. This is safe because in the other case (End - Start) 7653 // is zero, leading to a zero maximum backedge taken count. 7654 APInt MaxEnd = 7655 IsSigned ? APIntOps::smin(getSignedRange(RHS).getSignedMax(), Limit) 7656 : APIntOps::umin(getUnsignedRange(RHS).getUnsignedMax(), Limit); 7657 7658 const SCEV *MaxBECount; 7659 if (isa<SCEVConstant>(BECount)) 7660 MaxBECount = BECount; 7661 else 7662 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart), 7663 getConstant(MinStride), false); 7664 7665 if (isa<SCEVCouldNotCompute>(MaxBECount)) 7666 MaxBECount = BECount; 7667 7668 return ExitLimit(BECount, MaxBECount); 7669 } 7670 7671 ScalarEvolution::ExitLimit 7672 ScalarEvolution::HowManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 7673 const Loop *L, bool IsSigned, 7674 bool ControlsExit) { 7675 // We handle only IV > Invariant 7676 if (!isLoopInvariant(RHS, L)) 7677 return getCouldNotCompute(); 7678 7679 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 7680 7681 // Avoid weird loops 7682 if (!IV || IV->getLoop() != L || !IV->isAffine()) 7683 return getCouldNotCompute(); 7684 7685 bool NoWrap = ControlsExit && 7686 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 7687 7688 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 7689 7690 // Avoid negative or zero stride values 7691 if (!isKnownPositive(Stride)) 7692 return getCouldNotCompute(); 7693 7694 // Avoid proven overflow cases: this will ensure that the backedge taken count 7695 // will not generate any unsigned overflow. Relaxed no-overflow conditions 7696 // exploit NoWrapFlags, allowing to optimize in presence of undefined 7697 // behaviors like the case of C language. 7698 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap)) 7699 return getCouldNotCompute(); 7700 7701 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT 7702 : ICmpInst::ICMP_UGT; 7703 7704 const SCEV *Start = IV->getStart(); 7705 const SCEV *End = RHS; 7706 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) { 7707 const SCEV *Diff = getMinusSCEV(RHS, Start); 7708 // If we have NoWrap set, then we can assume that the increment won't 7709 // overflow, in which case if RHS - Start is a constant, we don't need to 7710 // do a max operation since we can just figure it out statically 7711 if (NoWrap && isa<SCEVConstant>(Diff)) { 7712 APInt D = dyn_cast<const SCEVConstant>(Diff)->getValue()->getValue(); 7713 if (!D.isNegative()) 7714 End = Start; 7715 } else 7716 End = IsSigned ? getSMinExpr(RHS, Start) 7717 : getUMinExpr(RHS, Start); 7718 } 7719 7720 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false); 7721 7722 APInt MaxStart = IsSigned ? getSignedRange(Start).getSignedMax() 7723 : getUnsignedRange(Start).getUnsignedMax(); 7724 7725 APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin() 7726 : getUnsignedRange(Stride).getUnsignedMin(); 7727 7728 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 7729 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 7730 : APInt::getMinValue(BitWidth) + (MinStride - 1); 7731 7732 // Although End can be a MIN expression we estimate MinEnd considering only 7733 // the case End = RHS. This is safe because in the other case (Start - End) 7734 // is zero, leading to a zero maximum backedge taken count. 7735 APInt MinEnd = 7736 IsSigned ? APIntOps::smax(getSignedRange(RHS).getSignedMin(), Limit) 7737 : APIntOps::umax(getUnsignedRange(RHS).getUnsignedMin(), Limit); 7738 7739 7740 const SCEV *MaxBECount = getCouldNotCompute(); 7741 if (isa<SCEVConstant>(BECount)) 7742 MaxBECount = BECount; 7743 else 7744 MaxBECount = computeBECount(getConstant(MaxStart - MinEnd), 7745 getConstant(MinStride), false); 7746 7747 if (isa<SCEVCouldNotCompute>(MaxBECount)) 7748 MaxBECount = BECount; 7749 7750 return ExitLimit(BECount, MaxBECount); 7751 } 7752 7753 /// getNumIterationsInRange - Return the number of iterations of this loop that 7754 /// produce values in the specified constant range. Another way of looking at 7755 /// this is that it returns the first iteration number where the value is not in 7756 /// the condition, thus computing the exit count. If the iteration count can't 7757 /// be computed, an instance of SCEVCouldNotCompute is returned. 7758 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range, 7759 ScalarEvolution &SE) const { 7760 if (Range.isFullSet()) // Infinite loop. 7761 return SE.getCouldNotCompute(); 7762 7763 // If the start is a non-zero constant, shift the range to simplify things. 7764 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 7765 if (!SC->getValue()->isZero()) { 7766 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end()); 7767 Operands[0] = SE.getConstant(SC->getType(), 0); 7768 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 7769 getNoWrapFlags(FlagNW)); 7770 if (const SCEVAddRecExpr *ShiftedAddRec = 7771 dyn_cast<SCEVAddRecExpr>(Shifted)) 7772 return ShiftedAddRec->getNumIterationsInRange( 7773 Range.subtract(SC->getValue()->getValue()), SE); 7774 // This is strange and shouldn't happen. 7775 return SE.getCouldNotCompute(); 7776 } 7777 7778 // The only time we can solve this is when we have all constant indices. 7779 // Otherwise, we cannot determine the overflow conditions. 7780 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) 7781 if (!isa<SCEVConstant>(getOperand(i))) 7782 return SE.getCouldNotCompute(); 7783 7784 7785 // Okay at this point we know that all elements of the chrec are constants and 7786 // that the start element is zero. 7787 7788 // First check to see if the range contains zero. If not, the first 7789 // iteration exits. 7790 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 7791 if (!Range.contains(APInt(BitWidth, 0))) 7792 return SE.getConstant(getType(), 0); 7793 7794 if (isAffine()) { 7795 // If this is an affine expression then we have this situation: 7796 // Solve {0,+,A} in Range === Ax in Range 7797 7798 // We know that zero is in the range. If A is positive then we know that 7799 // the upper value of the range must be the first possible exit value. 7800 // If A is negative then the lower of the range is the last possible loop 7801 // value. Also note that we already checked for a full range. 7802 APInt One(BitWidth,1); 7803 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue(); 7804 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower(); 7805 7806 // The exit value should be (End+A)/A. 7807 APInt ExitVal = (End + A).udiv(A); 7808 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 7809 7810 // Evaluate at the exit value. If we really did fall out of the valid 7811 // range, then we computed our trip count, otherwise wrap around or other 7812 // things must have happened. 7813 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 7814 if (Range.contains(Val->getValue())) 7815 return SE.getCouldNotCompute(); // Something strange happened 7816 7817 // Ensure that the previous value is in the range. This is a sanity check. 7818 assert(Range.contains( 7819 EvaluateConstantChrecAtConstant(this, 7820 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) && 7821 "Linear scev computation is off in a bad way!"); 7822 return SE.getConstant(ExitValue); 7823 } else if (isQuadratic()) { 7824 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the 7825 // quadratic equation to solve it. To do this, we must frame our problem in 7826 // terms of figuring out when zero is crossed, instead of when 7827 // Range.getUpper() is crossed. 7828 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end()); 7829 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper())); 7830 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), 7831 // getNoWrapFlags(FlagNW) 7832 FlagAnyWrap); 7833 7834 // Next, solve the constructed addrec 7835 std::pair<const SCEV *,const SCEV *> Roots = 7836 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE); 7837 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first); 7838 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second); 7839 if (R1) { 7840 // Pick the smallest positive root value. 7841 if (ConstantInt *CB = 7842 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT, 7843 R1->getValue(), R2->getValue()))) { 7844 if (!CB->getZExtValue()) 7845 std::swap(R1, R2); // R1 is the minimum root now. 7846 7847 // Make sure the root is not off by one. The returned iteration should 7848 // not be in the range, but the previous one should be. When solving 7849 // for "X*X < 5", for example, we should not return a root of 2. 7850 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this, 7851 R1->getValue(), 7852 SE); 7853 if (Range.contains(R1Val->getValue())) { 7854 // The next iteration must be out of the range... 7855 ConstantInt *NextVal = 7856 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1); 7857 7858 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); 7859 if (!Range.contains(R1Val->getValue())) 7860 return SE.getConstant(NextVal); 7861 return SE.getCouldNotCompute(); // Something strange happened 7862 } 7863 7864 // If R1 was not in the range, then it is a good return value. Make 7865 // sure that R1-1 WAS in the range though, just in case. 7866 ConstantInt *NextVal = 7867 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()-1); 7868 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); 7869 if (Range.contains(R1Val->getValue())) 7870 return R1; 7871 return SE.getCouldNotCompute(); // Something strange happened 7872 } 7873 } 7874 } 7875 7876 return SE.getCouldNotCompute(); 7877 } 7878 7879 namespace { 7880 struct FindUndefs { 7881 bool Found; 7882 FindUndefs() : Found(false) {} 7883 7884 bool follow(const SCEV *S) { 7885 if (const SCEVUnknown *C = dyn_cast<SCEVUnknown>(S)) { 7886 if (isa<UndefValue>(C->getValue())) 7887 Found = true; 7888 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) { 7889 if (isa<UndefValue>(C->getValue())) 7890 Found = true; 7891 } 7892 7893 // Keep looking if we haven't found it yet. 7894 return !Found; 7895 } 7896 bool isDone() const { 7897 // Stop recursion if we have found an undef. 7898 return Found; 7899 } 7900 }; 7901 } 7902 7903 // Return true when S contains at least an undef value. 7904 static inline bool 7905 containsUndefs(const SCEV *S) { 7906 FindUndefs F; 7907 SCEVTraversal<FindUndefs> ST(F); 7908 ST.visitAll(S); 7909 7910 return F.Found; 7911 } 7912 7913 namespace { 7914 // Collect all steps of SCEV expressions. 7915 struct SCEVCollectStrides { 7916 ScalarEvolution &SE; 7917 SmallVectorImpl<const SCEV *> &Strides; 7918 7919 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) 7920 : SE(SE), Strides(S) {} 7921 7922 bool follow(const SCEV *S) { 7923 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 7924 Strides.push_back(AR->getStepRecurrence(SE)); 7925 return true; 7926 } 7927 bool isDone() const { return false; } 7928 }; 7929 7930 // Collect all SCEVUnknown and SCEVMulExpr expressions. 7931 struct SCEVCollectTerms { 7932 SmallVectorImpl<const SCEV *> &Terms; 7933 7934 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) 7935 : Terms(T) {} 7936 7937 bool follow(const SCEV *S) { 7938 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S)) { 7939 if (!containsUndefs(S)) 7940 Terms.push_back(S); 7941 7942 // Stop recursion: once we collected a term, do not walk its operands. 7943 return false; 7944 } 7945 7946 // Keep looking. 7947 return true; 7948 } 7949 bool isDone() const { return false; } 7950 }; 7951 } 7952 7953 /// Find parametric terms in this SCEVAddRecExpr. 7954 void ScalarEvolution::collectParametricTerms(const SCEV *Expr, 7955 SmallVectorImpl<const SCEV *> &Terms) { 7956 SmallVector<const SCEV *, 4> Strides; 7957 SCEVCollectStrides StrideCollector(*this, Strides); 7958 visitAll(Expr, StrideCollector); 7959 7960 DEBUG({ 7961 dbgs() << "Strides:\n"; 7962 for (const SCEV *S : Strides) 7963 dbgs() << *S << "\n"; 7964 }); 7965 7966 for (const SCEV *S : Strides) { 7967 SCEVCollectTerms TermCollector(Terms); 7968 visitAll(S, TermCollector); 7969 } 7970 7971 DEBUG({ 7972 dbgs() << "Terms:\n"; 7973 for (const SCEV *T : Terms) 7974 dbgs() << *T << "\n"; 7975 }); 7976 } 7977 7978 static bool findArrayDimensionsRec(ScalarEvolution &SE, 7979 SmallVectorImpl<const SCEV *> &Terms, 7980 SmallVectorImpl<const SCEV *> &Sizes) { 7981 int Last = Terms.size() - 1; 7982 const SCEV *Step = Terms[Last]; 7983 7984 // End of recursion. 7985 if (Last == 0) { 7986 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { 7987 SmallVector<const SCEV *, 2> Qs; 7988 for (const SCEV *Op : M->operands()) 7989 if (!isa<SCEVConstant>(Op)) 7990 Qs.push_back(Op); 7991 7992 Step = SE.getMulExpr(Qs); 7993 } 7994 7995 Sizes.push_back(Step); 7996 return true; 7997 } 7998 7999 for (const SCEV *&Term : Terms) { 8000 // Normalize the terms before the next call to findArrayDimensionsRec. 8001 const SCEV *Q, *R; 8002 SCEVDivision::divide(SE, Term, Step, &Q, &R); 8003 8004 // Bail out when GCD does not evenly divide one of the terms. 8005 if (!R->isZero()) 8006 return false; 8007 8008 Term = Q; 8009 } 8010 8011 // Remove all SCEVConstants. 8012 Terms.erase(std::remove_if(Terms.begin(), Terms.end(), [](const SCEV *E) { 8013 return isa<SCEVConstant>(E); 8014 }), 8015 Terms.end()); 8016 8017 if (Terms.size() > 0) 8018 if (!findArrayDimensionsRec(SE, Terms, Sizes)) 8019 return false; 8020 8021 Sizes.push_back(Step); 8022 return true; 8023 } 8024 8025 namespace { 8026 struct FindParameter { 8027 bool FoundParameter; 8028 FindParameter() : FoundParameter(false) {} 8029 8030 bool follow(const SCEV *S) { 8031 if (isa<SCEVUnknown>(S)) { 8032 FoundParameter = true; 8033 // Stop recursion: we found a parameter. 8034 return false; 8035 } 8036 // Keep looking. 8037 return true; 8038 } 8039 bool isDone() const { 8040 // Stop recursion if we have found a parameter. 8041 return FoundParameter; 8042 } 8043 }; 8044 } 8045 8046 // Returns true when S contains at least a SCEVUnknown parameter. 8047 static inline bool 8048 containsParameters(const SCEV *S) { 8049 FindParameter F; 8050 SCEVTraversal<FindParameter> ST(F); 8051 ST.visitAll(S); 8052 8053 return F.FoundParameter; 8054 } 8055 8056 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. 8057 static inline bool 8058 containsParameters(SmallVectorImpl<const SCEV *> &Terms) { 8059 for (const SCEV *T : Terms) 8060 if (containsParameters(T)) 8061 return true; 8062 return false; 8063 } 8064 8065 // Return the number of product terms in S. 8066 static inline int numberOfTerms(const SCEV *S) { 8067 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) 8068 return Expr->getNumOperands(); 8069 return 1; 8070 } 8071 8072 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { 8073 if (isa<SCEVConstant>(T)) 8074 return nullptr; 8075 8076 if (isa<SCEVUnknown>(T)) 8077 return T; 8078 8079 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { 8080 SmallVector<const SCEV *, 2> Factors; 8081 for (const SCEV *Op : M->operands()) 8082 if (!isa<SCEVConstant>(Op)) 8083 Factors.push_back(Op); 8084 8085 return SE.getMulExpr(Factors); 8086 } 8087 8088 return T; 8089 } 8090 8091 /// Return the size of an element read or written by Inst. 8092 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 8093 Type *Ty; 8094 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 8095 Ty = Store->getValueOperand()->getType(); 8096 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 8097 Ty = Load->getType(); 8098 else 8099 return nullptr; 8100 8101 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 8102 return getSizeOfExpr(ETy, Ty); 8103 } 8104 8105 /// Second step of delinearization: compute the array dimensions Sizes from the 8106 /// set of Terms extracted from the memory access function of this SCEVAddRec. 8107 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, 8108 SmallVectorImpl<const SCEV *> &Sizes, 8109 const SCEV *ElementSize) const { 8110 8111 if (Terms.size() < 1 || !ElementSize) 8112 return; 8113 8114 // Early return when Terms do not contain parameters: we do not delinearize 8115 // non parametric SCEVs. 8116 if (!containsParameters(Terms)) 8117 return; 8118 8119 DEBUG({ 8120 dbgs() << "Terms:\n"; 8121 for (const SCEV *T : Terms) 8122 dbgs() << *T << "\n"; 8123 }); 8124 8125 // Remove duplicates. 8126 std::sort(Terms.begin(), Terms.end()); 8127 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); 8128 8129 // Put larger terms first. 8130 std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) { 8131 return numberOfTerms(LHS) > numberOfTerms(RHS); 8132 }); 8133 8134 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 8135 8136 // Divide all terms by the element size. 8137 for (const SCEV *&Term : Terms) { 8138 const SCEV *Q, *R; 8139 SCEVDivision::divide(SE, Term, ElementSize, &Q, &R); 8140 Term = Q; 8141 } 8142 8143 SmallVector<const SCEV *, 4> NewTerms; 8144 8145 // Remove constant factors. 8146 for (const SCEV *T : Terms) 8147 if (const SCEV *NewT = removeConstantFactors(SE, T)) 8148 NewTerms.push_back(NewT); 8149 8150 DEBUG({ 8151 dbgs() << "Terms after sorting:\n"; 8152 for (const SCEV *T : NewTerms) 8153 dbgs() << *T << "\n"; 8154 }); 8155 8156 if (NewTerms.empty() || 8157 !findArrayDimensionsRec(SE, NewTerms, Sizes)) { 8158 Sizes.clear(); 8159 return; 8160 } 8161 8162 // The last element to be pushed into Sizes is the size of an element. 8163 Sizes.push_back(ElementSize); 8164 8165 DEBUG({ 8166 dbgs() << "Sizes:\n"; 8167 for (const SCEV *S : Sizes) 8168 dbgs() << *S << "\n"; 8169 }); 8170 } 8171 8172 /// Third step of delinearization: compute the access functions for the 8173 /// Subscripts based on the dimensions in Sizes. 8174 void ScalarEvolution::computeAccessFunctions( 8175 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, 8176 SmallVectorImpl<const SCEV *> &Sizes) { 8177 8178 // Early exit in case this SCEV is not an affine multivariate function. 8179 if (Sizes.empty()) 8180 return; 8181 8182 if (auto AR = dyn_cast<SCEVAddRecExpr>(Expr)) 8183 if (!AR->isAffine()) 8184 return; 8185 8186 const SCEV *Res = Expr; 8187 int Last = Sizes.size() - 1; 8188 for (int i = Last; i >= 0; i--) { 8189 const SCEV *Q, *R; 8190 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); 8191 8192 DEBUG({ 8193 dbgs() << "Res: " << *Res << "\n"; 8194 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; 8195 dbgs() << "Res divided by Sizes[i]:\n"; 8196 dbgs() << "Quotient: " << *Q << "\n"; 8197 dbgs() << "Remainder: " << *R << "\n"; 8198 }); 8199 8200 Res = Q; 8201 8202 // Do not record the last subscript corresponding to the size of elements in 8203 // the array. 8204 if (i == Last) { 8205 8206 // Bail out if the remainder is too complex. 8207 if (isa<SCEVAddRecExpr>(R)) { 8208 Subscripts.clear(); 8209 Sizes.clear(); 8210 return; 8211 } 8212 8213 continue; 8214 } 8215 8216 // Record the access function for the current subscript. 8217 Subscripts.push_back(R); 8218 } 8219 8220 // Also push in last position the remainder of the last division: it will be 8221 // the access function of the innermost dimension. 8222 Subscripts.push_back(Res); 8223 8224 std::reverse(Subscripts.begin(), Subscripts.end()); 8225 8226 DEBUG({ 8227 dbgs() << "Subscripts:\n"; 8228 for (const SCEV *S : Subscripts) 8229 dbgs() << *S << "\n"; 8230 }); 8231 } 8232 8233 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and 8234 /// sizes of an array access. Returns the remainder of the delinearization that 8235 /// is the offset start of the array. The SCEV->delinearize algorithm computes 8236 /// the multiples of SCEV coefficients: that is a pattern matching of sub 8237 /// expressions in the stride and base of a SCEV corresponding to the 8238 /// computation of a GCD (greatest common divisor) of base and stride. When 8239 /// SCEV->delinearize fails, it returns the SCEV unchanged. 8240 /// 8241 /// For example: when analyzing the memory access A[i][j][k] in this loop nest 8242 /// 8243 /// void foo(long n, long m, long o, double A[n][m][o]) { 8244 /// 8245 /// for (long i = 0; i < n; i++) 8246 /// for (long j = 0; j < m; j++) 8247 /// for (long k = 0; k < o; k++) 8248 /// A[i][j][k] = 1.0; 8249 /// } 8250 /// 8251 /// the delinearization input is the following AddRec SCEV: 8252 /// 8253 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> 8254 /// 8255 /// From this SCEV, we are able to say that the base offset of the access is %A 8256 /// because it appears as an offset that does not divide any of the strides in 8257 /// the loops: 8258 /// 8259 /// CHECK: Base offset: %A 8260 /// 8261 /// and then SCEV->delinearize determines the size of some of the dimensions of 8262 /// the array as these are the multiples by which the strides are happening: 8263 /// 8264 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. 8265 /// 8266 /// Note that the outermost dimension remains of UnknownSize because there are 8267 /// no strides that would help identifying the size of the last dimension: when 8268 /// the array has been statically allocated, one could compute the size of that 8269 /// dimension by dividing the overall size of the array by the size of the known 8270 /// dimensions: %m * %o * 8. 8271 /// 8272 /// Finally delinearize provides the access functions for the array reference 8273 /// that does correspond to A[i][j][k] of the above C testcase: 8274 /// 8275 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] 8276 /// 8277 /// The testcases are checking the output of a function pass: 8278 /// DelinearizationPass that walks through all loads and stores of a function 8279 /// asking for the SCEV of the memory access with respect to all enclosing 8280 /// loops, calling SCEV->delinearize on that and printing the results. 8281 8282 void ScalarEvolution::delinearize(const SCEV *Expr, 8283 SmallVectorImpl<const SCEV *> &Subscripts, 8284 SmallVectorImpl<const SCEV *> &Sizes, 8285 const SCEV *ElementSize) { 8286 // First step: collect parametric terms. 8287 SmallVector<const SCEV *, 4> Terms; 8288 collectParametricTerms(Expr, Terms); 8289 8290 if (Terms.empty()) 8291 return; 8292 8293 // Second step: find subscript sizes. 8294 findArrayDimensions(Terms, Sizes, ElementSize); 8295 8296 if (Sizes.empty()) 8297 return; 8298 8299 // Third step: compute the access functions for each subscript. 8300 computeAccessFunctions(Expr, Subscripts, Sizes); 8301 8302 if (Subscripts.empty()) 8303 return; 8304 8305 DEBUG({ 8306 dbgs() << "succeeded to delinearize " << *Expr << "\n"; 8307 dbgs() << "ArrayDecl[UnknownSize]"; 8308 for (const SCEV *S : Sizes) 8309 dbgs() << "[" << *S << "]"; 8310 8311 dbgs() << "\nArrayRef"; 8312 for (const SCEV *S : Subscripts) 8313 dbgs() << "[" << *S << "]"; 8314 dbgs() << "\n"; 8315 }); 8316 } 8317 8318 //===----------------------------------------------------------------------===// 8319 // SCEVCallbackVH Class Implementation 8320 //===----------------------------------------------------------------------===// 8321 8322 void ScalarEvolution::SCEVCallbackVH::deleted() { 8323 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 8324 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 8325 SE->ConstantEvolutionLoopExitValue.erase(PN); 8326 SE->ValueExprMap.erase(getValPtr()); 8327 // this now dangles! 8328 } 8329 8330 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 8331 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 8332 8333 // Forget all the expressions associated with users of the old value, 8334 // so that future queries will recompute the expressions using the new 8335 // value. 8336 Value *Old = getValPtr(); 8337 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end()); 8338 SmallPtrSet<User *, 8> Visited; 8339 while (!Worklist.empty()) { 8340 User *U = Worklist.pop_back_val(); 8341 // Deleting the Old value will cause this to dangle. Postpone 8342 // that until everything else is done. 8343 if (U == Old) 8344 continue; 8345 if (!Visited.insert(U).second) 8346 continue; 8347 if (PHINode *PN = dyn_cast<PHINode>(U)) 8348 SE->ConstantEvolutionLoopExitValue.erase(PN); 8349 SE->ValueExprMap.erase(U); 8350 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end()); 8351 } 8352 // Delete the Old value. 8353 if (PHINode *PN = dyn_cast<PHINode>(Old)) 8354 SE->ConstantEvolutionLoopExitValue.erase(PN); 8355 SE->ValueExprMap.erase(Old); 8356 // this now dangles! 8357 } 8358 8359 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 8360 : CallbackVH(V), SE(se) {} 8361 8362 //===----------------------------------------------------------------------===// 8363 // ScalarEvolution Class Implementation 8364 //===----------------------------------------------------------------------===// 8365 8366 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 8367 AssumptionCache &AC, DominatorTree &DT, 8368 LoopInfo &LI) 8369 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 8370 CouldNotCompute(new SCEVCouldNotCompute()), 8371 WalkingBEDominatingConds(false), ValuesAtScopes(64), LoopDispositions(64), 8372 BlockDispositions(64), FirstUnknown(nullptr) {} 8373 8374 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 8375 : F(Arg.F), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), LI(Arg.LI), 8376 CouldNotCompute(std::move(Arg.CouldNotCompute)), 8377 ValueExprMap(std::move(Arg.ValueExprMap)), 8378 WalkingBEDominatingConds(false), 8379 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 8380 ConstantEvolutionLoopExitValue( 8381 std::move(Arg.ConstantEvolutionLoopExitValue)), 8382 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 8383 LoopDispositions(std::move(Arg.LoopDispositions)), 8384 BlockDispositions(std::move(Arg.BlockDispositions)), 8385 UnsignedRanges(std::move(Arg.UnsignedRanges)), 8386 SignedRanges(std::move(Arg.SignedRanges)), 8387 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 8388 SCEVAllocator(std::move(Arg.SCEVAllocator)), 8389 FirstUnknown(Arg.FirstUnknown) { 8390 Arg.FirstUnknown = nullptr; 8391 } 8392 8393 ScalarEvolution::~ScalarEvolution() { 8394 // Iterate through all the SCEVUnknown instances and call their 8395 // destructors, so that they release their references to their values. 8396 for (SCEVUnknown *U = FirstUnknown; U;) { 8397 SCEVUnknown *Tmp = U; 8398 U = U->Next; 8399 Tmp->~SCEVUnknown(); 8400 } 8401 FirstUnknown = nullptr; 8402 8403 ValueExprMap.clear(); 8404 8405 // Free any extra memory created for ExitNotTakenInfo in the unlikely event 8406 // that a loop had multiple computable exits. 8407 for (DenseMap<const Loop*, BackedgeTakenInfo>::iterator I = 8408 BackedgeTakenCounts.begin(), E = BackedgeTakenCounts.end(); 8409 I != E; ++I) { 8410 I->second.clear(); 8411 } 8412 8413 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 8414 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 8415 } 8416 8417 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 8418 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 8419 } 8420 8421 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 8422 const Loop *L) { 8423 // Print all inner loops first 8424 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I) 8425 PrintLoopInfo(OS, SE, *I); 8426 8427 OS << "Loop "; 8428 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 8429 OS << ": "; 8430 8431 SmallVector<BasicBlock *, 8> ExitBlocks; 8432 L->getExitBlocks(ExitBlocks); 8433 if (ExitBlocks.size() != 1) 8434 OS << "<multiple exits> "; 8435 8436 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 8437 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L); 8438 } else { 8439 OS << "Unpredictable backedge-taken count. "; 8440 } 8441 8442 OS << "\n" 8443 "Loop "; 8444 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 8445 OS << ": "; 8446 8447 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) { 8448 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L); 8449 } else { 8450 OS << "Unpredictable max backedge-taken count. "; 8451 } 8452 8453 OS << "\n"; 8454 } 8455 8456 void ScalarEvolution::print(raw_ostream &OS) const { 8457 // ScalarEvolution's implementation of the print method is to print 8458 // out SCEV values of all instructions that are interesting. Doing 8459 // this potentially causes it to create new SCEV objects though, 8460 // which technically conflicts with the const qualifier. This isn't 8461 // observable from outside the class though, so casting away the 8462 // const isn't dangerous. 8463 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 8464 8465 OS << "Classifying expressions for: "; 8466 F.printAsOperand(OS, /*PrintType=*/false); 8467 OS << "\n"; 8468 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) 8469 if (isSCEVable(I->getType()) && !isa<CmpInst>(*I)) { 8470 OS << *I << '\n'; 8471 OS << " --> "; 8472 const SCEV *SV = SE.getSCEV(&*I); 8473 SV->print(OS); 8474 if (!isa<SCEVCouldNotCompute>(SV)) { 8475 OS << " U: "; 8476 SE.getUnsignedRange(SV).print(OS); 8477 OS << " S: "; 8478 SE.getSignedRange(SV).print(OS); 8479 } 8480 8481 const Loop *L = LI.getLoopFor((*I).getParent()); 8482 8483 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 8484 if (AtUse != SV) { 8485 OS << " --> "; 8486 AtUse->print(OS); 8487 if (!isa<SCEVCouldNotCompute>(AtUse)) { 8488 OS << " U: "; 8489 SE.getUnsignedRange(AtUse).print(OS); 8490 OS << " S: "; 8491 SE.getSignedRange(AtUse).print(OS); 8492 } 8493 } 8494 8495 if (L) { 8496 OS << "\t\t" "Exits: "; 8497 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 8498 if (!SE.isLoopInvariant(ExitValue, L)) { 8499 OS << "<<Unknown>>"; 8500 } else { 8501 OS << *ExitValue; 8502 } 8503 } 8504 8505 OS << "\n"; 8506 } 8507 8508 OS << "Determining loop execution counts for: "; 8509 F.printAsOperand(OS, /*PrintType=*/false); 8510 OS << "\n"; 8511 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I) 8512 PrintLoopInfo(OS, &SE, *I); 8513 } 8514 8515 ScalarEvolution::LoopDisposition 8516 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 8517 auto &Values = LoopDispositions[S]; 8518 for (auto &V : Values) { 8519 if (V.getPointer() == L) 8520 return V.getInt(); 8521 } 8522 Values.emplace_back(L, LoopVariant); 8523 LoopDisposition D = computeLoopDisposition(S, L); 8524 auto &Values2 = LoopDispositions[S]; 8525 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 8526 if (V.getPointer() == L) { 8527 V.setInt(D); 8528 break; 8529 } 8530 } 8531 return D; 8532 } 8533 8534 ScalarEvolution::LoopDisposition 8535 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 8536 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 8537 case scConstant: 8538 return LoopInvariant; 8539 case scTruncate: 8540 case scZeroExtend: 8541 case scSignExtend: 8542 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 8543 case scAddRecExpr: { 8544 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 8545 8546 // If L is the addrec's loop, it's computable. 8547 if (AR->getLoop() == L) 8548 return LoopComputable; 8549 8550 // Add recurrences are never invariant in the function-body (null loop). 8551 if (!L) 8552 return LoopVariant; 8553 8554 // This recurrence is variant w.r.t. L if L contains AR's loop. 8555 if (L->contains(AR->getLoop())) 8556 return LoopVariant; 8557 8558 // This recurrence is invariant w.r.t. L if AR's loop contains L. 8559 if (AR->getLoop()->contains(L)) 8560 return LoopInvariant; 8561 8562 // This recurrence is variant w.r.t. L if any of its operands 8563 // are variant. 8564 for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end(); 8565 I != E; ++I) 8566 if (!isLoopInvariant(*I, L)) 8567 return LoopVariant; 8568 8569 // Otherwise it's loop-invariant. 8570 return LoopInvariant; 8571 } 8572 case scAddExpr: 8573 case scMulExpr: 8574 case scUMaxExpr: 8575 case scSMaxExpr: { 8576 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 8577 bool HasVarying = false; 8578 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end(); 8579 I != E; ++I) { 8580 LoopDisposition D = getLoopDisposition(*I, L); 8581 if (D == LoopVariant) 8582 return LoopVariant; 8583 if (D == LoopComputable) 8584 HasVarying = true; 8585 } 8586 return HasVarying ? LoopComputable : LoopInvariant; 8587 } 8588 case scUDivExpr: { 8589 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 8590 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 8591 if (LD == LoopVariant) 8592 return LoopVariant; 8593 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 8594 if (RD == LoopVariant) 8595 return LoopVariant; 8596 return (LD == LoopInvariant && RD == LoopInvariant) ? 8597 LoopInvariant : LoopComputable; 8598 } 8599 case scUnknown: 8600 // All non-instruction values are loop invariant. All instructions are loop 8601 // invariant if they are not contained in the specified loop. 8602 // Instructions are never considered invariant in the function body 8603 // (null loop) because they are defined within the "loop". 8604 if (Instruction *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 8605 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 8606 return LoopInvariant; 8607 case scCouldNotCompute: 8608 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 8609 } 8610 llvm_unreachable("Unknown SCEV kind!"); 8611 } 8612 8613 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 8614 return getLoopDisposition(S, L) == LoopInvariant; 8615 } 8616 8617 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 8618 return getLoopDisposition(S, L) == LoopComputable; 8619 } 8620 8621 ScalarEvolution::BlockDisposition 8622 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 8623 auto &Values = BlockDispositions[S]; 8624 for (auto &V : Values) { 8625 if (V.getPointer() == BB) 8626 return V.getInt(); 8627 } 8628 Values.emplace_back(BB, DoesNotDominateBlock); 8629 BlockDisposition D = computeBlockDisposition(S, BB); 8630 auto &Values2 = BlockDispositions[S]; 8631 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 8632 if (V.getPointer() == BB) { 8633 V.setInt(D); 8634 break; 8635 } 8636 } 8637 return D; 8638 } 8639 8640 ScalarEvolution::BlockDisposition 8641 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 8642 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 8643 case scConstant: 8644 return ProperlyDominatesBlock; 8645 case scTruncate: 8646 case scZeroExtend: 8647 case scSignExtend: 8648 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 8649 case scAddRecExpr: { 8650 // This uses a "dominates" query instead of "properly dominates" query 8651 // to test for proper dominance too, because the instruction which 8652 // produces the addrec's value is a PHI, and a PHI effectively properly 8653 // dominates its entire containing block. 8654 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 8655 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 8656 return DoesNotDominateBlock; 8657 } 8658 // FALL THROUGH into SCEVNAryExpr handling. 8659 case scAddExpr: 8660 case scMulExpr: 8661 case scUMaxExpr: 8662 case scSMaxExpr: { 8663 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 8664 bool Proper = true; 8665 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end(); 8666 I != E; ++I) { 8667 BlockDisposition D = getBlockDisposition(*I, BB); 8668 if (D == DoesNotDominateBlock) 8669 return DoesNotDominateBlock; 8670 if (D == DominatesBlock) 8671 Proper = false; 8672 } 8673 return Proper ? ProperlyDominatesBlock : DominatesBlock; 8674 } 8675 case scUDivExpr: { 8676 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 8677 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 8678 BlockDisposition LD = getBlockDisposition(LHS, BB); 8679 if (LD == DoesNotDominateBlock) 8680 return DoesNotDominateBlock; 8681 BlockDisposition RD = getBlockDisposition(RHS, BB); 8682 if (RD == DoesNotDominateBlock) 8683 return DoesNotDominateBlock; 8684 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 8685 ProperlyDominatesBlock : DominatesBlock; 8686 } 8687 case scUnknown: 8688 if (Instruction *I = 8689 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 8690 if (I->getParent() == BB) 8691 return DominatesBlock; 8692 if (DT.properlyDominates(I->getParent(), BB)) 8693 return ProperlyDominatesBlock; 8694 return DoesNotDominateBlock; 8695 } 8696 return ProperlyDominatesBlock; 8697 case scCouldNotCompute: 8698 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 8699 } 8700 llvm_unreachable("Unknown SCEV kind!"); 8701 } 8702 8703 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 8704 return getBlockDisposition(S, BB) >= DominatesBlock; 8705 } 8706 8707 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 8708 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 8709 } 8710 8711 namespace { 8712 // Search for a SCEV expression node within an expression tree. 8713 // Implements SCEVTraversal::Visitor. 8714 struct SCEVSearch { 8715 const SCEV *Node; 8716 bool IsFound; 8717 8718 SCEVSearch(const SCEV *N): Node(N), IsFound(false) {} 8719 8720 bool follow(const SCEV *S) { 8721 IsFound |= (S == Node); 8722 return !IsFound; 8723 } 8724 bool isDone() const { return IsFound; } 8725 }; 8726 } 8727 8728 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 8729 SCEVSearch Search(Op); 8730 visitAll(S, Search); 8731 return Search.IsFound; 8732 } 8733 8734 void ScalarEvolution::forgetMemoizedResults(const SCEV *S) { 8735 ValuesAtScopes.erase(S); 8736 LoopDispositions.erase(S); 8737 BlockDispositions.erase(S); 8738 UnsignedRanges.erase(S); 8739 SignedRanges.erase(S); 8740 8741 for (DenseMap<const Loop*, BackedgeTakenInfo>::iterator I = 8742 BackedgeTakenCounts.begin(), E = BackedgeTakenCounts.end(); I != E; ) { 8743 BackedgeTakenInfo &BEInfo = I->second; 8744 if (BEInfo.hasOperand(S, this)) { 8745 BEInfo.clear(); 8746 BackedgeTakenCounts.erase(I++); 8747 } 8748 else 8749 ++I; 8750 } 8751 } 8752 8753 typedef DenseMap<const Loop *, std::string> VerifyMap; 8754 8755 /// replaceSubString - Replaces all occurrences of From in Str with To. 8756 static void replaceSubString(std::string &Str, StringRef From, StringRef To) { 8757 size_t Pos = 0; 8758 while ((Pos = Str.find(From, Pos)) != std::string::npos) { 8759 Str.replace(Pos, From.size(), To.data(), To.size()); 8760 Pos += To.size(); 8761 } 8762 } 8763 8764 /// getLoopBackedgeTakenCounts - Helper method for verifyAnalysis. 8765 static void 8766 getLoopBackedgeTakenCounts(Loop *L, VerifyMap &Map, ScalarEvolution &SE) { 8767 for (Loop::reverse_iterator I = L->rbegin(), E = L->rend(); I != E; ++I) { 8768 getLoopBackedgeTakenCounts(*I, Map, SE); // recurse. 8769 8770 std::string &S = Map[L]; 8771 if (S.empty()) { 8772 raw_string_ostream OS(S); 8773 SE.getBackedgeTakenCount(L)->print(OS); 8774 8775 // false and 0 are semantically equivalent. This can happen in dead loops. 8776 replaceSubString(OS.str(), "false", "0"); 8777 // Remove wrap flags, their use in SCEV is highly fragile. 8778 // FIXME: Remove this when SCEV gets smarter about them. 8779 replaceSubString(OS.str(), "<nw>", ""); 8780 replaceSubString(OS.str(), "<nsw>", ""); 8781 replaceSubString(OS.str(), "<nuw>", ""); 8782 } 8783 } 8784 } 8785 8786 void ScalarEvolution::verify() const { 8787 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 8788 8789 // Gather stringified backedge taken counts for all loops using SCEV's caches. 8790 // FIXME: It would be much better to store actual values instead of strings, 8791 // but SCEV pointers will change if we drop the caches. 8792 VerifyMap BackedgeDumpsOld, BackedgeDumpsNew; 8793 for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I) 8794 getLoopBackedgeTakenCounts(*I, BackedgeDumpsOld, SE); 8795 8796 // Gather stringified backedge taken counts for all loops using a fresh 8797 // ScalarEvolution object. 8798 ScalarEvolution SE2(F, TLI, AC, DT, LI); 8799 for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I) 8800 getLoopBackedgeTakenCounts(*I, BackedgeDumpsNew, SE2); 8801 8802 // Now compare whether they're the same with and without caches. This allows 8803 // verifying that no pass changed the cache. 8804 assert(BackedgeDumpsOld.size() == BackedgeDumpsNew.size() && 8805 "New loops suddenly appeared!"); 8806 8807 for (VerifyMap::iterator OldI = BackedgeDumpsOld.begin(), 8808 OldE = BackedgeDumpsOld.end(), 8809 NewI = BackedgeDumpsNew.begin(); 8810 OldI != OldE; ++OldI, ++NewI) { 8811 assert(OldI->first == NewI->first && "Loop order changed!"); 8812 8813 // Compare the stringified SCEVs. We don't care if undef backedgetaken count 8814 // changes. 8815 // FIXME: We currently ignore SCEV changes from/to CouldNotCompute. This 8816 // means that a pass is buggy or SCEV has to learn a new pattern but is 8817 // usually not harmful. 8818 if (OldI->second != NewI->second && 8819 OldI->second.find("undef") == std::string::npos && 8820 NewI->second.find("undef") == std::string::npos && 8821 OldI->second != "***COULDNOTCOMPUTE***" && 8822 NewI->second != "***COULDNOTCOMPUTE***") { 8823 dbgs() << "SCEVValidator: SCEV for loop '" 8824 << OldI->first->getHeader()->getName() 8825 << "' changed from '" << OldI->second 8826 << "' to '" << NewI->second << "'!\n"; 8827 std::abort(); 8828 } 8829 } 8830 8831 // TODO: Verify more things. 8832 } 8833 8834 char ScalarEvolutionAnalysis::PassID; 8835 8836 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 8837 AnalysisManager<Function> *AM) { 8838 return ScalarEvolution(F, AM->getResult<TargetLibraryAnalysis>(F), 8839 AM->getResult<AssumptionAnalysis>(F), 8840 AM->getResult<DominatorTreeAnalysis>(F), 8841 AM->getResult<LoopAnalysis>(F)); 8842 } 8843 8844 PreservedAnalyses 8845 ScalarEvolutionPrinterPass::run(Function &F, AnalysisManager<Function> *AM) { 8846 AM->getResult<ScalarEvolutionAnalysis>(F).print(OS); 8847 return PreservedAnalyses::all(); 8848 } 8849 8850 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 8851 "Scalar Evolution Analysis", false, true) 8852 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 8853 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 8854 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 8855 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 8856 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 8857 "Scalar Evolution Analysis", false, true) 8858 char ScalarEvolutionWrapperPass::ID = 0; 8859 8860 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 8861 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 8862 } 8863 8864 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 8865 SE.reset(new ScalarEvolution( 8866 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(), 8867 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 8868 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 8869 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 8870 return false; 8871 } 8872 8873 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 8874 8875 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 8876 SE->print(OS); 8877 } 8878 8879 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 8880 if (!VerifySCEV) 8881 return; 8882 8883 SE->verify(); 8884 } 8885 8886 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 8887 AU.setPreservesAll(); 8888 AU.addRequiredTransitive<AssumptionCacheTracker>(); 8889 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 8890 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 8891 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 8892 } 8893