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