1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===// 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. These classes are reference counted, managed by the SCEVHandle 18 // class. We only create one SCEV of a particular shape, so pointer-comparisons 19 // for equality are legal. 20 // 21 // One important aspect of the SCEV objects is that they are never cyclic, even 22 // if there is a cycle in the dataflow for an expression (ie, a PHI node). If 23 // the PHI node is one of the idioms that we can represent (e.g., a polynomial 24 // recurrence) then we represent it directly as a recurrence node, otherwise we 25 // represent it as a SCEVUnknown node. 26 // 27 // In addition to being able to represent expressions of various types, we also 28 // have folders that are used to build the *canonical* representation for a 29 // particular expression. These folders are capable of using a variety of 30 // rewrite rules to simplify the expressions. 31 // 32 // Once the folders are defined, we can implement the more interesting 33 // higher-level code, such as the code that recognizes PHI nodes of various 34 // types, computes the execution count of a loop, etc. 35 // 36 // TODO: We should use these routines and value representations to implement 37 // dependence analysis! 38 // 39 //===----------------------------------------------------------------------===// 40 // 41 // There are several good references for the techniques used in this analysis. 42 // 43 // Chains of recurrences -- a method to expedite the evaluation 44 // of closed-form functions 45 // Olaf Bachmann, Paul S. Wang, Eugene V. Zima 46 // 47 // On computational properties of chains of recurrences 48 // Eugene V. Zima 49 // 50 // Symbolic Evaluation of Chains of Recurrences for Loop Optimization 51 // Robert A. van Engelen 52 // 53 // Efficient Symbolic Analysis for Optimizing Compilers 54 // Robert A. van Engelen 55 // 56 // Using the chains of recurrences algebra for data dependence testing and 57 // induction variable substitution 58 // MS Thesis, Johnie Birch 59 // 60 //===----------------------------------------------------------------------===// 61 62 #define DEBUG_TYPE "scalar-evolution" 63 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 64 #include "llvm/Constants.h" 65 #include "llvm/DerivedTypes.h" 66 #include "llvm/GlobalVariable.h" 67 #include "llvm/Instructions.h" 68 #include "llvm/Analysis/ConstantFolding.h" 69 #include "llvm/Analysis/Dominators.h" 70 #include "llvm/Analysis/LoopInfo.h" 71 #include "llvm/Assembly/Writer.h" 72 #include "llvm/Target/TargetData.h" 73 #include "llvm/Transforms/Scalar.h" 74 #include "llvm/Support/CFG.h" 75 #include "llvm/Support/CommandLine.h" 76 #include "llvm/Support/Compiler.h" 77 #include "llvm/Support/ConstantRange.h" 78 #include "llvm/Support/GetElementPtrTypeIterator.h" 79 #include "llvm/Support/InstIterator.h" 80 #include "llvm/Support/ManagedStatic.h" 81 #include "llvm/Support/MathExtras.h" 82 #include "llvm/Support/raw_ostream.h" 83 #include "llvm/ADT/Statistic.h" 84 #include "llvm/ADT/STLExtras.h" 85 #include <ostream> 86 #include <algorithm> 87 #include <cmath> 88 using namespace llvm; 89 90 STATISTIC(NumArrayLenItCounts, 91 "Number of trip counts computed with array length"); 92 STATISTIC(NumTripCountsComputed, 93 "Number of loops with predictable loop counts"); 94 STATISTIC(NumTripCountsNotComputed, 95 "Number of loops without predictable loop counts"); 96 STATISTIC(NumBruteForceTripCountsComputed, 97 "Number of loops with trip counts computed by force"); 98 99 static cl::opt<unsigned> 100 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, 101 cl::desc("Maximum number of iterations SCEV will " 102 "symbolically execute a constant derived loop"), 103 cl::init(100)); 104 105 static RegisterPass<ScalarEvolution> 106 R("scalar-evolution", "Scalar Evolution Analysis", false, true); 107 char ScalarEvolution::ID = 0; 108 109 //===----------------------------------------------------------------------===// 110 // SCEV class definitions 111 //===----------------------------------------------------------------------===// 112 113 //===----------------------------------------------------------------------===// 114 // Implementation of the SCEV class. 115 // 116 SCEV::~SCEV() {} 117 void SCEV::dump() const { 118 print(errs()); 119 errs() << '\n'; 120 } 121 122 void SCEV::print(std::ostream &o) const { 123 raw_os_ostream OS(o); 124 print(OS); 125 } 126 127 bool SCEV::isZero() const { 128 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 129 return SC->getValue()->isZero(); 130 return false; 131 } 132 133 134 SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {} 135 SCEVCouldNotCompute::~SCEVCouldNotCompute() {} 136 137 bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const { 138 assert(0 && "Attempt to use a SCEVCouldNotCompute object!"); 139 return false; 140 } 141 142 const Type *SCEVCouldNotCompute::getType() const { 143 assert(0 && "Attempt to use a SCEVCouldNotCompute object!"); 144 return 0; 145 } 146 147 bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const { 148 assert(0 && "Attempt to use a SCEVCouldNotCompute object!"); 149 return false; 150 } 151 152 SCEVHandle SCEVCouldNotCompute:: 153 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym, 154 const SCEVHandle &Conc, 155 ScalarEvolution &SE) const { 156 return this; 157 } 158 159 void SCEVCouldNotCompute::print(raw_ostream &OS) const { 160 OS << "***COULDNOTCOMPUTE***"; 161 } 162 163 bool SCEVCouldNotCompute::classof(const SCEV *S) { 164 return S->getSCEVType() == scCouldNotCompute; 165 } 166 167 168 // SCEVConstants - Only allow the creation of one SCEVConstant for any 169 // particular value. Don't use a SCEVHandle here, or else the object will 170 // never be deleted! 171 static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants; 172 173 174 SCEVConstant::~SCEVConstant() { 175 SCEVConstants->erase(V); 176 } 177 178 SCEVHandle ScalarEvolution::getConstant(ConstantInt *V) { 179 SCEVConstant *&R = (*SCEVConstants)[V]; 180 if (R == 0) R = new SCEVConstant(V); 181 return R; 182 } 183 184 SCEVHandle ScalarEvolution::getConstant(const APInt& Val) { 185 return getConstant(ConstantInt::get(Val)); 186 } 187 188 const Type *SCEVConstant::getType() const { return V->getType(); } 189 190 void SCEVConstant::print(raw_ostream &OS) const { 191 WriteAsOperand(OS, V, false); 192 } 193 194 SCEVCastExpr::SCEVCastExpr(unsigned SCEVTy, 195 const SCEVHandle &op, const Type *ty) 196 : SCEV(SCEVTy), Op(op), Ty(ty) {} 197 198 SCEVCastExpr::~SCEVCastExpr() {} 199 200 bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const { 201 return Op->dominates(BB, DT); 202 } 203 204 // SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any 205 // particular input. Don't use a SCEVHandle here, or else the object will 206 // never be deleted! 207 static ManagedStatic<std::map<std::pair<SCEV*, const Type*>, 208 SCEVTruncateExpr*> > SCEVTruncates; 209 210 SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty) 211 : SCEVCastExpr(scTruncate, op, ty) { 212 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) && 213 (Ty->isInteger() || isa<PointerType>(Ty)) && 214 "Cannot truncate non-integer value!"); 215 } 216 217 SCEVTruncateExpr::~SCEVTruncateExpr() { 218 SCEVTruncates->erase(std::make_pair(Op, Ty)); 219 } 220 221 void SCEVTruncateExpr::print(raw_ostream &OS) const { 222 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")"; 223 } 224 225 // SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any 226 // particular input. Don't use a SCEVHandle here, or else the object will never 227 // be deleted! 228 static ManagedStatic<std::map<std::pair<SCEV*, const Type*>, 229 SCEVZeroExtendExpr*> > SCEVZeroExtends; 230 231 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty) 232 : SCEVCastExpr(scZeroExtend, op, ty) { 233 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) && 234 (Ty->isInteger() || isa<PointerType>(Ty)) && 235 "Cannot zero extend non-integer value!"); 236 } 237 238 SCEVZeroExtendExpr::~SCEVZeroExtendExpr() { 239 SCEVZeroExtends->erase(std::make_pair(Op, Ty)); 240 } 241 242 void SCEVZeroExtendExpr::print(raw_ostream &OS) const { 243 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")"; 244 } 245 246 // SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any 247 // particular input. Don't use a SCEVHandle here, or else the object will never 248 // be deleted! 249 static ManagedStatic<std::map<std::pair<SCEV*, const Type*>, 250 SCEVSignExtendExpr*> > SCEVSignExtends; 251 252 SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty) 253 : SCEVCastExpr(scSignExtend, op, ty) { 254 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) && 255 (Ty->isInteger() || isa<PointerType>(Ty)) && 256 "Cannot sign extend non-integer value!"); 257 } 258 259 SCEVSignExtendExpr::~SCEVSignExtendExpr() { 260 SCEVSignExtends->erase(std::make_pair(Op, Ty)); 261 } 262 263 void SCEVSignExtendExpr::print(raw_ostream &OS) const { 264 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")"; 265 } 266 267 // SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any 268 // particular input. Don't use a SCEVHandle here, or else the object will never 269 // be deleted! 270 static ManagedStatic<std::map<std::pair<unsigned, std::vector<SCEV*> >, 271 SCEVCommutativeExpr*> > SCEVCommExprs; 272 273 SCEVCommutativeExpr::~SCEVCommutativeExpr() { 274 SCEVCommExprs->erase(std::make_pair(getSCEVType(), 275 std::vector<SCEV*>(Operands.begin(), 276 Operands.end()))); 277 } 278 279 void SCEVCommutativeExpr::print(raw_ostream &OS) const { 280 assert(Operands.size() > 1 && "This plus expr shouldn't exist!"); 281 const char *OpStr = getOperationStr(); 282 OS << "(" << *Operands[0]; 283 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 284 OS << OpStr << *Operands[i]; 285 OS << ")"; 286 } 287 288 SCEVHandle SCEVCommutativeExpr:: 289 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym, 290 const SCEVHandle &Conc, 291 ScalarEvolution &SE) const { 292 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 293 SCEVHandle H = 294 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE); 295 if (H != getOperand(i)) { 296 std::vector<SCEVHandle> NewOps; 297 NewOps.reserve(getNumOperands()); 298 for (unsigned j = 0; j != i; ++j) 299 NewOps.push_back(getOperand(j)); 300 NewOps.push_back(H); 301 for (++i; i != e; ++i) 302 NewOps.push_back(getOperand(i)-> 303 replaceSymbolicValuesWithConcrete(Sym, Conc, SE)); 304 305 if (isa<SCEVAddExpr>(this)) 306 return SE.getAddExpr(NewOps); 307 else if (isa<SCEVMulExpr>(this)) 308 return SE.getMulExpr(NewOps); 309 else if (isa<SCEVSMaxExpr>(this)) 310 return SE.getSMaxExpr(NewOps); 311 else if (isa<SCEVUMaxExpr>(this)) 312 return SE.getUMaxExpr(NewOps); 313 else 314 assert(0 && "Unknown commutative expr!"); 315 } 316 } 317 return this; 318 } 319 320 bool SCEVCommutativeExpr::dominates(BasicBlock *BB, DominatorTree *DT) const { 321 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 322 if (!getOperand(i)->dominates(BB, DT)) 323 return false; 324 } 325 return true; 326 } 327 328 329 // SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular 330 // input. Don't use a SCEVHandle here, or else the object will never be 331 // deleted! 332 static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>, 333 SCEVUDivExpr*> > SCEVUDivs; 334 335 SCEVUDivExpr::~SCEVUDivExpr() { 336 SCEVUDivs->erase(std::make_pair(LHS, RHS)); 337 } 338 339 bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const { 340 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT); 341 } 342 343 void SCEVUDivExpr::print(raw_ostream &OS) const { 344 OS << "(" << *LHS << " /u " << *RHS << ")"; 345 } 346 347 const Type *SCEVUDivExpr::getType() const { 348 return LHS->getType(); 349 } 350 351 // SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any 352 // particular input. Don't use a SCEVHandle here, or else the object will never 353 // be deleted! 354 static ManagedStatic<std::map<std::pair<const Loop *, std::vector<SCEV*> >, 355 SCEVAddRecExpr*> > SCEVAddRecExprs; 356 357 SCEVAddRecExpr::~SCEVAddRecExpr() { 358 SCEVAddRecExprs->erase(std::make_pair(L, 359 std::vector<SCEV*>(Operands.begin(), 360 Operands.end()))); 361 } 362 363 bool SCEVAddRecExpr::dominates(BasicBlock *BB, DominatorTree *DT) const { 364 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 365 if (!getOperand(i)->dominates(BB, DT)) 366 return false; 367 } 368 return true; 369 } 370 371 372 SCEVHandle SCEVAddRecExpr:: 373 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym, 374 const SCEVHandle &Conc, 375 ScalarEvolution &SE) const { 376 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 377 SCEVHandle H = 378 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE); 379 if (H != getOperand(i)) { 380 std::vector<SCEVHandle> NewOps; 381 NewOps.reserve(getNumOperands()); 382 for (unsigned j = 0; j != i; ++j) 383 NewOps.push_back(getOperand(j)); 384 NewOps.push_back(H); 385 for (++i; i != e; ++i) 386 NewOps.push_back(getOperand(i)-> 387 replaceSymbolicValuesWithConcrete(Sym, Conc, SE)); 388 389 return SE.getAddRecExpr(NewOps, L); 390 } 391 } 392 return this; 393 } 394 395 396 bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const { 397 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't 398 // contain L and if the start is invariant. 399 return !QueryLoop->contains(L->getHeader()) && 400 getOperand(0)->isLoopInvariant(QueryLoop); 401 } 402 403 404 void SCEVAddRecExpr::print(raw_ostream &OS) const { 405 OS << "{" << *Operands[0]; 406 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 407 OS << ",+," << *Operands[i]; 408 OS << "}<" << L->getHeader()->getName() + ">"; 409 } 410 411 // SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular 412 // value. Don't use a SCEVHandle here, or else the object will never be 413 // deleted! 414 static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns; 415 416 SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); } 417 418 bool SCEVUnknown::isLoopInvariant(const Loop *L) const { 419 // All non-instruction values are loop invariant. All instructions are loop 420 // invariant if they are not contained in the specified loop. 421 if (Instruction *I = dyn_cast<Instruction>(V)) 422 return !L->contains(I->getParent()); 423 return true; 424 } 425 426 bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const { 427 if (Instruction *I = dyn_cast<Instruction>(getValue())) 428 return DT->dominates(I->getParent(), BB); 429 return true; 430 } 431 432 const Type *SCEVUnknown::getType() const { 433 return V->getType(); 434 } 435 436 void SCEVUnknown::print(raw_ostream &OS) const { 437 if (isa<PointerType>(V->getType())) 438 OS << "(ptrtoint " << *V->getType() << " "; 439 WriteAsOperand(OS, V, false); 440 if (isa<PointerType>(V->getType())) 441 OS << " to iPTR)"; 442 } 443 444 //===----------------------------------------------------------------------===// 445 // SCEV Utilities 446 //===----------------------------------------------------------------------===// 447 448 namespace { 449 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less 450 /// than the complexity of the RHS. This comparator is used to canonicalize 451 /// expressions. 452 struct VISIBILITY_HIDDEN SCEVComplexityCompare { 453 bool operator()(const SCEV *LHS, const SCEV *RHS) const { 454 return LHS->getSCEVType() < RHS->getSCEVType(); 455 } 456 }; 457 } 458 459 /// GroupByComplexity - Given a list of SCEV objects, order them by their 460 /// complexity, and group objects of the same complexity together by value. 461 /// When this routine is finished, we know that any duplicates in the vector are 462 /// consecutive and that complexity is monotonically increasing. 463 /// 464 /// Note that we go take special precautions to ensure that we get determinstic 465 /// results from this routine. In other words, we don't want the results of 466 /// this to depend on where the addresses of various SCEV objects happened to 467 /// land in memory. 468 /// 469 static void GroupByComplexity(std::vector<SCEVHandle> &Ops) { 470 if (Ops.size() < 2) return; // Noop 471 if (Ops.size() == 2) { 472 // This is the common case, which also happens to be trivially simple. 473 // Special case it. 474 if (SCEVComplexityCompare()(Ops[1], Ops[0])) 475 std::swap(Ops[0], Ops[1]); 476 return; 477 } 478 479 // Do the rough sort by complexity. 480 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare()); 481 482 // Now that we are sorted by complexity, group elements of the same 483 // complexity. Note that this is, at worst, N^2, but the vector is likely to 484 // be extremely short in practice. Note that we take this approach because we 485 // do not want to depend on the addresses of the objects we are grouping. 486 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { 487 SCEV *S = Ops[i]; 488 unsigned Complexity = S->getSCEVType(); 489 490 // If there are any objects of the same complexity and same value as this 491 // one, group them. 492 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { 493 if (Ops[j] == S) { // Found a duplicate. 494 // Move it to immediately after i'th element. 495 std::swap(Ops[i+1], Ops[j]); 496 ++i; // no need to rescan it. 497 if (i == e-2) return; // Done! 498 } 499 } 500 } 501 } 502 503 504 505 //===----------------------------------------------------------------------===// 506 // Simple SCEV method implementations 507 //===----------------------------------------------------------------------===// 508 509 /// BinomialCoefficient - Compute BC(It, K). The result has width W. 510 // Assume, K > 0. 511 static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K, 512 ScalarEvolution &SE, 513 const Type* ResultTy) { 514 // Handle the simplest case efficiently. 515 if (K == 1) 516 return SE.getTruncateOrZeroExtend(It, ResultTy); 517 518 // We are using the following formula for BC(It, K): 519 // 520 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! 521 // 522 // Suppose, W is the bitwidth of the return value. We must be prepared for 523 // overflow. Hence, we must assure that the result of our computation is 524 // equal to the accurate one modulo 2^W. Unfortunately, division isn't 525 // safe in modular arithmetic. 526 // 527 // However, this code doesn't use exactly that formula; the formula it uses 528 // is something like the following, where T is the number of factors of 2 in 529 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is 530 // exponentiation: 531 // 532 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) 533 // 534 // This formula is trivially equivalent to the previous formula. However, 535 // this formula can be implemented much more efficiently. The trick is that 536 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular 537 // arithmetic. To do exact division in modular arithmetic, all we have 538 // to do is multiply by the inverse. Therefore, this step can be done at 539 // width W. 540 // 541 // The next issue is how to safely do the division by 2^T. The way this 542 // is done is by doing the multiplication step at a width of at least W + T 543 // bits. This way, the bottom W+T bits of the product are accurate. Then, 544 // when we perform the division by 2^T (which is equivalent to a right shift 545 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get 546 // truncated out after the division by 2^T. 547 // 548 // In comparison to just directly using the first formula, this technique 549 // is much more efficient; using the first formula requires W * K bits, 550 // but this formula less than W + K bits. Also, the first formula requires 551 // a division step, whereas this formula only requires multiplies and shifts. 552 // 553 // It doesn't matter whether the subtraction step is done in the calculation 554 // width or the input iteration count's width; if the subtraction overflows, 555 // the result must be zero anyway. We prefer here to do it in the width of 556 // the induction variable because it helps a lot for certain cases; CodeGen 557 // isn't smart enough to ignore the overflow, which leads to much less 558 // efficient code if the width of the subtraction is wider than the native 559 // register width. 560 // 561 // (It's possible to not widen at all by pulling out factors of 2 before 562 // the multiplication; for example, K=2 can be calculated as 563 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires 564 // extra arithmetic, so it's not an obvious win, and it gets 565 // much more complicated for K > 3.) 566 567 // Protection from insane SCEVs; this bound is conservative, 568 // but it probably doesn't matter. 569 if (K > 1000) 570 return SE.getCouldNotCompute(); 571 572 unsigned W = SE.getTypeSizeInBits(ResultTy); 573 574 // Calculate K! / 2^T and T; we divide out the factors of two before 575 // multiplying for calculating K! / 2^T to avoid overflow. 576 // Other overflow doesn't matter because we only care about the bottom 577 // W bits of the result. 578 APInt OddFactorial(W, 1); 579 unsigned T = 1; 580 for (unsigned i = 3; i <= K; ++i) { 581 APInt Mult(W, i); 582 unsigned TwoFactors = Mult.countTrailingZeros(); 583 T += TwoFactors; 584 Mult = Mult.lshr(TwoFactors); 585 OddFactorial *= Mult; 586 } 587 588 // We need at least W + T bits for the multiplication step 589 unsigned CalculationBits = W + T; 590 591 // Calcuate 2^T, at width T+W. 592 APInt DivFactor = APInt(CalculationBits, 1).shl(T); 593 594 // Calculate the multiplicative inverse of K! / 2^T; 595 // this multiplication factor will perform the exact division by 596 // K! / 2^T. 597 APInt Mod = APInt::getSignedMinValue(W+1); 598 APInt MultiplyFactor = OddFactorial.zext(W+1); 599 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); 600 MultiplyFactor = MultiplyFactor.trunc(W); 601 602 // Calculate the product, at width T+W 603 const IntegerType *CalculationTy = IntegerType::get(CalculationBits); 604 SCEVHandle Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); 605 for (unsigned i = 1; i != K; ++i) { 606 SCEVHandle S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType())); 607 Dividend = SE.getMulExpr(Dividend, 608 SE.getTruncateOrZeroExtend(S, CalculationTy)); 609 } 610 611 // Divide by 2^T 612 SCEVHandle DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); 613 614 // Truncate the result, and divide by K! / 2^T. 615 616 return SE.getMulExpr(SE.getConstant(MultiplyFactor), 617 SE.getTruncateOrZeroExtend(DivResult, ResultTy)); 618 } 619 620 /// evaluateAtIteration - Return the value of this chain of recurrences at 621 /// the specified iteration number. We can evaluate this recurrence by 622 /// multiplying each element in the chain by the binomial coefficient 623 /// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as: 624 /// 625 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) 626 /// 627 /// where BC(It, k) stands for binomial coefficient. 628 /// 629 SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It, 630 ScalarEvolution &SE) const { 631 SCEVHandle Result = getStart(); 632 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 633 // The computation is correct in the face of overflow provided that the 634 // multiplication is performed _after_ the evaluation of the binomial 635 // coefficient. 636 SCEVHandle Coeff = BinomialCoefficient(It, i, SE, getType()); 637 if (isa<SCEVCouldNotCompute>(Coeff)) 638 return Coeff; 639 640 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff)); 641 } 642 return Result; 643 } 644 645 //===----------------------------------------------------------------------===// 646 // SCEV Expression folder implementations 647 //===----------------------------------------------------------------------===// 648 649 SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op, 650 const Type *Ty) { 651 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && 652 "This is not a truncating conversion!"); 653 assert(isSCEVable(Ty) && 654 "This is not a conversion to a SCEVable type!"); 655 Ty = getEffectiveSCEVType(Ty); 656 657 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 658 return getUnknown( 659 ConstantExpr::getTrunc(SC->getValue(), Ty)); 660 661 // trunc(trunc(x)) --> trunc(x) 662 if (SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) 663 return getTruncateExpr(ST->getOperand(), Ty); 664 665 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing 666 if (SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 667 return getTruncateOrSignExtend(SS->getOperand(), Ty); 668 669 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing 670 if (SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 671 return getTruncateOrZeroExtend(SZ->getOperand(), Ty); 672 673 // If the input value is a chrec scev made out of constants, truncate 674 // all of the constants. 675 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 676 std::vector<SCEVHandle> Operands; 677 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 678 // FIXME: This should allow truncation of other expression types! 679 if (isa<SCEVConstant>(AddRec->getOperand(i))) 680 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty)); 681 else 682 break; 683 if (Operands.size() == AddRec->getNumOperands()) 684 return getAddRecExpr(Operands, AddRec->getLoop()); 685 } 686 687 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)]; 688 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty); 689 return Result; 690 } 691 692 SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op, 693 const Type *Ty) { 694 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 695 "This is not an extending conversion!"); 696 assert(isSCEVable(Ty) && 697 "This is not a conversion to a SCEVable type!"); 698 Ty = getEffectiveSCEVType(Ty); 699 700 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) { 701 const Type *IntTy = getEffectiveSCEVType(Ty); 702 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy); 703 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty); 704 return getUnknown(C); 705 } 706 707 // zext(zext(x)) --> zext(x) 708 if (SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 709 return getZeroExtendExpr(SZ->getOperand(), Ty); 710 711 // If the input value is a chrec scev, and we can prove that the value 712 // did not overflow the old, smaller, value, we can zero extend all of the 713 // operands (often constants). This allows analysis of something like 714 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } 715 if (SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 716 if (AR->isAffine()) { 717 // Check whether the backedge-taken count is SCEVCouldNotCompute. 718 // Note that this serves two purposes: It filters out loops that are 719 // simply not analyzable, and it covers the case where this code is 720 // being called from within backedge-taken count analysis, such that 721 // attempting to ask for the backedge-taken count would likely result 722 // in infinite recursion. In the later case, the analysis code will 723 // cope with a conservative value, and it will take care to purge 724 // that value once it has finished. 725 SCEVHandle MaxBECount = getMaxBackedgeTakenCount(AR->getLoop()); 726 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 727 // Manually compute the final value for AR, checking for 728 // overflow. 729 SCEVHandle Start = AR->getStart(); 730 SCEVHandle Step = AR->getStepRecurrence(*this); 731 732 // Check whether the backedge-taken count can be losslessly casted to 733 // the addrec's type. The count is always unsigned. 734 SCEVHandle CastedMaxBECount = 735 getTruncateOrZeroExtend(MaxBECount, Start->getType()); 736 if (MaxBECount == 737 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType())) { 738 const Type *WideTy = 739 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2); 740 // Check whether Start+Step*MaxBECount has no unsigned overflow. 741 SCEVHandle ZMul = 742 getMulExpr(CastedMaxBECount, 743 getTruncateOrZeroExtend(Step, Start->getType())); 744 SCEVHandle Add = getAddExpr(Start, ZMul); 745 if (getZeroExtendExpr(Add, WideTy) == 746 getAddExpr(getZeroExtendExpr(Start, WideTy), 747 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy), 748 getZeroExtendExpr(Step, WideTy)))) 749 // Return the expression with the addrec on the outside. 750 return getAddRecExpr(getZeroExtendExpr(Start, Ty), 751 getZeroExtendExpr(Step, Ty), 752 AR->getLoop()); 753 754 // Similar to above, only this time treat the step value as signed. 755 // This covers loops that count down. 756 SCEVHandle SMul = 757 getMulExpr(CastedMaxBECount, 758 getTruncateOrSignExtend(Step, Start->getType())); 759 Add = getAddExpr(Start, SMul); 760 if (getZeroExtendExpr(Add, WideTy) == 761 getAddExpr(getZeroExtendExpr(Start, WideTy), 762 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy), 763 getSignExtendExpr(Step, WideTy)))) 764 // Return the expression with the addrec on the outside. 765 return getAddRecExpr(getZeroExtendExpr(Start, Ty), 766 getSignExtendExpr(Step, Ty), 767 AR->getLoop()); 768 } 769 } 770 } 771 772 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)]; 773 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty); 774 return Result; 775 } 776 777 SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op, 778 const Type *Ty) { 779 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 780 "This is not an extending conversion!"); 781 assert(isSCEVable(Ty) && 782 "This is not a conversion to a SCEVable type!"); 783 Ty = getEffectiveSCEVType(Ty); 784 785 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) { 786 const Type *IntTy = getEffectiveSCEVType(Ty); 787 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy); 788 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty); 789 return getUnknown(C); 790 } 791 792 // sext(sext(x)) --> sext(x) 793 if (SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 794 return getSignExtendExpr(SS->getOperand(), Ty); 795 796 // If the input value is a chrec scev, and we can prove that the value 797 // did not overflow the old, smaller, value, we can sign extend all of the 798 // operands (often constants). This allows analysis of something like 799 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 800 if (SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 801 if (AR->isAffine()) { 802 // Check whether the backedge-taken count is SCEVCouldNotCompute. 803 // Note that this serves two purposes: It filters out loops that are 804 // simply not analyzable, and it covers the case where this code is 805 // being called from within backedge-taken count analysis, such that 806 // attempting to ask for the backedge-taken count would likely result 807 // in infinite recursion. In the later case, the analysis code will 808 // cope with a conservative value, and it will take care to purge 809 // that value once it has finished. 810 SCEVHandle MaxBECount = getMaxBackedgeTakenCount(AR->getLoop()); 811 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 812 // Manually compute the final value for AR, checking for 813 // overflow. 814 SCEVHandle Start = AR->getStart(); 815 SCEVHandle Step = AR->getStepRecurrence(*this); 816 817 // Check whether the backedge-taken count can be losslessly casted to 818 // the addrec's type. The count is always unsigned. 819 SCEVHandle CastedMaxBECount = 820 getTruncateOrZeroExtend(MaxBECount, Start->getType()); 821 if (MaxBECount == 822 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType())) { 823 const Type *WideTy = 824 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2); 825 // Check whether Start+Step*MaxBECount has no signed overflow. 826 SCEVHandle SMul = 827 getMulExpr(CastedMaxBECount, 828 getTruncateOrSignExtend(Step, Start->getType())); 829 SCEVHandle Add = getAddExpr(Start, SMul); 830 if (getSignExtendExpr(Add, WideTy) == 831 getAddExpr(getSignExtendExpr(Start, WideTy), 832 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy), 833 getSignExtendExpr(Step, WideTy)))) 834 // Return the expression with the addrec on the outside. 835 return getAddRecExpr(getSignExtendExpr(Start, Ty), 836 getSignExtendExpr(Step, Ty), 837 AR->getLoop()); 838 } 839 } 840 } 841 842 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)]; 843 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty); 844 return Result; 845 } 846 847 // get - Get a canonical add expression, or something simpler if possible. 848 SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) { 849 assert(!Ops.empty() && "Cannot get empty add!"); 850 if (Ops.size() == 1) return Ops[0]; 851 852 // Sort by complexity, this groups all similar expression types together. 853 GroupByComplexity(Ops); 854 855 // If there are any constants, fold them together. 856 unsigned Idx = 0; 857 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 858 ++Idx; 859 assert(Idx < Ops.size()); 860 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 861 // We found two constants, fold them together! 862 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() + 863 RHSC->getValue()->getValue()); 864 Ops[0] = getConstant(Fold); 865 Ops.erase(Ops.begin()+1); // Erase the folded element 866 if (Ops.size() == 1) return Ops[0]; 867 LHSC = cast<SCEVConstant>(Ops[0]); 868 } 869 870 // If we are left with a constant zero being added, strip it off. 871 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) { 872 Ops.erase(Ops.begin()); 873 --Idx; 874 } 875 } 876 877 if (Ops.size() == 1) return Ops[0]; 878 879 // Okay, check to see if the same value occurs in the operand list twice. If 880 // so, merge them together into an multiply expression. Since we sorted the 881 // list, these values are required to be adjacent. 882 const Type *Ty = Ops[0]->getType(); 883 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 884 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 885 // Found a match, merge the two values into a multiply, and add any 886 // remaining values to the result. 887 SCEVHandle Two = getIntegerSCEV(2, Ty); 888 SCEVHandle Mul = getMulExpr(Ops[i], Two); 889 if (Ops.size() == 2) 890 return Mul; 891 Ops.erase(Ops.begin()+i, Ops.begin()+i+2); 892 Ops.push_back(Mul); 893 return getAddExpr(Ops); 894 } 895 896 // Now we know the first non-constant operand. Skip past any cast SCEVs. 897 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 898 ++Idx; 899 900 // If there are add operands they would be next. 901 if (Idx < Ops.size()) { 902 bool DeletedAdd = false; 903 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 904 // If we have an add, expand the add operands onto the end of the operands 905 // list. 906 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end()); 907 Ops.erase(Ops.begin()+Idx); 908 DeletedAdd = true; 909 } 910 911 // If we deleted at least one add, we added operands to the end of the list, 912 // and they are not necessarily sorted. Recurse to resort and resimplify 913 // any operands we just aquired. 914 if (DeletedAdd) 915 return getAddExpr(Ops); 916 } 917 918 // Skip over the add expression until we get to a multiply. 919 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 920 ++Idx; 921 922 // If we are adding something to a multiply expression, make sure the 923 // something is not already an operand of the multiply. If so, merge it into 924 // the multiply. 925 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 926 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 927 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 928 SCEV *MulOpSCEV = Mul->getOperand(MulOp); 929 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 930 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) { 931 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 932 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0); 933 if (Mul->getNumOperands() != 2) { 934 // If the multiply has more than two operands, we must get the 935 // Y*Z term. 936 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end()); 937 MulOps.erase(MulOps.begin()+MulOp); 938 InnerMul = getMulExpr(MulOps); 939 } 940 SCEVHandle One = getIntegerSCEV(1, Ty); 941 SCEVHandle AddOne = getAddExpr(InnerMul, One); 942 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]); 943 if (Ops.size() == 2) return OuterMul; 944 if (AddOp < Idx) { 945 Ops.erase(Ops.begin()+AddOp); 946 Ops.erase(Ops.begin()+Idx-1); 947 } else { 948 Ops.erase(Ops.begin()+Idx); 949 Ops.erase(Ops.begin()+AddOp-1); 950 } 951 Ops.push_back(OuterMul); 952 return getAddExpr(Ops); 953 } 954 955 // Check this multiply against other multiplies being added together. 956 for (unsigned OtherMulIdx = Idx+1; 957 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 958 ++OtherMulIdx) { 959 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 960 // If MulOp occurs in OtherMul, we can fold the two multiplies 961 // together. 962 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 963 OMulOp != e; ++OMulOp) 964 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 965 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 966 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0); 967 if (Mul->getNumOperands() != 2) { 968 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end()); 969 MulOps.erase(MulOps.begin()+MulOp); 970 InnerMul1 = getMulExpr(MulOps); 971 } 972 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0); 973 if (OtherMul->getNumOperands() != 2) { 974 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(), 975 OtherMul->op_end()); 976 MulOps.erase(MulOps.begin()+OMulOp); 977 InnerMul2 = getMulExpr(MulOps); 978 } 979 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2); 980 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum); 981 if (Ops.size() == 2) return OuterMul; 982 Ops.erase(Ops.begin()+Idx); 983 Ops.erase(Ops.begin()+OtherMulIdx-1); 984 Ops.push_back(OuterMul); 985 return getAddExpr(Ops); 986 } 987 } 988 } 989 } 990 991 // If there are any add recurrences in the operands list, see if any other 992 // added values are loop invariant. If so, we can fold them into the 993 // recurrence. 994 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 995 ++Idx; 996 997 // Scan over all recurrences, trying to fold loop invariants into them. 998 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 999 // Scan all of the other operands to this add and add them to the vector if 1000 // they are loop invariant w.r.t. the recurrence. 1001 std::vector<SCEVHandle> LIOps; 1002 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 1003 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 1004 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) { 1005 LIOps.push_back(Ops[i]); 1006 Ops.erase(Ops.begin()+i); 1007 --i; --e; 1008 } 1009 1010 // If we found some loop invariants, fold them into the recurrence. 1011 if (!LIOps.empty()) { 1012 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 1013 LIOps.push_back(AddRec->getStart()); 1014 1015 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end()); 1016 AddRecOps[0] = getAddExpr(LIOps); 1017 1018 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop()); 1019 // If all of the other operands were loop invariant, we are done. 1020 if (Ops.size() == 1) return NewRec; 1021 1022 // Otherwise, add the folded AddRec by the non-liv parts. 1023 for (unsigned i = 0;; ++i) 1024 if (Ops[i] == AddRec) { 1025 Ops[i] = NewRec; 1026 break; 1027 } 1028 return getAddExpr(Ops); 1029 } 1030 1031 // Okay, if there weren't any loop invariants to be folded, check to see if 1032 // there are multiple AddRec's with the same loop induction variable being 1033 // added together. If so, we can fold them. 1034 for (unsigned OtherIdx = Idx+1; 1035 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx) 1036 if (OtherIdx != Idx) { 1037 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 1038 if (AddRec->getLoop() == OtherAddRec->getLoop()) { 1039 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D} 1040 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end()); 1041 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) { 1042 if (i >= NewOps.size()) { 1043 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i, 1044 OtherAddRec->op_end()); 1045 break; 1046 } 1047 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i)); 1048 } 1049 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop()); 1050 1051 if (Ops.size() == 2) return NewAddRec; 1052 1053 Ops.erase(Ops.begin()+Idx); 1054 Ops.erase(Ops.begin()+OtherIdx-1); 1055 Ops.push_back(NewAddRec); 1056 return getAddExpr(Ops); 1057 } 1058 } 1059 1060 // Otherwise couldn't fold anything into this recurrence. Move onto the 1061 // next one. 1062 } 1063 1064 // Okay, it looks like we really DO need an add expr. Check to see if we 1065 // already have one, otherwise create a new one. 1066 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end()); 1067 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr, 1068 SCEVOps)]; 1069 if (Result == 0) Result = new SCEVAddExpr(Ops); 1070 return Result; 1071 } 1072 1073 1074 SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) { 1075 assert(!Ops.empty() && "Cannot get empty mul!"); 1076 1077 // Sort by complexity, this groups all similar expression types together. 1078 GroupByComplexity(Ops); 1079 1080 // If there are any constants, fold them together. 1081 unsigned Idx = 0; 1082 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 1083 1084 // C1*(C2+V) -> C1*C2 + C1*V 1085 if (Ops.size() == 2) 1086 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 1087 if (Add->getNumOperands() == 2 && 1088 isa<SCEVConstant>(Add->getOperand(0))) 1089 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)), 1090 getMulExpr(LHSC, Add->getOperand(1))); 1091 1092 1093 ++Idx; 1094 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 1095 // We found two constants, fold them together! 1096 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() * 1097 RHSC->getValue()->getValue()); 1098 Ops[0] = getConstant(Fold); 1099 Ops.erase(Ops.begin()+1); // Erase the folded element 1100 if (Ops.size() == 1) return Ops[0]; 1101 LHSC = cast<SCEVConstant>(Ops[0]); 1102 } 1103 1104 // If we are left with a constant one being multiplied, strip it off. 1105 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) { 1106 Ops.erase(Ops.begin()); 1107 --Idx; 1108 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) { 1109 // If we have a multiply of zero, it will always be zero. 1110 return Ops[0]; 1111 } 1112 } 1113 1114 // Skip over the add expression until we get to a multiply. 1115 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 1116 ++Idx; 1117 1118 if (Ops.size() == 1) 1119 return Ops[0]; 1120 1121 // If there are mul operands inline them all into this expression. 1122 if (Idx < Ops.size()) { 1123 bool DeletedMul = false; 1124 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 1125 // If we have an mul, expand the mul operands onto the end of the operands 1126 // list. 1127 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end()); 1128 Ops.erase(Ops.begin()+Idx); 1129 DeletedMul = true; 1130 } 1131 1132 // If we deleted at least one mul, we added operands to the end of the list, 1133 // and they are not necessarily sorted. Recurse to resort and resimplify 1134 // any operands we just aquired. 1135 if (DeletedMul) 1136 return getMulExpr(Ops); 1137 } 1138 1139 // If there are any add recurrences in the operands list, see if any other 1140 // added values are loop invariant. If so, we can fold them into the 1141 // recurrence. 1142 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 1143 ++Idx; 1144 1145 // Scan over all recurrences, trying to fold loop invariants into them. 1146 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 1147 // Scan all of the other operands to this mul and add them to the vector if 1148 // they are loop invariant w.r.t. the recurrence. 1149 std::vector<SCEVHandle> LIOps; 1150 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 1151 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 1152 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) { 1153 LIOps.push_back(Ops[i]); 1154 Ops.erase(Ops.begin()+i); 1155 --i; --e; 1156 } 1157 1158 // If we found some loop invariants, fold them into the recurrence. 1159 if (!LIOps.empty()) { 1160 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 1161 std::vector<SCEVHandle> NewOps; 1162 NewOps.reserve(AddRec->getNumOperands()); 1163 if (LIOps.size() == 1) { 1164 SCEV *Scale = LIOps[0]; 1165 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 1166 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i))); 1167 } else { 1168 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 1169 std::vector<SCEVHandle> MulOps(LIOps); 1170 MulOps.push_back(AddRec->getOperand(i)); 1171 NewOps.push_back(getMulExpr(MulOps)); 1172 } 1173 } 1174 1175 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop()); 1176 1177 // If all of the other operands were loop invariant, we are done. 1178 if (Ops.size() == 1) return NewRec; 1179 1180 // Otherwise, multiply the folded AddRec by the non-liv parts. 1181 for (unsigned i = 0;; ++i) 1182 if (Ops[i] == AddRec) { 1183 Ops[i] = NewRec; 1184 break; 1185 } 1186 return getMulExpr(Ops); 1187 } 1188 1189 // Okay, if there weren't any loop invariants to be folded, check to see if 1190 // there are multiple AddRec's with the same loop induction variable being 1191 // multiplied together. If so, we can fold them. 1192 for (unsigned OtherIdx = Idx+1; 1193 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx) 1194 if (OtherIdx != Idx) { 1195 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 1196 if (AddRec->getLoop() == OtherAddRec->getLoop()) { 1197 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D} 1198 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec; 1199 SCEVHandle NewStart = getMulExpr(F->getStart(), 1200 G->getStart()); 1201 SCEVHandle B = F->getStepRecurrence(*this); 1202 SCEVHandle D = G->getStepRecurrence(*this); 1203 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D), 1204 getMulExpr(G, B), 1205 getMulExpr(B, D)); 1206 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep, 1207 F->getLoop()); 1208 if (Ops.size() == 2) return NewAddRec; 1209 1210 Ops.erase(Ops.begin()+Idx); 1211 Ops.erase(Ops.begin()+OtherIdx-1); 1212 Ops.push_back(NewAddRec); 1213 return getMulExpr(Ops); 1214 } 1215 } 1216 1217 // Otherwise couldn't fold anything into this recurrence. Move onto the 1218 // next one. 1219 } 1220 1221 // Okay, it looks like we really DO need an mul expr. Check to see if we 1222 // already have one, otherwise create a new one. 1223 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end()); 1224 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr, 1225 SCEVOps)]; 1226 if (Result == 0) 1227 Result = new SCEVMulExpr(Ops); 1228 return Result; 1229 } 1230 1231 SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) { 1232 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 1233 if (RHSC->getValue()->equalsInt(1)) 1234 return LHS; // X udiv 1 --> x 1235 1236 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 1237 Constant *LHSCV = LHSC->getValue(); 1238 Constant *RHSCV = RHSC->getValue(); 1239 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV)); 1240 } 1241 } 1242 1243 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow. 1244 1245 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)]; 1246 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS); 1247 return Result; 1248 } 1249 1250 1251 /// SCEVAddRecExpr::get - Get a add recurrence expression for the 1252 /// specified loop. Simplify the expression as much as possible. 1253 SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start, 1254 const SCEVHandle &Step, const Loop *L) { 1255 std::vector<SCEVHandle> Operands; 1256 Operands.push_back(Start); 1257 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 1258 if (StepChrec->getLoop() == L) { 1259 Operands.insert(Operands.end(), StepChrec->op_begin(), 1260 StepChrec->op_end()); 1261 return getAddRecExpr(Operands, L); 1262 } 1263 1264 Operands.push_back(Step); 1265 return getAddRecExpr(Operands, L); 1266 } 1267 1268 /// SCEVAddRecExpr::get - Get a add recurrence expression for the 1269 /// specified loop. Simplify the expression as much as possible. 1270 SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands, 1271 const Loop *L) { 1272 if (Operands.size() == 1) return Operands[0]; 1273 1274 if (Operands.back()->isZero()) { 1275 Operands.pop_back(); 1276 return getAddRecExpr(Operands, L); // {X,+,0} --> X 1277 } 1278 1279 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 1280 if (SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 1281 const Loop* NestedLoop = NestedAR->getLoop(); 1282 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) { 1283 std::vector<SCEVHandle> NestedOperands(NestedAR->op_begin(), 1284 NestedAR->op_end()); 1285 SCEVHandle NestedARHandle(NestedAR); 1286 Operands[0] = NestedAR->getStart(); 1287 NestedOperands[0] = getAddRecExpr(Operands, L); 1288 return getAddRecExpr(NestedOperands, NestedLoop); 1289 } 1290 } 1291 1292 SCEVAddRecExpr *&Result = 1293 (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(), 1294 Operands.end()))]; 1295 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L); 1296 return Result; 1297 } 1298 1299 SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS, 1300 const SCEVHandle &RHS) { 1301 std::vector<SCEVHandle> Ops; 1302 Ops.push_back(LHS); 1303 Ops.push_back(RHS); 1304 return getSMaxExpr(Ops); 1305 } 1306 1307 SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) { 1308 assert(!Ops.empty() && "Cannot get empty smax!"); 1309 if (Ops.size() == 1) return Ops[0]; 1310 1311 // Sort by complexity, this groups all similar expression types together. 1312 GroupByComplexity(Ops); 1313 1314 // If there are any constants, fold them together. 1315 unsigned Idx = 0; 1316 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 1317 ++Idx; 1318 assert(Idx < Ops.size()); 1319 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 1320 // We found two constants, fold them together! 1321 ConstantInt *Fold = ConstantInt::get( 1322 APIntOps::smax(LHSC->getValue()->getValue(), 1323 RHSC->getValue()->getValue())); 1324 Ops[0] = getConstant(Fold); 1325 Ops.erase(Ops.begin()+1); // Erase the folded element 1326 if (Ops.size() == 1) return Ops[0]; 1327 LHSC = cast<SCEVConstant>(Ops[0]); 1328 } 1329 1330 // If we are left with a constant -inf, strip it off. 1331 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) { 1332 Ops.erase(Ops.begin()); 1333 --Idx; 1334 } 1335 } 1336 1337 if (Ops.size() == 1) return Ops[0]; 1338 1339 // Find the first SMax 1340 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr) 1341 ++Idx; 1342 1343 // Check to see if one of the operands is an SMax. If so, expand its operands 1344 // onto our operand list, and recurse to simplify. 1345 if (Idx < Ops.size()) { 1346 bool DeletedSMax = false; 1347 while (SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) { 1348 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end()); 1349 Ops.erase(Ops.begin()+Idx); 1350 DeletedSMax = true; 1351 } 1352 1353 if (DeletedSMax) 1354 return getSMaxExpr(Ops); 1355 } 1356 1357 // Okay, check to see if the same value occurs in the operand list twice. If 1358 // so, delete one. Since we sorted the list, these values are required to 1359 // be adjacent. 1360 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 1361 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y 1362 Ops.erase(Ops.begin()+i, Ops.begin()+i+1); 1363 --i; --e; 1364 } 1365 1366 if (Ops.size() == 1) return Ops[0]; 1367 1368 assert(!Ops.empty() && "Reduced smax down to nothing!"); 1369 1370 // Okay, it looks like we really DO need an smax expr. Check to see if we 1371 // already have one, otherwise create a new one. 1372 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end()); 1373 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr, 1374 SCEVOps)]; 1375 if (Result == 0) Result = new SCEVSMaxExpr(Ops); 1376 return Result; 1377 } 1378 1379 SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS, 1380 const SCEVHandle &RHS) { 1381 std::vector<SCEVHandle> Ops; 1382 Ops.push_back(LHS); 1383 Ops.push_back(RHS); 1384 return getUMaxExpr(Ops); 1385 } 1386 1387 SCEVHandle ScalarEvolution::getUMaxExpr(std::vector<SCEVHandle> Ops) { 1388 assert(!Ops.empty() && "Cannot get empty umax!"); 1389 if (Ops.size() == 1) return Ops[0]; 1390 1391 // Sort by complexity, this groups all similar expression types together. 1392 GroupByComplexity(Ops); 1393 1394 // If there are any constants, fold them together. 1395 unsigned Idx = 0; 1396 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 1397 ++Idx; 1398 assert(Idx < Ops.size()); 1399 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 1400 // We found two constants, fold them together! 1401 ConstantInt *Fold = ConstantInt::get( 1402 APIntOps::umax(LHSC->getValue()->getValue(), 1403 RHSC->getValue()->getValue())); 1404 Ops[0] = getConstant(Fold); 1405 Ops.erase(Ops.begin()+1); // Erase the folded element 1406 if (Ops.size() == 1) return Ops[0]; 1407 LHSC = cast<SCEVConstant>(Ops[0]); 1408 } 1409 1410 // If we are left with a constant zero, strip it off. 1411 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) { 1412 Ops.erase(Ops.begin()); 1413 --Idx; 1414 } 1415 } 1416 1417 if (Ops.size() == 1) return Ops[0]; 1418 1419 // Find the first UMax 1420 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr) 1421 ++Idx; 1422 1423 // Check to see if one of the operands is a UMax. If so, expand its operands 1424 // onto our operand list, and recurse to simplify. 1425 if (Idx < Ops.size()) { 1426 bool DeletedUMax = false; 1427 while (SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) { 1428 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end()); 1429 Ops.erase(Ops.begin()+Idx); 1430 DeletedUMax = true; 1431 } 1432 1433 if (DeletedUMax) 1434 return getUMaxExpr(Ops); 1435 } 1436 1437 // Okay, check to see if the same value occurs in the operand list twice. If 1438 // so, delete one. Since we sorted the list, these values are required to 1439 // be adjacent. 1440 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 1441 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y 1442 Ops.erase(Ops.begin()+i, Ops.begin()+i+1); 1443 --i; --e; 1444 } 1445 1446 if (Ops.size() == 1) return Ops[0]; 1447 1448 assert(!Ops.empty() && "Reduced umax down to nothing!"); 1449 1450 // Okay, it looks like we really DO need a umax expr. Check to see if we 1451 // already have one, otherwise create a new one. 1452 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end()); 1453 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr, 1454 SCEVOps)]; 1455 if (Result == 0) Result = new SCEVUMaxExpr(Ops); 1456 return Result; 1457 } 1458 1459 SCEVHandle ScalarEvolution::getUnknown(Value *V) { 1460 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 1461 return getConstant(CI); 1462 if (isa<ConstantPointerNull>(V)) 1463 return getIntegerSCEV(0, V->getType()); 1464 SCEVUnknown *&Result = (*SCEVUnknowns)[V]; 1465 if (Result == 0) Result = new SCEVUnknown(V); 1466 return Result; 1467 } 1468 1469 //===----------------------------------------------------------------------===// 1470 // Basic SCEV Analysis and PHI Idiom Recognition Code 1471 // 1472 1473 /// deleteValueFromRecords - This method should be called by the 1474 /// client before it removes an instruction from the program, to make sure 1475 /// that no dangling references are left around. 1476 void ScalarEvolution::deleteValueFromRecords(Value *V) { 1477 SmallVector<Value *, 16> Worklist; 1478 1479 if (Scalars.erase(V)) { 1480 if (PHINode *PN = dyn_cast<PHINode>(V)) 1481 ConstantEvolutionLoopExitValue.erase(PN); 1482 Worklist.push_back(V); 1483 } 1484 1485 while (!Worklist.empty()) { 1486 Value *VV = Worklist.back(); 1487 Worklist.pop_back(); 1488 1489 for (Instruction::use_iterator UI = VV->use_begin(), UE = VV->use_end(); 1490 UI != UE; ++UI) { 1491 Instruction *Inst = cast<Instruction>(*UI); 1492 if (Scalars.erase(Inst)) { 1493 if (PHINode *PN = dyn_cast<PHINode>(VV)) 1494 ConstantEvolutionLoopExitValue.erase(PN); 1495 Worklist.push_back(Inst); 1496 } 1497 } 1498 } 1499 } 1500 1501 /// isSCEVable - Test if values of the given type are analyzable within 1502 /// the SCEV framework. This primarily includes integer types, and it 1503 /// can optionally include pointer types if the ScalarEvolution class 1504 /// has access to target-specific information. 1505 bool ScalarEvolution::isSCEVable(const Type *Ty) const { 1506 // Integers are always SCEVable. 1507 if (Ty->isInteger()) 1508 return true; 1509 1510 // Pointers are SCEVable if TargetData information is available 1511 // to provide pointer size information. 1512 if (isa<PointerType>(Ty)) 1513 return TD != NULL; 1514 1515 // Otherwise it's not SCEVable. 1516 return false; 1517 } 1518 1519 /// getTypeSizeInBits - Return the size in bits of the specified type, 1520 /// for which isSCEVable must return true. 1521 uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const { 1522 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 1523 1524 // If we have a TargetData, use it! 1525 if (TD) 1526 return TD->getTypeSizeInBits(Ty); 1527 1528 // Otherwise, we support only integer types. 1529 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!"); 1530 return Ty->getPrimitiveSizeInBits(); 1531 } 1532 1533 /// getEffectiveSCEVType - Return a type with the same bitwidth as 1534 /// the given type and which represents how SCEV will treat the given 1535 /// type, for which isSCEVable must return true. For pointer types, 1536 /// this is the pointer-sized integer type. 1537 const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const { 1538 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 1539 1540 if (Ty->isInteger()) 1541 return Ty; 1542 1543 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!"); 1544 return TD->getIntPtrType(); 1545 } 1546 1547 SCEVHandle ScalarEvolution::getCouldNotCompute() { 1548 return UnknownValue; 1549 } 1550 1551 // hasSCEV - Return true if the SCEV for this value has already been 1552 /// computed. 1553 bool ScalarEvolution::hasSCEV(Value *V) const { 1554 return Scalars.count(V); 1555 } 1556 1557 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the 1558 /// expression and create a new one. 1559 SCEVHandle ScalarEvolution::getSCEV(Value *V) { 1560 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 1561 1562 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V); 1563 if (I != Scalars.end()) return I->second; 1564 SCEVHandle S = createSCEV(V); 1565 Scalars.insert(std::make_pair(V, S)); 1566 return S; 1567 } 1568 1569 /// getIntegerSCEV - Given an integer or FP type, create a constant for the 1570 /// specified signed integer value and return a SCEV for the constant. 1571 SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) { 1572 Ty = getEffectiveSCEVType(Ty); 1573 Constant *C; 1574 if (Val == 0) 1575 C = Constant::getNullValue(Ty); 1576 else if (Ty->isFloatingPoint()) 1577 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle : 1578 APFloat::IEEEdouble, Val)); 1579 else 1580 C = ConstantInt::get(Ty, Val); 1581 return getUnknown(C); 1582 } 1583 1584 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V 1585 /// 1586 SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) { 1587 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 1588 return getUnknown(ConstantExpr::getNeg(VC->getValue())); 1589 1590 const Type *Ty = V->getType(); 1591 Ty = getEffectiveSCEVType(Ty); 1592 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(Ty))); 1593 } 1594 1595 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V 1596 SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) { 1597 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 1598 return getUnknown(ConstantExpr::getNot(VC->getValue())); 1599 1600 const Type *Ty = V->getType(); 1601 Ty = getEffectiveSCEVType(Ty); 1602 SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(Ty)); 1603 return getMinusSCEV(AllOnes, V); 1604 } 1605 1606 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS. 1607 /// 1608 SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS, 1609 const SCEVHandle &RHS) { 1610 // X - Y --> X + -Y 1611 return getAddExpr(LHS, getNegativeSCEV(RHS)); 1612 } 1613 1614 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the 1615 /// input value to the specified type. If the type must be extended, it is zero 1616 /// extended. 1617 SCEVHandle 1618 ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V, 1619 const Type *Ty) { 1620 const Type *SrcTy = V->getType(); 1621 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) && 1622 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) && 1623 "Cannot truncate or zero extend with non-integer arguments!"); 1624 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 1625 return V; // No conversion 1626 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 1627 return getTruncateExpr(V, Ty); 1628 return getZeroExtendExpr(V, Ty); 1629 } 1630 1631 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the 1632 /// input value to the specified type. If the type must be extended, it is sign 1633 /// extended. 1634 SCEVHandle 1635 ScalarEvolution::getTruncateOrSignExtend(const SCEVHandle &V, 1636 const Type *Ty) { 1637 const Type *SrcTy = V->getType(); 1638 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) && 1639 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) && 1640 "Cannot truncate or zero extend with non-integer arguments!"); 1641 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 1642 return V; // No conversion 1643 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 1644 return getTruncateExpr(V, Ty); 1645 return getSignExtendExpr(V, Ty); 1646 } 1647 1648 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for 1649 /// the specified instruction and replaces any references to the symbolic value 1650 /// SymName with the specified value. This is used during PHI resolution. 1651 void ScalarEvolution:: 1652 ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName, 1653 const SCEVHandle &NewVal) { 1654 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I); 1655 if (SI == Scalars.end()) return; 1656 1657 SCEVHandle NV = 1658 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this); 1659 if (NV == SI->second) return; // No change. 1660 1661 SI->second = NV; // Update the scalars map! 1662 1663 // Any instruction values that use this instruction might also need to be 1664 // updated! 1665 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); 1666 UI != E; ++UI) 1667 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal); 1668 } 1669 1670 /// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in 1671 /// a loop header, making it a potential recurrence, or it doesn't. 1672 /// 1673 SCEVHandle ScalarEvolution::createNodeForPHI(PHINode *PN) { 1674 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized. 1675 if (const Loop *L = LI->getLoopFor(PN->getParent())) 1676 if (L->getHeader() == PN->getParent()) { 1677 // If it lives in the loop header, it has two incoming values, one 1678 // from outside the loop, and one from inside. 1679 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0)); 1680 unsigned BackEdge = IncomingEdge^1; 1681 1682 // While we are analyzing this PHI node, handle its value symbolically. 1683 SCEVHandle SymbolicName = getUnknown(PN); 1684 assert(Scalars.find(PN) == Scalars.end() && 1685 "PHI node already processed?"); 1686 Scalars.insert(std::make_pair(PN, SymbolicName)); 1687 1688 // Using this symbolic name for the PHI, analyze the value coming around 1689 // the back-edge. 1690 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge)); 1691 1692 // NOTE: If BEValue is loop invariant, we know that the PHI node just 1693 // has a special value for the first iteration of the loop. 1694 1695 // If the value coming around the backedge is an add with the symbolic 1696 // value we just inserted, then we found a simple induction variable! 1697 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 1698 // If there is a single occurrence of the symbolic value, replace it 1699 // with a recurrence. 1700 unsigned FoundIndex = Add->getNumOperands(); 1701 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 1702 if (Add->getOperand(i) == SymbolicName) 1703 if (FoundIndex == e) { 1704 FoundIndex = i; 1705 break; 1706 } 1707 1708 if (FoundIndex != Add->getNumOperands()) { 1709 // Create an add with everything but the specified operand. 1710 std::vector<SCEVHandle> Ops; 1711 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 1712 if (i != FoundIndex) 1713 Ops.push_back(Add->getOperand(i)); 1714 SCEVHandle Accum = getAddExpr(Ops); 1715 1716 // This is not a valid addrec if the step amount is varying each 1717 // loop iteration, but is not itself an addrec in this loop. 1718 if (Accum->isLoopInvariant(L) || 1719 (isa<SCEVAddRecExpr>(Accum) && 1720 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 1721 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge)); 1722 SCEVHandle PHISCEV = getAddRecExpr(StartVal, Accum, L); 1723 1724 // Okay, for the entire analysis of this edge we assumed the PHI 1725 // to be symbolic. We now need to go back and update all of the 1726 // entries for the scalars that use the PHI (except for the PHI 1727 // itself) to use the new analyzed value instead of the "symbolic" 1728 // value. 1729 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV); 1730 return PHISCEV; 1731 } 1732 } 1733 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) { 1734 // Otherwise, this could be a loop like this: 1735 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 1736 // In this case, j = {1,+,1} and BEValue is j. 1737 // Because the other in-value of i (0) fits the evolution of BEValue 1738 // i really is an addrec evolution. 1739 if (AddRec->getLoop() == L && AddRec->isAffine()) { 1740 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge)); 1741 1742 // If StartVal = j.start - j.stride, we can use StartVal as the 1743 // initial step of the addrec evolution. 1744 if (StartVal == getMinusSCEV(AddRec->getOperand(0), 1745 AddRec->getOperand(1))) { 1746 SCEVHandle PHISCEV = 1747 getAddRecExpr(StartVal, AddRec->getOperand(1), L); 1748 1749 // Okay, for the entire analysis of this edge we assumed the PHI 1750 // to be symbolic. We now need to go back and update all of the 1751 // entries for the scalars that use the PHI (except for the PHI 1752 // itself) to use the new analyzed value instead of the "symbolic" 1753 // value. 1754 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV); 1755 return PHISCEV; 1756 } 1757 } 1758 } 1759 1760 return SymbolicName; 1761 } 1762 1763 // If it's not a loop phi, we can't handle it yet. 1764 return getUnknown(PN); 1765 } 1766 1767 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S is 1768 /// guaranteed to end in (at every loop iteration). It is, at the same time, 1769 /// the minimum number of times S is divisible by 2. For example, given {4,+,8} 1770 /// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S. 1771 static uint32_t GetMinTrailingZeros(SCEVHandle S, const ScalarEvolution &SE) { 1772 if (SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 1773 return C->getValue()->getValue().countTrailingZeros(); 1774 1775 if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 1776 return std::min(GetMinTrailingZeros(T->getOperand(), SE), 1777 (uint32_t)SE.getTypeSizeInBits(T->getType())); 1778 1779 if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 1780 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE); 1781 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ? 1782 SE.getTypeSizeInBits(E->getOperand()->getType()) : OpRes; 1783 } 1784 1785 if (SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 1786 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE); 1787 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ? 1788 SE.getTypeSizeInBits(E->getOperand()->getType()) : OpRes; 1789 } 1790 1791 if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 1792 // The result is the min of all operands results. 1793 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE); 1794 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 1795 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE)); 1796 return MinOpRes; 1797 } 1798 1799 if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 1800 // The result is the sum of all operands results. 1801 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0), SE); 1802 uint32_t BitWidth = SE.getTypeSizeInBits(M->getType()); 1803 for (unsigned i = 1, e = M->getNumOperands(); 1804 SumOpRes != BitWidth && i != e; ++i) 1805 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i), SE), 1806 BitWidth); 1807 return SumOpRes; 1808 } 1809 1810 if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 1811 // The result is the min of all operands results. 1812 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE); 1813 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 1814 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE)); 1815 return MinOpRes; 1816 } 1817 1818 if (SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 1819 // The result is the min of all operands results. 1820 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE); 1821 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 1822 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE)); 1823 return MinOpRes; 1824 } 1825 1826 if (SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 1827 // The result is the min of all operands results. 1828 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE); 1829 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 1830 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE)); 1831 return MinOpRes; 1832 } 1833 1834 // SCEVUDivExpr, SCEVUnknown 1835 return 0; 1836 } 1837 1838 /// createSCEV - We know that there is no SCEV for the specified value. 1839 /// Analyze the expression. 1840 /// 1841 SCEVHandle ScalarEvolution::createSCEV(Value *V) { 1842 if (!isSCEVable(V->getType())) 1843 return getUnknown(V); 1844 1845 unsigned Opcode = Instruction::UserOp1; 1846 if (Instruction *I = dyn_cast<Instruction>(V)) 1847 Opcode = I->getOpcode(); 1848 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) 1849 Opcode = CE->getOpcode(); 1850 else 1851 return getUnknown(V); 1852 1853 User *U = cast<User>(V); 1854 switch (Opcode) { 1855 case Instruction::Add: 1856 return getAddExpr(getSCEV(U->getOperand(0)), 1857 getSCEV(U->getOperand(1))); 1858 case Instruction::Mul: 1859 return getMulExpr(getSCEV(U->getOperand(0)), 1860 getSCEV(U->getOperand(1))); 1861 case Instruction::UDiv: 1862 return getUDivExpr(getSCEV(U->getOperand(0)), 1863 getSCEV(U->getOperand(1))); 1864 case Instruction::Sub: 1865 return getMinusSCEV(getSCEV(U->getOperand(0)), 1866 getSCEV(U->getOperand(1))); 1867 case Instruction::And: 1868 // For an expression like x&255 that merely masks off the high bits, 1869 // use zext(trunc(x)) as the SCEV expression. 1870 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) { 1871 if (CI->isNullValue()) 1872 return getSCEV(U->getOperand(1)); 1873 if (CI->isAllOnesValue()) 1874 return getSCEV(U->getOperand(0)); 1875 const APInt &A = CI->getValue(); 1876 unsigned Ones = A.countTrailingOnes(); 1877 if (APIntOps::isMask(Ones, A)) 1878 return 1879 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)), 1880 IntegerType::get(Ones)), 1881 U->getType()); 1882 } 1883 break; 1884 case Instruction::Or: 1885 // If the RHS of the Or is a constant, we may have something like: 1886 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 1887 // optimizations will transparently handle this case. 1888 // 1889 // In order for this transformation to be safe, the LHS must be of the 1890 // form X*(2^n) and the Or constant must be less than 2^n. 1891 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) { 1892 SCEVHandle LHS = getSCEV(U->getOperand(0)); 1893 const APInt &CIVal = CI->getValue(); 1894 if (GetMinTrailingZeros(LHS, *this) >= 1895 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) 1896 return getAddExpr(LHS, getSCEV(U->getOperand(1))); 1897 } 1898 break; 1899 case Instruction::Xor: 1900 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) { 1901 // If the RHS of the xor is a signbit, then this is just an add. 1902 // Instcombine turns add of signbit into xor as a strength reduction step. 1903 if (CI->getValue().isSignBit()) 1904 return getAddExpr(getSCEV(U->getOperand(0)), 1905 getSCEV(U->getOperand(1))); 1906 1907 // If the RHS of xor is -1, then this is a not operation. 1908 else if (CI->isAllOnesValue()) 1909 return getNotSCEV(getSCEV(U->getOperand(0))); 1910 } 1911 break; 1912 1913 case Instruction::Shl: 1914 // Turn shift left of a constant amount into a multiply. 1915 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) { 1916 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth(); 1917 Constant *X = ConstantInt::get( 1918 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth))); 1919 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X)); 1920 } 1921 break; 1922 1923 case Instruction::LShr: 1924 // Turn logical shift right of a constant into a unsigned divide. 1925 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) { 1926 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth(); 1927 Constant *X = ConstantInt::get( 1928 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth))); 1929 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X)); 1930 } 1931 break; 1932 1933 case Instruction::AShr: 1934 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression. 1935 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) 1936 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0))) 1937 if (L->getOpcode() == Instruction::Shl && 1938 L->getOperand(1) == U->getOperand(1)) { 1939 unsigned BitWidth = getTypeSizeInBits(U->getType()); 1940 uint64_t Amt = BitWidth - CI->getZExtValue(); 1941 if (Amt == BitWidth) 1942 return getSCEV(L->getOperand(0)); // shift by zero --> noop 1943 if (Amt > BitWidth) 1944 return getIntegerSCEV(0, U->getType()); // value is undefined 1945 return 1946 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)), 1947 IntegerType::get(Amt)), 1948 U->getType()); 1949 } 1950 break; 1951 1952 case Instruction::Trunc: 1953 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 1954 1955 case Instruction::ZExt: 1956 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 1957 1958 case Instruction::SExt: 1959 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 1960 1961 case Instruction::BitCast: 1962 // BitCasts are no-op casts so we just eliminate the cast. 1963 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 1964 return getSCEV(U->getOperand(0)); 1965 break; 1966 1967 case Instruction::IntToPtr: 1968 if (!TD) break; // Without TD we can't analyze pointers. 1969 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)), 1970 TD->getIntPtrType()); 1971 1972 case Instruction::PtrToInt: 1973 if (!TD) break; // Without TD we can't analyze pointers. 1974 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)), 1975 U->getType()); 1976 1977 case Instruction::GetElementPtr: { 1978 if (!TD) break; // Without TD we can't analyze pointers. 1979 const Type *IntPtrTy = TD->getIntPtrType(); 1980 Value *Base = U->getOperand(0); 1981 SCEVHandle TotalOffset = getIntegerSCEV(0, IntPtrTy); 1982 gep_type_iterator GTI = gep_type_begin(U); 1983 for (GetElementPtrInst::op_iterator I = next(U->op_begin()), 1984 E = U->op_end(); 1985 I != E; ++I) { 1986 Value *Index = *I; 1987 // Compute the (potentially symbolic) offset in bytes for this index. 1988 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) { 1989 // For a struct, add the member offset. 1990 const StructLayout &SL = *TD->getStructLayout(STy); 1991 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue(); 1992 uint64_t Offset = SL.getElementOffset(FieldNo); 1993 TotalOffset = getAddExpr(TotalOffset, 1994 getIntegerSCEV(Offset, IntPtrTy)); 1995 } else { 1996 // For an array, add the element offset, explicitly scaled. 1997 SCEVHandle LocalOffset = getSCEV(Index); 1998 if (!isa<PointerType>(LocalOffset->getType())) 1999 // Getelementptr indicies are signed. 2000 LocalOffset = getTruncateOrSignExtend(LocalOffset, 2001 IntPtrTy); 2002 LocalOffset = 2003 getMulExpr(LocalOffset, 2004 getIntegerSCEV(TD->getTypePaddedSize(*GTI), 2005 IntPtrTy)); 2006 TotalOffset = getAddExpr(TotalOffset, LocalOffset); 2007 } 2008 } 2009 return getAddExpr(getSCEV(Base), TotalOffset); 2010 } 2011 2012 case Instruction::PHI: 2013 return createNodeForPHI(cast<PHINode>(U)); 2014 2015 case Instruction::Select: 2016 // This could be a smax or umax that was lowered earlier. 2017 // Try to recover it. 2018 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) { 2019 Value *LHS = ICI->getOperand(0); 2020 Value *RHS = ICI->getOperand(1); 2021 switch (ICI->getPredicate()) { 2022 case ICmpInst::ICMP_SLT: 2023 case ICmpInst::ICMP_SLE: 2024 std::swap(LHS, RHS); 2025 // fall through 2026 case ICmpInst::ICMP_SGT: 2027 case ICmpInst::ICMP_SGE: 2028 if (LHS == U->getOperand(1) && RHS == U->getOperand(2)) 2029 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS)); 2030 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1)) 2031 // ~smax(~x, ~y) == smin(x, y). 2032 return getNotSCEV(getSMaxExpr( 2033 getNotSCEV(getSCEV(LHS)), 2034 getNotSCEV(getSCEV(RHS)))); 2035 break; 2036 case ICmpInst::ICMP_ULT: 2037 case ICmpInst::ICMP_ULE: 2038 std::swap(LHS, RHS); 2039 // fall through 2040 case ICmpInst::ICMP_UGT: 2041 case ICmpInst::ICMP_UGE: 2042 if (LHS == U->getOperand(1) && RHS == U->getOperand(2)) 2043 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS)); 2044 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1)) 2045 // ~umax(~x, ~y) == umin(x, y) 2046 return getNotSCEV(getUMaxExpr(getNotSCEV(getSCEV(LHS)), 2047 getNotSCEV(getSCEV(RHS)))); 2048 break; 2049 default: 2050 break; 2051 } 2052 } 2053 2054 default: // We cannot analyze this expression. 2055 break; 2056 } 2057 2058 return getUnknown(V); 2059 } 2060 2061 2062 2063 //===----------------------------------------------------------------------===// 2064 // Iteration Count Computation Code 2065 // 2066 2067 /// getBackedgeTakenCount - If the specified loop has a predictable 2068 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute 2069 /// object. The backedge-taken count is the number of times the loop header 2070 /// will be branched to from within the loop. This is one less than the 2071 /// trip count of the loop, since it doesn't count the first iteration, 2072 /// when the header is branched to from outside the loop. 2073 /// 2074 /// Note that it is not valid to call this method on a loop without a 2075 /// loop-invariant backedge-taken count (see 2076 /// hasLoopInvariantBackedgeTakenCount). 2077 /// 2078 SCEVHandle ScalarEvolution::getBackedgeTakenCount(const Loop *L) { 2079 return getBackedgeTakenInfo(L).Exact; 2080 } 2081 2082 /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except 2083 /// return the least SCEV value that is known never to be less than the 2084 /// actual backedge taken count. 2085 SCEVHandle ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) { 2086 return getBackedgeTakenInfo(L).Max; 2087 } 2088 2089 const ScalarEvolution::BackedgeTakenInfo & 2090 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 2091 // Initially insert a CouldNotCompute for this loop. If the insertion 2092 // succeeds, procede to actually compute a backedge-taken count and 2093 // update the value. The temporary CouldNotCompute value tells SCEV 2094 // code elsewhere that it shouldn't attempt to request a new 2095 // backedge-taken count, which could result in infinite recursion. 2096 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair = 2097 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute())); 2098 if (Pair.second) { 2099 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L); 2100 if (ItCount.Exact != UnknownValue) { 2101 assert(ItCount.Exact->isLoopInvariant(L) && 2102 ItCount.Max->isLoopInvariant(L) && 2103 "Computed trip count isn't loop invariant for loop!"); 2104 ++NumTripCountsComputed; 2105 2106 // Update the value in the map. 2107 Pair.first->second = ItCount; 2108 } else if (isa<PHINode>(L->getHeader()->begin())) { 2109 // Only count loops that have phi nodes as not being computable. 2110 ++NumTripCountsNotComputed; 2111 } 2112 2113 // Now that we know more about the trip count for this loop, forget any 2114 // existing SCEV values for PHI nodes in this loop since they are only 2115 // conservative estimates made without the benefit 2116 // of trip count information. 2117 if (ItCount.hasAnyInfo()) 2118 for (BasicBlock::iterator I = L->getHeader()->begin(); 2119 PHINode *PN = dyn_cast<PHINode>(I); ++I) 2120 deleteValueFromRecords(PN); 2121 } 2122 return Pair.first->second; 2123 } 2124 2125 /// forgetLoopBackedgeTakenCount - This method should be called by the 2126 /// client when it has changed a loop in a way that may effect 2127 /// ScalarEvolution's ability to compute a trip count, or if the loop 2128 /// is deleted. 2129 void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) { 2130 BackedgeTakenCounts.erase(L); 2131 } 2132 2133 /// ComputeBackedgeTakenCount - Compute the number of times the backedge 2134 /// of the specified loop will execute. 2135 ScalarEvolution::BackedgeTakenInfo 2136 ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) { 2137 // If the loop has a non-one exit block count, we can't analyze it. 2138 SmallVector<BasicBlock*, 8> ExitBlocks; 2139 L->getExitBlocks(ExitBlocks); 2140 if (ExitBlocks.size() != 1) return UnknownValue; 2141 2142 // Okay, there is one exit block. Try to find the condition that causes the 2143 // loop to be exited. 2144 BasicBlock *ExitBlock = ExitBlocks[0]; 2145 2146 BasicBlock *ExitingBlock = 0; 2147 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock); 2148 PI != E; ++PI) 2149 if (L->contains(*PI)) { 2150 if (ExitingBlock == 0) 2151 ExitingBlock = *PI; 2152 else 2153 return UnknownValue; // More than one block exiting! 2154 } 2155 assert(ExitingBlock && "No exits from loop, something is broken!"); 2156 2157 // Okay, we've computed the exiting block. See what condition causes us to 2158 // exit. 2159 // 2160 // FIXME: we should be able to handle switch instructions (with a single exit) 2161 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator()); 2162 if (ExitBr == 0) return UnknownValue; 2163 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!"); 2164 2165 // At this point, we know we have a conditional branch that determines whether 2166 // the loop is exited. However, we don't know if the branch is executed each 2167 // time through the loop. If not, then the execution count of the branch will 2168 // not be equal to the trip count of the loop. 2169 // 2170 // Currently we check for this by checking to see if the Exit branch goes to 2171 // the loop header. If so, we know it will always execute the same number of 2172 // times as the loop. We also handle the case where the exit block *is* the 2173 // loop header. This is common for un-rotated loops. More extensive analysis 2174 // could be done to handle more cases here. 2175 if (ExitBr->getSuccessor(0) != L->getHeader() && 2176 ExitBr->getSuccessor(1) != L->getHeader() && 2177 ExitBr->getParent() != L->getHeader()) 2178 return UnknownValue; 2179 2180 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition()); 2181 2182 // If it's not an integer comparison then compute it the hard way. 2183 // Note that ICmpInst deals with pointer comparisons too so we must check 2184 // the type of the operand. 2185 if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType())) 2186 return ComputeBackedgeTakenCountExhaustively(L, ExitBr->getCondition(), 2187 ExitBr->getSuccessor(0) == ExitBlock); 2188 2189 // If the condition was exit on true, convert the condition to exit on false 2190 ICmpInst::Predicate Cond; 2191 if (ExitBr->getSuccessor(1) == ExitBlock) 2192 Cond = ExitCond->getPredicate(); 2193 else 2194 Cond = ExitCond->getInversePredicate(); 2195 2196 // Handle common loops like: for (X = "string"; *X; ++X) 2197 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 2198 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 2199 SCEVHandle ItCnt = 2200 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond); 2201 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt; 2202 } 2203 2204 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0)); 2205 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1)); 2206 2207 // Try to evaluate any dependencies out of the loop. 2208 SCEVHandle Tmp = getSCEVAtScope(LHS, L); 2209 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp; 2210 Tmp = getSCEVAtScope(RHS, L); 2211 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp; 2212 2213 // At this point, we would like to compute how many iterations of the 2214 // loop the predicate will return true for these inputs. 2215 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) { 2216 // If there is a loop-invariant, force it into the RHS. 2217 std::swap(LHS, RHS); 2218 Cond = ICmpInst::getSwappedPredicate(Cond); 2219 } 2220 2221 // If we have a comparison of a chrec against a constant, try to use value 2222 // ranges to answer this query. 2223 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 2224 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 2225 if (AddRec->getLoop() == L) { 2226 // Form the comparison range using the constant of the correct type so 2227 // that the ConstantRange class knows to do a signed or unsigned 2228 // comparison. 2229 ConstantInt *CompVal = RHSC->getValue(); 2230 const Type *RealTy = ExitCond->getOperand(0)->getType(); 2231 CompVal = dyn_cast<ConstantInt>( 2232 ConstantExpr::getBitCast(CompVal, RealTy)); 2233 if (CompVal) { 2234 // Form the constant range. 2235 ConstantRange CompRange( 2236 ICmpInst::makeConstantRange(Cond, CompVal->getValue())); 2237 2238 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, *this); 2239 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 2240 } 2241 } 2242 2243 switch (Cond) { 2244 case ICmpInst::ICMP_NE: { // while (X != Y) 2245 // Convert to: while (X-Y != 0) 2246 SCEVHandle TC = HowFarToZero(getMinusSCEV(LHS, RHS), L); 2247 if (!isa<SCEVCouldNotCompute>(TC)) return TC; 2248 break; 2249 } 2250 case ICmpInst::ICMP_EQ: { 2251 // Convert to: while (X-Y == 0) // while (X == Y) 2252 SCEVHandle TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L); 2253 if (!isa<SCEVCouldNotCompute>(TC)) return TC; 2254 break; 2255 } 2256 case ICmpInst::ICMP_SLT: { 2257 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true); 2258 if (BTI.hasAnyInfo()) return BTI; 2259 break; 2260 } 2261 case ICmpInst::ICMP_SGT: { 2262 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS), 2263 getNotSCEV(RHS), L, true); 2264 if (BTI.hasAnyInfo()) return BTI; 2265 break; 2266 } 2267 case ICmpInst::ICMP_ULT: { 2268 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false); 2269 if (BTI.hasAnyInfo()) return BTI; 2270 break; 2271 } 2272 case ICmpInst::ICMP_UGT: { 2273 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS), 2274 getNotSCEV(RHS), L, false); 2275 if (BTI.hasAnyInfo()) return BTI; 2276 break; 2277 } 2278 default: 2279 #if 0 2280 errs() << "ComputeBackedgeTakenCount "; 2281 if (ExitCond->getOperand(0)->getType()->isUnsigned()) 2282 errs() << "[unsigned] "; 2283 errs() << *LHS << " " 2284 << Instruction::getOpcodeName(Instruction::ICmp) 2285 << " " << *RHS << "\n"; 2286 #endif 2287 break; 2288 } 2289 return 2290 ComputeBackedgeTakenCountExhaustively(L, ExitCond, 2291 ExitBr->getSuccessor(0) == ExitBlock); 2292 } 2293 2294 static ConstantInt * 2295 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 2296 ScalarEvolution &SE) { 2297 SCEVHandle InVal = SE.getConstant(C); 2298 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE); 2299 assert(isa<SCEVConstant>(Val) && 2300 "Evaluation of SCEV at constant didn't fold correctly?"); 2301 return cast<SCEVConstant>(Val)->getValue(); 2302 } 2303 2304 /// GetAddressedElementFromGlobal - Given a global variable with an initializer 2305 /// and a GEP expression (missing the pointer index) indexing into it, return 2306 /// the addressed element of the initializer or null if the index expression is 2307 /// invalid. 2308 static Constant * 2309 GetAddressedElementFromGlobal(GlobalVariable *GV, 2310 const std::vector<ConstantInt*> &Indices) { 2311 Constant *Init = GV->getInitializer(); 2312 for (unsigned i = 0, e = Indices.size(); i != e; ++i) { 2313 uint64_t Idx = Indices[i]->getZExtValue(); 2314 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) { 2315 assert(Idx < CS->getNumOperands() && "Bad struct index!"); 2316 Init = cast<Constant>(CS->getOperand(Idx)); 2317 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) { 2318 if (Idx >= CA->getNumOperands()) return 0; // Bogus program 2319 Init = cast<Constant>(CA->getOperand(Idx)); 2320 } else if (isa<ConstantAggregateZero>(Init)) { 2321 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) { 2322 assert(Idx < STy->getNumElements() && "Bad struct index!"); 2323 Init = Constant::getNullValue(STy->getElementType(Idx)); 2324 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) { 2325 if (Idx >= ATy->getNumElements()) return 0; // Bogus program 2326 Init = Constant::getNullValue(ATy->getElementType()); 2327 } else { 2328 assert(0 && "Unknown constant aggregate type!"); 2329 } 2330 return 0; 2331 } else { 2332 return 0; // Unknown initializer type 2333 } 2334 } 2335 return Init; 2336 } 2337 2338 /// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of 2339 /// 'icmp op load X, cst', try to see if we can compute the backedge 2340 /// execution count. 2341 SCEVHandle ScalarEvolution:: 2342 ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI, Constant *RHS, 2343 const Loop *L, 2344 ICmpInst::Predicate predicate) { 2345 if (LI->isVolatile()) return UnknownValue; 2346 2347 // Check to see if the loaded pointer is a getelementptr of a global. 2348 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 2349 if (!GEP) return UnknownValue; 2350 2351 // Make sure that it is really a constant global we are gepping, with an 2352 // initializer, and make sure the first IDX is really 0. 2353 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 2354 if (!GV || !GV->isConstant() || !GV->hasInitializer() || 2355 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 2356 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 2357 return UnknownValue; 2358 2359 // Okay, we allow one non-constant index into the GEP instruction. 2360 Value *VarIdx = 0; 2361 std::vector<ConstantInt*> Indexes; 2362 unsigned VarIdxNum = 0; 2363 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 2364 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 2365 Indexes.push_back(CI); 2366 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 2367 if (VarIdx) return UnknownValue; // Multiple non-constant idx's. 2368 VarIdx = GEP->getOperand(i); 2369 VarIdxNum = i-2; 2370 Indexes.push_back(0); 2371 } 2372 2373 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 2374 // Check to see if X is a loop variant variable value now. 2375 SCEVHandle Idx = getSCEV(VarIdx); 2376 SCEVHandle Tmp = getSCEVAtScope(Idx, L); 2377 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp; 2378 2379 // We can only recognize very limited forms of loop index expressions, in 2380 // particular, only affine AddRec's like {C1,+,C2}. 2381 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 2382 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) || 2383 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 2384 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 2385 return UnknownValue; 2386 2387 unsigned MaxSteps = MaxBruteForceIterations; 2388 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 2389 ConstantInt *ItCst = 2390 ConstantInt::get(IdxExpr->getType(), IterationNum); 2391 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 2392 2393 // Form the GEP offset. 2394 Indexes[VarIdxNum] = Val; 2395 2396 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes); 2397 if (Result == 0) break; // Cannot compute! 2398 2399 // Evaluate the condition for this iteration. 2400 Result = ConstantExpr::getICmp(predicate, Result, RHS); 2401 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 2402 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 2403 #if 0 2404 errs() << "\n***\n*** Computed loop count " << *ItCst 2405 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader() 2406 << "***\n"; 2407 #endif 2408 ++NumArrayLenItCounts; 2409 return getConstant(ItCst); // Found terminating iteration! 2410 } 2411 } 2412 return UnknownValue; 2413 } 2414 2415 2416 /// CanConstantFold - Return true if we can constant fold an instruction of the 2417 /// specified type, assuming that all operands were constants. 2418 static bool CanConstantFold(const Instruction *I) { 2419 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 2420 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I)) 2421 return true; 2422 2423 if (const CallInst *CI = dyn_cast<CallInst>(I)) 2424 if (const Function *F = CI->getCalledFunction()) 2425 return canConstantFoldCallTo(F); 2426 return false; 2427 } 2428 2429 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 2430 /// in the loop that V is derived from. We allow arbitrary operations along the 2431 /// way, but the operands of an operation must either be constants or a value 2432 /// derived from a constant PHI. If this expression does not fit with these 2433 /// constraints, return null. 2434 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 2435 // If this is not an instruction, or if this is an instruction outside of the 2436 // loop, it can't be derived from a loop PHI. 2437 Instruction *I = dyn_cast<Instruction>(V); 2438 if (I == 0 || !L->contains(I->getParent())) return 0; 2439 2440 if (PHINode *PN = dyn_cast<PHINode>(I)) { 2441 if (L->getHeader() == I->getParent()) 2442 return PN; 2443 else 2444 // We don't currently keep track of the control flow needed to evaluate 2445 // PHIs, so we cannot handle PHIs inside of loops. 2446 return 0; 2447 } 2448 2449 // If we won't be able to constant fold this expression even if the operands 2450 // are constants, return early. 2451 if (!CanConstantFold(I)) return 0; 2452 2453 // Otherwise, we can evaluate this instruction if all of its operands are 2454 // constant or derived from a PHI node themselves. 2455 PHINode *PHI = 0; 2456 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op) 2457 if (!(isa<Constant>(I->getOperand(Op)) || 2458 isa<GlobalValue>(I->getOperand(Op)))) { 2459 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L); 2460 if (P == 0) return 0; // Not evolving from PHI 2461 if (PHI == 0) 2462 PHI = P; 2463 else if (PHI != P) 2464 return 0; // Evolving from multiple different PHIs. 2465 } 2466 2467 // This is a expression evolving from a constant PHI! 2468 return PHI; 2469 } 2470 2471 /// EvaluateExpression - Given an expression that passes the 2472 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 2473 /// in the loop has the value PHIVal. If we can't fold this expression for some 2474 /// reason, return null. 2475 static Constant *EvaluateExpression(Value *V, Constant *PHIVal) { 2476 if (isa<PHINode>(V)) return PHIVal; 2477 if (Constant *C = dyn_cast<Constant>(V)) return C; 2478 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV; 2479 Instruction *I = cast<Instruction>(V); 2480 2481 std::vector<Constant*> Operands; 2482 Operands.resize(I->getNumOperands()); 2483 2484 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 2485 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal); 2486 if (Operands[i] == 0) return 0; 2487 } 2488 2489 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 2490 return ConstantFoldCompareInstOperands(CI->getPredicate(), 2491 &Operands[0], Operands.size()); 2492 else 2493 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), 2494 &Operands[0], Operands.size()); 2495 } 2496 2497 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 2498 /// in the header of its containing loop, we know the loop executes a 2499 /// constant number of times, and the PHI node is just a recurrence 2500 /// involving constants, fold it. 2501 Constant *ScalarEvolution:: 2502 getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs, const Loop *L){ 2503 std::map<PHINode*, Constant*>::iterator I = 2504 ConstantEvolutionLoopExitValue.find(PN); 2505 if (I != ConstantEvolutionLoopExitValue.end()) 2506 return I->second; 2507 2508 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations))) 2509 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it. 2510 2511 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 2512 2513 // Since the loop is canonicalized, the PHI node must have two entries. One 2514 // entry must be a constant (coming in from outside of the loop), and the 2515 // second must be derived from the same PHI. 2516 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1)); 2517 Constant *StartCST = 2518 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge)); 2519 if (StartCST == 0) 2520 return RetVal = 0; // Must be a constant. 2521 2522 Value *BEValue = PN->getIncomingValue(SecondIsBackedge); 2523 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L); 2524 if (PN2 != PN) 2525 return RetVal = 0; // Not derived from same PHI. 2526 2527 // Execute the loop symbolically to determine the exit value. 2528 if (BEs.getActiveBits() >= 32) 2529 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it! 2530 2531 unsigned NumIterations = BEs.getZExtValue(); // must be in range 2532 unsigned IterationNum = 0; 2533 for (Constant *PHIVal = StartCST; ; ++IterationNum) { 2534 if (IterationNum == NumIterations) 2535 return RetVal = PHIVal; // Got exit value! 2536 2537 // Compute the value of the PHI node for the next iteration. 2538 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal); 2539 if (NextPHI == PHIVal) 2540 return RetVal = NextPHI; // Stopped evolving! 2541 if (NextPHI == 0) 2542 return 0; // Couldn't evaluate! 2543 PHIVal = NextPHI; 2544 } 2545 } 2546 2547 /// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a 2548 /// constant number of times (the condition evolves only from constants), 2549 /// try to evaluate a few iterations of the loop until we get the exit 2550 /// condition gets a value of ExitWhen (true or false). If we cannot 2551 /// evaluate the trip count of the loop, return UnknownValue. 2552 SCEVHandle ScalarEvolution:: 2553 ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) { 2554 PHINode *PN = getConstantEvolvingPHI(Cond, L); 2555 if (PN == 0) return UnknownValue; 2556 2557 // Since the loop is canonicalized, the PHI node must have two entries. One 2558 // entry must be a constant (coming in from outside of the loop), and the 2559 // second must be derived from the same PHI. 2560 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1)); 2561 Constant *StartCST = 2562 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge)); 2563 if (StartCST == 0) return UnknownValue; // Must be a constant. 2564 2565 Value *BEValue = PN->getIncomingValue(SecondIsBackedge); 2566 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L); 2567 if (PN2 != PN) return UnknownValue; // Not derived from same PHI. 2568 2569 // Okay, we find a PHI node that defines the trip count of this loop. Execute 2570 // the loop symbolically to determine when the condition gets a value of 2571 // "ExitWhen". 2572 unsigned IterationNum = 0; 2573 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 2574 for (Constant *PHIVal = StartCST; 2575 IterationNum != MaxIterations; ++IterationNum) { 2576 ConstantInt *CondVal = 2577 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal)); 2578 2579 // Couldn't symbolically evaluate. 2580 if (!CondVal) return UnknownValue; 2581 2582 if (CondVal->getValue() == uint64_t(ExitWhen)) { 2583 ConstantEvolutionLoopExitValue[PN] = PHIVal; 2584 ++NumBruteForceTripCountsComputed; 2585 return getConstant(ConstantInt::get(Type::Int32Ty, IterationNum)); 2586 } 2587 2588 // Compute the value of the PHI node for the next iteration. 2589 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal); 2590 if (NextPHI == 0 || NextPHI == PHIVal) 2591 return UnknownValue; // Couldn't evaluate or not making progress... 2592 PHIVal = NextPHI; 2593 } 2594 2595 // Too many iterations were needed to evaluate. 2596 return UnknownValue; 2597 } 2598 2599 /// getSCEVAtScope - Compute the value of the specified expression within the 2600 /// indicated loop (which may be null to indicate in no loop). If the 2601 /// expression cannot be evaluated, return UnknownValue. 2602 SCEVHandle ScalarEvolution::getSCEVAtScope(SCEV *V, const Loop *L) { 2603 // FIXME: this should be turned into a virtual method on SCEV! 2604 2605 if (isa<SCEVConstant>(V)) return V; 2606 2607 // If this instruction is evolved from a constant-evolving PHI, compute the 2608 // exit value from the loop without using SCEVs. 2609 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 2610 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 2611 const Loop *LI = (*this->LI)[I->getParent()]; 2612 if (LI && LI->getParentLoop() == L) // Looking for loop exit value. 2613 if (PHINode *PN = dyn_cast<PHINode>(I)) 2614 if (PN->getParent() == LI->getHeader()) { 2615 // Okay, there is no closed form solution for the PHI node. Check 2616 // to see if the loop that contains it has a known backedge-taken 2617 // count. If so, we may be able to force computation of the exit 2618 // value. 2619 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(LI); 2620 if (SCEVConstant *BTCC = 2621 dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 2622 // Okay, we know how many times the containing loop executes. If 2623 // this is a constant evolving PHI node, get the final value at 2624 // the specified iteration number. 2625 Constant *RV = getConstantEvolutionLoopExitValue(PN, 2626 BTCC->getValue()->getValue(), 2627 LI); 2628 if (RV) return getUnknown(RV); 2629 } 2630 } 2631 2632 // Okay, this is an expression that we cannot symbolically evaluate 2633 // into a SCEV. Check to see if it's possible to symbolically evaluate 2634 // the arguments into constants, and if so, try to constant propagate the 2635 // result. This is particularly useful for computing loop exit values. 2636 if (CanConstantFold(I)) { 2637 std::vector<Constant*> Operands; 2638 Operands.reserve(I->getNumOperands()); 2639 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 2640 Value *Op = I->getOperand(i); 2641 if (Constant *C = dyn_cast<Constant>(Op)) { 2642 Operands.push_back(C); 2643 } else { 2644 // If any of the operands is non-constant and if they are 2645 // non-integer and non-pointer, don't even try to analyze them 2646 // with scev techniques. 2647 if (!isSCEVable(Op->getType())) 2648 return V; 2649 2650 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L); 2651 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) { 2652 Constant *C = SC->getValue(); 2653 if (C->getType() != Op->getType()) 2654 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 2655 Op->getType(), 2656 false), 2657 C, Op->getType()); 2658 Operands.push_back(C); 2659 } else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) { 2660 if (Constant *C = dyn_cast<Constant>(SU->getValue())) { 2661 if (C->getType() != Op->getType()) 2662 C = 2663 ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 2664 Op->getType(), 2665 false), 2666 C, Op->getType()); 2667 Operands.push_back(C); 2668 } else 2669 return V; 2670 } else { 2671 return V; 2672 } 2673 } 2674 } 2675 2676 Constant *C; 2677 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 2678 C = ConstantFoldCompareInstOperands(CI->getPredicate(), 2679 &Operands[0], Operands.size()); 2680 else 2681 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(), 2682 &Operands[0], Operands.size()); 2683 return getUnknown(C); 2684 } 2685 } 2686 2687 // This is some other type of SCEVUnknown, just return it. 2688 return V; 2689 } 2690 2691 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 2692 // Avoid performing the look-up in the common case where the specified 2693 // expression has no loop-variant portions. 2694 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 2695 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 2696 if (OpAtScope != Comm->getOperand(i)) { 2697 if (OpAtScope == UnknownValue) return UnknownValue; 2698 // Okay, at least one of these operands is loop variant but might be 2699 // foldable. Build a new instance of the folded commutative expression. 2700 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i); 2701 NewOps.push_back(OpAtScope); 2702 2703 for (++i; i != e; ++i) { 2704 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 2705 if (OpAtScope == UnknownValue) return UnknownValue; 2706 NewOps.push_back(OpAtScope); 2707 } 2708 if (isa<SCEVAddExpr>(Comm)) 2709 return getAddExpr(NewOps); 2710 if (isa<SCEVMulExpr>(Comm)) 2711 return getMulExpr(NewOps); 2712 if (isa<SCEVSMaxExpr>(Comm)) 2713 return getSMaxExpr(NewOps); 2714 if (isa<SCEVUMaxExpr>(Comm)) 2715 return getUMaxExpr(NewOps); 2716 assert(0 && "Unknown commutative SCEV type!"); 2717 } 2718 } 2719 // If we got here, all operands are loop invariant. 2720 return Comm; 2721 } 2722 2723 if (SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 2724 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L); 2725 if (LHS == UnknownValue) return LHS; 2726 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L); 2727 if (RHS == UnknownValue) return RHS; 2728 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 2729 return Div; // must be loop invariant 2730 return getUDivExpr(LHS, RHS); 2731 } 2732 2733 // If this is a loop recurrence for a loop that does not contain L, then we 2734 // are dealing with the final value computed by the loop. 2735 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 2736 if (!L || !AddRec->getLoop()->contains(L->getHeader())) { 2737 // To evaluate this recurrence, we need to know how many times the AddRec 2738 // loop iterates. Compute this now. 2739 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 2740 if (BackedgeTakenCount == UnknownValue) return UnknownValue; 2741 2742 // Then, evaluate the AddRec. 2743 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 2744 } 2745 return UnknownValue; 2746 } 2747 2748 if (SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 2749 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L); 2750 if (Op == UnknownValue) return Op; 2751 if (Op == Cast->getOperand()) 2752 return Cast; // must be loop invariant 2753 return getZeroExtendExpr(Op, Cast->getType()); 2754 } 2755 2756 if (SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 2757 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L); 2758 if (Op == UnknownValue) return Op; 2759 if (Op == Cast->getOperand()) 2760 return Cast; // must be loop invariant 2761 return getSignExtendExpr(Op, Cast->getType()); 2762 } 2763 2764 if (SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 2765 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L); 2766 if (Op == UnknownValue) return Op; 2767 if (Op == Cast->getOperand()) 2768 return Cast; // must be loop invariant 2769 return getTruncateExpr(Op, Cast->getType()); 2770 } 2771 2772 assert(0 && "Unknown SCEV type!"); 2773 } 2774 2775 /// getSCEVAtScope - Return a SCEV expression handle for the specified value 2776 /// at the specified scope in the program. The L value specifies a loop 2777 /// nest to evaluate the expression at, where null is the top-level or a 2778 /// specified loop is immediately inside of the loop. 2779 /// 2780 /// This method can be used to compute the exit value for a variable defined 2781 /// in a loop by querying what the value will hold in the parent loop. 2782 /// 2783 /// If this value is not computable at this scope, a SCEVCouldNotCompute 2784 /// object is returned. 2785 SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 2786 return getSCEVAtScope(getSCEV(V), L); 2787 } 2788 2789 /// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the 2790 /// following equation: 2791 /// 2792 /// A * X = B (mod N) 2793 /// 2794 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 2795 /// A and B isn't important. 2796 /// 2797 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 2798 static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B, 2799 ScalarEvolution &SE) { 2800 uint32_t BW = A.getBitWidth(); 2801 assert(BW == B.getBitWidth() && "Bit widths must be the same."); 2802 assert(A != 0 && "A must be non-zero."); 2803 2804 // 1. D = gcd(A, N) 2805 // 2806 // The gcd of A and N may have only one prime factor: 2. The number of 2807 // trailing zeros in A is its multiplicity 2808 uint32_t Mult2 = A.countTrailingZeros(); 2809 // D = 2^Mult2 2810 2811 // 2. Check if B is divisible by D. 2812 // 2813 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 2814 // is not less than multiplicity of this prime factor for D. 2815 if (B.countTrailingZeros() < Mult2) 2816 return SE.getCouldNotCompute(); 2817 2818 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 2819 // modulo (N / D). 2820 // 2821 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this 2822 // bit width during computations. 2823 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 2824 APInt Mod(BW + 1, 0); 2825 Mod.set(BW - Mult2); // Mod = N / D 2826 APInt I = AD.multiplicativeInverse(Mod); 2827 2828 // 4. Compute the minimum unsigned root of the equation: 2829 // I * (B / D) mod (N / D) 2830 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod); 2831 2832 // The result is guaranteed to be less than 2^BW so we may truncate it to BW 2833 // bits. 2834 return SE.getConstant(Result.trunc(BW)); 2835 } 2836 2837 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the 2838 /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which 2839 /// might be the same) or two SCEVCouldNotCompute objects. 2840 /// 2841 static std::pair<SCEVHandle,SCEVHandle> 2842 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 2843 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 2844 SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 2845 SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 2846 SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 2847 2848 // We currently can only solve this if the coefficients are constants. 2849 if (!LC || !MC || !NC) { 2850 SCEV *CNC = SE.getCouldNotCompute(); 2851 return std::make_pair(CNC, CNC); 2852 } 2853 2854 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth(); 2855 const APInt &L = LC->getValue()->getValue(); 2856 const APInt &M = MC->getValue()->getValue(); 2857 const APInt &N = NC->getValue()->getValue(); 2858 APInt Two(BitWidth, 2); 2859 APInt Four(BitWidth, 4); 2860 2861 { 2862 using namespace APIntOps; 2863 const APInt& C = L; 2864 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C 2865 // The B coefficient is M-N/2 2866 APInt B(M); 2867 B -= sdiv(N,Two); 2868 2869 // The A coefficient is N/2 2870 APInt A(N.sdiv(Two)); 2871 2872 // Compute the B^2-4ac term. 2873 APInt SqrtTerm(B); 2874 SqrtTerm *= B; 2875 SqrtTerm -= Four * (A * C); 2876 2877 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest 2878 // integer value or else APInt::sqrt() will assert. 2879 APInt SqrtVal(SqrtTerm.sqrt()); 2880 2881 // Compute the two solutions for the quadratic formula. 2882 // The divisions must be performed as signed divisions. 2883 APInt NegB(-B); 2884 APInt TwoA( A << 1 ); 2885 if (TwoA.isMinValue()) { 2886 SCEV *CNC = SE.getCouldNotCompute(); 2887 return std::make_pair(CNC, CNC); 2888 } 2889 2890 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA)); 2891 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA)); 2892 2893 return std::make_pair(SE.getConstant(Solution1), 2894 SE.getConstant(Solution2)); 2895 } // end APIntOps namespace 2896 } 2897 2898 /// HowFarToZero - Return the number of times a backedge comparing the specified 2899 /// value to zero will execute. If not computable, return UnknownValue 2900 SCEVHandle ScalarEvolution::HowFarToZero(SCEV *V, const Loop *L) { 2901 // If the value is a constant 2902 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 2903 // If the value is already zero, the branch will execute zero times. 2904 if (C->getValue()->isZero()) return C; 2905 return UnknownValue; // Otherwise it will loop infinitely. 2906 } 2907 2908 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V); 2909 if (!AddRec || AddRec->getLoop() != L) 2910 return UnknownValue; 2911 2912 if (AddRec->isAffine()) { 2913 // If this is an affine expression, the execution count of this branch is 2914 // the minimum unsigned root of the following equation: 2915 // 2916 // Start + Step*N = 0 (mod 2^BW) 2917 // 2918 // equivalent to: 2919 // 2920 // Step*N = -Start (mod 2^BW) 2921 // 2922 // where BW is the common bit width of Start and Step. 2923 2924 // Get the initial value for the loop. 2925 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 2926 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue; 2927 2928 SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 2929 2930 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) { 2931 // For now we handle only constant steps. 2932 2933 // First, handle unitary steps. 2934 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so: 2935 return getNegativeSCEV(Start); // N = -Start (as unsigned) 2936 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so: 2937 return Start; // N = Start (as unsigned) 2938 2939 // Then, try to solve the above equation provided that Start is constant. 2940 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) 2941 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(), 2942 -StartC->getValue()->getValue(), 2943 *this); 2944 } 2945 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) { 2946 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 2947 // the quadratic equation to solve it. 2948 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec, 2949 *this); 2950 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first); 2951 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second); 2952 if (R1) { 2953 #if 0 2954 errs() << "HFTZ: " << *V << " - sol#1: " << *R1 2955 << " sol#2: " << *R2 << "\n"; 2956 #endif 2957 // Pick the smallest positive root value. 2958 if (ConstantInt *CB = 2959 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT, 2960 R1->getValue(), R2->getValue()))) { 2961 if (CB->getZExtValue() == false) 2962 std::swap(R1, R2); // R1 is the minimum root now. 2963 2964 // We can only use this value if the chrec ends up with an exact zero 2965 // value at this index. When solving for "X*X != 5", for example, we 2966 // should not accept a root of 2. 2967 SCEVHandle Val = AddRec->evaluateAtIteration(R1, *this); 2968 if (Val->isZero()) 2969 return R1; // We found a quadratic root! 2970 } 2971 } 2972 } 2973 2974 return UnknownValue; 2975 } 2976 2977 /// HowFarToNonZero - Return the number of times a backedge checking the 2978 /// specified value for nonzero will execute. If not computable, return 2979 /// UnknownValue 2980 SCEVHandle ScalarEvolution::HowFarToNonZero(SCEV *V, const Loop *L) { 2981 // Loops that look like: while (X == 0) are very strange indeed. We don't 2982 // handle them yet except for the trivial case. This could be expanded in the 2983 // future as needed. 2984 2985 // If the value is a constant, check to see if it is known to be non-zero 2986 // already. If so, the backedge will execute zero times. 2987 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 2988 if (!C->getValue()->isNullValue()) 2989 return getIntegerSCEV(0, C->getType()); 2990 return UnknownValue; // Otherwise it will loop infinitely. 2991 } 2992 2993 // We could implement others, but I really doubt anyone writes loops like 2994 // this, and if they did, they would already be constant folded. 2995 return UnknownValue; 2996 } 2997 2998 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB 2999 /// (which may not be an immediate predecessor) which has exactly one 3000 /// successor from which BB is reachable, or null if no such block is 3001 /// found. 3002 /// 3003 BasicBlock * 3004 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) { 3005 // If the block has a unique predecessor, then there is no path from the 3006 // predecessor to the block that does not go through the direct edge 3007 // from the predecessor to the block. 3008 if (BasicBlock *Pred = BB->getSinglePredecessor()) 3009 return Pred; 3010 3011 // A loop's header is defined to be a block that dominates the loop. 3012 // If the loop has a preheader, it must be a block that has exactly 3013 // one successor that can reach BB. This is slightly more strict 3014 // than necessary, but works if critical edges are split. 3015 if (Loop *L = LI->getLoopFor(BB)) 3016 return L->getLoopPreheader(); 3017 3018 return 0; 3019 } 3020 3021 /// isLoopGuardedByCond - Test whether entry to the loop is protected by 3022 /// a conditional between LHS and RHS. This is used to help avoid max 3023 /// expressions in loop trip counts. 3024 bool ScalarEvolution::isLoopGuardedByCond(const Loop *L, 3025 ICmpInst::Predicate Pred, 3026 SCEV *LHS, SCEV *RHS) { 3027 BasicBlock *Preheader = L->getLoopPreheader(); 3028 BasicBlock *PreheaderDest = L->getHeader(); 3029 3030 // Starting at the preheader, climb up the predecessor chain, as long as 3031 // there are predecessors that can be found that have unique successors 3032 // leading to the original header. 3033 for (; Preheader; 3034 PreheaderDest = Preheader, 3035 Preheader = getPredecessorWithUniqueSuccessorForBB(Preheader)) { 3036 3037 BranchInst *LoopEntryPredicate = 3038 dyn_cast<BranchInst>(Preheader->getTerminator()); 3039 if (!LoopEntryPredicate || 3040 LoopEntryPredicate->isUnconditional()) 3041 continue; 3042 3043 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition()); 3044 if (!ICI) continue; 3045 3046 // Now that we found a conditional branch that dominates the loop, check to 3047 // see if it is the comparison we are looking for. 3048 Value *PreCondLHS = ICI->getOperand(0); 3049 Value *PreCondRHS = ICI->getOperand(1); 3050 ICmpInst::Predicate Cond; 3051 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest) 3052 Cond = ICI->getPredicate(); 3053 else 3054 Cond = ICI->getInversePredicate(); 3055 3056 if (Cond == Pred) 3057 ; // An exact match. 3058 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE) 3059 ; // The actual condition is beyond sufficient. 3060 else 3061 // Check a few special cases. 3062 switch (Cond) { 3063 case ICmpInst::ICMP_UGT: 3064 if (Pred == ICmpInst::ICMP_ULT) { 3065 std::swap(PreCondLHS, PreCondRHS); 3066 Cond = ICmpInst::ICMP_ULT; 3067 break; 3068 } 3069 continue; 3070 case ICmpInst::ICMP_SGT: 3071 if (Pred == ICmpInst::ICMP_SLT) { 3072 std::swap(PreCondLHS, PreCondRHS); 3073 Cond = ICmpInst::ICMP_SLT; 3074 break; 3075 } 3076 continue; 3077 case ICmpInst::ICMP_NE: 3078 // Expressions like (x >u 0) are often canonicalized to (x != 0), 3079 // so check for this case by checking if the NE is comparing against 3080 // a minimum or maximum constant. 3081 if (!ICmpInst::isTrueWhenEqual(Pred)) 3082 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) { 3083 const APInt &A = CI->getValue(); 3084 switch (Pred) { 3085 case ICmpInst::ICMP_SLT: 3086 if (A.isMaxSignedValue()) break; 3087 continue; 3088 case ICmpInst::ICMP_SGT: 3089 if (A.isMinSignedValue()) break; 3090 continue; 3091 case ICmpInst::ICMP_ULT: 3092 if (A.isMaxValue()) break; 3093 continue; 3094 case ICmpInst::ICMP_UGT: 3095 if (A.isMinValue()) break; 3096 continue; 3097 default: 3098 continue; 3099 } 3100 Cond = ICmpInst::ICMP_NE; 3101 // NE is symmetric but the original comparison may not be. Swap 3102 // the operands if necessary so that they match below. 3103 if (isa<SCEVConstant>(LHS)) 3104 std::swap(PreCondLHS, PreCondRHS); 3105 break; 3106 } 3107 continue; 3108 default: 3109 // We weren't able to reconcile the condition. 3110 continue; 3111 } 3112 3113 if (!PreCondLHS->getType()->isInteger()) continue; 3114 3115 SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS); 3116 SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS); 3117 if ((LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) || 3118 (LHS == getNotSCEV(PreCondRHSSCEV) && 3119 RHS == getNotSCEV(PreCondLHSSCEV))) 3120 return true; 3121 } 3122 3123 return false; 3124 } 3125 3126 /// HowManyLessThans - Return the number of times a backedge containing the 3127 /// specified less-than comparison will execute. If not computable, return 3128 /// UnknownValue. 3129 ScalarEvolution::BackedgeTakenInfo ScalarEvolution:: 3130 HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L, bool isSigned) { 3131 // Only handle: "ADDREC < LoopInvariant". 3132 if (!RHS->isLoopInvariant(L)) return UnknownValue; 3133 3134 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS); 3135 if (!AddRec || AddRec->getLoop() != L) 3136 return UnknownValue; 3137 3138 if (AddRec->isAffine()) { 3139 // FORNOW: We only support unit strides. 3140 unsigned BitWidth = getTypeSizeInBits(AddRec->getType()); 3141 SCEVHandle Step = AddRec->getStepRecurrence(*this); 3142 SCEVHandle NegOne = getIntegerSCEV(-1, AddRec->getType()); 3143 3144 // TODO: handle non-constant strides. 3145 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step); 3146 if (!CStep || CStep->isZero()) 3147 return UnknownValue; 3148 if (CStep->getValue()->getValue() == 1) { 3149 // With unit stride, the iteration never steps past the limit value. 3150 } else if (CStep->getValue()->getValue().isStrictlyPositive()) { 3151 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) { 3152 // Test whether a positive iteration iteration can step past the limit 3153 // value and past the maximum value for its type in a single step. 3154 if (isSigned) { 3155 APInt Max = APInt::getSignedMaxValue(BitWidth); 3156 if ((Max - CStep->getValue()->getValue()) 3157 .slt(CLimit->getValue()->getValue())) 3158 return UnknownValue; 3159 } else { 3160 APInt Max = APInt::getMaxValue(BitWidth); 3161 if ((Max - CStep->getValue()->getValue()) 3162 .ult(CLimit->getValue()->getValue())) 3163 return UnknownValue; 3164 } 3165 } else 3166 // TODO: handle non-constant limit values below. 3167 return UnknownValue; 3168 } else 3169 // TODO: handle negative strides below. 3170 return UnknownValue; 3171 3172 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant 3173 // m. So, we count the number of iterations in which {n,+,s} < m is true. 3174 // Note that we cannot simply return max(m-n,0)/s because it's not safe to 3175 // treat m-n as signed nor unsigned due to overflow possibility. 3176 3177 // First, we get the value of the LHS in the first iteration: n 3178 SCEVHandle Start = AddRec->getOperand(0); 3179 3180 // Determine the minimum constant start value. 3181 SCEVHandle MinStart = isa<SCEVConstant>(Start) ? Start : 3182 getConstant(isSigned ? APInt::getSignedMinValue(BitWidth) : 3183 APInt::getMinValue(BitWidth)); 3184 3185 // If we know that the condition is true in order to enter the loop, 3186 // then we know that it will run exactly (m-n)/s times. Otherwise, we 3187 // only know if will execute (max(m,n)-n)/s times. In both cases, the 3188 // division must round up. 3189 SCEVHandle End = RHS; 3190 if (!isLoopGuardedByCond(L, 3191 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT, 3192 getMinusSCEV(Start, Step), RHS)) 3193 End = isSigned ? getSMaxExpr(RHS, Start) 3194 : getUMaxExpr(RHS, Start); 3195 3196 // Determine the maximum constant end value. 3197 SCEVHandle MaxEnd = isa<SCEVConstant>(End) ? End : 3198 getConstant(isSigned ? APInt::getSignedMaxValue(BitWidth) : 3199 APInt::getMaxValue(BitWidth)); 3200 3201 // Finally, we subtract these two values and divide, rounding up, to get 3202 // the number of times the backedge is executed. 3203 SCEVHandle BECount = getUDivExpr(getAddExpr(getMinusSCEV(End, Start), 3204 getAddExpr(Step, NegOne)), 3205 Step); 3206 3207 // The maximum backedge count is similar, except using the minimum start 3208 // value and the maximum end value. 3209 SCEVHandle MaxBECount = getUDivExpr(getAddExpr(getMinusSCEV(MaxEnd, 3210 MinStart), 3211 getAddExpr(Step, NegOne)), 3212 Step); 3213 3214 return BackedgeTakenInfo(BECount, MaxBECount); 3215 } 3216 3217 return UnknownValue; 3218 } 3219 3220 /// getNumIterationsInRange - Return the number of iterations of this loop that 3221 /// produce values in the specified constant range. Another way of looking at 3222 /// this is that it returns the first iteration number where the value is not in 3223 /// the condition, thus computing the exit count. If the iteration count can't 3224 /// be computed, an instance of SCEVCouldNotCompute is returned. 3225 SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range, 3226 ScalarEvolution &SE) const { 3227 if (Range.isFullSet()) // Infinite loop. 3228 return SE.getCouldNotCompute(); 3229 3230 // If the start is a non-zero constant, shift the range to simplify things. 3231 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 3232 if (!SC->getValue()->isZero()) { 3233 std::vector<SCEVHandle> Operands(op_begin(), op_end()); 3234 Operands[0] = SE.getIntegerSCEV(0, SC->getType()); 3235 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop()); 3236 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 3237 return ShiftedAddRec->getNumIterationsInRange( 3238 Range.subtract(SC->getValue()->getValue()), SE); 3239 // This is strange and shouldn't happen. 3240 return SE.getCouldNotCompute(); 3241 } 3242 3243 // The only time we can solve this is when we have all constant indices. 3244 // Otherwise, we cannot determine the overflow conditions. 3245 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) 3246 if (!isa<SCEVConstant>(getOperand(i))) 3247 return SE.getCouldNotCompute(); 3248 3249 3250 // Okay at this point we know that all elements of the chrec are constants and 3251 // that the start element is zero. 3252 3253 // First check to see if the range contains zero. If not, the first 3254 // iteration exits. 3255 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 3256 if (!Range.contains(APInt(BitWidth, 0))) 3257 return SE.getConstant(ConstantInt::get(getType(),0)); 3258 3259 if (isAffine()) { 3260 // If this is an affine expression then we have this situation: 3261 // Solve {0,+,A} in Range === Ax in Range 3262 3263 // We know that zero is in the range. If A is positive then we know that 3264 // the upper value of the range must be the first possible exit value. 3265 // If A is negative then the lower of the range is the last possible loop 3266 // value. Also note that we already checked for a full range. 3267 APInt One(BitWidth,1); 3268 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue(); 3269 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower(); 3270 3271 // The exit value should be (End+A)/A. 3272 APInt ExitVal = (End + A).udiv(A); 3273 ConstantInt *ExitValue = ConstantInt::get(ExitVal); 3274 3275 // Evaluate at the exit value. If we really did fall out of the valid 3276 // range, then we computed our trip count, otherwise wrap around or other 3277 // things must have happened. 3278 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 3279 if (Range.contains(Val->getValue())) 3280 return SE.getCouldNotCompute(); // Something strange happened 3281 3282 // Ensure that the previous value is in the range. This is a sanity check. 3283 assert(Range.contains( 3284 EvaluateConstantChrecAtConstant(this, 3285 ConstantInt::get(ExitVal - One), SE)->getValue()) && 3286 "Linear scev computation is off in a bad way!"); 3287 return SE.getConstant(ExitValue); 3288 } else if (isQuadratic()) { 3289 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the 3290 // quadratic equation to solve it. To do this, we must frame our problem in 3291 // terms of figuring out when zero is crossed, instead of when 3292 // Range.getUpper() is crossed. 3293 std::vector<SCEVHandle> NewOps(op_begin(), op_end()); 3294 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper())); 3295 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop()); 3296 3297 // Next, solve the constructed addrec 3298 std::pair<SCEVHandle,SCEVHandle> Roots = 3299 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE); 3300 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first); 3301 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second); 3302 if (R1) { 3303 // Pick the smallest positive root value. 3304 if (ConstantInt *CB = 3305 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT, 3306 R1->getValue(), R2->getValue()))) { 3307 if (CB->getZExtValue() == false) 3308 std::swap(R1, R2); // R1 is the minimum root now. 3309 3310 // Make sure the root is not off by one. The returned iteration should 3311 // not be in the range, but the previous one should be. When solving 3312 // for "X*X < 5", for example, we should not return a root of 2. 3313 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this, 3314 R1->getValue(), 3315 SE); 3316 if (Range.contains(R1Val->getValue())) { 3317 // The next iteration must be out of the range... 3318 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1); 3319 3320 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); 3321 if (!Range.contains(R1Val->getValue())) 3322 return SE.getConstant(NextVal); 3323 return SE.getCouldNotCompute(); // Something strange happened 3324 } 3325 3326 // If R1 was not in the range, then it is a good return value. Make 3327 // sure that R1-1 WAS in the range though, just in case. 3328 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1); 3329 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); 3330 if (Range.contains(R1Val->getValue())) 3331 return R1; 3332 return SE.getCouldNotCompute(); // Something strange happened 3333 } 3334 } 3335 } 3336 3337 return SE.getCouldNotCompute(); 3338 } 3339 3340 3341 3342 //===----------------------------------------------------------------------===// 3343 // ScalarEvolution Class Implementation 3344 //===----------------------------------------------------------------------===// 3345 3346 ScalarEvolution::ScalarEvolution() 3347 : FunctionPass(&ID), UnknownValue(new SCEVCouldNotCompute()) { 3348 } 3349 3350 bool ScalarEvolution::runOnFunction(Function &F) { 3351 this->F = &F; 3352 LI = &getAnalysis<LoopInfo>(); 3353 TD = getAnalysisIfAvailable<TargetData>(); 3354 return false; 3355 } 3356 3357 void ScalarEvolution::releaseMemory() { 3358 Scalars.clear(); 3359 BackedgeTakenCounts.clear(); 3360 ConstantEvolutionLoopExitValue.clear(); 3361 } 3362 3363 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const { 3364 AU.setPreservesAll(); 3365 AU.addRequiredTransitive<LoopInfo>(); 3366 } 3367 3368 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 3369 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 3370 } 3371 3372 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 3373 const Loop *L) { 3374 // Print all inner loops first 3375 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I) 3376 PrintLoopInfo(OS, SE, *I); 3377 3378 OS << "Loop " << L->getHeader()->getName() << ": "; 3379 3380 SmallVector<BasicBlock*, 8> ExitBlocks; 3381 L->getExitBlocks(ExitBlocks); 3382 if (ExitBlocks.size() != 1) 3383 OS << "<multiple exits> "; 3384 3385 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 3386 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L); 3387 } else { 3388 OS << "Unpredictable backedge-taken count. "; 3389 } 3390 3391 OS << "\n"; 3392 } 3393 3394 void ScalarEvolution::print(raw_ostream &OS, const Module* ) const { 3395 // ScalarEvolution's implementaiton of the print method is to print 3396 // out SCEV values of all instructions that are interesting. Doing 3397 // this potentially causes it to create new SCEV objects though, 3398 // which technically conflicts with the const qualifier. This isn't 3399 // observable from outside the class though (the hasSCEV function 3400 // notwithstanding), so casting away the const isn't dangerous. 3401 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this); 3402 3403 OS << "Classifying expressions for: " << F->getName() << "\n"; 3404 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) 3405 if (isSCEVable(I->getType())) { 3406 OS << *I; 3407 OS << " --> "; 3408 SCEVHandle SV = SE.getSCEV(&*I); 3409 SV->print(OS); 3410 OS << "\t\t"; 3411 3412 if (const Loop *L = LI->getLoopFor((*I).getParent())) { 3413 OS << "Exits: "; 3414 SCEVHandle ExitValue = SE.getSCEVAtScope(&*I, L->getParentLoop()); 3415 if (isa<SCEVCouldNotCompute>(ExitValue)) { 3416 OS << "<<Unknown>>"; 3417 } else { 3418 OS << *ExitValue; 3419 } 3420 } 3421 3422 3423 OS << "\n"; 3424 } 3425 3426 OS << "Determining loop execution counts for: " << F->getName() << "\n"; 3427 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I) 3428 PrintLoopInfo(OS, &SE, *I); 3429 } 3430 3431 void ScalarEvolution::print(std::ostream &o, const Module *M) const { 3432 raw_os_ostream OS(o); 3433 print(OS, M); 3434 } 3435