LLVM API Documentation
00001 //===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file was developed by the LLVM research group and is distributed under 00006 // the University of Illinois Open Source License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file contains the implementation of the scalar evolution analysis 00011 // engine, which is used primarily to analyze expressions involving induction 00012 // variables in loops. 00013 // 00014 // There are several aspects to this library. First is the representation of 00015 // scalar expressions, which are represented as subclasses of the SCEV class. 00016 // These classes are used to represent certain types of subexpressions that we 00017 // can handle. These classes are reference counted, managed by the SCEVHandle 00018 // class. We only create one SCEV of a particular shape, so pointer-comparisons 00019 // for equality are legal. 00020 // 00021 // One important aspect of the SCEV objects is that they are never cyclic, even 00022 // if there is a cycle in the dataflow for an expression (ie, a PHI node). If 00023 // the PHI node is one of the idioms that we can represent (e.g., a polynomial 00024 // recurrence) then we represent it directly as a recurrence node, otherwise we 00025 // represent it as a SCEVUnknown node. 00026 // 00027 // In addition to being able to represent expressions of various types, we also 00028 // have folders that are used to build the *canonical* representation for a 00029 // particular expression. These folders are capable of using a variety of 00030 // rewrite rules to simplify the expressions. 00031 // 00032 // Once the folders are defined, we can implement the more interesting 00033 // higher-level code, such as the code that recognizes PHI nodes of various 00034 // types, computes the execution count of a loop, etc. 00035 // 00036 // TODO: We should use these routines and value representations to implement 00037 // dependence analysis! 00038 // 00039 //===----------------------------------------------------------------------===// 00040 // 00041 // There are several good references for the techniques used in this analysis. 00042 // 00043 // Chains of recurrences -- a method to expedite the evaluation 00044 // of closed-form functions 00045 // Olaf Bachmann, Paul S. Wang, Eugene V. Zima 00046 // 00047 // On computational properties of chains of recurrences 00048 // Eugene V. Zima 00049 // 00050 // Symbolic Evaluation of Chains of Recurrences for Loop Optimization 00051 // Robert A. van Engelen 00052 // 00053 // Efficient Symbolic Analysis for Optimizing Compilers 00054 // Robert A. van Engelen 00055 // 00056 // Using the chains of recurrences algebra for data dependence testing and 00057 // induction variable substitution 00058 // MS Thesis, Johnie Birch 00059 // 00060 //===----------------------------------------------------------------------===// 00061 00062 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 00063 #include "llvm/Constants.h" 00064 #include "llvm/DerivedTypes.h" 00065 #include "llvm/GlobalVariable.h" 00066 #include "llvm/Instructions.h" 00067 #include "llvm/Analysis/ConstantFolding.h" 00068 #include "llvm/Analysis/LoopInfo.h" 00069 #include "llvm/Assembly/Writer.h" 00070 #include "llvm/Transforms/Scalar.h" 00071 #include "llvm/Support/CFG.h" 00072 #include "llvm/Support/ConstantRange.h" 00073 #include "llvm/Support/InstIterator.h" 00074 #include "llvm/Support/CommandLine.h" 00075 #include "llvm/ADT/Statistic.h" 00076 #include <cmath> 00077 #include <iostream> 00078 #include <algorithm> 00079 using namespace llvm; 00080 00081 namespace { 00082 RegisterAnalysis<ScalarEvolution> 00083 R("scalar-evolution", "Scalar Evolution Analysis"); 00084 00085 Statistic<> 00086 NumBruteForceEvaluations("scalar-evolution", 00087 "Number of brute force evaluations needed to " 00088 "calculate high-order polynomial exit values"); 00089 Statistic<> 00090 NumArrayLenItCounts("scalar-evolution", 00091 "Number of trip counts computed with array length"); 00092 Statistic<> 00093 NumTripCountsComputed("scalar-evolution", 00094 "Number of loops with predictable loop counts"); 00095 Statistic<> 00096 NumTripCountsNotComputed("scalar-evolution", 00097 "Number of loops without predictable loop counts"); 00098 Statistic<> 00099 NumBruteForceTripCountsComputed("scalar-evolution", 00100 "Number of loops with trip counts computed by force"); 00101 00102 cl::opt<unsigned> 00103 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, 00104 cl::desc("Maximum number of iterations SCEV will " 00105 "symbolically execute a constant derived loop"), 00106 cl::init(100)); 00107 } 00108 00109 //===----------------------------------------------------------------------===// 00110 // SCEV class definitions 00111 //===----------------------------------------------------------------------===// 00112 00113 //===----------------------------------------------------------------------===// 00114 // Implementation of the SCEV class. 00115 // 00116 SCEV::~SCEV() {} 00117 void SCEV::dump() const { 00118 print(std::cerr); 00119 } 00120 00121 /// getValueRange - Return the tightest constant bounds that this value is 00122 /// known to have. This method is only valid on integer SCEV objects. 00123 ConstantRange SCEV::getValueRange() const { 00124 const Type *Ty = getType(); 00125 assert(Ty->isInteger() && "Can't get range for a non-integer SCEV!"); 00126 Ty = Ty->getUnsignedVersion(); 00127 // Default to a full range if no better information is available. 00128 return ConstantRange(getType()); 00129 } 00130 00131 00132 SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {} 00133 00134 bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const { 00135 assert(0 && "Attempt to use a SCEVCouldNotCompute object!"); 00136 return false; 00137 } 00138 00139 const Type *SCEVCouldNotCompute::getType() const { 00140 assert(0 && "Attempt to use a SCEVCouldNotCompute object!"); 00141 return 0; 00142 } 00143 00144 bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const { 00145 assert(0 && "Attempt to use a SCEVCouldNotCompute object!"); 00146 return false; 00147 } 00148 00149 SCEVHandle SCEVCouldNotCompute:: 00150 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym, 00151 const SCEVHandle &Conc) const { 00152 return this; 00153 } 00154 00155 void SCEVCouldNotCompute::print(std::ostream &OS) const { 00156 OS << "***COULDNOTCOMPUTE***"; 00157 } 00158 00159 bool SCEVCouldNotCompute::classof(const SCEV *S) { 00160 return S->getSCEVType() == scCouldNotCompute; 00161 } 00162 00163 00164 // SCEVConstants - Only allow the creation of one SCEVConstant for any 00165 // particular value. Don't use a SCEVHandle here, or else the object will 00166 // never be deleted! 00167 static std::map<ConstantInt*, SCEVConstant*> SCEVConstants; 00168 00169 00170 SCEVConstant::~SCEVConstant() { 00171 SCEVConstants.erase(V); 00172 } 00173 00174 SCEVHandle SCEVConstant::get(ConstantInt *V) { 00175 // Make sure that SCEVConstant instances are all unsigned. 00176 if (V->getType()->isSigned()) { 00177 const Type *NewTy = V->getType()->getUnsignedVersion(); 00178 V = cast<ConstantUInt>(ConstantExpr::getCast(V, NewTy)); 00179 } 00180 00181 SCEVConstant *&R = SCEVConstants[V]; 00182 if (R == 0) R = new SCEVConstant(V); 00183 return R; 00184 } 00185 00186 ConstantRange SCEVConstant::getValueRange() const { 00187 return ConstantRange(V); 00188 } 00189 00190 const Type *SCEVConstant::getType() const { return V->getType(); } 00191 00192 void SCEVConstant::print(std::ostream &OS) const { 00193 WriteAsOperand(OS, V, false); 00194 } 00195 00196 // SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any 00197 // particular input. Don't use a SCEVHandle here, or else the object will 00198 // never be deleted! 00199 static std::map<std::pair<SCEV*, const Type*>, SCEVTruncateExpr*> SCEVTruncates; 00200 00201 SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty) 00202 : SCEV(scTruncate), Op(op), Ty(ty) { 00203 assert(Op->getType()->isInteger() && Ty->isInteger() && 00204 Ty->isUnsigned() && 00205 "Cannot truncate non-integer value!"); 00206 assert(Op->getType()->getPrimitiveSize() > Ty->getPrimitiveSize() && 00207 "This is not a truncating conversion!"); 00208 } 00209 00210 SCEVTruncateExpr::~SCEVTruncateExpr() { 00211 SCEVTruncates.erase(std::make_pair(Op, Ty)); 00212 } 00213 00214 ConstantRange SCEVTruncateExpr::getValueRange() const { 00215 return getOperand()->getValueRange().truncate(getType()); 00216 } 00217 00218 void SCEVTruncateExpr::print(std::ostream &OS) const { 00219 OS << "(truncate " << *Op << " to " << *Ty << ")"; 00220 } 00221 00222 // SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any 00223 // particular input. Don't use a SCEVHandle here, or else the object will never 00224 // be deleted! 00225 static std::map<std::pair<SCEV*, const Type*>, 00226 SCEVZeroExtendExpr*> SCEVZeroExtends; 00227 00228 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty) 00229 : SCEV(scTruncate), Op(op), Ty(ty) { 00230 assert(Op->getType()->isInteger() && Ty->isInteger() && 00231 Ty->isUnsigned() && 00232 "Cannot zero extend non-integer value!"); 00233 assert(Op->getType()->getPrimitiveSize() < Ty->getPrimitiveSize() && 00234 "This is not an extending conversion!"); 00235 } 00236 00237 SCEVZeroExtendExpr::~SCEVZeroExtendExpr() { 00238 SCEVZeroExtends.erase(std::make_pair(Op, Ty)); 00239 } 00240 00241 ConstantRange SCEVZeroExtendExpr::getValueRange() const { 00242 return getOperand()->getValueRange().zeroExtend(getType()); 00243 } 00244 00245 void SCEVZeroExtendExpr::print(std::ostream &OS) const { 00246 OS << "(zeroextend " << *Op << " to " << *Ty << ")"; 00247 } 00248 00249 // SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any 00250 // particular input. Don't use a SCEVHandle here, or else the object will never 00251 // be deleted! 00252 static std::map<std::pair<unsigned, std::vector<SCEV*> >, 00253 SCEVCommutativeExpr*> SCEVCommExprs; 00254 00255 SCEVCommutativeExpr::~SCEVCommutativeExpr() { 00256 SCEVCommExprs.erase(std::make_pair(getSCEVType(), 00257 std::vector<SCEV*>(Operands.begin(), 00258 Operands.end()))); 00259 } 00260 00261 void SCEVCommutativeExpr::print(std::ostream &OS) const { 00262 assert(Operands.size() > 1 && "This plus expr shouldn't exist!"); 00263 const char *OpStr = getOperationStr(); 00264 OS << "(" << *Operands[0]; 00265 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 00266 OS << OpStr << *Operands[i]; 00267 OS << ")"; 00268 } 00269 00270 SCEVHandle SCEVCommutativeExpr:: 00271 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym, 00272 const SCEVHandle &Conc) const { 00273 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 00274 SCEVHandle H = getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc); 00275 if (H != getOperand(i)) { 00276 std::vector<SCEVHandle> NewOps; 00277 NewOps.reserve(getNumOperands()); 00278 for (unsigned j = 0; j != i; ++j) 00279 NewOps.push_back(getOperand(j)); 00280 NewOps.push_back(H); 00281 for (++i; i != e; ++i) 00282 NewOps.push_back(getOperand(i)-> 00283 replaceSymbolicValuesWithConcrete(Sym, Conc)); 00284 00285 if (isa<SCEVAddExpr>(this)) 00286 return SCEVAddExpr::get(NewOps); 00287 else if (isa<SCEVMulExpr>(this)) 00288 return SCEVMulExpr::get(NewOps); 00289 else 00290 assert(0 && "Unknown commutative expr!"); 00291 } 00292 } 00293 return this; 00294 } 00295 00296 00297 // SCEVSDivs - Only allow the creation of one SCEVSDivExpr for any particular 00298 // input. Don't use a SCEVHandle here, or else the object will never be 00299 // deleted! 00300 static std::map<std::pair<SCEV*, SCEV*>, SCEVSDivExpr*> SCEVSDivs; 00301 00302 SCEVSDivExpr::~SCEVSDivExpr() { 00303 SCEVSDivs.erase(std::make_pair(LHS, RHS)); 00304 } 00305 00306 void SCEVSDivExpr::print(std::ostream &OS) const { 00307 OS << "(" << *LHS << " /s " << *RHS << ")"; 00308 } 00309 00310 const Type *SCEVSDivExpr::getType() const { 00311 const Type *Ty = LHS->getType(); 00312 if (Ty->isUnsigned()) Ty = Ty->getSignedVersion(); 00313 return Ty; 00314 } 00315 00316 // SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any 00317 // particular input. Don't use a SCEVHandle here, or else the object will never 00318 // be deleted! 00319 static std::map<std::pair<const Loop *, std::vector<SCEV*> >, 00320 SCEVAddRecExpr*> SCEVAddRecExprs; 00321 00322 SCEVAddRecExpr::~SCEVAddRecExpr() { 00323 SCEVAddRecExprs.erase(std::make_pair(L, 00324 std::vector<SCEV*>(Operands.begin(), 00325 Operands.end()))); 00326 } 00327 00328 SCEVHandle SCEVAddRecExpr:: 00329 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym, 00330 const SCEVHandle &Conc) const { 00331 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 00332 SCEVHandle H = getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc); 00333 if (H != getOperand(i)) { 00334 std::vector<SCEVHandle> NewOps; 00335 NewOps.reserve(getNumOperands()); 00336 for (unsigned j = 0; j != i; ++j) 00337 NewOps.push_back(getOperand(j)); 00338 NewOps.push_back(H); 00339 for (++i; i != e; ++i) 00340 NewOps.push_back(getOperand(i)-> 00341 replaceSymbolicValuesWithConcrete(Sym, Conc)); 00342 00343 return get(NewOps, L); 00344 } 00345 } 00346 return this; 00347 } 00348 00349 00350 bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const { 00351 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't 00352 // contain L and if the start is invariant. 00353 return !QueryLoop->contains(L->getHeader()) && 00354 getOperand(0)->isLoopInvariant(QueryLoop); 00355 } 00356 00357 00358 void SCEVAddRecExpr::print(std::ostream &OS) const { 00359 OS << "{" << *Operands[0]; 00360 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 00361 OS << ",+," << *Operands[i]; 00362 OS << "}<" << L->getHeader()->getName() + ">"; 00363 } 00364 00365 // SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular 00366 // value. Don't use a SCEVHandle here, or else the object will never be 00367 // deleted! 00368 static std::map<Value*, SCEVUnknown*> SCEVUnknowns; 00369 00370 SCEVUnknown::~SCEVUnknown() { SCEVUnknowns.erase(V); } 00371 00372 bool SCEVUnknown::isLoopInvariant(const Loop *L) const { 00373 // All non-instruction values are loop invariant. All instructions are loop 00374 // invariant if they are not contained in the specified loop. 00375 if (Instruction *I = dyn_cast<Instruction>(V)) 00376 return !L->contains(I->getParent()); 00377 return true; 00378 } 00379 00380 const Type *SCEVUnknown::getType() const { 00381 return V->getType(); 00382 } 00383 00384 void SCEVUnknown::print(std::ostream &OS) const { 00385 WriteAsOperand(OS, V, false); 00386 } 00387 00388 //===----------------------------------------------------------------------===// 00389 // SCEV Utilities 00390 //===----------------------------------------------------------------------===// 00391 00392 namespace { 00393 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less 00394 /// than the complexity of the RHS. This comparator is used to canonicalize 00395 /// expressions. 00396 struct SCEVComplexityCompare { 00397 bool operator()(SCEV *LHS, SCEV *RHS) { 00398 return LHS->getSCEVType() < RHS->getSCEVType(); 00399 } 00400 }; 00401 } 00402 00403 /// GroupByComplexity - Given a list of SCEV objects, order them by their 00404 /// complexity, and group objects of the same complexity together by value. 00405 /// When this routine is finished, we know that any duplicates in the vector are 00406 /// consecutive and that complexity is monotonically increasing. 00407 /// 00408 /// Note that we go take special precautions to ensure that we get determinstic 00409 /// results from this routine. In other words, we don't want the results of 00410 /// this to depend on where the addresses of various SCEV objects happened to 00411 /// land in memory. 00412 /// 00413 static void GroupByComplexity(std::vector<SCEVHandle> &Ops) { 00414 if (Ops.size() < 2) return; // Noop 00415 if (Ops.size() == 2) { 00416 // This is the common case, which also happens to be trivially simple. 00417 // Special case it. 00418 if (Ops[0]->getSCEVType() > Ops[1]->getSCEVType()) 00419 std::swap(Ops[0], Ops[1]); 00420 return; 00421 } 00422 00423 // Do the rough sort by complexity. 00424 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare()); 00425 00426 // Now that we are sorted by complexity, group elements of the same 00427 // complexity. Note that this is, at worst, N^2, but the vector is likely to 00428 // be extremely short in practice. Note that we take this approach because we 00429 // do not want to depend on the addresses of the objects we are grouping. 00430 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { 00431 SCEV *S = Ops[i]; 00432 unsigned Complexity = S->getSCEVType(); 00433 00434 // If there are any objects of the same complexity and same value as this 00435 // one, group them. 00436 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { 00437 if (Ops[j] == S) { // Found a duplicate. 00438 // Move it to immediately after i'th element. 00439 std::swap(Ops[i+1], Ops[j]); 00440 ++i; // no need to rescan it. 00441 if (i == e-2) return; // Done! 00442 } 00443 } 00444 } 00445 } 00446 00447 00448 00449 //===----------------------------------------------------------------------===// 00450 // Simple SCEV method implementations 00451 //===----------------------------------------------------------------------===// 00452 00453 /// getIntegerSCEV - Given an integer or FP type, create a constant for the 00454 /// specified signed integer value and return a SCEV for the constant. 00455 SCEVHandle SCEVUnknown::getIntegerSCEV(int Val, const Type *Ty) { 00456 Constant *C; 00457 if (Val == 0) 00458 C = Constant::getNullValue(Ty); 00459 else if (Ty->isFloatingPoint()) 00460 C = ConstantFP::get(Ty, Val); 00461 else if (Ty->isSigned()) 00462 C = ConstantSInt::get(Ty, Val); 00463 else { 00464 C = ConstantSInt::get(Ty->getSignedVersion(), Val); 00465 C = ConstantExpr::getCast(C, Ty); 00466 } 00467 return SCEVUnknown::get(C); 00468 } 00469 00470 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the 00471 /// input value to the specified type. If the type must be extended, it is zero 00472 /// extended. 00473 static SCEVHandle getTruncateOrZeroExtend(const SCEVHandle &V, const Type *Ty) { 00474 const Type *SrcTy = V->getType(); 00475 assert(SrcTy->isInteger() && Ty->isInteger() && 00476 "Cannot truncate or zero extend with non-integer arguments!"); 00477 if (SrcTy->getPrimitiveSize() == Ty->getPrimitiveSize()) 00478 return V; // No conversion 00479 if (SrcTy->getPrimitiveSize() > Ty->getPrimitiveSize()) 00480 return SCEVTruncateExpr::get(V, Ty); 00481 return SCEVZeroExtendExpr::get(V, Ty); 00482 } 00483 00484 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V 00485 /// 00486 SCEVHandle SCEV::getNegativeSCEV(const SCEVHandle &V) { 00487 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 00488 return SCEVUnknown::get(ConstantExpr::getNeg(VC->getValue())); 00489 00490 return SCEVMulExpr::get(V, SCEVUnknown::getIntegerSCEV(-1, V->getType())); 00491 } 00492 00493 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS. 00494 /// 00495 SCEVHandle SCEV::getMinusSCEV(const SCEVHandle &LHS, const SCEVHandle &RHS) { 00496 // X - Y --> X + -Y 00497 return SCEVAddExpr::get(LHS, SCEV::getNegativeSCEV(RHS)); 00498 } 00499 00500 00501 /// PartialFact - Compute V!/(V-NumSteps)! 00502 static SCEVHandle PartialFact(SCEVHandle V, unsigned NumSteps) { 00503 // Handle this case efficiently, it is common to have constant iteration 00504 // counts while computing loop exit values. 00505 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) { 00506 uint64_t Val = SC->getValue()->getRawValue(); 00507 uint64_t Result = 1; 00508 for (; NumSteps; --NumSteps) 00509 Result *= Val-(NumSteps-1); 00510 Constant *Res = ConstantUInt::get(Type::ULongTy, Result); 00511 return SCEVUnknown::get(ConstantExpr::getCast(Res, V->getType())); 00512 } 00513 00514 const Type *Ty = V->getType(); 00515 if (NumSteps == 0) 00516 return SCEVUnknown::getIntegerSCEV(1, Ty); 00517 00518 SCEVHandle Result = V; 00519 for (unsigned i = 1; i != NumSteps; ++i) 00520 Result = SCEVMulExpr::get(Result, SCEV::getMinusSCEV(V, 00521 SCEVUnknown::getIntegerSCEV(i, Ty))); 00522 return Result; 00523 } 00524 00525 00526 /// evaluateAtIteration - Return the value of this chain of recurrences at 00527 /// the specified iteration number. We can evaluate this recurrence by 00528 /// multiplying each element in the chain by the binomial coefficient 00529 /// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as: 00530 /// 00531 /// A*choose(It, 0) + B*choose(It, 1) + C*choose(It, 2) + D*choose(It, 3) 00532 /// 00533 /// FIXME/VERIFY: I don't trust that this is correct in the face of overflow. 00534 /// Is the binomial equation safe using modular arithmetic?? 00535 /// 00536 SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It) const { 00537 SCEVHandle Result = getStart(); 00538 int Divisor = 1; 00539 const Type *Ty = It->getType(); 00540 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 00541 SCEVHandle BC = PartialFact(It, i); 00542 Divisor *= i; 00543 SCEVHandle Val = SCEVSDivExpr::get(SCEVMulExpr::get(BC, getOperand(i)), 00544 SCEVUnknown::getIntegerSCEV(Divisor,Ty)); 00545 Result = SCEVAddExpr::get(Result, Val); 00546 } 00547 return Result; 00548 } 00549 00550 00551 //===----------------------------------------------------------------------===// 00552 // SCEV Expression folder implementations 00553 //===----------------------------------------------------------------------===// 00554 00555 SCEVHandle SCEVTruncateExpr::get(const SCEVHandle &Op, const Type *Ty) { 00556 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 00557 return SCEVUnknown::get(ConstantExpr::getCast(SC->getValue(), Ty)); 00558 00559 // If the input value is a chrec scev made out of constants, truncate 00560 // all of the constants. 00561 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 00562 std::vector<SCEVHandle> Operands; 00563 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 00564 // FIXME: This should allow truncation of other expression types! 00565 if (isa<SCEVConstant>(AddRec->getOperand(i))) 00566 Operands.push_back(get(AddRec->getOperand(i), Ty)); 00567 else 00568 break; 00569 if (Operands.size() == AddRec->getNumOperands()) 00570 return SCEVAddRecExpr::get(Operands, AddRec->getLoop()); 00571 } 00572 00573 SCEVTruncateExpr *&Result = SCEVTruncates[std::make_pair(Op, Ty)]; 00574 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty); 00575 return Result; 00576 } 00577 00578 SCEVHandle SCEVZeroExtendExpr::get(const SCEVHandle &Op, const Type *Ty) { 00579 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 00580 return SCEVUnknown::get(ConstantExpr::getCast(SC->getValue(), Ty)); 00581 00582 // FIXME: If the input value is a chrec scev, and we can prove that the value 00583 // did not overflow the old, smaller, value, we can zero extend all of the 00584 // operands (often constants). This would allow analysis of something like 00585 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } 00586 00587 SCEVZeroExtendExpr *&Result = SCEVZeroExtends[std::make_pair(Op, Ty)]; 00588 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty); 00589 return Result; 00590 } 00591 00592 // get - Get a canonical add expression, or something simpler if possible. 00593 SCEVHandle SCEVAddExpr::get(std::vector<SCEVHandle> &Ops) { 00594 assert(!Ops.empty() && "Cannot get empty add!"); 00595 if (Ops.size() == 1) return Ops[0]; 00596 00597 // Sort by complexity, this groups all similar expression types together. 00598 GroupByComplexity(Ops); 00599 00600 // If there are any constants, fold them together. 00601 unsigned Idx = 0; 00602 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 00603 ++Idx; 00604 assert(Idx < Ops.size()); 00605 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 00606 // We found two constants, fold them together! 00607 Constant *Fold = ConstantExpr::getAdd(LHSC->getValue(), RHSC->getValue()); 00608 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) { 00609 Ops[0] = SCEVConstant::get(CI); 00610 Ops.erase(Ops.begin()+1); // Erase the folded element 00611 if (Ops.size() == 1) return Ops[0]; 00612 LHSC = cast<SCEVConstant>(Ops[0]); 00613 } else { 00614 // If we couldn't fold the expression, move to the next constant. Note 00615 // that this is impossible to happen in practice because we always 00616 // constant fold constant ints to constant ints. 00617 ++Idx; 00618 } 00619 } 00620 00621 // If we are left with a constant zero being added, strip it off. 00622 if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) { 00623 Ops.erase(Ops.begin()); 00624 --Idx; 00625 } 00626 } 00627 00628 if (Ops.size() == 1) return Ops[0]; 00629 00630 // Okay, check to see if the same value occurs in the operand list twice. If 00631 // so, merge them together into an multiply expression. Since we sorted the 00632 // list, these values are required to be adjacent. 00633 const Type *Ty = Ops[0]->getType(); 00634 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 00635 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 00636 // Found a match, merge the two values into a multiply, and add any 00637 // remaining values to the result. 00638 SCEVHandle Two = SCEVUnknown::getIntegerSCEV(2, Ty); 00639 SCEVHandle Mul = SCEVMulExpr::get(Ops[i], Two); 00640 if (Ops.size() == 2) 00641 return Mul; 00642 Ops.erase(Ops.begin()+i, Ops.begin()+i+2); 00643 Ops.push_back(Mul); 00644 return SCEVAddExpr::get(Ops); 00645 } 00646 00647 // Okay, now we know the first non-constant operand. If there are add 00648 // operands they would be next. 00649 if (Idx < Ops.size()) { 00650 bool DeletedAdd = false; 00651 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 00652 // If we have an add, expand the add operands onto the end of the operands 00653 // list. 00654 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end()); 00655 Ops.erase(Ops.begin()+Idx); 00656 DeletedAdd = true; 00657 } 00658 00659 // If we deleted at least one add, we added operands to the end of the list, 00660 // and they are not necessarily sorted. Recurse to resort and resimplify 00661 // any operands we just aquired. 00662 if (DeletedAdd) 00663 return get(Ops); 00664 } 00665 00666 // Skip over the add expression until we get to a multiply. 00667 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 00668 ++Idx; 00669 00670 // If we are adding something to a multiply expression, make sure the 00671 // something is not already an operand of the multiply. If so, merge it into 00672 // the multiply. 00673 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 00674 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 00675 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 00676 SCEV *MulOpSCEV = Mul->getOperand(MulOp); 00677 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 00678 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) { 00679 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 00680 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0); 00681 if (Mul->getNumOperands() != 2) { 00682 // If the multiply has more than two operands, we must get the 00683 // Y*Z term. 00684 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end()); 00685 MulOps.erase(MulOps.begin()+MulOp); 00686 InnerMul = SCEVMulExpr::get(MulOps); 00687 } 00688 SCEVHandle One = SCEVUnknown::getIntegerSCEV(1, Ty); 00689 SCEVHandle AddOne = SCEVAddExpr::get(InnerMul, One); 00690 SCEVHandle OuterMul = SCEVMulExpr::get(AddOne, Ops[AddOp]); 00691 if (Ops.size() == 2) return OuterMul; 00692 if (AddOp < Idx) { 00693 Ops.erase(Ops.begin()+AddOp); 00694 Ops.erase(Ops.begin()+Idx-1); 00695 } else { 00696 Ops.erase(Ops.begin()+Idx); 00697 Ops.erase(Ops.begin()+AddOp-1); 00698 } 00699 Ops.push_back(OuterMul); 00700 return SCEVAddExpr::get(Ops); 00701 } 00702 00703 // Check this multiply against other multiplies being added together. 00704 for (unsigned OtherMulIdx = Idx+1; 00705 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 00706 ++OtherMulIdx) { 00707 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 00708 // If MulOp occurs in OtherMul, we can fold the two multiplies 00709 // together. 00710 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 00711 OMulOp != e; ++OMulOp) 00712 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 00713 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 00714 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0); 00715 if (Mul->getNumOperands() != 2) { 00716 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end()); 00717 MulOps.erase(MulOps.begin()+MulOp); 00718 InnerMul1 = SCEVMulExpr::get(MulOps); 00719 } 00720 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0); 00721 if (OtherMul->getNumOperands() != 2) { 00722 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(), 00723 OtherMul->op_end()); 00724 MulOps.erase(MulOps.begin()+OMulOp); 00725 InnerMul2 = SCEVMulExpr::get(MulOps); 00726 } 00727 SCEVHandle InnerMulSum = SCEVAddExpr::get(InnerMul1,InnerMul2); 00728 SCEVHandle OuterMul = SCEVMulExpr::get(MulOpSCEV, InnerMulSum); 00729 if (Ops.size() == 2) return OuterMul; 00730 Ops.erase(Ops.begin()+Idx); 00731 Ops.erase(Ops.begin()+OtherMulIdx-1); 00732 Ops.push_back(OuterMul); 00733 return SCEVAddExpr::get(Ops); 00734 } 00735 } 00736 } 00737 } 00738 00739 // If there are any add recurrences in the operands list, see if any other 00740 // added values are loop invariant. If so, we can fold them into the 00741 // recurrence. 00742 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 00743 ++Idx; 00744 00745 // Scan over all recurrences, trying to fold loop invariants into them. 00746 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 00747 // Scan all of the other operands to this add and add them to the vector if 00748 // they are loop invariant w.r.t. the recurrence. 00749 std::vector<SCEVHandle> LIOps; 00750 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 00751 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 00752 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) { 00753 LIOps.push_back(Ops[i]); 00754 Ops.erase(Ops.begin()+i); 00755 --i; --e; 00756 } 00757 00758 // If we found some loop invariants, fold them into the recurrence. 00759 if (!LIOps.empty()) { 00760 // NLI + LI + { Start,+,Step} --> NLI + { LI+Start,+,Step } 00761 LIOps.push_back(AddRec->getStart()); 00762 00763 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end()); 00764 AddRecOps[0] = SCEVAddExpr::get(LIOps); 00765 00766 SCEVHandle NewRec = SCEVAddRecExpr::get(AddRecOps, AddRec->getLoop()); 00767 // If all of the other operands were loop invariant, we are done. 00768 if (Ops.size() == 1) return NewRec; 00769 00770 // Otherwise, add the folded AddRec by the non-liv parts. 00771 for (unsigned i = 0;; ++i) 00772 if (Ops[i] == AddRec) { 00773 Ops[i] = NewRec; 00774 break; 00775 } 00776 return SCEVAddExpr::get(Ops); 00777 } 00778 00779 // Okay, if there weren't any loop invariants to be folded, check to see if 00780 // there are multiple AddRec's with the same loop induction variable being 00781 // added together. If so, we can fold them. 00782 for (unsigned OtherIdx = Idx+1; 00783 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx) 00784 if (OtherIdx != Idx) { 00785 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 00786 if (AddRec->getLoop() == OtherAddRec->getLoop()) { 00787 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D} 00788 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end()); 00789 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) { 00790 if (i >= NewOps.size()) { 00791 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i, 00792 OtherAddRec->op_end()); 00793 break; 00794 } 00795 NewOps[i] = SCEVAddExpr::get(NewOps[i], OtherAddRec->getOperand(i)); 00796 } 00797 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop()); 00798 00799 if (Ops.size() == 2) return NewAddRec; 00800 00801 Ops.erase(Ops.begin()+Idx); 00802 Ops.erase(Ops.begin()+OtherIdx-1); 00803 Ops.push_back(NewAddRec); 00804 return SCEVAddExpr::get(Ops); 00805 } 00806 } 00807 00808 // Otherwise couldn't fold anything into this recurrence. Move onto the 00809 // next one. 00810 } 00811 00812 // Okay, it looks like we really DO need an add expr. Check to see if we 00813 // already have one, otherwise create a new one. 00814 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end()); 00815 SCEVCommutativeExpr *&Result = SCEVCommExprs[std::make_pair(scAddExpr, 00816 SCEVOps)]; 00817 if (Result == 0) Result = new SCEVAddExpr(Ops); 00818 return Result; 00819 } 00820 00821 00822 SCEVHandle SCEVMulExpr::get(std::vector<SCEVHandle> &Ops) { 00823 assert(!Ops.empty() && "Cannot get empty mul!"); 00824 00825 // Sort by complexity, this groups all similar expression types together. 00826 GroupByComplexity(Ops); 00827 00828 // If there are any constants, fold them together. 00829 unsigned Idx = 0; 00830 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 00831 00832 // C1*(C2+V) -> C1*C2 + C1*V 00833 if (Ops.size() == 2) 00834 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 00835 if (Add->getNumOperands() == 2 && 00836 isa<SCEVConstant>(Add->getOperand(0))) 00837 return SCEVAddExpr::get(SCEVMulExpr::get(LHSC, Add->getOperand(0)), 00838 SCEVMulExpr::get(LHSC, Add->getOperand(1))); 00839 00840 00841 ++Idx; 00842 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 00843 // We found two constants, fold them together! 00844 Constant *Fold = ConstantExpr::getMul(LHSC->getValue(), RHSC->getValue()); 00845 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) { 00846 Ops[0] = SCEVConstant::get(CI); 00847 Ops.erase(Ops.begin()+1); // Erase the folded element 00848 if (Ops.size() == 1) return Ops[0]; 00849 LHSC = cast<SCEVConstant>(Ops[0]); 00850 } else { 00851 // If we couldn't fold the expression, move to the next constant. Note 00852 // that this is impossible to happen in practice because we always 00853 // constant fold constant ints to constant ints. 00854 ++Idx; 00855 } 00856 } 00857 00858 // If we are left with a constant one being multiplied, strip it off. 00859 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) { 00860 Ops.erase(Ops.begin()); 00861 --Idx; 00862 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) { 00863 // If we have a multiply of zero, it will always be zero. 00864 return Ops[0]; 00865 } 00866 } 00867 00868 // Skip over the add expression until we get to a multiply. 00869 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 00870 ++Idx; 00871 00872 if (Ops.size() == 1) 00873 return Ops[0]; 00874 00875 // If there are mul operands inline them all into this expression. 00876 if (Idx < Ops.size()) { 00877 bool DeletedMul = false; 00878 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 00879 // If we have an mul, expand the mul operands onto the end of the operands 00880 // list. 00881 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end()); 00882 Ops.erase(Ops.begin()+Idx); 00883 DeletedMul = true; 00884 } 00885 00886 // If we deleted at least one mul, we added operands to the end of the list, 00887 // and they are not necessarily sorted. Recurse to resort and resimplify 00888 // any operands we just aquired. 00889 if (DeletedMul) 00890 return get(Ops); 00891 } 00892 00893 // If there are any add recurrences in the operands list, see if any other 00894 // added values are loop invariant. If so, we can fold them into the 00895 // recurrence. 00896 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 00897 ++Idx; 00898 00899 // Scan over all recurrences, trying to fold loop invariants into them. 00900 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 00901 // Scan all of the other operands to this mul and add them to the vector if 00902 // they are loop invariant w.r.t. the recurrence. 00903 std::vector<SCEVHandle> LIOps; 00904 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 00905 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 00906 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) { 00907 LIOps.push_back(Ops[i]); 00908 Ops.erase(Ops.begin()+i); 00909 --i; --e; 00910 } 00911 00912 // If we found some loop invariants, fold them into the recurrence. 00913 if (!LIOps.empty()) { 00914 // NLI * LI * { Start,+,Step} --> NLI * { LI*Start,+,LI*Step } 00915 std::vector<SCEVHandle> NewOps; 00916 NewOps.reserve(AddRec->getNumOperands()); 00917 if (LIOps.size() == 1) { 00918 SCEV *Scale = LIOps[0]; 00919 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 00920 NewOps.push_back(SCEVMulExpr::get(Scale, AddRec->getOperand(i))); 00921 } else { 00922 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 00923 std::vector<SCEVHandle> MulOps(LIOps); 00924 MulOps.push_back(AddRec->getOperand(i)); 00925 NewOps.push_back(SCEVMulExpr::get(MulOps)); 00926 } 00927 } 00928 00929 SCEVHandle NewRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop()); 00930 00931 // If all of the other operands were loop invariant, we are done. 00932 if (Ops.size() == 1) return NewRec; 00933 00934 // Otherwise, multiply the folded AddRec by the non-liv parts. 00935 for (unsigned i = 0;; ++i) 00936 if (Ops[i] == AddRec) { 00937 Ops[i] = NewRec; 00938 break; 00939 } 00940 return SCEVMulExpr::get(Ops); 00941 } 00942 00943 // Okay, if there weren't any loop invariants to be folded, check to see if 00944 // there are multiple AddRec's with the same loop induction variable being 00945 // multiplied together. If so, we can fold them. 00946 for (unsigned OtherIdx = Idx+1; 00947 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx) 00948 if (OtherIdx != Idx) { 00949 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 00950 if (AddRec->getLoop() == OtherAddRec->getLoop()) { 00951 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D} 00952 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec; 00953 SCEVHandle NewStart = SCEVMulExpr::get(F->getStart(), 00954 G->getStart()); 00955 SCEVHandle B = F->getStepRecurrence(); 00956 SCEVHandle D = G->getStepRecurrence(); 00957 SCEVHandle NewStep = SCEVAddExpr::get(SCEVMulExpr::get(F, D), 00958 SCEVMulExpr::get(G, B), 00959 SCEVMulExpr::get(B, D)); 00960 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewStart, NewStep, 00961 F->getLoop()); 00962 if (Ops.size() == 2) return NewAddRec; 00963 00964 Ops.erase(Ops.begin()+Idx); 00965 Ops.erase(Ops.begin()+OtherIdx-1); 00966 Ops.push_back(NewAddRec); 00967 return SCEVMulExpr::get(Ops); 00968 } 00969 } 00970 00971 // Otherwise couldn't fold anything into this recurrence. Move onto the 00972 // next one. 00973 } 00974 00975 // Okay, it looks like we really DO need an mul expr. Check to see if we 00976 // already have one, otherwise create a new one. 00977 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end()); 00978 SCEVCommutativeExpr *&Result = SCEVCommExprs[std::make_pair(scMulExpr, 00979 SCEVOps)]; 00980 if (Result == 0) 00981 Result = new SCEVMulExpr(Ops); 00982 return Result; 00983 } 00984 00985 SCEVHandle SCEVSDivExpr::get(const SCEVHandle &LHS, const SCEVHandle &RHS) { 00986 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 00987 if (RHSC->getValue()->equalsInt(1)) 00988 return LHS; // X /s 1 --> x 00989 if (RHSC->getValue()->isAllOnesValue()) 00990 return SCEV::getNegativeSCEV(LHS); // X /s -1 --> -x 00991 00992 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 00993 Constant *LHSCV = LHSC->getValue(); 00994 Constant *RHSCV = RHSC->getValue(); 00995 if (LHSCV->getType()->isUnsigned()) 00996 LHSCV = ConstantExpr::getCast(LHSCV, 00997 LHSCV->getType()->getSignedVersion()); 00998 if (RHSCV->getType()->isUnsigned()) 00999 RHSCV = ConstantExpr::getCast(RHSCV, LHSCV->getType()); 01000 return SCEVUnknown::get(ConstantExpr::getDiv(LHSCV, RHSCV)); 01001 } 01002 } 01003 01004 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow. 01005 01006 SCEVSDivExpr *&Result = SCEVSDivs[std::make_pair(LHS, RHS)]; 01007 if (Result == 0) Result = new SCEVSDivExpr(LHS, RHS); 01008 return Result; 01009 } 01010 01011 01012 /// SCEVAddRecExpr::get - Get a add recurrence expression for the 01013 /// specified loop. Simplify the expression as much as possible. 01014 SCEVHandle SCEVAddRecExpr::get(const SCEVHandle &Start, 01015 const SCEVHandle &Step, const Loop *L) { 01016 std::vector<SCEVHandle> Operands; 01017 Operands.push_back(Start); 01018 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 01019 if (StepChrec->getLoop() == L) { 01020 Operands.insert(Operands.end(), StepChrec->op_begin(), 01021 StepChrec->op_end()); 01022 return get(Operands, L); 01023 } 01024 01025 Operands.push_back(Step); 01026 return get(Operands, L); 01027 } 01028 01029 /// SCEVAddRecExpr::get - Get a add recurrence expression for the 01030 /// specified loop. Simplify the expression as much as possible. 01031 SCEVHandle SCEVAddRecExpr::get(std::vector<SCEVHandle> &Operands, 01032 const Loop *L) { 01033 if (Operands.size() == 1) return Operands[0]; 01034 01035 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Operands.back())) 01036 if (StepC->getValue()->isNullValue()) { 01037 Operands.pop_back(); 01038 return get(Operands, L); // { X,+,0 } --> X 01039 } 01040 01041 SCEVAddRecExpr *&Result = 01042 SCEVAddRecExprs[std::make_pair(L, std::vector<SCEV*>(Operands.begin(), 01043 Operands.end()))]; 01044 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L); 01045 return Result; 01046 } 01047 01048 SCEVHandle SCEVUnknown::get(Value *V) { 01049 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 01050 return SCEVConstant::get(CI); 01051 SCEVUnknown *&Result = SCEVUnknowns[V]; 01052 if (Result == 0) Result = new SCEVUnknown(V); 01053 return Result; 01054 } 01055 01056 01057 //===----------------------------------------------------------------------===// 01058 // ScalarEvolutionsImpl Definition and Implementation 01059 //===----------------------------------------------------------------------===// 01060 // 01061 /// ScalarEvolutionsImpl - This class implements the main driver for the scalar 01062 /// evolution code. 01063 /// 01064 namespace { 01065 struct ScalarEvolutionsImpl { 01066 /// F - The function we are analyzing. 01067 /// 01068 Function &F; 01069 01070 /// LI - The loop information for the function we are currently analyzing. 01071 /// 01072 LoopInfo &LI; 01073 01074 /// UnknownValue - This SCEV is used to represent unknown trip counts and 01075 /// things. 01076 SCEVHandle UnknownValue; 01077 01078 /// Scalars - This is a cache of the scalars we have analyzed so far. 01079 /// 01080 std::map<Value*, SCEVHandle> Scalars; 01081 01082 /// IterationCounts - Cache the iteration count of the loops for this 01083 /// function as they are computed. 01084 std::map<const Loop*, SCEVHandle> IterationCounts; 01085 01086 /// ConstantEvolutionLoopExitValue - This map contains entries for all of 01087 /// the PHI instructions that we attempt to compute constant evolutions for. 01088 /// This allows us to avoid potentially expensive recomputation of these 01089 /// properties. An instruction maps to null if we are unable to compute its 01090 /// exit value. 01091 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue; 01092 01093 public: 01094 ScalarEvolutionsImpl(Function &f, LoopInfo &li) 01095 : F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {} 01096 01097 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the 01098 /// expression and create a new one. 01099 SCEVHandle getSCEV(Value *V); 01100 01101 /// hasSCEV - Return true if the SCEV for this value has already been 01102 /// computed. 01103 bool hasSCEV(Value *V) const { 01104 return Scalars.count(V); 01105 } 01106 01107 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for 01108 /// the specified value. 01109 void setSCEV(Value *V, const SCEVHandle &H) { 01110 bool isNew = Scalars.insert(std::make_pair(V, H)).second; 01111 assert(isNew && "This entry already existed!"); 01112 } 01113 01114 01115 /// getSCEVAtScope - Compute the value of the specified expression within 01116 /// the indicated loop (which may be null to indicate in no loop). If the 01117 /// expression cannot be evaluated, return UnknownValue itself. 01118 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L); 01119 01120 01121 /// hasLoopInvariantIterationCount - Return true if the specified loop has 01122 /// an analyzable loop-invariant iteration count. 01123 bool hasLoopInvariantIterationCount(const Loop *L); 01124 01125 /// getIterationCount - If the specified loop has a predictable iteration 01126 /// count, return it. Note that it is not valid to call this method on a 01127 /// loop without a loop-invariant iteration count. 01128 SCEVHandle getIterationCount(const Loop *L); 01129 01130 /// deleteInstructionFromRecords - This method should be called by the 01131 /// client before it removes an instruction from the program, to make sure 01132 /// that no dangling references are left around. 01133 void deleteInstructionFromRecords(Instruction *I); 01134 01135 private: 01136 /// createSCEV - We know that there is no SCEV for the specified value. 01137 /// Analyze the expression. 01138 SCEVHandle createSCEV(Value *V); 01139 SCEVHandle createNodeForCast(CastInst *CI); 01140 01141 /// createNodeForPHI - Provide the special handling we need to analyze PHI 01142 /// SCEVs. 01143 SCEVHandle createNodeForPHI(PHINode *PN); 01144 01145 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value 01146 /// for the specified instruction and replaces any references to the 01147 /// symbolic value SymName with the specified value. This is used during 01148 /// PHI resolution. 01149 void ReplaceSymbolicValueWithConcrete(Instruction *I, 01150 const SCEVHandle &SymName, 01151 const SCEVHandle &NewVal); 01152 01153 /// ComputeIterationCount - Compute the number of times the specified loop 01154 /// will iterate. 01155 SCEVHandle ComputeIterationCount(const Loop *L); 01156 01157 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of 01158 /// 'setcc load X, cst', try to se if we can compute the trip count. 01159 SCEVHandle ComputeLoadConstantCompareIterationCount(LoadInst *LI, 01160 Constant *RHS, 01161 const Loop *L, 01162 unsigned SetCCOpcode); 01163 01164 /// ComputeIterationCountExhaustively - If the trip is known to execute a 01165 /// constant number of times (the condition evolves only from constants), 01166 /// try to evaluate a few iterations of the loop until we get the exit 01167 /// condition gets a value of ExitWhen (true or false). If we cannot 01168 /// evaluate the trip count of the loop, return UnknownValue. 01169 SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond, 01170 bool ExitWhen); 01171 01172 /// HowFarToZero - Return the number of times a backedge comparing the 01173 /// specified value to zero will execute. If not computable, return 01174 /// UnknownValue. 01175 SCEVHandle HowFarToZero(SCEV *V, const Loop *L); 01176 01177 /// HowFarToNonZero - Return the number of times a backedge checking the 01178 /// specified value for nonzero will execute. If not computable, return 01179 /// UnknownValue. 01180 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L); 01181 01182 /// HowManyLessThans - Return the number of times a backedge containing the 01183 /// specified less-than comparison will execute. If not computable, return 01184 /// UnknownValue. 01185 SCEVHandle HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L); 01186 01187 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 01188 /// in the header of its containing loop, we know the loop executes a 01189 /// constant number of times, and the PHI node is just a recurrence 01190 /// involving constants, fold it. 01191 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, uint64_t Its, 01192 const Loop *L); 01193 }; 01194 } 01195 01196 //===----------------------------------------------------------------------===// 01197 // Basic SCEV Analysis and PHI Idiom Recognition Code 01198 // 01199 01200 /// deleteInstructionFromRecords - This method should be called by the 01201 /// client before it removes an instruction from the program, to make sure 01202 /// that no dangling references are left around. 01203 void ScalarEvolutionsImpl::deleteInstructionFromRecords(Instruction *I) { 01204 Scalars.erase(I); 01205 if (PHINode *PN = dyn_cast<PHINode>(I)) 01206 ConstantEvolutionLoopExitValue.erase(PN); 01207 } 01208 01209 01210 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the 01211 /// expression and create a new one. 01212 SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) { 01213 assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!"); 01214 01215 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V); 01216 if (I != Scalars.end()) return I->second; 01217 SCEVHandle S = createSCEV(V); 01218 Scalars.insert(std::make_pair(V, S)); 01219 return S; 01220 } 01221 01222 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for 01223 /// the specified instruction and replaces any references to the symbolic value 01224 /// SymName with the specified value. This is used during PHI resolution. 01225 void ScalarEvolutionsImpl:: 01226 ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName, 01227 const SCEVHandle &NewVal) { 01228 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I); 01229 if (SI == Scalars.end()) return; 01230 01231 SCEVHandle NV = 01232 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal); 01233 if (NV == SI->second) return; // No change. 01234 01235 SI->second = NV; // Update the scalars map! 01236 01237 // Any instruction values that use this instruction might also need to be 01238 // updated! 01239 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); 01240 UI != E; ++UI) 01241 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal); 01242 } 01243 01244 /// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in 01245 /// a loop header, making it a potential recurrence, or it doesn't. 01246 /// 01247 SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) { 01248 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized. 01249 if (const Loop *L = LI.getLoopFor(PN->getParent())) 01250 if (L->getHeader() == PN->getParent()) { 01251 // If it lives in the loop header, it has two incoming values, one 01252 // from outside the loop, and one from inside. 01253 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0)); 01254 unsigned BackEdge = IncomingEdge^1; 01255 01256 // While we are analyzing this PHI node, handle its value symbolically. 01257 SCEVHandle SymbolicName = SCEVUnknown::get(PN); 01258 assert(Scalars.find(PN) == Scalars.end() && 01259 "PHI node already processed?"); 01260 Scalars.insert(std::make_pair(PN, SymbolicName)); 01261 01262 // Using this symbolic name for the PHI, analyze the value coming around 01263 // the back-edge. 01264 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge)); 01265 01266 // NOTE: If BEValue is loop invariant, we know that the PHI node just 01267 // has a special value for the first iteration of the loop. 01268 01269 // If the value coming around the backedge is an add with the symbolic 01270 // value we just inserted, then we found a simple induction variable! 01271 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 01272 // If there is a single occurrence of the symbolic value, replace it 01273 // with a recurrence. 01274 unsigned FoundIndex = Add->getNumOperands(); 01275 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 01276 if (Add->getOperand(i) == SymbolicName) 01277 if (FoundIndex == e) { 01278 FoundIndex = i; 01279 break; 01280 } 01281 01282 if (FoundIndex != Add->getNumOperands()) { 01283 // Create an add with everything but the specified operand. 01284 std::vector<SCEVHandle> Ops; 01285 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 01286 if (i != FoundIndex) 01287 Ops.push_back(Add->getOperand(i)); 01288 SCEVHandle Accum = SCEVAddExpr::get(Ops); 01289 01290 // This is not a valid addrec if the step amount is varying each 01291 // loop iteration, but is not itself an addrec in this loop. 01292 if (Accum->isLoopInvariant(L) || 01293 (isa<SCEVAddRecExpr>(Accum) && 01294 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 01295 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge)); 01296 SCEVHandle PHISCEV = SCEVAddRecExpr::get(StartVal, Accum, L); 01297 01298 // Okay, for the entire analysis of this edge we assumed the PHI 01299 // to be symbolic. We now need to go back and update all of the 01300 // entries for the scalars that use the PHI (except for the PHI 01301 // itself) to use the new analyzed value instead of the "symbolic" 01302 // value. 01303 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV); 01304 return PHISCEV; 01305 } 01306 } 01307 } 01308 01309 return SymbolicName; 01310 } 01311 01312 // If it's not a loop phi, we can't handle it yet. 01313 return SCEVUnknown::get(PN); 01314 } 01315 01316 /// createNodeForCast - Handle the various forms of casts that we support. 01317 /// 01318 SCEVHandle ScalarEvolutionsImpl::createNodeForCast(CastInst *CI) { 01319 const Type *SrcTy = CI->getOperand(0)->getType(); 01320 const Type *DestTy = CI->getType(); 01321 01322 // If this is a noop cast (ie, conversion from int to uint), ignore it. 01323 if (SrcTy->isLosslesslyConvertibleTo(DestTy)) 01324 return getSCEV(CI->getOperand(0)); 01325 01326 if (SrcTy->isInteger() && DestTy->isInteger()) { 01327 // Otherwise, if this is a truncating integer cast, we can represent this 01328 // cast. 01329 if (SrcTy->getPrimitiveSize() > DestTy->getPrimitiveSize()) 01330 return SCEVTruncateExpr::get(getSCEV(CI->getOperand(0)), 01331 CI->getType()->getUnsignedVersion()); 01332 if (SrcTy->isUnsigned() && 01333 SrcTy->getPrimitiveSize() > DestTy->getPrimitiveSize()) 01334 return SCEVZeroExtendExpr::get(getSCEV(CI->getOperand(0)), 01335 CI->getType()->getUnsignedVersion()); 01336 } 01337 01338 // If this is an sign or zero extending cast and we can prove that the value 01339 // will never overflow, we could do similar transformations. 01340 01341 // Otherwise, we can't handle this cast! 01342 return SCEVUnknown::get(CI); 01343 } 01344 01345 01346 /// createSCEV - We know that there is no SCEV for the specified value. 01347 /// Analyze the expression. 01348 /// 01349 SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) { 01350 if (Instruction *I = dyn_cast<Instruction>(V)) { 01351 switch (I->getOpcode()) { 01352 case Instruction::Add: 01353 return SCEVAddExpr::get(getSCEV(I->getOperand(0)), 01354 getSCEV(I->getOperand(1))); 01355 case Instruction::Mul: 01356 return SCEVMulExpr::get(getSCEV(I->getOperand(0)), 01357 getSCEV(I->getOperand(1))); 01358 case Instruction::Div: 01359 if (V->getType()->isInteger() && V->getType()->isSigned()) 01360 return SCEVSDivExpr::get(getSCEV(I->getOperand(0)), 01361 getSCEV(I->getOperand(1))); 01362 break; 01363 01364 case Instruction::Sub: 01365 return SCEV::getMinusSCEV(getSCEV(I->getOperand(0)), 01366 getSCEV(I->getOperand(1))); 01367 01368 case Instruction::Shl: 01369 // Turn shift left of a constant amount into a multiply. 01370 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) { 01371 Constant *X = ConstantInt::get(V->getType(), 1); 01372 X = ConstantExpr::getShl(X, SA); 01373 return SCEVMulExpr::get(getSCEV(I->getOperand(0)), getSCEV(X)); 01374 } 01375 break; 01376 01377 case Instruction::Cast: 01378 return createNodeForCast(cast<CastInst>(I)); 01379 01380 case Instruction::PHI: 01381 return createNodeForPHI(cast<PHINode>(I)); 01382 01383 default: // We cannot analyze this expression. 01384 break; 01385 } 01386 } 01387 01388 return SCEVUnknown::get(V); 01389 } 01390 01391 01392 01393 //===----------------------------------------------------------------------===// 01394 // Iteration Count Computation Code 01395 // 01396 01397 /// getIterationCount - If the specified loop has a predictable iteration 01398 /// count, return it. Note that it is not valid to call this method on a 01399 /// loop without a loop-invariant iteration count. 01400 SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) { 01401 std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L); 01402 if (I == IterationCounts.end()) { 01403 SCEVHandle ItCount = ComputeIterationCount(L); 01404 I = IterationCounts.insert(std::make_pair(L, ItCount)).first; 01405 if (ItCount != UnknownValue) { 01406 assert(ItCount->isLoopInvariant(L) && 01407 "Computed trip count isn't loop invariant for loop!"); 01408 ++NumTripCountsComputed; 01409 } else if (isa<PHINode>(L->getHeader()->begin())) { 01410 // Only count loops that have phi nodes as not being computable. 01411 ++NumTripCountsNotComputed; 01412 } 01413 } 01414 return I->second; 01415 } 01416 01417 /// ComputeIterationCount - Compute the number of times the specified loop 01418 /// will iterate. 01419 SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) { 01420 // If the loop has a non-one exit block count, we can't analyze it. 01421 std::vector<BasicBlock*> ExitBlocks; 01422 L->getExitBlocks(ExitBlocks); 01423 if (ExitBlocks.size() != 1) return UnknownValue; 01424 01425 // Okay, there is one exit block. Try to find the condition that causes the 01426 // loop to be exited. 01427 BasicBlock *ExitBlock = ExitBlocks[0]; 01428 01429 BasicBlock *ExitingBlock = 0; 01430 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock); 01431 PI != E; ++PI) 01432 if (L->contains(*PI)) { 01433 if (ExitingBlock == 0) 01434 ExitingBlock = *PI; 01435 else 01436 return UnknownValue; // More than one block exiting! 01437 } 01438 assert(ExitingBlock && "No exits from loop, something is broken!"); 01439 01440 // Okay, we've computed the exiting block. See what condition causes us to 01441 // exit. 01442 // 01443 // FIXME: we should be able to handle switch instructions (with a single exit) 01444 // FIXME: We should handle cast of int to bool as well 01445 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator()); 01446 if (ExitBr == 0) return UnknownValue; 01447 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!"); 01448 SetCondInst *ExitCond = dyn_cast<SetCondInst>(ExitBr->getCondition()); 01449 if (ExitCond == 0) // Not a setcc 01450 return ComputeIterationCountExhaustively(L, ExitBr->getCondition(), 01451 ExitBr->getSuccessor(0) == ExitBlock); 01452 01453 // If the condition was exit on true, convert the condition to exit on false. 01454 Instruction::BinaryOps Cond; 01455 if (ExitBr->getSuccessor(1) == ExitBlock) 01456 Cond = ExitCond->getOpcode(); 01457 else 01458 Cond = ExitCond->getInverseCondition(); 01459 01460 // Handle common loops like: for (X = "string"; *X; ++X) 01461 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 01462 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 01463 SCEVHandle ItCnt = 01464 ComputeLoadConstantCompareIterationCount(LI, RHS, L, Cond); 01465 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt; 01466 } 01467 01468 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0)); 01469 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1)); 01470 01471 // Try to evaluate any dependencies out of the loop. 01472 SCEVHandle Tmp = getSCEVAtScope(LHS, L); 01473 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp; 01474 Tmp = getSCEVAtScope(RHS, L); 01475 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp; 01476 01477 // At this point, we would like to compute how many iterations of the loop the 01478 // predicate will return true for these inputs. 01479 if (isa<SCEVConstant>(LHS) && !isa<SCEVConstant>(RHS)) { 01480 // If there is a constant, force it into the RHS. 01481 std::swap(LHS, RHS); 01482 Cond = SetCondInst::getSwappedCondition(Cond); 01483 } 01484 01485 // FIXME: think about handling pointer comparisons! i.e.: 01486 // while (P != P+100) ++P; 01487 01488 // If we have a comparison of a chrec against a constant, try to use value 01489 // ranges to answer this query. 01490 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 01491 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 01492 if (AddRec->getLoop() == L) { 01493 // Form the comparison range using the constant of the correct type so 01494 // that the ConstantRange class knows to do a signed or unsigned 01495 // comparison. 01496 ConstantInt *CompVal = RHSC->getValue(); 01497 const Type *RealTy = ExitCond->getOperand(0)->getType(); 01498 CompVal = dyn_cast<ConstantInt>(ConstantExpr::getCast(CompVal, RealTy)); 01499 if (CompVal) { 01500 // Form the constant range. 01501 ConstantRange CompRange(Cond, CompVal); 01502 01503 // Now that we have it, if it's signed, convert it to an unsigned 01504 // range. 01505 if (CompRange.getLower()->getType()->isSigned()) { 01506 const Type *NewTy = RHSC->getValue()->getType(); 01507 Constant *NewL = ConstantExpr::getCast(CompRange.getLower(), NewTy); 01508 Constant *NewU = ConstantExpr::getCast(CompRange.getUpper(), NewTy); 01509 CompRange = ConstantRange(NewL, NewU); 01510 } 01511 01512 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange); 01513 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 01514 } 01515 } 01516 01517 switch (Cond) { 01518 case Instruction::SetNE: // while (X != Y) 01519 // Convert to: while (X-Y != 0) 01520 if (LHS->getType()->isInteger()) { 01521 SCEVHandle TC = HowFarToZero(SCEV::getMinusSCEV(LHS, RHS), L); 01522 if (!isa<SCEVCouldNotCompute>(TC)) return TC; 01523 } 01524 break; 01525 case Instruction::SetEQ: 01526 // Convert to: while (X-Y == 0) // while (X == Y) 01527 if (LHS->getType()->isInteger()) { 01528 SCEVHandle TC = HowFarToNonZero(SCEV::getMinusSCEV(LHS, RHS), L); 01529 if (!isa<SCEVCouldNotCompute>(TC)) return TC; 01530 } 01531 break; 01532 case Instruction::SetLT: 01533 if (LHS->getType()->isInteger() && 01534 ExitCond->getOperand(0)->getType()->isSigned()) { 01535 SCEVHandle TC = HowManyLessThans(LHS, RHS, L); 01536 if (!isa<SCEVCouldNotCompute>(TC)) return TC; 01537 } 01538 break; 01539 case Instruction::SetGT: 01540 if (LHS->getType()->isInteger() && 01541 ExitCond->getOperand(0)->getType()->isSigned()) { 01542 SCEVHandle TC = HowManyLessThans(RHS, LHS, L); 01543 if (!isa<SCEVCouldNotCompute>(TC)) return TC; 01544 } 01545 break; 01546 default: 01547 #if 0 01548 std::cerr << "ComputeIterationCount "; 01549 if (ExitCond->getOperand(0)->getType()->isUnsigned()) 01550 std::cerr << "[unsigned] "; 01551 std::cerr << *LHS << " " 01552 << Instruction::getOpcodeName(Cond) << " " << *RHS << "\n"; 01553 #endif 01554 break; 01555 } 01556 01557 return ComputeIterationCountExhaustively(L, ExitCond, 01558 ExitBr->getSuccessor(0) == ExitBlock); 01559 } 01560 01561 static ConstantInt * 01562 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, Constant *C) { 01563 SCEVHandle InVal = SCEVConstant::get(cast<ConstantInt>(C)); 01564 SCEVHandle Val = AddRec->evaluateAtIteration(InVal); 01565 assert(isa<SCEVConstant>(Val) && 01566 "Evaluation of SCEV at constant didn't fold correctly?"); 01567 return cast<SCEVConstant>(Val)->getValue(); 01568 } 01569 01570 /// GetAddressedElementFromGlobal - Given a global variable with an initializer 01571 /// and a GEP expression (missing the pointer index) indexing into it, return 01572 /// the addressed element of the initializer or null if the index expression is 01573 /// invalid. 01574 static Constant * 01575 GetAddressedElementFromGlobal(GlobalVariable *GV, 01576 const std::vector<ConstantInt*> &Indices) { 01577 Constant *Init = GV->getInitializer(); 01578 for (unsigned i = 0, e = Indices.size(); i != e; ++i) { 01579 uint64_t Idx = Indices[i]->getRawValue(); 01580 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) { 01581 assert(Idx < CS->getNumOperands() && "Bad struct index!"); 01582 Init = cast<Constant>(CS->getOperand(Idx)); 01583 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) { 01584 if (Idx >= CA->getNumOperands()) return 0; // Bogus program 01585 Init = cast<Constant>(CA->getOperand(Idx)); 01586 } else if (isa<ConstantAggregateZero>(Init)) { 01587 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) { 01588 assert(Idx < STy->getNumElements() && "Bad struct index!"); 01589 Init = Constant::getNullValue(STy->getElementType(Idx)); 01590 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) { 01591 if (Idx >= ATy->getNumElements()) return 0; // Bogus program 01592 Init = Constant::getNullValue(ATy->getElementType()); 01593 } else { 01594 assert(0 && "Unknown constant aggregate type!"); 01595 } 01596 return 0; 01597 } else { 01598 return 0; // Unknown initializer type 01599 } 01600 } 01601 return Init; 01602 } 01603 01604 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of 01605 /// 'setcc load X, cst', try to se if we can compute the trip count. 01606 SCEVHandle ScalarEvolutionsImpl:: 01607 ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS, 01608 const Loop *L, unsigned SetCCOpcode) { 01609 if (LI->isVolatile()) return UnknownValue; 01610 01611 // Check to see if the loaded pointer is a getelementptr of a global. 01612 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 01613 if (!GEP) return UnknownValue; 01614 01615 // Make sure that it is really a constant global we are gepping, with an 01616 // initializer, and make sure the first IDX is really 0. 01617 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 01618 if (!GV || !GV->isConstant() || !GV->hasInitializer() || 01619 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 01620 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 01621 return UnknownValue; 01622 01623 // Okay, we allow one non-constant index into the GEP instruction. 01624 Value *VarIdx = 0; 01625 std::vector<ConstantInt*> Indexes; 01626 unsigned VarIdxNum = 0; 01627 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 01628 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 01629 Indexes.push_back(CI); 01630 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 01631 if (VarIdx) return UnknownValue; // Multiple non-constant idx's. 01632 VarIdx = GEP->getOperand(i); 01633 VarIdxNum = i-2; 01634 Indexes.push_back(0); 01635 } 01636 01637 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 01638 // Check to see if X is a loop variant variable value now. 01639 SCEVHandle Idx = getSCEV(VarIdx); 01640 SCEVHandle Tmp = getSCEVAtScope(Idx, L); 01641 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp; 01642 01643 // We can only recognize very limited forms of loop index expressions, in 01644 // particular, only affine AddRec's like {C1,+,C2}. 01645 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 01646 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) || 01647 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 01648 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 01649 return UnknownValue; 01650 01651 unsigned MaxSteps = MaxBruteForceIterations; 01652 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 01653 ConstantUInt *ItCst = 01654 ConstantUInt::get(IdxExpr->getType()->getUnsignedVersion(), IterationNum); 01655 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst); 01656 01657 // Form the GEP offset. 01658 Indexes[VarIdxNum] = Val; 01659 01660 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes); 01661 if (Result == 0) break; // Cannot compute! 01662 01663 // Evaluate the condition for this iteration. 01664 Result = ConstantExpr::get(SetCCOpcode, Result, RHS); 01665 if (!isa<ConstantBool>(Result)) break; // Couldn't decide for sure 01666 if (Result == ConstantBool::False) { 01667 #if 0 01668 std::cerr << "\n***\n*** Computed loop count " << *ItCst 01669 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader() 01670 << "***\n"; 01671 #endif 01672 ++NumArrayLenItCounts; 01673 return SCEVConstant::get(ItCst); // Found terminating iteration! 01674 } 01675 } 01676 return UnknownValue; 01677 } 01678 01679 01680 /// CanConstantFold - Return true if we can constant fold an instruction of the 01681 /// specified type, assuming that all operands were constants. 01682 static bool CanConstantFold(const Instruction *I) { 01683 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I) || 01684 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I)) 01685 return true; 01686 01687 if (const CallInst *CI = dyn_cast<CallInst>(I)) 01688 if (const Function *F = CI->getCalledFunction()) 01689 return canConstantFoldCallTo((Function*)F); // FIXME: elim cast 01690 return false; 01691 } 01692 01693 /// ConstantFold - Constant fold an instruction of the specified type with the 01694 /// specified constant operands. This function may modify the operands vector. 01695 static Constant *ConstantFold(const Instruction *I, 01696 std::vector<Constant*> &Operands) { 01697 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I)) 01698 return ConstantExpr::get(I->getOpcode(), Operands[0], Operands[1]); 01699 01700 switch (I->getOpcode()) { 01701 case Instruction::Cast: 01702 return ConstantExpr::getCast(Operands[0], I->getType()); 01703 case Instruction::Select: 01704 return ConstantExpr::getSelect(Operands[0], Operands[1], Operands[2]); 01705 case Instruction::Call: 01706 if (Function *GV = dyn_cast<Function>(Operands[0])) { 01707 Operands.erase(Operands.begin()); 01708 return ConstantFoldCall(cast<Function>(GV), Operands); 01709 } 01710 01711 return 0; 01712 case Instruction::GetElementPtr: 01713 Constant *Base = Operands[0]; 01714 Operands.erase(Operands.begin()); 01715 return ConstantExpr::getGetElementPtr(Base, Operands); 01716 } 01717 return 0; 01718 } 01719 01720 01721 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 01722 /// in the loop that V is derived from. We allow arbitrary operations along the 01723 /// way, but the operands of an operation must either be constants or a value 01724 /// derived from a constant PHI. If this expression does not fit with these 01725 /// constraints, return null. 01726 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 01727 // If this is not an instruction, or if this is an instruction outside of the 01728 // loop, it can't be derived from a loop PHI. 01729 Instruction *I = dyn_cast<Instruction>(V); 01730 if (I == 0 || !L->contains(I->getParent())) return 0; 01731 01732 if (PHINode *PN = dyn_cast<PHINode>(I)) 01733 if (L->getHeader() == I->getParent()) 01734 return PN; 01735 else 01736 // We don't currently keep track of the control flow needed to evaluate 01737 // PHIs, so we cannot handle PHIs inside of loops. 01738 return 0; 01739 01740 // If we won't be able to constant fold this expression even if the operands 01741 // are constants, return early. 01742 if (!CanConstantFold(I)) return 0; 01743 01744 // Otherwise, we can evaluate this instruction if all of its operands are 01745 // constant or derived from a PHI node themselves. 01746 PHINode *PHI = 0; 01747 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op) 01748 if (!(isa<Constant>(I->getOperand(Op)) || 01749 isa<GlobalValue>(I->getOperand(Op)))) { 01750 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L); 01751 if (P == 0) return 0; // Not evolving from PHI 01752 if (PHI == 0) 01753 PHI = P; 01754 else if (PHI != P) 01755 return 0; // Evolving from multiple different PHIs. 01756 } 01757 01758 // This is a expression evolving from a constant PHI! 01759 return PHI; 01760 } 01761 01762 /// EvaluateExpression - Given an expression that passes the 01763 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 01764 /// in the loop has the value PHIVal. If we can't fold this expression for some 01765 /// reason, return null. 01766 static Constant *EvaluateExpression(Value *V, Constant *PHIVal) { 01767 if (isa<PHINode>(V)) return PHIVal; 01768 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) 01769 return GV; 01770 if (Constant *C = dyn_cast<Constant>(V)) return C; 01771 Instruction *I = cast<Instruction>(V); 01772 01773 std::vector<Constant*> Operands; 01774 Operands.resize(I->getNumOperands()); 01775 01776 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 01777 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal); 01778 if (Operands[i] == 0) return 0; 01779 } 01780 01781 return ConstantFold(I, Operands); 01782 } 01783 01784 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 01785 /// in the header of its containing loop, we know the loop executes a 01786 /// constant number of times, and the PHI node is just a recurrence 01787 /// involving constants, fold it. 01788 Constant *ScalarEvolutionsImpl:: 01789 getConstantEvolutionLoopExitValue(PHINode *PN, uint64_t Its, const Loop *L) { 01790 std::map<PHINode*, Constant*>::iterator I = 01791 ConstantEvolutionLoopExitValue.find(PN); 01792 if (I != ConstantEvolutionLoopExitValue.end()) 01793 return I->second; 01794 01795 if (Its > MaxBruteForceIterations) 01796 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it. 01797 01798 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 01799 01800 // Since the loop is canonicalized, the PHI node must have two entries. One 01801 // entry must be a constant (coming in from outside of the loop), and the 01802 // second must be derived from the same PHI. 01803 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1)); 01804 Constant *StartCST = 01805 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge)); 01806 if (StartCST == 0) 01807 return RetVal = 0; // Must be a constant. 01808 01809 Value *BEValue = PN->getIncomingValue(SecondIsBackedge); 01810 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L); 01811 if (PN2 != PN) 01812 return RetVal = 0; // Not derived from same PHI. 01813 01814 // Execute the loop symbolically to determine the exit value. 01815 unsigned IterationNum = 0; 01816 unsigned NumIterations = Its; 01817 if (NumIterations != Its) 01818 return RetVal = 0; // More than 2^32 iterations?? 01819 01820 for (Constant *PHIVal = StartCST; ; ++IterationNum) { 01821 if (IterationNum == NumIterations) 01822 return RetVal = PHIVal; // Got exit value! 01823 01824 // Compute the value of the PHI node for the next iteration. 01825 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal); 01826 if (NextPHI == PHIVal) 01827 return RetVal = NextPHI; // Stopped evolving! 01828 if (NextPHI == 0) 01829 return 0; // Couldn't evaluate! 01830 PHIVal = NextPHI; 01831 } 01832 } 01833 01834 /// ComputeIterationCountExhaustively - If the trip is known to execute a 01835 /// constant number of times (the condition evolves only from constants), 01836 /// try to evaluate a few iterations of the loop until we get the exit 01837 /// condition gets a value of ExitWhen (true or false). If we cannot 01838 /// evaluate the trip count of the loop, return UnknownValue. 01839 SCEVHandle ScalarEvolutionsImpl:: 01840 ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) { 01841 PHINode *PN = getConstantEvolvingPHI(Cond, L); 01842 if (PN == 0) return UnknownValue; 01843 01844 // Since the loop is canonicalized, the PHI node must have two entries. One 01845 // entry must be a constant (coming in from outside of the loop), and the 01846 // second must be derived from the same PHI. 01847 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1)); 01848 Constant *StartCST = 01849 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge)); 01850 if (StartCST == 0) return UnknownValue; // Must be a constant. 01851 01852 Value *BEValue = PN->getIncomingValue(SecondIsBackedge); 01853 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L); 01854 if (PN2 != PN) return UnknownValue; // Not derived from same PHI. 01855 01856 // Okay, we find a PHI node that defines the trip count of this loop. Execute 01857 // the loop symbolically to determine when the condition gets a value of 01858 // "ExitWhen". 01859 unsigned IterationNum = 0; 01860 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 01861 for (Constant *PHIVal = StartCST; 01862 IterationNum != MaxIterations; ++IterationNum) { 01863 ConstantBool *CondVal = 01864 dyn_cast_or_null<ConstantBool>(EvaluateExpression(Cond, PHIVal)); 01865 if (!CondVal) return UnknownValue; // Couldn't symbolically evaluate. 01866 01867 if (CondVal->getValue() == ExitWhen) { 01868 ConstantEvolutionLoopExitValue[PN] = PHIVal; 01869 ++NumBruteForceTripCountsComputed; 01870 return SCEVConstant::get(ConstantUInt::get(Type::UIntTy, IterationNum)); 01871 } 01872 01873 // Compute the value of the PHI node for the next iteration. 01874 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal); 01875 if (NextPHI == 0 || NextPHI == PHIVal) 01876 return UnknownValue; // Couldn't evaluate or not making progress... 01877 PHIVal = NextPHI; 01878 } 01879 01880 // Too many iterations were needed to evaluate. 01881 return UnknownValue; 01882 } 01883 01884 /// getSCEVAtScope - Compute the value of the specified expression within the 01885 /// indicated loop (which may be null to indicate in no loop). If the 01886 /// expression cannot be evaluated, return UnknownValue. 01887 SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) { 01888 // FIXME: this should be turned into a virtual method on SCEV! 01889 01890 if (isa<SCEVConstant>(V)) return V; 01891 01892 // If this instruction is evolves from a constant-evolving PHI, compute the 01893 // exit value from the loop without using SCEVs. 01894 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 01895 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 01896 const Loop *LI = this->LI[I->getParent()]; 01897 if (LI && LI->getParentLoop() == L) // Looking for loop exit value. 01898 if (PHINode *PN = dyn_cast<PHINode>(I)) 01899 if (PN->getParent() == LI->getHeader()) { 01900 // Okay, there is no closed form solution for the PHI node. Check 01901 // to see if the loop that contains it has a known iteration count. 01902 // If so, we may be able to force computation of the exit value. 01903 SCEVHandle IterationCount = getIterationCount(LI); 01904 if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) { 01905 // Okay, we know how many times the containing loop executes. If 01906 // this is a constant evolving PHI node, get the final value at 01907 // the specified iteration number. 01908 Constant *RV = getConstantEvolutionLoopExitValue(PN, 01909 ICC->getValue()->getRawValue(), 01910 LI); 01911 if (RV) return SCEVUnknown::get(RV); 01912 } 01913 } 01914 01915 // Okay, this is a some expression that we cannot symbolically evaluate 01916 // into a SCEV. Check to see if it's possible to symbolically evaluate 01917 // the arguments into constants, and if see, try to constant propagate the 01918 // result. This is particularly useful for computing loop exit values. 01919 if (CanConstantFold(I)) { 01920 std::vector<Constant*> Operands; 01921 Operands.reserve(I->getNumOperands()); 01922 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 01923 Value *Op = I->getOperand(i); 01924 if (Constant *C = dyn_cast<Constant>(Op)) { 01925 Operands.push_back(C); 01926 } else { 01927 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L); 01928 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) 01929 Operands.push_back(ConstantExpr::getCast(SC->getValue(), 01930 Op->getType())); 01931 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) { 01932 if (Constant *C = dyn_cast<Constant>(SU->getValue())) 01933 Operands.push_back(ConstantExpr::getCast(C, Op->getType())); 01934 else 01935 return V; 01936 } else { 01937 return V; 01938 } 01939 } 01940 } 01941 return SCEVUnknown::get(ConstantFold(I, Operands)); 01942 } 01943 } 01944 01945 // This is some other type of SCEVUnknown, just return it. 01946 return V; 01947 } 01948 01949 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 01950 // Avoid performing the look-up in the common case where the specified 01951 // expression has no loop-variant portions. 01952 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 01953 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 01954 if (OpAtScope != Comm->getOperand(i)) { 01955 if (OpAtScope == UnknownValue) return UnknownValue; 01956 // Okay, at least one of these operands is loop variant but might be 01957 // foldable. Build a new instance of the folded commutative expression. 01958 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i); 01959 NewOps.push_back(OpAtScope); 01960 01961 for (++i; i != e; ++i) { 01962 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 01963 if (OpAtScope == UnknownValue) return UnknownValue; 01964 NewOps.push_back(OpAtScope); 01965 } 01966 if (isa<SCEVAddExpr>(Comm)) 01967 return SCEVAddExpr::get(NewOps); 01968 assert(isa<SCEVMulExpr>(Comm) && "Only know about add and mul!"); 01969 return SCEVMulExpr::get(NewOps); 01970 } 01971 } 01972 // If we got here, all operands are loop invariant. 01973 return Comm; 01974 } 01975 01976 if (SCEVSDivExpr *Div = dyn_cast<SCEVSDivExpr>(V)) { 01977 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L); 01978 if (LHS == UnknownValue) return LHS; 01979 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L); 01980 if (RHS == UnknownValue) return RHS; 01981 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 01982 return Div; // must be loop invariant 01983 return SCEVSDivExpr::get(LHS, RHS); 01984 } 01985 01986 // If this is a loop recurrence for a loop that does not contain L, then we 01987 // are dealing with the final value computed by the loop. 01988 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 01989 if (!L || !AddRec->getLoop()->contains(L->getHeader())) { 01990 // To evaluate this recurrence, we need to know how many times the AddRec 01991 // loop iterates. Compute this now. 01992 SCEVHandle IterationCount = getIterationCount(AddRec->getLoop()); 01993 if (IterationCount == UnknownValue) return UnknownValue; 01994 IterationCount = getTruncateOrZeroExtend(IterationCount, 01995 AddRec->getType()); 01996 01997 // If the value is affine, simplify the expression evaluation to just 01998 // Start + Step*IterationCount. 01999 if (AddRec->isAffine()) 02000 return SCEVAddExpr::get(AddRec->getStart(), 02001 SCEVMulExpr::get(IterationCount, 02002 AddRec->getOperand(1))); 02003 02004 // Otherwise, evaluate it the hard way. 02005 return AddRec->evaluateAtIteration(IterationCount); 02006 } 02007 return UnknownValue; 02008 } 02009 02010 //assert(0 && "Unknown SCEV type!"); 02011 return UnknownValue; 02012 } 02013 02014 02015 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the 02016 /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which 02017 /// might be the same) or two SCEVCouldNotCompute objects. 02018 /// 02019 static std::pair<SCEVHandle,SCEVHandle> 02020 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec) { 02021 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 02022 SCEVConstant *L = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 02023 SCEVConstant *M = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 02024 SCEVConstant *N = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 02025 02026 // We currently can only solve this if the coefficients are constants. 02027 if (!L || !M || !N) { 02028 SCEV *CNC = new SCEVCouldNotCompute(); 02029 return std::make_pair(CNC, CNC); 02030 } 02031 02032 Constant *Two = ConstantInt::get(L->getValue()->getType(), 2); 02033 02034 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C 02035 Constant *C = L->getValue(); 02036 // The B coefficient is M-N/2 02037 Constant *B = ConstantExpr::getSub(M->getValue(), 02038 ConstantExpr::getDiv(N->getValue(), 02039 Two)); 02040 // The A coefficient is N/2 02041 Constant *A = ConstantExpr::getDiv(N->getValue(), Two); 02042 02043 // Compute the B^2-4ac term. 02044 Constant *SqrtTerm = 02045 ConstantExpr::getMul(ConstantInt::get(C->getType(), 4), 02046 ConstantExpr::getMul(A, C)); 02047 SqrtTerm = ConstantExpr::getSub(ConstantExpr::getMul(B, B), SqrtTerm); 02048 02049 // Compute floor(sqrt(B^2-4ac)) 02050 ConstantUInt *SqrtVal = 02051 cast<ConstantUInt>(ConstantExpr::getCast(SqrtTerm, 02052 SqrtTerm->getType()->getUnsignedVersion())); 02053 uint64_t SqrtValV = SqrtVal->getValue(); 02054 uint64_t SqrtValV2 = (uint64_t)sqrt((double)SqrtValV); 02055 // The square root might not be precise for arbitrary 64-bit integer 02056 // values. Do some sanity checks to ensure it's correct. 02057 if (SqrtValV2*SqrtValV2 > SqrtValV || 02058 (SqrtValV2+1)*(SqrtValV2+1) <= SqrtValV) { 02059 SCEV *CNC = new SCEVCouldNotCompute(); 02060 return std::make_pair(CNC, CNC); 02061 } 02062 02063 SqrtVal = ConstantUInt::get(Type::ULongTy, SqrtValV2); 02064 SqrtTerm = ConstantExpr::getCast(SqrtVal, SqrtTerm->getType()); 02065 02066 Constant *NegB = ConstantExpr::getNeg(B); 02067 Constant *TwoA = ConstantExpr::getMul(A, Two); 02068 02069 // The divisions must be performed as signed divisions. 02070 const Type *SignedTy = NegB->getType()->getSignedVersion(); 02071 NegB = ConstantExpr::getCast(NegB, SignedTy); 02072 TwoA = ConstantExpr::getCast(TwoA, SignedTy); 02073 SqrtTerm = ConstantExpr::getCast(SqrtTerm, SignedTy); 02074 02075 Constant *Solution1 = 02076 ConstantExpr::getDiv(ConstantExpr::getAdd(NegB, SqrtTerm), TwoA); 02077 Constant *Solution2 = 02078 ConstantExpr::getDiv(ConstantExpr::getSub(NegB, SqrtTerm), TwoA); 02079 return std::make_pair(SCEVUnknown::get(Solution1), 02080 SCEVUnknown::get(Solution2)); 02081 } 02082 02083 /// HowFarToZero - Return the number of times a backedge comparing the specified 02084 /// value to zero will execute. If not computable, return UnknownValue 02085 SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) { 02086 // If the value is a constant 02087 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 02088 // If the value is already zero, the branch will execute zero times. 02089 if (C->getValue()->isNullValue()) return C; 02090 return UnknownValue; // Otherwise it will loop infinitely. 02091 } 02092 02093 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V); 02094 if (!AddRec || AddRec->getLoop() != L) 02095 return UnknownValue; 02096 02097 if (AddRec->isAffine()) { 02098 // If this is an affine expression the execution count of this branch is 02099 // equal to: 02100 // 02101 // (0 - Start/Step) iff Start % Step == 0 02102 // 02103 // Get the initial value for the loop. 02104 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 02105 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue; 02106 SCEVHandle Step = AddRec->getOperand(1); 02107 02108 Step = getSCEVAtScope(Step, L->getParentLoop()); 02109 02110 // Figure out if Start % Step == 0. 02111 // FIXME: We should add DivExpr and RemExpr operations to our AST. 02112 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) { 02113 if (StepC->getValue()->equalsInt(1)) // N % 1 == 0 02114 return SCEV::getNegativeSCEV(Start); // 0 - Start/1 == -Start 02115 if (StepC->getValue()->isAllOnesValue()) // N % -1 == 0 02116 return Start; // 0 - Start/-1 == Start 02117 02118 // Check to see if Start is divisible by SC with no remainder. 02119 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) { 02120 ConstantInt *StartCC = StartC->getValue(); 02121 Constant *StartNegC = ConstantExpr::getNeg(StartCC); 02122 Constant *Rem = ConstantExpr::getRem(StartNegC, StepC->getValue()); 02123 if (Rem->isNullValue()) { 02124 Constant *Result =ConstantExpr::getDiv(StartNegC,StepC->getValue()); 02125 return SCEVUnknown::get(Result); 02126 } 02127 } 02128 } 02129 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) { 02130 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 02131 // the quadratic equation to solve it. 02132 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec); 02133 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first); 02134 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second); 02135 if (R1) { 02136 #if 0 02137 std::cerr << "HFTZ: " << *V << " - sol#1: " << *R1 02138 << " sol#2: " << *R2 << "\n"; 02139 #endif 02140 // Pick the smallest positive root value. 02141 assert(R1->getType()->isUnsigned()&&"Didn't canonicalize to unsigned?"); 02142 if (ConstantBool *CB = 02143 dyn_cast<ConstantBool>(ConstantExpr::getSetLT(R1->getValue(), 02144 R2->getValue()))) { 02145 if (CB != ConstantBool::True) 02146 std::swap(R1, R2); // R1 is the minimum root now. 02147 02148 // We can only use this value if the chrec ends up with an exact zero 02149 // value at this index. When solving for "X*X != 5", for example, we 02150 // should not accept a root of 2. 02151 SCEVHandle Val = AddRec->evaluateAtIteration(R1); 02152 if (SCEVConstant *EvalVal = dyn_cast<SCEVConstant>(Val)) 02153 if (EvalVal->getValue()->isNullValue()) 02154 return R1; // We found a quadratic root! 02155 } 02156 } 02157 } 02158 02159 return UnknownValue; 02160 } 02161 02162 /// HowFarToNonZero - Return the number of times a backedge checking the 02163 /// specified value for nonzero will execute. If not computable, return 02164 /// UnknownValue 02165 SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) { 02166 // Loops that look like: while (X == 0) are very strange indeed. We don't 02167 // handle them yet except for the trivial case. This could be expanded in the 02168 // future as needed. 02169 02170 // If the value is a constant, check to see if it is known to be non-zero 02171 // already. If so, the backedge will execute zero times. 02172 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 02173 Constant *Zero = Constant::getNullValue(C->getValue()->getType()); 02174 Constant *NonZero = ConstantExpr::getSetNE(C->getValue(), Zero); 02175 if (NonZero == ConstantBool::True) 02176 return getSCEV(Zero); 02177 return UnknownValue; // Otherwise it will loop infinitely. 02178 } 02179 02180 // We could implement others, but I really doubt anyone writes loops like 02181 // this, and if they did, they would already be constant folded. 02182 return UnknownValue; 02183 } 02184 02185 /// HowManyLessThans - Return the number of times a backedge containing the 02186 /// specified less-than comparison will execute. If not computable, return 02187 /// UnknownValue. 02188 SCEVHandle ScalarEvolutionsImpl:: 02189 HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L) { 02190 // Only handle: "ADDREC < LoopInvariant". 02191 if (!RHS->isLoopInvariant(L)) return UnknownValue; 02192 02193 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS); 02194 if (!AddRec || AddRec->getLoop() != L) 02195 return UnknownValue; 02196 02197 if (AddRec->isAffine()) { 02198 // FORNOW: We only support unit strides. 02199 SCEVHandle One = SCEVUnknown::getIntegerSCEV(1, RHS->getType()); 02200 if (AddRec->getOperand(1) != One) 02201 return UnknownValue; 02202 02203 // The number of iterations for "[n,+,1] < m", is m-n. However, we don't 02204 // know that m is >= n on input to the loop. If it is, the condition return 02205 // true zero times. What we really should return, for full generality, is 02206 // SMAX(0, m-n). Since we cannot check this, we will instead check for a 02207 // canonical loop form: most do-loops will have a check that dominates the 02208 // loop, that only enters the loop if [n-1]<m. If we can find this check, 02209 // we know that the SMAX will evaluate to m-n, because we know that m >= n. 02210 02211 // Search for the check. 02212 BasicBlock *Preheader = L->getLoopPreheader(); 02213 BasicBlock *PreheaderDest = L->getHeader(); 02214 if (Preheader == 0) return UnknownValue; 02215 02216 BranchInst *LoopEntryPredicate = 02217 dyn_cast<BranchInst>(Preheader->getTerminator()); 02218 if (!LoopEntryPredicate) return UnknownValue; 02219 02220 // This might be a critical edge broken out. If the loop preheader ends in 02221 // an unconditional branch to the loop, check to see if the preheader has a 02222 // single predecessor, and if so, look for its terminator. 02223 while (LoopEntryPredicate->isUnconditional()) { 02224 PreheaderDest = Preheader; 02225 Preheader = Preheader->getSinglePredecessor(); 02226 if (!Preheader) return UnknownValue; // Multiple preds. 02227 02228 LoopEntryPredicate = 02229 dyn_cast<BranchInst>(Preheader->getTerminator()); 02230 if (!LoopEntryPredicate) return UnknownValue; 02231 } 02232 02233 // Now that we found a conditional branch that dominates the loop, check to 02234 // see if it is the comparison we are looking for. 02235 SetCondInst *SCI =dyn_cast<SetCondInst>(LoopEntryPredicate->getCondition()); 02236 if (!SCI) return UnknownValue; 02237 Value *PreCondLHS = SCI->getOperand(0); 02238 Value *PreCondRHS = SCI->getOperand(1); 02239 Instruction::BinaryOps Cond; 02240 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest) 02241 Cond = SCI->getOpcode(); 02242 else 02243 Cond = SCI->getInverseCondition(); 02244 02245 switch (Cond) { 02246 case Instruction::SetGT: 02247 std::swap(PreCondLHS, PreCondRHS); 02248 Cond = Instruction::SetLT; 02249 // Fall Through. 02250 case Instruction::SetLT: 02251 if (PreCondLHS->getType()->isInteger() && 02252 PreCondLHS->getType()->isSigned()) { 02253 if (RHS != getSCEV(PreCondRHS)) 02254 return UnknownValue; // Not a comparison against 'm'. 02255 02256 if (SCEV::getMinusSCEV(AddRec->getOperand(0), One) 02257 != getSCEV(PreCondLHS)) 02258 return UnknownValue; // Not a comparison against 'n-1'. 02259 break; 02260 } else { 02261 return UnknownValue; 02262 } 02263 default: break; 02264 } 02265 02266 //std::cerr << "Computed Loop Trip Count as: " << 02267 // *SCEV::getMinusSCEV(RHS, AddRec->getOperand(0)) << "\n"; 02268 return SCEV::getMinusSCEV(RHS, AddRec->getOperand(0)); 02269 } 02270 02271 return UnknownValue; 02272 } 02273 02274 /// getNumIterationsInRange - Return the number of iterations of this loop that 02275 /// produce values in the specified constant range. Another way of looking at 02276 /// this is that it returns the first iteration number where the value is not in 02277 /// the condition, thus computing the exit count. If the iteration count can't 02278 /// be computed, an instance of SCEVCouldNotCompute is returned. 02279 SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range) const { 02280 if (Range.isFullSet()) // Infinite loop. 02281 return new SCEVCouldNotCompute(); 02282 02283 // If the start is a non-zero constant, shift the range to simplify things. 02284 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 02285 if (!SC->getValue()->isNullValue()) { 02286 std::vector<SCEVHandle> Operands(op_begin(), op_end()); 02287 Operands[0] = SCEVUnknown::getIntegerSCEV(0, SC->getType()); 02288 SCEVHandle Shifted = SCEVAddRecExpr::get(Operands, getLoop()); 02289 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 02290 return ShiftedAddRec->getNumIterationsInRange( 02291 Range.subtract(SC->getValue())); 02292 // This is strange and shouldn't happen. 02293 return new SCEVCouldNotCompute(); 02294 } 02295 02296 // The only time we can solve this is when we have all constant indices. 02297 // Otherwise, we cannot determine the overflow conditions. 02298 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) 02299 if (!isa<SCEVConstant>(getOperand(i))) 02300 return new SCEVCouldNotCompute(); 02301 02302 02303 // Okay at this point we know that all elements of the chrec are constants and 02304 // that the start element is zero. 02305 02306 // First check to see if the range contains zero. If not, the first 02307 // iteration exits. 02308 ConstantInt *Zero = ConstantInt::get(getType(), 0); 02309 if (!Range.contains(Zero)) return SCEVConstant::get(Zero); 02310 02311 if (isAffine()) { 02312 // If this is an affine expression then we have this situation: 02313 // Solve {0,+,A} in Range === Ax in Range 02314 02315 // Since we know that zero is in the range, we know that the upper value of 02316 // the range must be the first possible exit value. Also note that we 02317 // already checked for a full range. 02318 ConstantInt *Upper = cast<ConstantInt>(Range.getUpper()); 02319 ConstantInt *A = cast<SCEVConstant>(getOperand(1))->getValue(); 02320 ConstantInt *One = ConstantInt::get(getType(), 1); 02321 02322 // The exit value should be (Upper+A-1)/A. 02323 Constant *ExitValue = Upper; 02324 if (A != One) { 02325 ExitValue = ConstantExpr::getSub(ConstantExpr::getAdd(Upper, A), One); 02326 ExitValue = ConstantExpr::getDiv(ExitValue, A); 02327 } 02328 assert(isa<ConstantInt>(ExitValue) && 02329 "Constant folding of integers not implemented?"); 02330 02331 // Evaluate at the exit value. If we really did fall out of the valid 02332 // range, then we computed our trip count, otherwise wrap around or other 02333 // things must have happened. 02334 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue); 02335 if (Range.contains(Val)) 02336 return new SCEVCouldNotCompute(); // Something strange happened 02337 02338 // Ensure that the previous value is in the range. This is a sanity check. 02339 assert(Range.contains(EvaluateConstantChrecAtConstant(this, 02340 ConstantExpr::getSub(ExitValue, One))) && 02341 "Linear scev computation is off in a bad way!"); 02342 return SCEVConstant::get(cast<ConstantInt>(ExitValue)); 02343 } else if (isQuadratic()) { 02344 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the 02345 // quadratic equation to solve it. To do this, we must frame our problem in 02346 // terms of figuring out when zero is crossed, instead of when 02347 // Range.getUpper() is crossed. 02348 std::vector<SCEVHandle> NewOps(op_begin(), op_end()); 02349 NewOps[0] = SCEV::getNegativeSCEV(SCEVUnknown::get(Range.getUpper())); 02350 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, getLoop()); 02351 02352 // Next, solve the constructed addrec 02353 std::pair<SCEVHandle,SCEVHandle> Roots = 02354 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec)); 02355 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first); 02356 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second); 02357 if (R1) { 02358 // Pick the smallest positive root value. 02359 assert(R1->getType()->isUnsigned() && "Didn't canonicalize to unsigned?"); 02360 if (ConstantBool *CB = 02361 dyn_cast<ConstantBool>(ConstantExpr::getSetLT(R1->getValue(), 02362 R2->getValue()))) { 02363 if (CB != ConstantBool::True) 02364 std::swap(R1, R2); // R1 is the minimum root now. 02365 02366 // Make sure the root is not off by one. The returned iteration should 02367 // not be in the range, but the previous one should be. When solving 02368 // for "X*X < 5", for example, we should not return a root of 2. 02369 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this, 02370 R1->getValue()); 02371 if (Range.contains(R1Val)) { 02372 // The next iteration must be out of the range... 02373 Constant *NextVal = 02374 ConstantExpr::getAdd(R1->getValue(), 02375 ConstantInt::get(R1->getType(), 1)); 02376 02377 R1Val = EvaluateConstantChrecAtConstant(this, NextVal); 02378 if (!Range.contains(R1Val)) 02379 return SCEVUnknown::get(NextVal); 02380 return new SCEVCouldNotCompute(); // Something strange happened 02381 } 02382 02383 // If R1 was not in the range, then it is a good return value. Make 02384 // sure that R1-1 WAS in the range though, just in case. 02385 Constant *NextVal = 02386 ConstantExpr::getSub(R1->getValue(), 02387 ConstantInt::get(R1->getType(), 1)); 02388 R1Val = EvaluateConstantChrecAtConstant(this, NextVal); 02389 if (Range.contains(R1Val)) 02390 return R1; 02391 return new SCEVCouldNotCompute(); // Something strange happened 02392 } 02393 } 02394 } 02395 02396 // Fallback, if this is a general polynomial, figure out the progression 02397 // through brute force: evaluate until we find an iteration that fails the 02398 // test. This is likely to be slow, but getting an accurate trip count is 02399 // incredibly important, we will be able to simplify the exit test a lot, and 02400 // we are almost guaranteed to get a trip count in this case. 02401 ConstantInt *TestVal = ConstantInt::get(getType(), 0); 02402 ConstantInt *One = ConstantInt::get(getType(), 1); 02403 ConstantInt *EndVal = TestVal; // Stop when we wrap around. 02404 do { 02405 ++NumBruteForceEvaluations; 02406 SCEVHandle Val = evaluateAtIteration(SCEVConstant::get(TestVal)); 02407 if (!isa<SCEVConstant>(Val)) // This shouldn't happen. 02408 return new SCEVCouldNotCompute(); 02409 02410 // Check to see if we found the value! 02411 if (!Range.contains(cast<SCEVConstant>(Val)->getValue())) 02412 return SCEVConstant::get(TestVal); 02413 02414 // Increment to test the next index. 02415 TestVal = cast<ConstantInt>(ConstantExpr::getAdd(TestVal, One)); 02416 } while (TestVal != EndVal); 02417 02418 return new SCEVCouldNotCompute(); 02419 } 02420 02421 02422 02423 //===----------------------------------------------------------------------===// 02424 // ScalarEvolution Class Implementation 02425 //===----------------------------------------------------------------------===// 02426 02427 bool ScalarEvolution::runOnFunction(Function &F) { 02428 Impl = new ScalarEvolutionsImpl(F, getAnalysis<LoopInfo>()); 02429 return false; 02430 } 02431 02432 void ScalarEvolution::releaseMemory() { 02433 delete (ScalarEvolutionsImpl*)Impl; 02434 Impl = 0; 02435 } 02436 02437 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const { 02438 AU.setPreservesAll(); 02439 AU.addRequiredTransitive<LoopInfo>(); 02440 } 02441 02442 SCEVHandle ScalarEvolution::getSCEV(Value *V) const { 02443 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V); 02444 } 02445 02446 /// hasSCEV - Return true if the SCEV for this value has already been 02447 /// computed. 02448 bool ScalarEvolution::hasSCEV(Value *V) const { 02449 return ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V); 02450 } 02451 02452 02453 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for 02454 /// the specified value. 02455 void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) { 02456 ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H); 02457 } 02458 02459 02460 SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const { 02461 return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L); 02462 } 02463 02464 bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const { 02465 return !isa<SCEVCouldNotCompute>(getIterationCount(L)); 02466 } 02467 02468 SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const { 02469 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L); 02470 } 02471 02472 void ScalarEvolution::deleteInstructionFromRecords(Instruction *I) const { 02473 return ((ScalarEvolutionsImpl*)Impl)->deleteInstructionFromRecords(I); 02474 } 02475 02476 static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE, 02477 const Loop *L) { 02478 // Print all inner loops first 02479 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I) 02480 PrintLoopInfo(OS, SE, *I); 02481 02482 std::cerr << "Loop " << L->getHeader()->getName() << ": "; 02483 02484 std::vector<BasicBlock*> ExitBlocks; 02485 L->getExitBlocks(ExitBlocks); 02486 if (ExitBlocks.size() != 1) 02487 std::cerr << "<multiple exits> "; 02488 02489 if (SE->hasLoopInvariantIterationCount(L)) { 02490 std::cerr << *SE->getIterationCount(L) << " iterations! "; 02491 } else { 02492 std::cerr << "Unpredictable iteration count. "; 02493 } 02494 02495 std::cerr << "\n"; 02496 } 02497 02498 void ScalarEvolution::print(std::ostream &OS, const Module* ) const { 02499 Function &F = ((ScalarEvolutionsImpl*)Impl)->F; 02500 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI; 02501 02502 OS << "Classifying expressions for: " << F.getName() << "\n"; 02503 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) 02504 if (I->getType()->isInteger()) { 02505 OS << *I; 02506 OS << " --> "; 02507 SCEVHandle SV = getSCEV(&*I); 02508 SV->print(OS); 02509 OS << "\t\t"; 02510 02511 if ((*I).getType()->isIntegral()) { 02512 ConstantRange Bounds = SV->getValueRange(); 02513 if (!Bounds.isFullSet()) 02514 OS << "Bounds: " << Bounds << " "; 02515 } 02516 02517 if (const Loop *L = LI.getLoopFor((*I).getParent())) { 02518 OS << "Exits: "; 02519 SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop()); 02520 if (isa<SCEVCouldNotCompute>(ExitValue)) { 02521 OS << "<<Unknown>>"; 02522 } else { 02523 OS << *ExitValue; 02524 } 02525 } 02526 02527 02528 OS << "\n"; 02529 } 02530 02531 OS << "Determining loop execution counts for: " << F.getName() << "\n"; 02532 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I) 02533 PrintLoopInfo(OS, this, *I); 02534 } 02535