1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file was developed by the LLVM research group and is distributed under 6 // the University of Illinois Open Source 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/LoopInfo.h" 70 #include "llvm/Assembly/Writer.h" 71 #include "llvm/Transforms/Scalar.h" 72 #include "llvm/Support/CFG.h" 73 #include "llvm/Support/CommandLine.h" 74 #include "llvm/Support/Compiler.h" 75 #include "llvm/Support/ConstantRange.h" 76 #include "llvm/Support/InstIterator.h" 77 #include "llvm/Support/ManagedStatic.h" 78 #include "llvm/Support/MathExtras.h" 79 #include "llvm/Support/Streams.h" 80 #include "llvm/ADT/Statistic.h" 81 #include <ostream> 82 #include <algorithm> 83 #include <cmath> 84 using namespace llvm; 85 86 STATISTIC(NumBruteForceEvaluations, 87 "Number of brute force evaluations needed to " 88 "calculate high-order polynomial exit values"); 89 STATISTIC(NumArrayLenItCounts, 90 "Number of trip counts computed with array length"); 91 STATISTIC(NumTripCountsComputed, 92 "Number of loops with predictable loop counts"); 93 STATISTIC(NumTripCountsNotComputed, 94 "Number of loops without predictable loop counts"); 95 STATISTIC(NumBruteForceTripCountsComputed, 96 "Number of loops with trip counts computed by force"); 97 98 cl::opt<unsigned> 99 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, 100 cl::desc("Maximum number of iterations SCEV will " 101 "symbolically execute a constant derived loop"), 102 cl::init(100)); 103 104 namespace { 105 RegisterPass<ScalarEvolution> 106 R("scalar-evolution", "Scalar Evolution Analysis"); 107 } 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(cerr); 119 } 120 121 /// getValueRange - Return the tightest constant bounds that this value is 122 /// known to have. This method is only valid on integer SCEV objects. 123 ConstantRange SCEV::getValueRange() const { 124 const Type *Ty = getType(); 125 assert(Ty->isInteger() && "Can't get range for a non-integer SCEV!"); 126 // Default to a full range if no better information is available. 127 return ConstantRange(getType()); 128 } 129 130 131 SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {} 132 133 bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const { 134 assert(0 && "Attempt to use a SCEVCouldNotCompute object!"); 135 return false; 136 } 137 138 const Type *SCEVCouldNotCompute::getType() const { 139 assert(0 && "Attempt to use a SCEVCouldNotCompute object!"); 140 return 0; 141 } 142 143 bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const { 144 assert(0 && "Attempt to use a SCEVCouldNotCompute object!"); 145 return false; 146 } 147 148 SCEVHandle SCEVCouldNotCompute:: 149 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym, 150 const SCEVHandle &Conc) const { 151 return this; 152 } 153 154 void SCEVCouldNotCompute::print(std::ostream &OS) const { 155 OS << "***COULDNOTCOMPUTE***"; 156 } 157 158 bool SCEVCouldNotCompute::classof(const SCEV *S) { 159 return S->getSCEVType() == scCouldNotCompute; 160 } 161 162 163 // SCEVConstants - Only allow the creation of one SCEVConstant for any 164 // particular value. Don't use a SCEVHandle here, or else the object will 165 // never be deleted! 166 static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants; 167 168 169 SCEVConstant::~SCEVConstant() { 170 SCEVConstants->erase(V); 171 } 172 173 SCEVHandle SCEVConstant::get(ConstantInt *V) { 174 SCEVConstant *&R = (*SCEVConstants)[V]; 175 if (R == 0) R = new SCEVConstant(V); 176 return R; 177 } 178 179 ConstantRange SCEVConstant::getValueRange() const { 180 return ConstantRange(V->getValue()); 181 } 182 183 const Type *SCEVConstant::getType() const { return V->getType(); } 184 185 void SCEVConstant::print(std::ostream &OS) const { 186 WriteAsOperand(OS, V, false); 187 } 188 189 // SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any 190 // particular input. Don't use a SCEVHandle here, or else the object will 191 // never be deleted! 192 static ManagedStatic<std::map<std::pair<SCEV*, const Type*>, 193 SCEVTruncateExpr*> > SCEVTruncates; 194 195 SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty) 196 : SCEV(scTruncate), Op(op), Ty(ty) { 197 assert(Op->getType()->isInteger() && Ty->isInteger() && 198 "Cannot truncate non-integer value!"); 199 assert(Op->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits() 200 && "This is not a truncating conversion!"); 201 } 202 203 SCEVTruncateExpr::~SCEVTruncateExpr() { 204 SCEVTruncates->erase(std::make_pair(Op, Ty)); 205 } 206 207 ConstantRange SCEVTruncateExpr::getValueRange() const { 208 return getOperand()->getValueRange().truncate(getType()); 209 } 210 211 void SCEVTruncateExpr::print(std::ostream &OS) const { 212 OS << "(truncate " << *Op << " to " << *Ty << ")"; 213 } 214 215 // SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any 216 // particular input. Don't use a SCEVHandle here, or else the object will never 217 // be deleted! 218 static ManagedStatic<std::map<std::pair<SCEV*, const Type*>, 219 SCEVZeroExtendExpr*> > SCEVZeroExtends; 220 221 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty) 222 : SCEV(scZeroExtend), Op(op), Ty(ty) { 223 assert(Op->getType()->isInteger() && Ty->isInteger() && 224 "Cannot zero extend non-integer value!"); 225 assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits() 226 && "This is not an extending conversion!"); 227 } 228 229 SCEVZeroExtendExpr::~SCEVZeroExtendExpr() { 230 SCEVZeroExtends->erase(std::make_pair(Op, Ty)); 231 } 232 233 ConstantRange SCEVZeroExtendExpr::getValueRange() const { 234 return getOperand()->getValueRange().zeroExtend(getType()); 235 } 236 237 void SCEVZeroExtendExpr::print(std::ostream &OS) const { 238 OS << "(zeroextend " << *Op << " to " << *Ty << ")"; 239 } 240 241 // SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any 242 // particular input. Don't use a SCEVHandle here, or else the object will never 243 // be deleted! 244 static ManagedStatic<std::map<std::pair<unsigned, std::vector<SCEV*> >, 245 SCEVCommutativeExpr*> > SCEVCommExprs; 246 247 SCEVCommutativeExpr::~SCEVCommutativeExpr() { 248 SCEVCommExprs->erase(std::make_pair(getSCEVType(), 249 std::vector<SCEV*>(Operands.begin(), 250 Operands.end()))); 251 } 252 253 void SCEVCommutativeExpr::print(std::ostream &OS) const { 254 assert(Operands.size() > 1 && "This plus expr shouldn't exist!"); 255 const char *OpStr = getOperationStr(); 256 OS << "(" << *Operands[0]; 257 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 258 OS << OpStr << *Operands[i]; 259 OS << ")"; 260 } 261 262 SCEVHandle SCEVCommutativeExpr:: 263 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym, 264 const SCEVHandle &Conc) const { 265 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 266 SCEVHandle H = getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc); 267 if (H != getOperand(i)) { 268 std::vector<SCEVHandle> NewOps; 269 NewOps.reserve(getNumOperands()); 270 for (unsigned j = 0; j != i; ++j) 271 NewOps.push_back(getOperand(j)); 272 NewOps.push_back(H); 273 for (++i; i != e; ++i) 274 NewOps.push_back(getOperand(i)-> 275 replaceSymbolicValuesWithConcrete(Sym, Conc)); 276 277 if (isa<SCEVAddExpr>(this)) 278 return SCEVAddExpr::get(NewOps); 279 else if (isa<SCEVMulExpr>(this)) 280 return SCEVMulExpr::get(NewOps); 281 else 282 assert(0 && "Unknown commutative expr!"); 283 } 284 } 285 return this; 286 } 287 288 289 // SCEVSDivs - Only allow the creation of one SCEVSDivExpr for any particular 290 // input. Don't use a SCEVHandle here, or else the object will never be 291 // deleted! 292 static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>, 293 SCEVSDivExpr*> > SCEVSDivs; 294 295 SCEVSDivExpr::~SCEVSDivExpr() { 296 SCEVSDivs->erase(std::make_pair(LHS, RHS)); 297 } 298 299 void SCEVSDivExpr::print(std::ostream &OS) const { 300 OS << "(" << *LHS << " /s " << *RHS << ")"; 301 } 302 303 const Type *SCEVSDivExpr::getType() const { 304 return LHS->getType(); 305 } 306 307 // SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any 308 // particular input. Don't use a SCEVHandle here, or else the object will never 309 // be deleted! 310 static ManagedStatic<std::map<std::pair<const Loop *, std::vector<SCEV*> >, 311 SCEVAddRecExpr*> > SCEVAddRecExprs; 312 313 SCEVAddRecExpr::~SCEVAddRecExpr() { 314 SCEVAddRecExprs->erase(std::make_pair(L, 315 std::vector<SCEV*>(Operands.begin(), 316 Operands.end()))); 317 } 318 319 SCEVHandle SCEVAddRecExpr:: 320 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym, 321 const SCEVHandle &Conc) const { 322 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 323 SCEVHandle H = getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc); 324 if (H != getOperand(i)) { 325 std::vector<SCEVHandle> NewOps; 326 NewOps.reserve(getNumOperands()); 327 for (unsigned j = 0; j != i; ++j) 328 NewOps.push_back(getOperand(j)); 329 NewOps.push_back(H); 330 for (++i; i != e; ++i) 331 NewOps.push_back(getOperand(i)-> 332 replaceSymbolicValuesWithConcrete(Sym, Conc)); 333 334 return get(NewOps, L); 335 } 336 } 337 return this; 338 } 339 340 341 bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const { 342 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't 343 // contain L and if the start is invariant. 344 return !QueryLoop->contains(L->getHeader()) && 345 getOperand(0)->isLoopInvariant(QueryLoop); 346 } 347 348 349 void SCEVAddRecExpr::print(std::ostream &OS) const { 350 OS << "{" << *Operands[0]; 351 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 352 OS << ",+," << *Operands[i]; 353 OS << "}<" << L->getHeader()->getName() + ">"; 354 } 355 356 // SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular 357 // value. Don't use a SCEVHandle here, or else the object will never be 358 // deleted! 359 static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns; 360 361 SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); } 362 363 bool SCEVUnknown::isLoopInvariant(const Loop *L) const { 364 // All non-instruction values are loop invariant. All instructions are loop 365 // invariant if they are not contained in the specified loop. 366 if (Instruction *I = dyn_cast<Instruction>(V)) 367 return !L->contains(I->getParent()); 368 return true; 369 } 370 371 const Type *SCEVUnknown::getType() const { 372 return V->getType(); 373 } 374 375 void SCEVUnknown::print(std::ostream &OS) const { 376 WriteAsOperand(OS, V, false); 377 } 378 379 //===----------------------------------------------------------------------===// 380 // SCEV Utilities 381 //===----------------------------------------------------------------------===// 382 383 namespace { 384 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less 385 /// than the complexity of the RHS. This comparator is used to canonicalize 386 /// expressions. 387 struct VISIBILITY_HIDDEN SCEVComplexityCompare { 388 bool operator()(SCEV *LHS, SCEV *RHS) { 389 return LHS->getSCEVType() < RHS->getSCEVType(); 390 } 391 }; 392 } 393 394 /// GroupByComplexity - Given a list of SCEV objects, order them by their 395 /// complexity, and group objects of the same complexity together by value. 396 /// When this routine is finished, we know that any duplicates in the vector are 397 /// consecutive and that complexity is monotonically increasing. 398 /// 399 /// Note that we go take special precautions to ensure that we get determinstic 400 /// results from this routine. In other words, we don't want the results of 401 /// this to depend on where the addresses of various SCEV objects happened to 402 /// land in memory. 403 /// 404 static void GroupByComplexity(std::vector<SCEVHandle> &Ops) { 405 if (Ops.size() < 2) return; // Noop 406 if (Ops.size() == 2) { 407 // This is the common case, which also happens to be trivially simple. 408 // Special case it. 409 if (Ops[0]->getSCEVType() > Ops[1]->getSCEVType()) 410 std::swap(Ops[0], Ops[1]); 411 return; 412 } 413 414 // Do the rough sort by complexity. 415 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare()); 416 417 // Now that we are sorted by complexity, group elements of the same 418 // complexity. Note that this is, at worst, N^2, but the vector is likely to 419 // be extremely short in practice. Note that we take this approach because we 420 // do not want to depend on the addresses of the objects we are grouping. 421 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { 422 SCEV *S = Ops[i]; 423 unsigned Complexity = S->getSCEVType(); 424 425 // If there are any objects of the same complexity and same value as this 426 // one, group them. 427 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { 428 if (Ops[j] == S) { // Found a duplicate. 429 // Move it to immediately after i'th element. 430 std::swap(Ops[i+1], Ops[j]); 431 ++i; // no need to rescan it. 432 if (i == e-2) return; // Done! 433 } 434 } 435 } 436 } 437 438 439 440 //===----------------------------------------------------------------------===// 441 // Simple SCEV method implementations 442 //===----------------------------------------------------------------------===// 443 444 /// getIntegerSCEV - Given an integer or FP type, create a constant for the 445 /// specified signed integer value and return a SCEV for the constant. 446 SCEVHandle SCEVUnknown::getIntegerSCEV(int Val, const Type *Ty) { 447 Constant *C; 448 if (Val == 0) 449 C = Constant::getNullValue(Ty); 450 else if (Ty->isFloatingPoint()) 451 C = ConstantFP::get(Ty, Val); 452 else 453 C = ConstantInt::get(Ty, Val); 454 return SCEVUnknown::get(C); 455 } 456 457 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the 458 /// input value to the specified type. If the type must be extended, it is zero 459 /// extended. 460 static SCEVHandle getTruncateOrZeroExtend(const SCEVHandle &V, const Type *Ty) { 461 const Type *SrcTy = V->getType(); 462 assert(SrcTy->isInteger() && Ty->isInteger() && 463 "Cannot truncate or zero extend with non-integer arguments!"); 464 if (SrcTy->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits()) 465 return V; // No conversion 466 if (SrcTy->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()) 467 return SCEVTruncateExpr::get(V, Ty); 468 return SCEVZeroExtendExpr::get(V, Ty); 469 } 470 471 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V 472 /// 473 SCEVHandle SCEV::getNegativeSCEV(const SCEVHandle &V) { 474 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 475 return SCEVUnknown::get(ConstantExpr::getNeg(VC->getValue())); 476 477 return SCEVMulExpr::get(V, SCEVUnknown::getIntegerSCEV(-1, V->getType())); 478 } 479 480 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS. 481 /// 482 SCEVHandle SCEV::getMinusSCEV(const SCEVHandle &LHS, const SCEVHandle &RHS) { 483 // X - Y --> X + -Y 484 return SCEVAddExpr::get(LHS, SCEV::getNegativeSCEV(RHS)); 485 } 486 487 488 /// PartialFact - Compute V!/(V-NumSteps)! 489 static SCEVHandle PartialFact(SCEVHandle V, unsigned NumSteps) { 490 // Handle this case efficiently, it is common to have constant iteration 491 // counts while computing loop exit values. 492 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) { 493 APInt Val = SC->getValue()->getValue(); 494 APInt Result(Val.getBitWidth(), 1); 495 for (; NumSteps; --NumSteps) 496 Result *= Val-(NumSteps-1); 497 return SCEVUnknown::get(ConstantInt::get(V->getType(), Result)); 498 } 499 500 const Type *Ty = V->getType(); 501 if (NumSteps == 0) 502 return SCEVUnknown::getIntegerSCEV(1, Ty); 503 504 SCEVHandle Result = V; 505 for (unsigned i = 1; i != NumSteps; ++i) 506 Result = SCEVMulExpr::get(Result, SCEV::getMinusSCEV(V, 507 SCEVUnknown::getIntegerSCEV(i, Ty))); 508 return Result; 509 } 510 511 512 /// evaluateAtIteration - Return the value of this chain of recurrences at 513 /// the specified iteration number. We can evaluate this recurrence by 514 /// multiplying each element in the chain by the binomial coefficient 515 /// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as: 516 /// 517 /// A*choose(It, 0) + B*choose(It, 1) + C*choose(It, 2) + D*choose(It, 3) 518 /// 519 /// FIXME/VERIFY: I don't trust that this is correct in the face of overflow. 520 /// Is the binomial equation safe using modular arithmetic?? 521 /// 522 SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It) const { 523 SCEVHandle Result = getStart(); 524 int Divisor = 1; 525 const Type *Ty = It->getType(); 526 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 527 SCEVHandle BC = PartialFact(It, i); 528 Divisor *= i; 529 SCEVHandle Val = SCEVSDivExpr::get(SCEVMulExpr::get(BC, getOperand(i)), 530 SCEVUnknown::getIntegerSCEV(Divisor,Ty)); 531 Result = SCEVAddExpr::get(Result, Val); 532 } 533 return Result; 534 } 535 536 537 //===----------------------------------------------------------------------===// 538 // SCEV Expression folder implementations 539 //===----------------------------------------------------------------------===// 540 541 SCEVHandle SCEVTruncateExpr::get(const SCEVHandle &Op, const Type *Ty) { 542 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 543 return SCEVUnknown::get( 544 ConstantExpr::getTrunc(SC->getValue(), Ty)); 545 546 // If the input value is a chrec scev made out of constants, truncate 547 // all of the constants. 548 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 549 std::vector<SCEVHandle> Operands; 550 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 551 // FIXME: This should allow truncation of other expression types! 552 if (isa<SCEVConstant>(AddRec->getOperand(i))) 553 Operands.push_back(get(AddRec->getOperand(i), Ty)); 554 else 555 break; 556 if (Operands.size() == AddRec->getNumOperands()) 557 return SCEVAddRecExpr::get(Operands, AddRec->getLoop()); 558 } 559 560 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)]; 561 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty); 562 return Result; 563 } 564 565 SCEVHandle SCEVZeroExtendExpr::get(const SCEVHandle &Op, const Type *Ty) { 566 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 567 return SCEVUnknown::get( 568 ConstantExpr::getZExt(SC->getValue(), Ty)); 569 570 // FIXME: If the input value is a chrec scev, and we can prove that the value 571 // did not overflow the old, smaller, value, we can zero extend all of the 572 // operands (often constants). This would allow analysis of something like 573 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } 574 575 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)]; 576 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty); 577 return Result; 578 } 579 580 // get - Get a canonical add expression, or something simpler if possible. 581 SCEVHandle SCEVAddExpr::get(std::vector<SCEVHandle> &Ops) { 582 assert(!Ops.empty() && "Cannot get empty add!"); 583 if (Ops.size() == 1) return Ops[0]; 584 585 // Sort by complexity, this groups all similar expression types together. 586 GroupByComplexity(Ops); 587 588 // If there are any constants, fold them together. 589 unsigned Idx = 0; 590 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 591 ++Idx; 592 assert(Idx < Ops.size()); 593 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 594 // We found two constants, fold them together! 595 Constant *Fold = ConstantExpr::getAdd(LHSC->getValue(), RHSC->getValue()); 596 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) { 597 Ops[0] = SCEVConstant::get(CI); 598 Ops.erase(Ops.begin()+1); // Erase the folded element 599 if (Ops.size() == 1) return Ops[0]; 600 LHSC = cast<SCEVConstant>(Ops[0]); 601 } else { 602 // If we couldn't fold the expression, move to the next constant. Note 603 // that this is impossible to happen in practice because we always 604 // constant fold constant ints to constant ints. 605 ++Idx; 606 } 607 } 608 609 // If we are left with a constant zero being added, strip it off. 610 if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) { 611 Ops.erase(Ops.begin()); 612 --Idx; 613 } 614 } 615 616 if (Ops.size() == 1) return Ops[0]; 617 618 // Okay, check to see if the same value occurs in the operand list twice. If 619 // so, merge them together into an multiply expression. Since we sorted the 620 // list, these values are required to be adjacent. 621 const Type *Ty = Ops[0]->getType(); 622 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 623 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 624 // Found a match, merge the two values into a multiply, and add any 625 // remaining values to the result. 626 SCEVHandle Two = SCEVUnknown::getIntegerSCEV(2, Ty); 627 SCEVHandle Mul = SCEVMulExpr::get(Ops[i], Two); 628 if (Ops.size() == 2) 629 return Mul; 630 Ops.erase(Ops.begin()+i, Ops.begin()+i+2); 631 Ops.push_back(Mul); 632 return SCEVAddExpr::get(Ops); 633 } 634 635 // Okay, now we know the first non-constant operand. If there are add 636 // operands they would be next. 637 if (Idx < Ops.size()) { 638 bool DeletedAdd = false; 639 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 640 // If we have an add, expand the add operands onto the end of the operands 641 // list. 642 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end()); 643 Ops.erase(Ops.begin()+Idx); 644 DeletedAdd = true; 645 } 646 647 // If we deleted at least one add, we added operands to the end of the list, 648 // and they are not necessarily sorted. Recurse to resort and resimplify 649 // any operands we just aquired. 650 if (DeletedAdd) 651 return get(Ops); 652 } 653 654 // Skip over the add expression until we get to a multiply. 655 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 656 ++Idx; 657 658 // If we are adding something to a multiply expression, make sure the 659 // something is not already an operand of the multiply. If so, merge it into 660 // the multiply. 661 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 662 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 663 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 664 SCEV *MulOpSCEV = Mul->getOperand(MulOp); 665 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 666 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) { 667 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 668 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0); 669 if (Mul->getNumOperands() != 2) { 670 // If the multiply has more than two operands, we must get the 671 // Y*Z term. 672 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end()); 673 MulOps.erase(MulOps.begin()+MulOp); 674 InnerMul = SCEVMulExpr::get(MulOps); 675 } 676 SCEVHandle One = SCEVUnknown::getIntegerSCEV(1, Ty); 677 SCEVHandle AddOne = SCEVAddExpr::get(InnerMul, One); 678 SCEVHandle OuterMul = SCEVMulExpr::get(AddOne, Ops[AddOp]); 679 if (Ops.size() == 2) return OuterMul; 680 if (AddOp < Idx) { 681 Ops.erase(Ops.begin()+AddOp); 682 Ops.erase(Ops.begin()+Idx-1); 683 } else { 684 Ops.erase(Ops.begin()+Idx); 685 Ops.erase(Ops.begin()+AddOp-1); 686 } 687 Ops.push_back(OuterMul); 688 return SCEVAddExpr::get(Ops); 689 } 690 691 // Check this multiply against other multiplies being added together. 692 for (unsigned OtherMulIdx = Idx+1; 693 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 694 ++OtherMulIdx) { 695 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 696 // If MulOp occurs in OtherMul, we can fold the two multiplies 697 // together. 698 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 699 OMulOp != e; ++OMulOp) 700 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 701 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 702 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0); 703 if (Mul->getNumOperands() != 2) { 704 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end()); 705 MulOps.erase(MulOps.begin()+MulOp); 706 InnerMul1 = SCEVMulExpr::get(MulOps); 707 } 708 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0); 709 if (OtherMul->getNumOperands() != 2) { 710 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(), 711 OtherMul->op_end()); 712 MulOps.erase(MulOps.begin()+OMulOp); 713 InnerMul2 = SCEVMulExpr::get(MulOps); 714 } 715 SCEVHandle InnerMulSum = SCEVAddExpr::get(InnerMul1,InnerMul2); 716 SCEVHandle OuterMul = SCEVMulExpr::get(MulOpSCEV, InnerMulSum); 717 if (Ops.size() == 2) return OuterMul; 718 Ops.erase(Ops.begin()+Idx); 719 Ops.erase(Ops.begin()+OtherMulIdx-1); 720 Ops.push_back(OuterMul); 721 return SCEVAddExpr::get(Ops); 722 } 723 } 724 } 725 } 726 727 // If there are any add recurrences in the operands list, see if any other 728 // added values are loop invariant. If so, we can fold them into the 729 // recurrence. 730 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 731 ++Idx; 732 733 // Scan over all recurrences, trying to fold loop invariants into them. 734 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 735 // Scan all of the other operands to this add and add them to the vector if 736 // they are loop invariant w.r.t. the recurrence. 737 std::vector<SCEVHandle> LIOps; 738 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 739 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 740 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) { 741 LIOps.push_back(Ops[i]); 742 Ops.erase(Ops.begin()+i); 743 --i; --e; 744 } 745 746 // If we found some loop invariants, fold them into the recurrence. 747 if (!LIOps.empty()) { 748 // NLI + LI + { Start,+,Step} --> NLI + { LI+Start,+,Step } 749 LIOps.push_back(AddRec->getStart()); 750 751 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end()); 752 AddRecOps[0] = SCEVAddExpr::get(LIOps); 753 754 SCEVHandle NewRec = SCEVAddRecExpr::get(AddRecOps, AddRec->getLoop()); 755 // If all of the other operands were loop invariant, we are done. 756 if (Ops.size() == 1) return NewRec; 757 758 // Otherwise, add the folded AddRec by the non-liv parts. 759 for (unsigned i = 0;; ++i) 760 if (Ops[i] == AddRec) { 761 Ops[i] = NewRec; 762 break; 763 } 764 return SCEVAddExpr::get(Ops); 765 } 766 767 // Okay, if there weren't any loop invariants to be folded, check to see if 768 // there are multiple AddRec's with the same loop induction variable being 769 // added together. If so, we can fold them. 770 for (unsigned OtherIdx = Idx+1; 771 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx) 772 if (OtherIdx != Idx) { 773 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 774 if (AddRec->getLoop() == OtherAddRec->getLoop()) { 775 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D} 776 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end()); 777 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) { 778 if (i >= NewOps.size()) { 779 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i, 780 OtherAddRec->op_end()); 781 break; 782 } 783 NewOps[i] = SCEVAddExpr::get(NewOps[i], OtherAddRec->getOperand(i)); 784 } 785 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop()); 786 787 if (Ops.size() == 2) return NewAddRec; 788 789 Ops.erase(Ops.begin()+Idx); 790 Ops.erase(Ops.begin()+OtherIdx-1); 791 Ops.push_back(NewAddRec); 792 return SCEVAddExpr::get(Ops); 793 } 794 } 795 796 // Otherwise couldn't fold anything into this recurrence. Move onto the 797 // next one. 798 } 799 800 // Okay, it looks like we really DO need an add expr. Check to see if we 801 // already have one, otherwise create a new one. 802 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end()); 803 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr, 804 SCEVOps)]; 805 if (Result == 0) Result = new SCEVAddExpr(Ops); 806 return Result; 807 } 808 809 810 SCEVHandle SCEVMulExpr::get(std::vector<SCEVHandle> &Ops) { 811 assert(!Ops.empty() && "Cannot get empty mul!"); 812 813 // Sort by complexity, this groups all similar expression types together. 814 GroupByComplexity(Ops); 815 816 // If there are any constants, fold them together. 817 unsigned Idx = 0; 818 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 819 820 // C1*(C2+V) -> C1*C2 + C1*V 821 if (Ops.size() == 2) 822 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 823 if (Add->getNumOperands() == 2 && 824 isa<SCEVConstant>(Add->getOperand(0))) 825 return SCEVAddExpr::get(SCEVMulExpr::get(LHSC, Add->getOperand(0)), 826 SCEVMulExpr::get(LHSC, Add->getOperand(1))); 827 828 829 ++Idx; 830 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 831 // We found two constants, fold them together! 832 Constant *Fold = ConstantExpr::getMul(LHSC->getValue(), RHSC->getValue()); 833 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) { 834 Ops[0] = SCEVConstant::get(CI); 835 Ops.erase(Ops.begin()+1); // Erase the folded element 836 if (Ops.size() == 1) return Ops[0]; 837 LHSC = cast<SCEVConstant>(Ops[0]); 838 } else { 839 // If we couldn't fold the expression, move to the next constant. Note 840 // that this is impossible to happen in practice because we always 841 // constant fold constant ints to constant ints. 842 ++Idx; 843 } 844 } 845 846 // If we are left with a constant one being multiplied, strip it off. 847 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) { 848 Ops.erase(Ops.begin()); 849 --Idx; 850 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) { 851 // If we have a multiply of zero, it will always be zero. 852 return Ops[0]; 853 } 854 } 855 856 // Skip over the add expression until we get to a multiply. 857 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 858 ++Idx; 859 860 if (Ops.size() == 1) 861 return Ops[0]; 862 863 // If there are mul operands inline them all into this expression. 864 if (Idx < Ops.size()) { 865 bool DeletedMul = false; 866 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 867 // If we have an mul, expand the mul operands onto the end of the operands 868 // list. 869 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end()); 870 Ops.erase(Ops.begin()+Idx); 871 DeletedMul = true; 872 } 873 874 // If we deleted at least one mul, we added operands to the end of the list, 875 // and they are not necessarily sorted. Recurse to resort and resimplify 876 // any operands we just aquired. 877 if (DeletedMul) 878 return get(Ops); 879 } 880 881 // If there are any add recurrences in the operands list, see if any other 882 // added values are loop invariant. If so, we can fold them into the 883 // recurrence. 884 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 885 ++Idx; 886 887 // Scan over all recurrences, trying to fold loop invariants into them. 888 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 889 // Scan all of the other operands to this mul and add them to the vector if 890 // they are loop invariant w.r.t. the recurrence. 891 std::vector<SCEVHandle> LIOps; 892 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 893 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 894 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) { 895 LIOps.push_back(Ops[i]); 896 Ops.erase(Ops.begin()+i); 897 --i; --e; 898 } 899 900 // If we found some loop invariants, fold them into the recurrence. 901 if (!LIOps.empty()) { 902 // NLI * LI * { Start,+,Step} --> NLI * { LI*Start,+,LI*Step } 903 std::vector<SCEVHandle> NewOps; 904 NewOps.reserve(AddRec->getNumOperands()); 905 if (LIOps.size() == 1) { 906 SCEV *Scale = LIOps[0]; 907 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 908 NewOps.push_back(SCEVMulExpr::get(Scale, AddRec->getOperand(i))); 909 } else { 910 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 911 std::vector<SCEVHandle> MulOps(LIOps); 912 MulOps.push_back(AddRec->getOperand(i)); 913 NewOps.push_back(SCEVMulExpr::get(MulOps)); 914 } 915 } 916 917 SCEVHandle NewRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop()); 918 919 // If all of the other operands were loop invariant, we are done. 920 if (Ops.size() == 1) return NewRec; 921 922 // Otherwise, multiply the folded AddRec by the non-liv parts. 923 for (unsigned i = 0;; ++i) 924 if (Ops[i] == AddRec) { 925 Ops[i] = NewRec; 926 break; 927 } 928 return SCEVMulExpr::get(Ops); 929 } 930 931 // Okay, if there weren't any loop invariants to be folded, check to see if 932 // there are multiple AddRec's with the same loop induction variable being 933 // multiplied together. If so, we can fold them. 934 for (unsigned OtherIdx = Idx+1; 935 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx) 936 if (OtherIdx != Idx) { 937 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 938 if (AddRec->getLoop() == OtherAddRec->getLoop()) { 939 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D} 940 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec; 941 SCEVHandle NewStart = SCEVMulExpr::get(F->getStart(), 942 G->getStart()); 943 SCEVHandle B = F->getStepRecurrence(); 944 SCEVHandle D = G->getStepRecurrence(); 945 SCEVHandle NewStep = SCEVAddExpr::get(SCEVMulExpr::get(F, D), 946 SCEVMulExpr::get(G, B), 947 SCEVMulExpr::get(B, D)); 948 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewStart, NewStep, 949 F->getLoop()); 950 if (Ops.size() == 2) return NewAddRec; 951 952 Ops.erase(Ops.begin()+Idx); 953 Ops.erase(Ops.begin()+OtherIdx-1); 954 Ops.push_back(NewAddRec); 955 return SCEVMulExpr::get(Ops); 956 } 957 } 958 959 // Otherwise couldn't fold anything into this recurrence. Move onto the 960 // next one. 961 } 962 963 // Okay, it looks like we really DO need an mul expr. Check to see if we 964 // already have one, otherwise create a new one. 965 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end()); 966 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr, 967 SCEVOps)]; 968 if (Result == 0) 969 Result = new SCEVMulExpr(Ops); 970 return Result; 971 } 972 973 SCEVHandle SCEVSDivExpr::get(const SCEVHandle &LHS, const SCEVHandle &RHS) { 974 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 975 if (RHSC->getValue()->equalsInt(1)) 976 return LHS; // X sdiv 1 --> x 977 if (RHSC->getValue()->isAllOnesValue()) 978 return SCEV::getNegativeSCEV(LHS); // X sdiv -1 --> -x 979 980 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 981 Constant *LHSCV = LHSC->getValue(); 982 Constant *RHSCV = RHSC->getValue(); 983 return SCEVUnknown::get(ConstantExpr::getSDiv(LHSCV, RHSCV)); 984 } 985 } 986 987 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow. 988 989 SCEVSDivExpr *&Result = (*SCEVSDivs)[std::make_pair(LHS, RHS)]; 990 if (Result == 0) Result = new SCEVSDivExpr(LHS, RHS); 991 return Result; 992 } 993 994 995 /// SCEVAddRecExpr::get - Get a add recurrence expression for the 996 /// specified loop. Simplify the expression as much as possible. 997 SCEVHandle SCEVAddRecExpr::get(const SCEVHandle &Start, 998 const SCEVHandle &Step, const Loop *L) { 999 std::vector<SCEVHandle> Operands; 1000 Operands.push_back(Start); 1001 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 1002 if (StepChrec->getLoop() == L) { 1003 Operands.insert(Operands.end(), StepChrec->op_begin(), 1004 StepChrec->op_end()); 1005 return get(Operands, L); 1006 } 1007 1008 Operands.push_back(Step); 1009 return get(Operands, L); 1010 } 1011 1012 /// SCEVAddRecExpr::get - Get a add recurrence expression for the 1013 /// specified loop. Simplify the expression as much as possible. 1014 SCEVHandle SCEVAddRecExpr::get(std::vector<SCEVHandle> &Operands, 1015 const Loop *L) { 1016 if (Operands.size() == 1) return Operands[0]; 1017 1018 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Operands.back())) 1019 if (StepC->getValue()->isNullValue()) { 1020 Operands.pop_back(); 1021 return get(Operands, L); // { X,+,0 } --> X 1022 } 1023 1024 SCEVAddRecExpr *&Result = 1025 (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(), 1026 Operands.end()))]; 1027 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L); 1028 return Result; 1029 } 1030 1031 SCEVHandle SCEVUnknown::get(Value *V) { 1032 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 1033 return SCEVConstant::get(CI); 1034 SCEVUnknown *&Result = (*SCEVUnknowns)[V]; 1035 if (Result == 0) Result = new SCEVUnknown(V); 1036 return Result; 1037 } 1038 1039 1040 //===----------------------------------------------------------------------===// 1041 // ScalarEvolutionsImpl Definition and Implementation 1042 //===----------------------------------------------------------------------===// 1043 // 1044 /// ScalarEvolutionsImpl - This class implements the main driver for the scalar 1045 /// evolution code. 1046 /// 1047 namespace { 1048 struct VISIBILITY_HIDDEN ScalarEvolutionsImpl { 1049 /// F - The function we are analyzing. 1050 /// 1051 Function &F; 1052 1053 /// LI - The loop information for the function we are currently analyzing. 1054 /// 1055 LoopInfo &LI; 1056 1057 /// UnknownValue - This SCEV is used to represent unknown trip counts and 1058 /// things. 1059 SCEVHandle UnknownValue; 1060 1061 /// Scalars - This is a cache of the scalars we have analyzed so far. 1062 /// 1063 std::map<Value*, SCEVHandle> Scalars; 1064 1065 /// IterationCounts - Cache the iteration count of the loops for this 1066 /// function as they are computed. 1067 std::map<const Loop*, SCEVHandle> IterationCounts; 1068 1069 /// ConstantEvolutionLoopExitValue - This map contains entries for all of 1070 /// the PHI instructions that we attempt to compute constant evolutions for. 1071 /// This allows us to avoid potentially expensive recomputation of these 1072 /// properties. An instruction maps to null if we are unable to compute its 1073 /// exit value. 1074 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue; 1075 1076 public: 1077 ScalarEvolutionsImpl(Function &f, LoopInfo &li) 1078 : F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {} 1079 1080 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the 1081 /// expression and create a new one. 1082 SCEVHandle getSCEV(Value *V); 1083 1084 /// hasSCEV - Return true if the SCEV for this value has already been 1085 /// computed. 1086 bool hasSCEV(Value *V) const { 1087 return Scalars.count(V); 1088 } 1089 1090 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for 1091 /// the specified value. 1092 void setSCEV(Value *V, const SCEVHandle &H) { 1093 bool isNew = Scalars.insert(std::make_pair(V, H)).second; 1094 assert(isNew && "This entry already existed!"); 1095 } 1096 1097 1098 /// getSCEVAtScope - Compute the value of the specified expression within 1099 /// the indicated loop (which may be null to indicate in no loop). If the 1100 /// expression cannot be evaluated, return UnknownValue itself. 1101 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L); 1102 1103 1104 /// hasLoopInvariantIterationCount - Return true if the specified loop has 1105 /// an analyzable loop-invariant iteration count. 1106 bool hasLoopInvariantIterationCount(const Loop *L); 1107 1108 /// getIterationCount - If the specified loop has a predictable iteration 1109 /// count, return it. Note that it is not valid to call this method on a 1110 /// loop without a loop-invariant iteration count. 1111 SCEVHandle getIterationCount(const Loop *L); 1112 1113 /// deleteInstructionFromRecords - This method should be called by the 1114 /// client before it removes an instruction from the program, to make sure 1115 /// that no dangling references are left around. 1116 void deleteInstructionFromRecords(Instruction *I); 1117 1118 private: 1119 /// createSCEV - We know that there is no SCEV for the specified value. 1120 /// Analyze the expression. 1121 SCEVHandle createSCEV(Value *V); 1122 1123 /// createNodeForPHI - Provide the special handling we need to analyze PHI 1124 /// SCEVs. 1125 SCEVHandle createNodeForPHI(PHINode *PN); 1126 1127 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value 1128 /// for the specified instruction and replaces any references to the 1129 /// symbolic value SymName with the specified value. This is used during 1130 /// PHI resolution. 1131 void ReplaceSymbolicValueWithConcrete(Instruction *I, 1132 const SCEVHandle &SymName, 1133 const SCEVHandle &NewVal); 1134 1135 /// ComputeIterationCount - Compute the number of times the specified loop 1136 /// will iterate. 1137 SCEVHandle ComputeIterationCount(const Loop *L); 1138 1139 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of 1140 /// 'setcc load X, cst', try to se if we can compute the trip count. 1141 SCEVHandle ComputeLoadConstantCompareIterationCount(LoadInst *LI, 1142 Constant *RHS, 1143 const Loop *L, 1144 ICmpInst::Predicate p); 1145 1146 /// ComputeIterationCountExhaustively - If the trip is known to execute a 1147 /// constant number of times (the condition evolves only from constants), 1148 /// try to evaluate a few iterations of the loop until we get the exit 1149 /// condition gets a value of ExitWhen (true or false). If we cannot 1150 /// evaluate the trip count of the loop, return UnknownValue. 1151 SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond, 1152 bool ExitWhen); 1153 1154 /// HowFarToZero - Return the number of times a backedge comparing the 1155 /// specified value to zero will execute. If not computable, return 1156 /// UnknownValue. 1157 SCEVHandle HowFarToZero(SCEV *V, const Loop *L); 1158 1159 /// HowFarToNonZero - Return the number of times a backedge checking the 1160 /// specified value for nonzero will execute. If not computable, return 1161 /// UnknownValue. 1162 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L); 1163 1164 /// HowManyLessThans - Return the number of times a backedge containing the 1165 /// specified less-than comparison will execute. If not computable, return 1166 /// UnknownValue. 1167 SCEVHandle HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L); 1168 1169 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 1170 /// in the header of its containing loop, we know the loop executes a 1171 /// constant number of times, and the PHI node is just a recurrence 1172 /// involving constants, fold it. 1173 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, uint64_t Its, 1174 const Loop *L); 1175 }; 1176 } 1177 1178 //===----------------------------------------------------------------------===// 1179 // Basic SCEV Analysis and PHI Idiom Recognition Code 1180 // 1181 1182 /// deleteInstructionFromRecords - This method should be called by the 1183 /// client before it removes an instruction from the program, to make sure 1184 /// that no dangling references are left around. 1185 void ScalarEvolutionsImpl::deleteInstructionFromRecords(Instruction *I) { 1186 Scalars.erase(I); 1187 if (PHINode *PN = dyn_cast<PHINode>(I)) 1188 ConstantEvolutionLoopExitValue.erase(PN); 1189 } 1190 1191 1192 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the 1193 /// expression and create a new one. 1194 SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) { 1195 assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!"); 1196 1197 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V); 1198 if (I != Scalars.end()) return I->second; 1199 SCEVHandle S = createSCEV(V); 1200 Scalars.insert(std::make_pair(V, S)); 1201 return S; 1202 } 1203 1204 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for 1205 /// the specified instruction and replaces any references to the symbolic value 1206 /// SymName with the specified value. This is used during PHI resolution. 1207 void ScalarEvolutionsImpl:: 1208 ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName, 1209 const SCEVHandle &NewVal) { 1210 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I); 1211 if (SI == Scalars.end()) return; 1212 1213 SCEVHandle NV = 1214 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal); 1215 if (NV == SI->second) return; // No change. 1216 1217 SI->second = NV; // Update the scalars map! 1218 1219 // Any instruction values that use this instruction might also need to be 1220 // updated! 1221 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); 1222 UI != E; ++UI) 1223 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal); 1224 } 1225 1226 /// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in 1227 /// a loop header, making it a potential recurrence, or it doesn't. 1228 /// 1229 SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) { 1230 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized. 1231 if (const Loop *L = LI.getLoopFor(PN->getParent())) 1232 if (L->getHeader() == PN->getParent()) { 1233 // If it lives in the loop header, it has two incoming values, one 1234 // from outside the loop, and one from inside. 1235 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0)); 1236 unsigned BackEdge = IncomingEdge^1; 1237 1238 // While we are analyzing this PHI node, handle its value symbolically. 1239 SCEVHandle SymbolicName = SCEVUnknown::get(PN); 1240 assert(Scalars.find(PN) == Scalars.end() && 1241 "PHI node already processed?"); 1242 Scalars.insert(std::make_pair(PN, SymbolicName)); 1243 1244 // Using this symbolic name for the PHI, analyze the value coming around 1245 // the back-edge. 1246 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge)); 1247 1248 // NOTE: If BEValue is loop invariant, we know that the PHI node just 1249 // has a special value for the first iteration of the loop. 1250 1251 // If the value coming around the backedge is an add with the symbolic 1252 // value we just inserted, then we found a simple induction variable! 1253 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 1254 // If there is a single occurrence of the symbolic value, replace it 1255 // with a recurrence. 1256 unsigned FoundIndex = Add->getNumOperands(); 1257 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 1258 if (Add->getOperand(i) == SymbolicName) 1259 if (FoundIndex == e) { 1260 FoundIndex = i; 1261 break; 1262 } 1263 1264 if (FoundIndex != Add->getNumOperands()) { 1265 // Create an add with everything but the specified operand. 1266 std::vector<SCEVHandle> Ops; 1267 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 1268 if (i != FoundIndex) 1269 Ops.push_back(Add->getOperand(i)); 1270 SCEVHandle Accum = SCEVAddExpr::get(Ops); 1271 1272 // This is not a valid addrec if the step amount is varying each 1273 // loop iteration, but is not itself an addrec in this loop. 1274 if (Accum->isLoopInvariant(L) || 1275 (isa<SCEVAddRecExpr>(Accum) && 1276 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 1277 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge)); 1278 SCEVHandle PHISCEV = SCEVAddRecExpr::get(StartVal, Accum, L); 1279 1280 // Okay, for the entire analysis of this edge we assumed the PHI 1281 // to be symbolic. We now need to go back and update all of the 1282 // entries for the scalars that use the PHI (except for the PHI 1283 // itself) to use the new analyzed value instead of the "symbolic" 1284 // value. 1285 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV); 1286 return PHISCEV; 1287 } 1288 } 1289 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) { 1290 // Otherwise, this could be a loop like this: 1291 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 1292 // In this case, j = {1,+,1} and BEValue is j. 1293 // Because the other in-value of i (0) fits the evolution of BEValue 1294 // i really is an addrec evolution. 1295 if (AddRec->getLoop() == L && AddRec->isAffine()) { 1296 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge)); 1297 1298 // If StartVal = j.start - j.stride, we can use StartVal as the 1299 // initial step of the addrec evolution. 1300 if (StartVal == SCEV::getMinusSCEV(AddRec->getOperand(0), 1301 AddRec->getOperand(1))) { 1302 SCEVHandle PHISCEV = 1303 SCEVAddRecExpr::get(StartVal, AddRec->getOperand(1), L); 1304 1305 // Okay, for the entire analysis of this edge we assumed the PHI 1306 // to be symbolic. We now need to go back and update all of the 1307 // entries for the scalars that use the PHI (except for the PHI 1308 // itself) to use the new analyzed value instead of the "symbolic" 1309 // value. 1310 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV); 1311 return PHISCEV; 1312 } 1313 } 1314 } 1315 1316 return SymbolicName; 1317 } 1318 1319 // If it's not a loop phi, we can't handle it yet. 1320 return SCEVUnknown::get(PN); 1321 } 1322 1323 /// GetConstantFactor - Determine the largest constant factor that S has. For 1324 /// example, turn {4,+,8} -> 4. (S umod result) should always equal zero. 1325 static uint64_t GetConstantFactor(SCEVHandle S) { 1326 if (SCEVConstant *C = dyn_cast<SCEVConstant>(S)) { 1327 if (uint64_t V = C->getValue()->getZExtValue()) 1328 return V; 1329 else // Zero is a multiple of everything. 1330 return 1ULL << (S->getType()->getPrimitiveSizeInBits()-1); 1331 } 1332 1333 if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 1334 return GetConstantFactor(T->getOperand()) & 1335 cast<IntegerType>(T->getType())->getBitMask(); 1336 if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) 1337 return GetConstantFactor(E->getOperand()); 1338 1339 if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 1340 // The result is the min of all operands. 1341 uint64_t Res = GetConstantFactor(A->getOperand(0)); 1342 for (unsigned i = 1, e = A->getNumOperands(); i != e && Res > 1; ++i) 1343 Res = std::min(Res, GetConstantFactor(A->getOperand(i))); 1344 return Res; 1345 } 1346 1347 if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 1348 // The result is the product of all the operands. 1349 uint64_t Res = GetConstantFactor(M->getOperand(0)); 1350 for (unsigned i = 1, e = M->getNumOperands(); i != e; ++i) 1351 Res *= GetConstantFactor(M->getOperand(i)); 1352 return Res; 1353 } 1354 1355 if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 1356 // For now, we just handle linear expressions. 1357 if (A->getNumOperands() == 2) { 1358 // We want the GCD between the start and the stride value. 1359 uint64_t Start = GetConstantFactor(A->getOperand(0)); 1360 if (Start == 1) return 1; 1361 uint64_t Stride = GetConstantFactor(A->getOperand(1)); 1362 return GreatestCommonDivisor64(Start, Stride); 1363 } 1364 } 1365 1366 // SCEVSDivExpr, SCEVUnknown. 1367 return 1; 1368 } 1369 1370 /// createSCEV - We know that there is no SCEV for the specified value. 1371 /// Analyze the expression. 1372 /// 1373 SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) { 1374 if (Instruction *I = dyn_cast<Instruction>(V)) { 1375 switch (I->getOpcode()) { 1376 case Instruction::Add: 1377 return SCEVAddExpr::get(getSCEV(I->getOperand(0)), 1378 getSCEV(I->getOperand(1))); 1379 case Instruction::Mul: 1380 return SCEVMulExpr::get(getSCEV(I->getOperand(0)), 1381 getSCEV(I->getOperand(1))); 1382 case Instruction::SDiv: 1383 return SCEVSDivExpr::get(getSCEV(I->getOperand(0)), 1384 getSCEV(I->getOperand(1))); 1385 break; 1386 1387 case Instruction::Sub: 1388 return SCEV::getMinusSCEV(getSCEV(I->getOperand(0)), 1389 getSCEV(I->getOperand(1))); 1390 case Instruction::Or: 1391 // If the RHS of the Or is a constant, we may have something like: 1392 // X*4+1 which got turned into X*4|1. Handle this as an add so loop 1393 // optimizations will transparently handle this case. 1394 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) { 1395 SCEVHandle LHS = getSCEV(I->getOperand(0)); 1396 uint64_t CommonFact = GetConstantFactor(LHS); 1397 assert(CommonFact && "Common factor should at least be 1!"); 1398 if (CommonFact > CI->getZExtValue()) { 1399 // If the LHS is a multiple that is larger than the RHS, use +. 1400 return SCEVAddExpr::get(LHS, 1401 getSCEV(I->getOperand(1))); 1402 } 1403 } 1404 break; 1405 1406 case Instruction::Shl: 1407 // Turn shift left of a constant amount into a multiply. 1408 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) { 1409 Constant *X = ConstantInt::get(V->getType(), 1); 1410 X = ConstantExpr::getShl(X, SA); 1411 return SCEVMulExpr::get(getSCEV(I->getOperand(0)), getSCEV(X)); 1412 } 1413 break; 1414 1415 case Instruction::Trunc: 1416 return SCEVTruncateExpr::get(getSCEV(I->getOperand(0)), I->getType()); 1417 1418 case Instruction::ZExt: 1419 return SCEVZeroExtendExpr::get(getSCEV(I->getOperand(0)), I->getType()); 1420 1421 case Instruction::BitCast: 1422 // BitCasts are no-op casts so we just eliminate the cast. 1423 if (I->getType()->isInteger() && 1424 I->getOperand(0)->getType()->isInteger()) 1425 return getSCEV(I->getOperand(0)); 1426 break; 1427 1428 case Instruction::PHI: 1429 return createNodeForPHI(cast<PHINode>(I)); 1430 1431 default: // We cannot analyze this expression. 1432 break; 1433 } 1434 } 1435 1436 return SCEVUnknown::get(V); 1437 } 1438 1439 1440 1441 //===----------------------------------------------------------------------===// 1442 // Iteration Count Computation Code 1443 // 1444 1445 /// getIterationCount - If the specified loop has a predictable iteration 1446 /// count, return it. Note that it is not valid to call this method on a 1447 /// loop without a loop-invariant iteration count. 1448 SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) { 1449 std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L); 1450 if (I == IterationCounts.end()) { 1451 SCEVHandle ItCount = ComputeIterationCount(L); 1452 I = IterationCounts.insert(std::make_pair(L, ItCount)).first; 1453 if (ItCount != UnknownValue) { 1454 assert(ItCount->isLoopInvariant(L) && 1455 "Computed trip count isn't loop invariant for loop!"); 1456 ++NumTripCountsComputed; 1457 } else if (isa<PHINode>(L->getHeader()->begin())) { 1458 // Only count loops that have phi nodes as not being computable. 1459 ++NumTripCountsNotComputed; 1460 } 1461 } 1462 return I->second; 1463 } 1464 1465 /// ComputeIterationCount - Compute the number of times the specified loop 1466 /// will iterate. 1467 SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) { 1468 // If the loop has a non-one exit block count, we can't analyze it. 1469 std::vector<BasicBlock*> ExitBlocks; 1470 L->getExitBlocks(ExitBlocks); 1471 if (ExitBlocks.size() != 1) return UnknownValue; 1472 1473 // Okay, there is one exit block. Try to find the condition that causes the 1474 // loop to be exited. 1475 BasicBlock *ExitBlock = ExitBlocks[0]; 1476 1477 BasicBlock *ExitingBlock = 0; 1478 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock); 1479 PI != E; ++PI) 1480 if (L->contains(*PI)) { 1481 if (ExitingBlock == 0) 1482 ExitingBlock = *PI; 1483 else 1484 return UnknownValue; // More than one block exiting! 1485 } 1486 assert(ExitingBlock && "No exits from loop, something is broken!"); 1487 1488 // Okay, we've computed the exiting block. See what condition causes us to 1489 // exit. 1490 // 1491 // FIXME: we should be able to handle switch instructions (with a single exit) 1492 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator()); 1493 if (ExitBr == 0) return UnknownValue; 1494 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!"); 1495 1496 // At this point, we know we have a conditional branch that determines whether 1497 // the loop is exited. However, we don't know if the branch is executed each 1498 // time through the loop. If not, then the execution count of the branch will 1499 // not be equal to the trip count of the loop. 1500 // 1501 // Currently we check for this by checking to see if the Exit branch goes to 1502 // the loop header. If so, we know it will always execute the same number of 1503 // times as the loop. We also handle the case where the exit block *is* the 1504 // loop header. This is common for un-rotated loops. More extensive analysis 1505 // could be done to handle more cases here. 1506 if (ExitBr->getSuccessor(0) != L->getHeader() && 1507 ExitBr->getSuccessor(1) != L->getHeader() && 1508 ExitBr->getParent() != L->getHeader()) 1509 return UnknownValue; 1510 1511 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition()); 1512 1513 // If its not an integer comparison then compute it the hard way. 1514 // Note that ICmpInst deals with pointer comparisons too so we must check 1515 // the type of the operand. 1516 if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType())) 1517 return ComputeIterationCountExhaustively(L, ExitBr->getCondition(), 1518 ExitBr->getSuccessor(0) == ExitBlock); 1519 1520 // If the condition was exit on true, convert the condition to exit on false 1521 ICmpInst::Predicate Cond; 1522 if (ExitBr->getSuccessor(1) == ExitBlock) 1523 Cond = ExitCond->getPredicate(); 1524 else 1525 Cond = ExitCond->getInversePredicate(); 1526 1527 // Handle common loops like: for (X = "string"; *X; ++X) 1528 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 1529 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 1530 SCEVHandle ItCnt = 1531 ComputeLoadConstantCompareIterationCount(LI, RHS, L, Cond); 1532 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt; 1533 } 1534 1535 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0)); 1536 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1)); 1537 1538 // Try to evaluate any dependencies out of the loop. 1539 SCEVHandle Tmp = getSCEVAtScope(LHS, L); 1540 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp; 1541 Tmp = getSCEVAtScope(RHS, L); 1542 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp; 1543 1544 // At this point, we would like to compute how many iterations of the 1545 // loop the predicate will return true for these inputs. 1546 if (isa<SCEVConstant>(LHS) && !isa<SCEVConstant>(RHS)) { 1547 // If there is a constant, force it into the RHS. 1548 std::swap(LHS, RHS); 1549 Cond = ICmpInst::getSwappedPredicate(Cond); 1550 } 1551 1552 // FIXME: think about handling pointer comparisons! i.e.: 1553 // while (P != P+100) ++P; 1554 1555 // If we have a comparison of a chrec against a constant, try to use value 1556 // ranges to answer this query. 1557 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 1558 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 1559 if (AddRec->getLoop() == L) { 1560 // Form the comparison range using the constant of the correct type so 1561 // that the ConstantRange class knows to do a signed or unsigned 1562 // comparison. 1563 ConstantInt *CompVal = RHSC->getValue(); 1564 const Type *RealTy = ExitCond->getOperand(0)->getType(); 1565 CompVal = dyn_cast<ConstantInt>( 1566 ConstantExpr::getBitCast(CompVal, RealTy)); 1567 if (CompVal) { 1568 // Form the constant range. 1569 ConstantRange CompRange(Cond, CompVal->getValue()); 1570 1571 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, 1572 false /*Always treat as unsigned range*/); 1573 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 1574 } 1575 } 1576 1577 switch (Cond) { 1578 case ICmpInst::ICMP_NE: { // while (X != Y) 1579 // Convert to: while (X-Y != 0) 1580 SCEVHandle TC = HowFarToZero(SCEV::getMinusSCEV(LHS, RHS), L); 1581 if (!isa<SCEVCouldNotCompute>(TC)) return TC; 1582 break; 1583 } 1584 case ICmpInst::ICMP_EQ: { 1585 // Convert to: while (X-Y == 0) // while (X == Y) 1586 SCEVHandle TC = HowFarToNonZero(SCEV::getMinusSCEV(LHS, RHS), L); 1587 if (!isa<SCEVCouldNotCompute>(TC)) return TC; 1588 break; 1589 } 1590 case ICmpInst::ICMP_SLT: { 1591 SCEVHandle TC = HowManyLessThans(LHS, RHS, L); 1592 if (!isa<SCEVCouldNotCompute>(TC)) return TC; 1593 break; 1594 } 1595 case ICmpInst::ICMP_SGT: { 1596 SCEVHandle TC = HowManyLessThans(RHS, LHS, L); 1597 if (!isa<SCEVCouldNotCompute>(TC)) return TC; 1598 break; 1599 } 1600 default: 1601 #if 0 1602 cerr << "ComputeIterationCount "; 1603 if (ExitCond->getOperand(0)->getType()->isUnsigned()) 1604 cerr << "[unsigned] "; 1605 cerr << *LHS << " " 1606 << Instruction::getOpcodeName(Instruction::ICmp) 1607 << " " << *RHS << "\n"; 1608 #endif 1609 break; 1610 } 1611 return ComputeIterationCountExhaustively(L, ExitCond, 1612 ExitBr->getSuccessor(0) == ExitBlock); 1613 } 1614 1615 static ConstantInt * 1616 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, Constant *C) { 1617 SCEVHandle InVal = SCEVConstant::get(cast<ConstantInt>(C)); 1618 SCEVHandle Val = AddRec->evaluateAtIteration(InVal); 1619 assert(isa<SCEVConstant>(Val) && 1620 "Evaluation of SCEV at constant didn't fold correctly?"); 1621 return cast<SCEVConstant>(Val)->getValue(); 1622 } 1623 1624 /// GetAddressedElementFromGlobal - Given a global variable with an initializer 1625 /// and a GEP expression (missing the pointer index) indexing into it, return 1626 /// the addressed element of the initializer or null if the index expression is 1627 /// invalid. 1628 static Constant * 1629 GetAddressedElementFromGlobal(GlobalVariable *GV, 1630 const std::vector<ConstantInt*> &Indices) { 1631 Constant *Init = GV->getInitializer(); 1632 for (unsigned i = 0, e = Indices.size(); i != e; ++i) { 1633 uint64_t Idx = Indices[i]->getZExtValue(); 1634 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) { 1635 assert(Idx < CS->getNumOperands() && "Bad struct index!"); 1636 Init = cast<Constant>(CS->getOperand(Idx)); 1637 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) { 1638 if (Idx >= CA->getNumOperands()) return 0; // Bogus program 1639 Init = cast<Constant>(CA->getOperand(Idx)); 1640 } else if (isa<ConstantAggregateZero>(Init)) { 1641 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) { 1642 assert(Idx < STy->getNumElements() && "Bad struct index!"); 1643 Init = Constant::getNullValue(STy->getElementType(Idx)); 1644 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) { 1645 if (Idx >= ATy->getNumElements()) return 0; // Bogus program 1646 Init = Constant::getNullValue(ATy->getElementType()); 1647 } else { 1648 assert(0 && "Unknown constant aggregate type!"); 1649 } 1650 return 0; 1651 } else { 1652 return 0; // Unknown initializer type 1653 } 1654 } 1655 return Init; 1656 } 1657 1658 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of 1659 /// 'setcc load X, cst', try to se if we can compute the trip count. 1660 SCEVHandle ScalarEvolutionsImpl:: 1661 ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS, 1662 const Loop *L, 1663 ICmpInst::Predicate predicate) { 1664 if (LI->isVolatile()) return UnknownValue; 1665 1666 // Check to see if the loaded pointer is a getelementptr of a global. 1667 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 1668 if (!GEP) return UnknownValue; 1669 1670 // Make sure that it is really a constant global we are gepping, with an 1671 // initializer, and make sure the first IDX is really 0. 1672 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 1673 if (!GV || !GV->isConstant() || !GV->hasInitializer() || 1674 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 1675 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 1676 return UnknownValue; 1677 1678 // Okay, we allow one non-constant index into the GEP instruction. 1679 Value *VarIdx = 0; 1680 std::vector<ConstantInt*> Indexes; 1681 unsigned VarIdxNum = 0; 1682 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 1683 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 1684 Indexes.push_back(CI); 1685 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 1686 if (VarIdx) return UnknownValue; // Multiple non-constant idx's. 1687 VarIdx = GEP->getOperand(i); 1688 VarIdxNum = i-2; 1689 Indexes.push_back(0); 1690 } 1691 1692 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 1693 // Check to see if X is a loop variant variable value now. 1694 SCEVHandle Idx = getSCEV(VarIdx); 1695 SCEVHandle Tmp = getSCEVAtScope(Idx, L); 1696 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp; 1697 1698 // We can only recognize very limited forms of loop index expressions, in 1699 // particular, only affine AddRec's like {C1,+,C2}. 1700 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 1701 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) || 1702 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 1703 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 1704 return UnknownValue; 1705 1706 unsigned MaxSteps = MaxBruteForceIterations; 1707 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 1708 ConstantInt *ItCst = 1709 ConstantInt::get(IdxExpr->getType(), IterationNum); 1710 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst); 1711 1712 // Form the GEP offset. 1713 Indexes[VarIdxNum] = Val; 1714 1715 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes); 1716 if (Result == 0) break; // Cannot compute! 1717 1718 // Evaluate the condition for this iteration. 1719 Result = ConstantExpr::getICmp(predicate, Result, RHS); 1720 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 1721 if (cast<ConstantInt>(Result)->getZExtValue() == false) { 1722 #if 0 1723 cerr << "\n***\n*** Computed loop count " << *ItCst 1724 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader() 1725 << "***\n"; 1726 #endif 1727 ++NumArrayLenItCounts; 1728 return SCEVConstant::get(ItCst); // Found terminating iteration! 1729 } 1730 } 1731 return UnknownValue; 1732 } 1733 1734 1735 /// CanConstantFold - Return true if we can constant fold an instruction of the 1736 /// specified type, assuming that all operands were constants. 1737 static bool CanConstantFold(const Instruction *I) { 1738 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 1739 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I)) 1740 return true; 1741 1742 if (const CallInst *CI = dyn_cast<CallInst>(I)) 1743 if (const Function *F = CI->getCalledFunction()) 1744 return canConstantFoldCallTo((Function*)F); // FIXME: elim cast 1745 return false; 1746 } 1747 1748 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 1749 /// in the loop that V is derived from. We allow arbitrary operations along the 1750 /// way, but the operands of an operation must either be constants or a value 1751 /// derived from a constant PHI. If this expression does not fit with these 1752 /// constraints, return null. 1753 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 1754 // If this is not an instruction, or if this is an instruction outside of the 1755 // loop, it can't be derived from a loop PHI. 1756 Instruction *I = dyn_cast<Instruction>(V); 1757 if (I == 0 || !L->contains(I->getParent())) return 0; 1758 1759 if (PHINode *PN = dyn_cast<PHINode>(I)) 1760 if (L->getHeader() == I->getParent()) 1761 return PN; 1762 else 1763 // We don't currently keep track of the control flow needed to evaluate 1764 // PHIs, so we cannot handle PHIs inside of loops. 1765 return 0; 1766 1767 // If we won't be able to constant fold this expression even if the operands 1768 // are constants, return early. 1769 if (!CanConstantFold(I)) return 0; 1770 1771 // Otherwise, we can evaluate this instruction if all of its operands are 1772 // constant or derived from a PHI node themselves. 1773 PHINode *PHI = 0; 1774 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op) 1775 if (!(isa<Constant>(I->getOperand(Op)) || 1776 isa<GlobalValue>(I->getOperand(Op)))) { 1777 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L); 1778 if (P == 0) return 0; // Not evolving from PHI 1779 if (PHI == 0) 1780 PHI = P; 1781 else if (PHI != P) 1782 return 0; // Evolving from multiple different PHIs. 1783 } 1784 1785 // This is a expression evolving from a constant PHI! 1786 return PHI; 1787 } 1788 1789 /// EvaluateExpression - Given an expression that passes the 1790 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 1791 /// in the loop has the value PHIVal. If we can't fold this expression for some 1792 /// reason, return null. 1793 static Constant *EvaluateExpression(Value *V, Constant *PHIVal) { 1794 if (isa<PHINode>(V)) return PHIVal; 1795 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) 1796 return GV; 1797 if (Constant *C = dyn_cast<Constant>(V)) return C; 1798 Instruction *I = cast<Instruction>(V); 1799 1800 std::vector<Constant*> Operands; 1801 Operands.resize(I->getNumOperands()); 1802 1803 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 1804 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal); 1805 if (Operands[i] == 0) return 0; 1806 } 1807 1808 return ConstantFoldInstOperands(I, &Operands[0], Operands.size()); 1809 } 1810 1811 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 1812 /// in the header of its containing loop, we know the loop executes a 1813 /// constant number of times, and the PHI node is just a recurrence 1814 /// involving constants, fold it. 1815 Constant *ScalarEvolutionsImpl:: 1816 getConstantEvolutionLoopExitValue(PHINode *PN, uint64_t Its, const Loop *L) { 1817 std::map<PHINode*, Constant*>::iterator I = 1818 ConstantEvolutionLoopExitValue.find(PN); 1819 if (I != ConstantEvolutionLoopExitValue.end()) 1820 return I->second; 1821 1822 if (Its > MaxBruteForceIterations) 1823 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it. 1824 1825 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 1826 1827 // Since the loop is canonicalized, the PHI node must have two entries. One 1828 // entry must be a constant (coming in from outside of the loop), and the 1829 // second must be derived from the same PHI. 1830 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1)); 1831 Constant *StartCST = 1832 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge)); 1833 if (StartCST == 0) 1834 return RetVal = 0; // Must be a constant. 1835 1836 Value *BEValue = PN->getIncomingValue(SecondIsBackedge); 1837 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L); 1838 if (PN2 != PN) 1839 return RetVal = 0; // Not derived from same PHI. 1840 1841 // Execute the loop symbolically to determine the exit value. 1842 unsigned IterationNum = 0; 1843 unsigned NumIterations = Its; 1844 if (NumIterations != Its) 1845 return RetVal = 0; // More than 2^32 iterations?? 1846 1847 for (Constant *PHIVal = StartCST; ; ++IterationNum) { 1848 if (IterationNum == NumIterations) 1849 return RetVal = PHIVal; // Got exit value! 1850 1851 // Compute the value of the PHI node for the next iteration. 1852 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal); 1853 if (NextPHI == PHIVal) 1854 return RetVal = NextPHI; // Stopped evolving! 1855 if (NextPHI == 0) 1856 return 0; // Couldn't evaluate! 1857 PHIVal = NextPHI; 1858 } 1859 } 1860 1861 /// ComputeIterationCountExhaustively - If the trip is known to execute a 1862 /// constant number of times (the condition evolves only from constants), 1863 /// try to evaluate a few iterations of the loop until we get the exit 1864 /// condition gets a value of ExitWhen (true or false). If we cannot 1865 /// evaluate the trip count of the loop, return UnknownValue. 1866 SCEVHandle ScalarEvolutionsImpl:: 1867 ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) { 1868 PHINode *PN = getConstantEvolvingPHI(Cond, L); 1869 if (PN == 0) return UnknownValue; 1870 1871 // Since the loop is canonicalized, the PHI node must have two entries. One 1872 // entry must be a constant (coming in from outside of the loop), and the 1873 // second must be derived from the same PHI. 1874 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1)); 1875 Constant *StartCST = 1876 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge)); 1877 if (StartCST == 0) return UnknownValue; // Must be a constant. 1878 1879 Value *BEValue = PN->getIncomingValue(SecondIsBackedge); 1880 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L); 1881 if (PN2 != PN) return UnknownValue; // Not derived from same PHI. 1882 1883 // Okay, we find a PHI node that defines the trip count of this loop. Execute 1884 // the loop symbolically to determine when the condition gets a value of 1885 // "ExitWhen". 1886 unsigned IterationNum = 0; 1887 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 1888 for (Constant *PHIVal = StartCST; 1889 IterationNum != MaxIterations; ++IterationNum) { 1890 ConstantInt *CondVal = 1891 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal)); 1892 1893 // Couldn't symbolically evaluate. 1894 if (!CondVal) return UnknownValue; 1895 1896 if (CondVal->getZExtValue() == uint64_t(ExitWhen)) { 1897 ConstantEvolutionLoopExitValue[PN] = PHIVal; 1898 ++NumBruteForceTripCountsComputed; 1899 return SCEVConstant::get(ConstantInt::get(Type::Int32Ty, IterationNum)); 1900 } 1901 1902 // Compute the value of the PHI node for the next iteration. 1903 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal); 1904 if (NextPHI == 0 || NextPHI == PHIVal) 1905 return UnknownValue; // Couldn't evaluate or not making progress... 1906 PHIVal = NextPHI; 1907 } 1908 1909 // Too many iterations were needed to evaluate. 1910 return UnknownValue; 1911 } 1912 1913 /// getSCEVAtScope - Compute the value of the specified expression within the 1914 /// indicated loop (which may be null to indicate in no loop). If the 1915 /// expression cannot be evaluated, return UnknownValue. 1916 SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) { 1917 // FIXME: this should be turned into a virtual method on SCEV! 1918 1919 if (isa<SCEVConstant>(V)) return V; 1920 1921 // If this instruction is evolves from a constant-evolving PHI, compute the 1922 // exit value from the loop without using SCEVs. 1923 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 1924 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 1925 const Loop *LI = this->LI[I->getParent()]; 1926 if (LI && LI->getParentLoop() == L) // Looking for loop exit value. 1927 if (PHINode *PN = dyn_cast<PHINode>(I)) 1928 if (PN->getParent() == LI->getHeader()) { 1929 // Okay, there is no closed form solution for the PHI node. Check 1930 // to see if the loop that contains it has a known iteration count. 1931 // If so, we may be able to force computation of the exit value. 1932 SCEVHandle IterationCount = getIterationCount(LI); 1933 if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) { 1934 // Okay, we know how many times the containing loop executes. If 1935 // this is a constant evolving PHI node, get the final value at 1936 // the specified iteration number. 1937 Constant *RV = getConstantEvolutionLoopExitValue(PN, 1938 ICC->getValue()->getZExtValue(), 1939 LI); 1940 if (RV) return SCEVUnknown::get(RV); 1941 } 1942 } 1943 1944 // Okay, this is an expression that we cannot symbolically evaluate 1945 // into a SCEV. Check to see if it's possible to symbolically evaluate 1946 // the arguments into constants, and if so, try to constant propagate the 1947 // result. This is particularly useful for computing loop exit values. 1948 if (CanConstantFold(I)) { 1949 std::vector<Constant*> Operands; 1950 Operands.reserve(I->getNumOperands()); 1951 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 1952 Value *Op = I->getOperand(i); 1953 if (Constant *C = dyn_cast<Constant>(Op)) { 1954 Operands.push_back(C); 1955 } else { 1956 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L); 1957 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) 1958 Operands.push_back(ConstantExpr::getIntegerCast(SC->getValue(), 1959 Op->getType(), 1960 false)); 1961 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) { 1962 if (Constant *C = dyn_cast<Constant>(SU->getValue())) 1963 Operands.push_back(ConstantExpr::getIntegerCast(C, 1964 Op->getType(), 1965 false)); 1966 else 1967 return V; 1968 } else { 1969 return V; 1970 } 1971 } 1972 } 1973 Constant *C =ConstantFoldInstOperands(I, &Operands[0], Operands.size()); 1974 return SCEVUnknown::get(C); 1975 } 1976 } 1977 1978 // This is some other type of SCEVUnknown, just return it. 1979 return V; 1980 } 1981 1982 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 1983 // Avoid performing the look-up in the common case where the specified 1984 // expression has no loop-variant portions. 1985 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 1986 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 1987 if (OpAtScope != Comm->getOperand(i)) { 1988 if (OpAtScope == UnknownValue) return UnknownValue; 1989 // Okay, at least one of these operands is loop variant but might be 1990 // foldable. Build a new instance of the folded commutative expression. 1991 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i); 1992 NewOps.push_back(OpAtScope); 1993 1994 for (++i; i != e; ++i) { 1995 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 1996 if (OpAtScope == UnknownValue) return UnknownValue; 1997 NewOps.push_back(OpAtScope); 1998 } 1999 if (isa<SCEVAddExpr>(Comm)) 2000 return SCEVAddExpr::get(NewOps); 2001 assert(isa<SCEVMulExpr>(Comm) && "Only know about add and mul!"); 2002 return SCEVMulExpr::get(NewOps); 2003 } 2004 } 2005 // If we got here, all operands are loop invariant. 2006 return Comm; 2007 } 2008 2009 if (SCEVSDivExpr *Div = dyn_cast<SCEVSDivExpr>(V)) { 2010 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L); 2011 if (LHS == UnknownValue) return LHS; 2012 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L); 2013 if (RHS == UnknownValue) return RHS; 2014 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 2015 return Div; // must be loop invariant 2016 return SCEVSDivExpr::get(LHS, RHS); 2017 } 2018 2019 // If this is a loop recurrence for a loop that does not contain L, then we 2020 // are dealing with the final value computed by the loop. 2021 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 2022 if (!L || !AddRec->getLoop()->contains(L->getHeader())) { 2023 // To evaluate this recurrence, we need to know how many times the AddRec 2024 // loop iterates. Compute this now. 2025 SCEVHandle IterationCount = getIterationCount(AddRec->getLoop()); 2026 if (IterationCount == UnknownValue) return UnknownValue; 2027 IterationCount = getTruncateOrZeroExtend(IterationCount, 2028 AddRec->getType()); 2029 2030 // If the value is affine, simplify the expression evaluation to just 2031 // Start + Step*IterationCount. 2032 if (AddRec->isAffine()) 2033 return SCEVAddExpr::get(AddRec->getStart(), 2034 SCEVMulExpr::get(IterationCount, 2035 AddRec->getOperand(1))); 2036 2037 // Otherwise, evaluate it the hard way. 2038 return AddRec->evaluateAtIteration(IterationCount); 2039 } 2040 return UnknownValue; 2041 } 2042 2043 //assert(0 && "Unknown SCEV type!"); 2044 return UnknownValue; 2045 } 2046 2047 2048 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the 2049 /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which 2050 /// might be the same) or two SCEVCouldNotCompute objects. 2051 /// 2052 static std::pair<SCEVHandle,SCEVHandle> 2053 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec) { 2054 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 2055 SCEVConstant *L = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 2056 SCEVConstant *M = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 2057 SCEVConstant *N = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 2058 2059 // We currently can only solve this if the coefficients are constants. 2060 if (!L || !M || !N) { 2061 SCEV *CNC = new SCEVCouldNotCompute(); 2062 return std::make_pair(CNC, CNC); 2063 } 2064 2065 Constant *C = L->getValue(); 2066 Constant *Two = ConstantInt::get(C->getType(), 2); 2067 2068 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C 2069 // The B coefficient is M-N/2 2070 Constant *B = ConstantExpr::getSub(M->getValue(), 2071 ConstantExpr::getSDiv(N->getValue(), 2072 Two)); 2073 // The A coefficient is N/2 2074 Constant *A = ConstantExpr::getSDiv(N->getValue(), Two); 2075 2076 // Compute the B^2-4ac term. 2077 Constant *SqrtTerm = 2078 ConstantExpr::getMul(ConstantInt::get(C->getType(), 4), 2079 ConstantExpr::getMul(A, C)); 2080 SqrtTerm = ConstantExpr::getSub(ConstantExpr::getMul(B, B), SqrtTerm); 2081 2082 // Compute floor(sqrt(B^2-4ac)) 2083 uint64_t SqrtValV = cast<ConstantInt>(SqrtTerm)->getZExtValue(); 2084 uint64_t SqrtValV2 = (uint64_t)sqrt((double)SqrtValV); 2085 // The square root might not be precise for arbitrary 64-bit integer 2086 // values. Do some sanity checks to ensure it's correct. 2087 if (SqrtValV2*SqrtValV2 > SqrtValV || 2088 (SqrtValV2+1)*(SqrtValV2+1) <= SqrtValV) { 2089 SCEV *CNC = new SCEVCouldNotCompute(); 2090 return std::make_pair(CNC, CNC); 2091 } 2092 2093 ConstantInt *SqrtVal = ConstantInt::get(Type::Int64Ty, SqrtValV2); 2094 SqrtTerm = ConstantExpr::getTruncOrBitCast(SqrtVal, SqrtTerm->getType()); 2095 2096 Constant *NegB = ConstantExpr::getNeg(B); 2097 Constant *TwoA = ConstantExpr::getMul(A, Two); 2098 2099 // The divisions must be performed as signed divisions. 2100 Constant *Solution1 = 2101 ConstantExpr::getSDiv(ConstantExpr::getAdd(NegB, SqrtTerm), TwoA); 2102 Constant *Solution2 = 2103 ConstantExpr::getSDiv(ConstantExpr::getSub(NegB, SqrtTerm), TwoA); 2104 return std::make_pair(SCEVUnknown::get(Solution1), 2105 SCEVUnknown::get(Solution2)); 2106 } 2107 2108 /// HowFarToZero - Return the number of times a backedge comparing the specified 2109 /// value to zero will execute. If not computable, return UnknownValue 2110 SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) { 2111 // If the value is a constant 2112 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 2113 // If the value is already zero, the branch will execute zero times. 2114 if (C->getValue()->isNullValue()) return C; 2115 return UnknownValue; // Otherwise it will loop infinitely. 2116 } 2117 2118 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V); 2119 if (!AddRec || AddRec->getLoop() != L) 2120 return UnknownValue; 2121 2122 if (AddRec->isAffine()) { 2123 // If this is an affine expression the execution count of this branch is 2124 // equal to: 2125 // 2126 // (0 - Start/Step) iff Start % Step == 0 2127 // 2128 // Get the initial value for the loop. 2129 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 2130 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue; 2131 SCEVHandle Step = AddRec->getOperand(1); 2132 2133 Step = getSCEVAtScope(Step, L->getParentLoop()); 2134 2135 // Figure out if Start % Step == 0. 2136 // FIXME: We should add DivExpr and RemExpr operations to our AST. 2137 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) { 2138 if (StepC->getValue()->equalsInt(1)) // N % 1 == 0 2139 return SCEV::getNegativeSCEV(Start); // 0 - Start/1 == -Start 2140 if (StepC->getValue()->isAllOnesValue()) // N % -1 == 0 2141 return Start; // 0 - Start/-1 == Start 2142 2143 // Check to see if Start is divisible by SC with no remainder. 2144 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) { 2145 ConstantInt *StartCC = StartC->getValue(); 2146 Constant *StartNegC = ConstantExpr::getNeg(StartCC); 2147 Constant *Rem = ConstantExpr::getSRem(StartNegC, StepC->getValue()); 2148 if (Rem->isNullValue()) { 2149 Constant *Result =ConstantExpr::getSDiv(StartNegC,StepC->getValue()); 2150 return SCEVUnknown::get(Result); 2151 } 2152 } 2153 } 2154 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) { 2155 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 2156 // the quadratic equation to solve it. 2157 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec); 2158 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first); 2159 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second); 2160 if (R1) { 2161 #if 0 2162 cerr << "HFTZ: " << *V << " - sol#1: " << *R1 2163 << " sol#2: " << *R2 << "\n"; 2164 #endif 2165 // Pick the smallest positive root value. 2166 if (ConstantInt *CB = 2167 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT, 2168 R1->getValue(), R2->getValue()))) { 2169 if (CB->getZExtValue() == false) 2170 std::swap(R1, R2); // R1 is the minimum root now. 2171 2172 // We can only use this value if the chrec ends up with an exact zero 2173 // value at this index. When solving for "X*X != 5", for example, we 2174 // should not accept a root of 2. 2175 SCEVHandle Val = AddRec->evaluateAtIteration(R1); 2176 if (SCEVConstant *EvalVal = dyn_cast<SCEVConstant>(Val)) 2177 if (EvalVal->getValue()->isNullValue()) 2178 return R1; // We found a quadratic root! 2179 } 2180 } 2181 } 2182 2183 return UnknownValue; 2184 } 2185 2186 /// HowFarToNonZero - Return the number of times a backedge checking the 2187 /// specified value for nonzero will execute. If not computable, return 2188 /// UnknownValue 2189 SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) { 2190 // Loops that look like: while (X == 0) are very strange indeed. We don't 2191 // handle them yet except for the trivial case. This could be expanded in the 2192 // future as needed. 2193 2194 // If the value is a constant, check to see if it is known to be non-zero 2195 // already. If so, the backedge will execute zero times. 2196 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 2197 Constant *Zero = Constant::getNullValue(C->getValue()->getType()); 2198 Constant *NonZero = 2199 ConstantExpr::getICmp(ICmpInst::ICMP_NE, C->getValue(), Zero); 2200 if (NonZero == ConstantInt::getTrue()) 2201 return getSCEV(Zero); 2202 return UnknownValue; // Otherwise it will loop infinitely. 2203 } 2204 2205 // We could implement others, but I really doubt anyone writes loops like 2206 // this, and if they did, they would already be constant folded. 2207 return UnknownValue; 2208 } 2209 2210 /// HowManyLessThans - Return the number of times a backedge containing the 2211 /// specified less-than comparison will execute. If not computable, return 2212 /// UnknownValue. 2213 SCEVHandle ScalarEvolutionsImpl:: 2214 HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L) { 2215 // Only handle: "ADDREC < LoopInvariant". 2216 if (!RHS->isLoopInvariant(L)) return UnknownValue; 2217 2218 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS); 2219 if (!AddRec || AddRec->getLoop() != L) 2220 return UnknownValue; 2221 2222 if (AddRec->isAffine()) { 2223 // FORNOW: We only support unit strides. 2224 SCEVHandle One = SCEVUnknown::getIntegerSCEV(1, RHS->getType()); 2225 if (AddRec->getOperand(1) != One) 2226 return UnknownValue; 2227 2228 // The number of iterations for "[n,+,1] < m", is m-n. However, we don't 2229 // know that m is >= n on input to the loop. If it is, the condition return 2230 // true zero times. What we really should return, for full generality, is 2231 // SMAX(0, m-n). Since we cannot check this, we will instead check for a 2232 // canonical loop form: most do-loops will have a check that dominates the 2233 // loop, that only enters the loop if [n-1]<m. If we can find this check, 2234 // we know that the SMAX will evaluate to m-n, because we know that m >= n. 2235 2236 // Search for the check. 2237 BasicBlock *Preheader = L->getLoopPreheader(); 2238 BasicBlock *PreheaderDest = L->getHeader(); 2239 if (Preheader == 0) return UnknownValue; 2240 2241 BranchInst *LoopEntryPredicate = 2242 dyn_cast<BranchInst>(Preheader->getTerminator()); 2243 if (!LoopEntryPredicate) return UnknownValue; 2244 2245 // This might be a critical edge broken out. If the loop preheader ends in 2246 // an unconditional branch to the loop, check to see if the preheader has a 2247 // single predecessor, and if so, look for its terminator. 2248 while (LoopEntryPredicate->isUnconditional()) { 2249 PreheaderDest = Preheader; 2250 Preheader = Preheader->getSinglePredecessor(); 2251 if (!Preheader) return UnknownValue; // Multiple preds. 2252 2253 LoopEntryPredicate = 2254 dyn_cast<BranchInst>(Preheader->getTerminator()); 2255 if (!LoopEntryPredicate) return UnknownValue; 2256 } 2257 2258 // Now that we found a conditional branch that dominates the loop, check to 2259 // see if it is the comparison we are looking for. 2260 if (ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition())){ 2261 Value *PreCondLHS = ICI->getOperand(0); 2262 Value *PreCondRHS = ICI->getOperand(1); 2263 ICmpInst::Predicate Cond; 2264 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest) 2265 Cond = ICI->getPredicate(); 2266 else 2267 Cond = ICI->getInversePredicate(); 2268 2269 switch (Cond) { 2270 case ICmpInst::ICMP_UGT: 2271 std::swap(PreCondLHS, PreCondRHS); 2272 Cond = ICmpInst::ICMP_ULT; 2273 break; 2274 case ICmpInst::ICMP_SGT: 2275 std::swap(PreCondLHS, PreCondRHS); 2276 Cond = ICmpInst::ICMP_SLT; 2277 break; 2278 default: break; 2279 } 2280 2281 if (Cond == ICmpInst::ICMP_SLT) { 2282 if (PreCondLHS->getType()->isInteger()) { 2283 if (RHS != getSCEV(PreCondRHS)) 2284 return UnknownValue; // Not a comparison against 'm'. 2285 2286 if (SCEV::getMinusSCEV(AddRec->getOperand(0), One) 2287 != getSCEV(PreCondLHS)) 2288 return UnknownValue; // Not a comparison against 'n-1'. 2289 } 2290 else return UnknownValue; 2291 } else if (Cond == ICmpInst::ICMP_ULT) 2292 return UnknownValue; 2293 2294 // cerr << "Computed Loop Trip Count as: " 2295 // << // *SCEV::getMinusSCEV(RHS, AddRec->getOperand(0)) << "\n"; 2296 return SCEV::getMinusSCEV(RHS, AddRec->getOperand(0)); 2297 } 2298 else 2299 return UnknownValue; 2300 } 2301 2302 return UnknownValue; 2303 } 2304 2305 /// getNumIterationsInRange - Return the number of iterations of this loop that 2306 /// produce values in the specified constant range. Another way of looking at 2307 /// this is that it returns the first iteration number where the value is not in 2308 /// the condition, thus computing the exit count. If the iteration count can't 2309 /// be computed, an instance of SCEVCouldNotCompute is returned. 2310 SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range, 2311 bool isSigned) const { 2312 if (Range.isFullSet()) // Infinite loop. 2313 return new SCEVCouldNotCompute(); 2314 2315 // If the start is a non-zero constant, shift the range to simplify things. 2316 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 2317 if (!SC->getValue()->isNullValue()) { 2318 std::vector<SCEVHandle> Operands(op_begin(), op_end()); 2319 Operands[0] = SCEVUnknown::getIntegerSCEV(0, SC->getType()); 2320 SCEVHandle Shifted = SCEVAddRecExpr::get(Operands, getLoop()); 2321 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 2322 return ShiftedAddRec->getNumIterationsInRange( 2323 Range.subtract(SC->getValue()),isSigned); 2324 // This is strange and shouldn't happen. 2325 return new SCEVCouldNotCompute(); 2326 } 2327 2328 // The only time we can solve this is when we have all constant indices. 2329 // Otherwise, we cannot determine the overflow conditions. 2330 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) 2331 if (!isa<SCEVConstant>(getOperand(i))) 2332 return new SCEVCouldNotCompute(); 2333 2334 2335 // Okay at this point we know that all elements of the chrec are constants and 2336 // that the start element is zero. 2337 2338 // First check to see if the range contains zero. If not, the first 2339 // iteration exits. 2340 ConstantInt *Zero = ConstantInt::get(getType(), 0); 2341 if (!Range.contains(Zero, isSigned)) return SCEVConstant::get(Zero); 2342 2343 if (isAffine()) { 2344 // If this is an affine expression then we have this situation: 2345 // Solve {0,+,A} in Range === Ax in Range 2346 2347 // Since we know that zero is in the range, we know that the upper value of 2348 // the range must be the first possible exit value. Also note that we 2349 // already checked for a full range. 2350 ConstantInt *Upper = cast<ConstantInt>(Range.getUpper()); 2351 ConstantInt *A = cast<SCEVConstant>(getOperand(1))->getValue(); 2352 ConstantInt *One = ConstantInt::get(getType(), 1); 2353 2354 // The exit value should be (Upper+A-1)/A. 2355 Constant *ExitValue = Upper; 2356 if (A != One) { 2357 ExitValue = ConstantExpr::getSub(ConstantExpr::getAdd(Upper, A), One); 2358 ExitValue = ConstantExpr::getSDiv(ExitValue, A); 2359 } 2360 assert(isa<ConstantInt>(ExitValue) && 2361 "Constant folding of integers not implemented?"); 2362 2363 // Evaluate at the exit value. If we really did fall out of the valid 2364 // range, then we computed our trip count, otherwise wrap around or other 2365 // things must have happened. 2366 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue); 2367 if (Range.contains(Val, isSigned)) 2368 return new SCEVCouldNotCompute(); // Something strange happened 2369 2370 // Ensure that the previous value is in the range. This is a sanity check. 2371 assert(Range.contains(EvaluateConstantChrecAtConstant(this, 2372 ConstantExpr::getSub(ExitValue, One)), isSigned) && 2373 "Linear scev computation is off in a bad way!"); 2374 return SCEVConstant::get(cast<ConstantInt>(ExitValue)); 2375 } else if (isQuadratic()) { 2376 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the 2377 // quadratic equation to solve it. To do this, we must frame our problem in 2378 // terms of figuring out when zero is crossed, instead of when 2379 // Range.getUpper() is crossed. 2380 std::vector<SCEVHandle> NewOps(op_begin(), op_end()); 2381 NewOps[0] = SCEV::getNegativeSCEV(SCEVUnknown::get(Range.getUpper())); 2382 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, getLoop()); 2383 2384 // Next, solve the constructed addrec 2385 std::pair<SCEVHandle,SCEVHandle> Roots = 2386 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec)); 2387 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first); 2388 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second); 2389 if (R1) { 2390 // Pick the smallest positive root value. 2391 if (ConstantInt *CB = 2392 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT, 2393 R1->getValue(), R2->getValue()))) { 2394 if (CB->getZExtValue() == false) 2395 std::swap(R1, R2); // R1 is the minimum root now. 2396 2397 // Make sure the root is not off by one. The returned iteration should 2398 // not be in the range, but the previous one should be. When solving 2399 // for "X*X < 5", for example, we should not return a root of 2. 2400 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this, 2401 R1->getValue()); 2402 if (Range.contains(R1Val, isSigned)) { 2403 // The next iteration must be out of the range... 2404 Constant *NextVal = 2405 ConstantExpr::getAdd(R1->getValue(), 2406 ConstantInt::get(R1->getType(), 1)); 2407 2408 R1Val = EvaluateConstantChrecAtConstant(this, NextVal); 2409 if (!Range.contains(R1Val, isSigned)) 2410 return SCEVUnknown::get(NextVal); 2411 return new SCEVCouldNotCompute(); // Something strange happened 2412 } 2413 2414 // If R1 was not in the range, then it is a good return value. Make 2415 // sure that R1-1 WAS in the range though, just in case. 2416 Constant *NextVal = 2417 ConstantExpr::getSub(R1->getValue(), 2418 ConstantInt::get(R1->getType(), 1)); 2419 R1Val = EvaluateConstantChrecAtConstant(this, NextVal); 2420 if (Range.contains(R1Val, isSigned)) 2421 return R1; 2422 return new SCEVCouldNotCompute(); // Something strange happened 2423 } 2424 } 2425 } 2426 2427 // Fallback, if this is a general polynomial, figure out the progression 2428 // through brute force: evaluate until we find an iteration that fails the 2429 // test. This is likely to be slow, but getting an accurate trip count is 2430 // incredibly important, we will be able to simplify the exit test a lot, and 2431 // we are almost guaranteed to get a trip count in this case. 2432 ConstantInt *TestVal = ConstantInt::get(getType(), 0); 2433 ConstantInt *One = ConstantInt::get(getType(), 1); 2434 ConstantInt *EndVal = TestVal; // Stop when we wrap around. 2435 do { 2436 ++NumBruteForceEvaluations; 2437 SCEVHandle Val = evaluateAtIteration(SCEVConstant::get(TestVal)); 2438 if (!isa<SCEVConstant>(Val)) // This shouldn't happen. 2439 return new SCEVCouldNotCompute(); 2440 2441 // Check to see if we found the value! 2442 if (!Range.contains(cast<SCEVConstant>(Val)->getValue(), isSigned)) 2443 return SCEVConstant::get(TestVal); 2444 2445 // Increment to test the next index. 2446 TestVal = cast<ConstantInt>(ConstantExpr::getAdd(TestVal, One)); 2447 } while (TestVal != EndVal); 2448 2449 return new SCEVCouldNotCompute(); 2450 } 2451 2452 2453 2454 //===----------------------------------------------------------------------===// 2455 // ScalarEvolution Class Implementation 2456 //===----------------------------------------------------------------------===// 2457 2458 bool ScalarEvolution::runOnFunction(Function &F) { 2459 Impl = new ScalarEvolutionsImpl(F, getAnalysis<LoopInfo>()); 2460 return false; 2461 } 2462 2463 void ScalarEvolution::releaseMemory() { 2464 delete (ScalarEvolutionsImpl*)Impl; 2465 Impl = 0; 2466 } 2467 2468 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const { 2469 AU.setPreservesAll(); 2470 AU.addRequiredTransitive<LoopInfo>(); 2471 } 2472 2473 SCEVHandle ScalarEvolution::getSCEV(Value *V) const { 2474 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V); 2475 } 2476 2477 /// hasSCEV - Return true if the SCEV for this value has already been 2478 /// computed. 2479 bool ScalarEvolution::hasSCEV(Value *V) const { 2480 return ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V); 2481 } 2482 2483 2484 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for 2485 /// the specified value. 2486 void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) { 2487 ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H); 2488 } 2489 2490 2491 SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const { 2492 return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L); 2493 } 2494 2495 bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const { 2496 return !isa<SCEVCouldNotCompute>(getIterationCount(L)); 2497 } 2498 2499 SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const { 2500 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L); 2501 } 2502 2503 void ScalarEvolution::deleteInstructionFromRecords(Instruction *I) const { 2504 return ((ScalarEvolutionsImpl*)Impl)->deleteInstructionFromRecords(I); 2505 } 2506 2507 static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE, 2508 const Loop *L) { 2509 // Print all inner loops first 2510 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I) 2511 PrintLoopInfo(OS, SE, *I); 2512 2513 cerr << "Loop " << L->getHeader()->getName() << ": "; 2514 2515 std::vector<BasicBlock*> ExitBlocks; 2516 L->getExitBlocks(ExitBlocks); 2517 if (ExitBlocks.size() != 1) 2518 cerr << "<multiple exits> "; 2519 2520 if (SE->hasLoopInvariantIterationCount(L)) { 2521 cerr << *SE->getIterationCount(L) << " iterations! "; 2522 } else { 2523 cerr << "Unpredictable iteration count. "; 2524 } 2525 2526 cerr << "\n"; 2527 } 2528 2529 void ScalarEvolution::print(std::ostream &OS, const Module* ) const { 2530 Function &F = ((ScalarEvolutionsImpl*)Impl)->F; 2531 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI; 2532 2533 OS << "Classifying expressions for: " << F.getName() << "\n"; 2534 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) 2535 if (I->getType()->isInteger()) { 2536 OS << *I; 2537 OS << " --> "; 2538 SCEVHandle SV = getSCEV(&*I); 2539 SV->print(OS); 2540 OS << "\t\t"; 2541 2542 if ((*I).getType()->isInteger()) { 2543 ConstantRange Bounds = SV->getValueRange(); 2544 if (!Bounds.isFullSet()) 2545 OS << "Bounds: " << Bounds << " "; 2546 } 2547 2548 if (const Loop *L = LI.getLoopFor((*I).getParent())) { 2549 OS << "Exits: "; 2550 SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop()); 2551 if (isa<SCEVCouldNotCompute>(ExitValue)) { 2552 OS << "<<Unknown>>"; 2553 } else { 2554 OS << *ExitValue; 2555 } 2556 } 2557 2558 2559 OS << "\n"; 2560 } 2561 2562 OS << "Determining loop execution counts for: " << F.getName() << "\n"; 2563 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I) 2564 PrintLoopInfo(OS, this, *I); 2565 } 2566 2567