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