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