1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file contains the implementation of the scalar evolution analysis 11 // engine, which is used primarily to analyze expressions involving induction 12 // variables in loops. 13 // 14 // There are several aspects to this library. First is the representation of 15 // scalar expressions, which are represented as subclasses of the SCEV class. 16 // These classes are used to represent certain types of subexpressions that we 17 // can handle. These classes are reference counted, managed by the const SCEV* 18 // class. We only create one SCEV of a particular shape, so pointer-comparisons 19 // for equality are legal. 20 // 21 // One important aspect of the SCEV objects is that they are never cyclic, even 22 // if there is a cycle in the dataflow for an expression (ie, a PHI node). If 23 // the PHI node is one of the idioms that we can represent (e.g., a polynomial 24 // recurrence) then we represent it directly as a recurrence node, otherwise we 25 // represent it as a SCEVUnknown node. 26 // 27 // In addition to being able to represent expressions of various types, we also 28 // have folders that are used to build the *canonical* representation for a 29 // particular expression. These folders are capable of using a variety of 30 // rewrite rules to simplify the expressions. 31 // 32 // Once the folders are defined, we can implement the more interesting 33 // higher-level code, such as the code that recognizes PHI nodes of various 34 // types, computes the execution count of a loop, etc. 35 // 36 // TODO: We should use these routines and value representations to implement 37 // dependence analysis! 38 // 39 //===----------------------------------------------------------------------===// 40 // 41 // There are several good references for the techniques used in this analysis. 42 // 43 // Chains of recurrences -- a method to expedite the evaluation 44 // of closed-form functions 45 // Olaf Bachmann, Paul S. Wang, Eugene V. Zima 46 // 47 // On computational properties of chains of recurrences 48 // Eugene V. Zima 49 // 50 // Symbolic Evaluation of Chains of Recurrences for Loop Optimization 51 // Robert A. van Engelen 52 // 53 // Efficient Symbolic Analysis for Optimizing Compilers 54 // Robert A. van Engelen 55 // 56 // Using the chains of recurrences algebra for data dependence testing and 57 // induction variable substitution 58 // MS Thesis, Johnie Birch 59 // 60 //===----------------------------------------------------------------------===// 61 62 #define DEBUG_TYPE "scalar-evolution" 63 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 64 #include "llvm/Constants.h" 65 #include "llvm/DerivedTypes.h" 66 #include "llvm/GlobalVariable.h" 67 #include "llvm/Instructions.h" 68 #include "llvm/Analysis/ConstantFolding.h" 69 #include "llvm/Analysis/Dominators.h" 70 #include "llvm/Analysis/LoopInfo.h" 71 #include "llvm/Analysis/ValueTracking.h" 72 #include "llvm/Assembly/Writer.h" 73 #include "llvm/Target/TargetData.h" 74 #include "llvm/Support/CommandLine.h" 75 #include "llvm/Support/Compiler.h" 76 #include "llvm/Support/ConstantRange.h" 77 #include "llvm/Support/GetElementPtrTypeIterator.h" 78 #include "llvm/Support/InstIterator.h" 79 #include "llvm/Support/MathExtras.h" 80 #include "llvm/Support/raw_ostream.h" 81 #include "llvm/ADT/Statistic.h" 82 #include "llvm/ADT/STLExtras.h" 83 #include <algorithm> 84 using namespace llvm; 85 86 STATISTIC(NumArrayLenItCounts, 87 "Number of trip counts computed with array length"); 88 STATISTIC(NumTripCountsComputed, 89 "Number of loops with predictable loop counts"); 90 STATISTIC(NumTripCountsNotComputed, 91 "Number of loops without predictable loop counts"); 92 STATISTIC(NumBruteForceTripCountsComputed, 93 "Number of loops with trip counts computed by force"); 94 95 static cl::opt<unsigned> 96 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, 97 cl::desc("Maximum number of iterations SCEV will " 98 "symbolically execute a constant " 99 "derived loop"), 100 cl::init(100)); 101 102 static RegisterPass<ScalarEvolution> 103 R("scalar-evolution", "Scalar Evolution Analysis", false, true); 104 char ScalarEvolution::ID = 0; 105 106 //===----------------------------------------------------------------------===// 107 // SCEV class definitions 108 //===----------------------------------------------------------------------===// 109 110 //===----------------------------------------------------------------------===// 111 // Implementation of the SCEV class. 112 // 113 SCEV::~SCEV() {} 114 void SCEV::dump() const { 115 print(errs()); 116 errs() << '\n'; 117 } 118 119 void SCEV::print(std::ostream &o) const { 120 raw_os_ostream OS(o); 121 print(OS); 122 } 123 124 bool SCEV::isZero() const { 125 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 126 return SC->getValue()->isZero(); 127 return false; 128 } 129 130 bool SCEV::isOne() const { 131 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 132 return SC->getValue()->isOne(); 133 return false; 134 } 135 136 bool SCEV::isAllOnesValue() const { 137 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 138 return SC->getValue()->isAllOnesValue(); 139 return false; 140 } 141 142 SCEVCouldNotCompute::SCEVCouldNotCompute() : 143 SCEV(scCouldNotCompute) {} 144 145 void SCEVCouldNotCompute::Profile(FoldingSetNodeID &ID) const { 146 assert(0 && "Attempt to use a SCEVCouldNotCompute object!"); 147 } 148 149 bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const { 150 assert(0 && "Attempt to use a SCEVCouldNotCompute object!"); 151 return false; 152 } 153 154 const Type *SCEVCouldNotCompute::getType() const { 155 assert(0 && "Attempt to use a SCEVCouldNotCompute object!"); 156 return 0; 157 } 158 159 bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const { 160 assert(0 && "Attempt to use a SCEVCouldNotCompute object!"); 161 return false; 162 } 163 164 const SCEV * 165 SCEVCouldNotCompute::replaceSymbolicValuesWithConcrete( 166 const SCEV *Sym, 167 const SCEV *Conc, 168 ScalarEvolution &SE) const { 169 return this; 170 } 171 172 void SCEVCouldNotCompute::print(raw_ostream &OS) const { 173 OS << "***COULDNOTCOMPUTE***"; 174 } 175 176 bool SCEVCouldNotCompute::classof(const SCEV *S) { 177 return S->getSCEVType() == scCouldNotCompute; 178 } 179 180 const SCEV* ScalarEvolution::getConstant(ConstantInt *V) { 181 FoldingSetNodeID ID; 182 ID.AddInteger(scConstant); 183 ID.AddPointer(V); 184 void *IP = 0; 185 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 186 SCEV *S = SCEVAllocator.Allocate<SCEVConstant>(); 187 new (S) SCEVConstant(V); 188 UniqueSCEVs.InsertNode(S, IP); 189 return S; 190 } 191 192 const SCEV* ScalarEvolution::getConstant(const APInt& Val) { 193 return getConstant(ConstantInt::get(Val)); 194 } 195 196 const SCEV* 197 ScalarEvolution::getConstant(const Type *Ty, uint64_t V, bool isSigned) { 198 return getConstant(ConstantInt::get(cast<IntegerType>(Ty), V, isSigned)); 199 } 200 201 void SCEVConstant::Profile(FoldingSetNodeID &ID) const { 202 ID.AddInteger(scConstant); 203 ID.AddPointer(V); 204 } 205 206 const Type *SCEVConstant::getType() const { return V->getType(); } 207 208 void SCEVConstant::print(raw_ostream &OS) const { 209 WriteAsOperand(OS, V, false); 210 } 211 212 SCEVCastExpr::SCEVCastExpr(unsigned SCEVTy, 213 const SCEV* op, const Type *ty) 214 : SCEV(SCEVTy), Op(op), Ty(ty) {} 215 216 void SCEVCastExpr::Profile(FoldingSetNodeID &ID) const { 217 ID.AddInteger(getSCEVType()); 218 ID.AddPointer(Op); 219 ID.AddPointer(Ty); 220 } 221 222 bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const { 223 return Op->dominates(BB, DT); 224 } 225 226 SCEVTruncateExpr::SCEVTruncateExpr(const SCEV* op, const Type *ty) 227 : SCEVCastExpr(scTruncate, op, ty) { 228 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) && 229 (Ty->isInteger() || isa<PointerType>(Ty)) && 230 "Cannot truncate non-integer value!"); 231 } 232 233 void SCEVTruncateExpr::print(raw_ostream &OS) const { 234 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")"; 235 } 236 237 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEV* op, const Type *ty) 238 : SCEVCastExpr(scZeroExtend, op, ty) { 239 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) && 240 (Ty->isInteger() || isa<PointerType>(Ty)) && 241 "Cannot zero extend non-integer value!"); 242 } 243 244 void SCEVZeroExtendExpr::print(raw_ostream &OS) const { 245 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")"; 246 } 247 248 SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEV* op, const Type *ty) 249 : SCEVCastExpr(scSignExtend, op, ty) { 250 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) && 251 (Ty->isInteger() || isa<PointerType>(Ty)) && 252 "Cannot sign extend non-integer value!"); 253 } 254 255 void SCEVSignExtendExpr::print(raw_ostream &OS) const { 256 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")"; 257 } 258 259 void SCEVCommutativeExpr::print(raw_ostream &OS) const { 260 assert(Operands.size() > 1 && "This plus expr shouldn't exist!"); 261 const char *OpStr = getOperationStr(); 262 OS << "(" << *Operands[0]; 263 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 264 OS << OpStr << *Operands[i]; 265 OS << ")"; 266 } 267 268 const SCEV * 269 SCEVCommutativeExpr::replaceSymbolicValuesWithConcrete( 270 const SCEV *Sym, 271 const SCEV *Conc, 272 ScalarEvolution &SE) const { 273 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 274 const SCEV* H = 275 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE); 276 if (H != getOperand(i)) { 277 SmallVector<const SCEV*, 8> NewOps; 278 NewOps.reserve(getNumOperands()); 279 for (unsigned j = 0; j != i; ++j) 280 NewOps.push_back(getOperand(j)); 281 NewOps.push_back(H); 282 for (++i; i != e; ++i) 283 NewOps.push_back(getOperand(i)-> 284 replaceSymbolicValuesWithConcrete(Sym, Conc, SE)); 285 286 if (isa<SCEVAddExpr>(this)) 287 return SE.getAddExpr(NewOps); 288 else if (isa<SCEVMulExpr>(this)) 289 return SE.getMulExpr(NewOps); 290 else if (isa<SCEVSMaxExpr>(this)) 291 return SE.getSMaxExpr(NewOps); 292 else if (isa<SCEVUMaxExpr>(this)) 293 return SE.getUMaxExpr(NewOps); 294 else 295 assert(0 && "Unknown commutative expr!"); 296 } 297 } 298 return this; 299 } 300 301 void SCEVNAryExpr::Profile(FoldingSetNodeID &ID) const { 302 ID.AddInteger(getSCEVType()); 303 ID.AddInteger(Operands.size()); 304 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 305 ID.AddPointer(Operands[i]); 306 } 307 308 bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const { 309 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 310 if (!getOperand(i)->dominates(BB, DT)) 311 return false; 312 } 313 return true; 314 } 315 316 void SCEVUDivExpr::Profile(FoldingSetNodeID &ID) const { 317 ID.AddInteger(scUDivExpr); 318 ID.AddPointer(LHS); 319 ID.AddPointer(RHS); 320 } 321 322 bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const { 323 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT); 324 } 325 326 void SCEVUDivExpr::print(raw_ostream &OS) const { 327 OS << "(" << *LHS << " /u " << *RHS << ")"; 328 } 329 330 const Type *SCEVUDivExpr::getType() const { 331 // In most cases the types of LHS and RHS will be the same, but in some 332 // crazy cases one or the other may be a pointer. ScalarEvolution doesn't 333 // depend on the type for correctness, but handling types carefully can 334 // avoid extra casts in the SCEVExpander. The LHS is more likely to be 335 // a pointer type than the RHS, so use the RHS' type here. 336 return RHS->getType(); 337 } 338 339 void SCEVAddRecExpr::Profile(FoldingSetNodeID &ID) const { 340 ID.AddInteger(scAddRecExpr); 341 ID.AddInteger(Operands.size()); 342 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 343 ID.AddPointer(Operands[i]); 344 ID.AddPointer(L); 345 } 346 347 const SCEV * 348 SCEVAddRecExpr::replaceSymbolicValuesWithConcrete(const SCEV *Sym, 349 const SCEV *Conc, 350 ScalarEvolution &SE) const { 351 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 352 const SCEV* H = 353 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE); 354 if (H != getOperand(i)) { 355 SmallVector<const SCEV*, 8> NewOps; 356 NewOps.reserve(getNumOperands()); 357 for (unsigned j = 0; j != i; ++j) 358 NewOps.push_back(getOperand(j)); 359 NewOps.push_back(H); 360 for (++i; i != e; ++i) 361 NewOps.push_back(getOperand(i)-> 362 replaceSymbolicValuesWithConcrete(Sym, Conc, SE)); 363 364 return SE.getAddRecExpr(NewOps, L); 365 } 366 } 367 return this; 368 } 369 370 371 bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const { 372 // Add recurrences are never invariant in the function-body (null loop). 373 if (!QueryLoop) 374 return false; 375 376 // This recurrence is variant w.r.t. QueryLoop if QueryLoop contains L. 377 if (QueryLoop->contains(L->getHeader())) 378 return false; 379 380 // This recurrence is variant w.r.t. QueryLoop if any of its operands 381 // are variant. 382 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) 383 if (!getOperand(i)->isLoopInvariant(QueryLoop)) 384 return false; 385 386 // Otherwise it's loop-invariant. 387 return true; 388 } 389 390 391 void SCEVAddRecExpr::print(raw_ostream &OS) const { 392 OS << "{" << *Operands[0]; 393 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 394 OS << ",+," << *Operands[i]; 395 OS << "}<" << L->getHeader()->getName() + ">"; 396 } 397 398 void SCEVUnknown::Profile(FoldingSetNodeID &ID) const { 399 ID.AddInteger(scUnknown); 400 ID.AddPointer(V); 401 } 402 403 bool SCEVUnknown::isLoopInvariant(const Loop *L) const { 404 // All non-instruction values are loop invariant. All instructions are loop 405 // invariant if they are not contained in the specified loop. 406 // Instructions are never considered invariant in the function body 407 // (null loop) because they are defined within the "loop". 408 if (Instruction *I = dyn_cast<Instruction>(V)) 409 return L && !L->contains(I->getParent()); 410 return true; 411 } 412 413 bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const { 414 if (Instruction *I = dyn_cast<Instruction>(getValue())) 415 return DT->dominates(I->getParent(), BB); 416 return true; 417 } 418 419 const Type *SCEVUnknown::getType() const { 420 return V->getType(); 421 } 422 423 void SCEVUnknown::print(raw_ostream &OS) const { 424 WriteAsOperand(OS, V, false); 425 } 426 427 //===----------------------------------------------------------------------===// 428 // SCEV Utilities 429 //===----------------------------------------------------------------------===// 430 431 namespace { 432 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less 433 /// than the complexity of the RHS. This comparator is used to canonicalize 434 /// expressions. 435 class VISIBILITY_HIDDEN SCEVComplexityCompare { 436 LoopInfo *LI; 437 public: 438 explicit SCEVComplexityCompare(LoopInfo *li) : LI(li) {} 439 440 bool operator()(const SCEV *LHS, const SCEV *RHS) const { 441 // Primarily, sort the SCEVs by their getSCEVType(). 442 if (LHS->getSCEVType() != RHS->getSCEVType()) 443 return LHS->getSCEVType() < RHS->getSCEVType(); 444 445 // Aside from the getSCEVType() ordering, the particular ordering 446 // isn't very important except that it's beneficial to be consistent, 447 // so that (a + b) and (b + a) don't end up as different expressions. 448 449 // Sort SCEVUnknown values with some loose heuristics. TODO: This is 450 // not as complete as it could be. 451 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) { 452 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); 453 454 // Order pointer values after integer values. This helps SCEVExpander 455 // form GEPs. 456 if (isa<PointerType>(LU->getType()) && !isa<PointerType>(RU->getType())) 457 return false; 458 if (isa<PointerType>(RU->getType()) && !isa<PointerType>(LU->getType())) 459 return true; 460 461 // Compare getValueID values. 462 if (LU->getValue()->getValueID() != RU->getValue()->getValueID()) 463 return LU->getValue()->getValueID() < RU->getValue()->getValueID(); 464 465 // Sort arguments by their position. 466 if (const Argument *LA = dyn_cast<Argument>(LU->getValue())) { 467 const Argument *RA = cast<Argument>(RU->getValue()); 468 return LA->getArgNo() < RA->getArgNo(); 469 } 470 471 // For instructions, compare their loop depth, and their opcode. 472 // This is pretty loose. 473 if (Instruction *LV = dyn_cast<Instruction>(LU->getValue())) { 474 Instruction *RV = cast<Instruction>(RU->getValue()); 475 476 // Compare loop depths. 477 if (LI->getLoopDepth(LV->getParent()) != 478 LI->getLoopDepth(RV->getParent())) 479 return LI->getLoopDepth(LV->getParent()) < 480 LI->getLoopDepth(RV->getParent()); 481 482 // Compare opcodes. 483 if (LV->getOpcode() != RV->getOpcode()) 484 return LV->getOpcode() < RV->getOpcode(); 485 486 // Compare the number of operands. 487 if (LV->getNumOperands() != RV->getNumOperands()) 488 return LV->getNumOperands() < RV->getNumOperands(); 489 } 490 491 return false; 492 } 493 494 // Compare constant values. 495 if (const SCEVConstant *LC = dyn_cast<SCEVConstant>(LHS)) { 496 const SCEVConstant *RC = cast<SCEVConstant>(RHS); 497 return LC->getValue()->getValue().ult(RC->getValue()->getValue()); 498 } 499 500 // Compare addrec loop depths. 501 if (const SCEVAddRecExpr *LA = dyn_cast<SCEVAddRecExpr>(LHS)) { 502 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); 503 if (LA->getLoop()->getLoopDepth() != RA->getLoop()->getLoopDepth()) 504 return LA->getLoop()->getLoopDepth() < RA->getLoop()->getLoopDepth(); 505 } 506 507 // Lexicographically compare n-ary expressions. 508 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) { 509 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); 510 for (unsigned i = 0, e = LC->getNumOperands(); i != e; ++i) { 511 if (i >= RC->getNumOperands()) 512 return false; 513 if (operator()(LC->getOperand(i), RC->getOperand(i))) 514 return true; 515 if (operator()(RC->getOperand(i), LC->getOperand(i))) 516 return false; 517 } 518 return LC->getNumOperands() < RC->getNumOperands(); 519 } 520 521 // Lexicographically compare udiv expressions. 522 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) { 523 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); 524 if (operator()(LC->getLHS(), RC->getLHS())) 525 return true; 526 if (operator()(RC->getLHS(), LC->getLHS())) 527 return false; 528 if (operator()(LC->getRHS(), RC->getRHS())) 529 return true; 530 if (operator()(RC->getRHS(), LC->getRHS())) 531 return false; 532 return false; 533 } 534 535 // Compare cast expressions by operand. 536 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) { 537 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS); 538 return operator()(LC->getOperand(), RC->getOperand()); 539 } 540 541 assert(0 && "Unknown SCEV kind!"); 542 return false; 543 } 544 }; 545 } 546 547 /// GroupByComplexity - Given a list of SCEV objects, order them by their 548 /// complexity, and group objects of the same complexity together by value. 549 /// When this routine is finished, we know that any duplicates in the vector are 550 /// consecutive and that complexity is monotonically increasing. 551 /// 552 /// Note that we go take special precautions to ensure that we get determinstic 553 /// results from this routine. In other words, we don't want the results of 554 /// this to depend on where the addresses of various SCEV objects happened to 555 /// land in memory. 556 /// 557 static void GroupByComplexity(SmallVectorImpl<const SCEV*> &Ops, 558 LoopInfo *LI) { 559 if (Ops.size() < 2) return; // Noop 560 if (Ops.size() == 2) { 561 // This is the common case, which also happens to be trivially simple. 562 // Special case it. 563 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0])) 564 std::swap(Ops[0], Ops[1]); 565 return; 566 } 567 568 // Do the rough sort by complexity. 569 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI)); 570 571 // Now that we are sorted by complexity, group elements of the same 572 // complexity. Note that this is, at worst, N^2, but the vector is likely to 573 // be extremely short in practice. Note that we take this approach because we 574 // do not want to depend on the addresses of the objects we are grouping. 575 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { 576 const SCEV *S = Ops[i]; 577 unsigned Complexity = S->getSCEVType(); 578 579 // If there are any objects of the same complexity and same value as this 580 // one, group them. 581 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { 582 if (Ops[j] == S) { // Found a duplicate. 583 // Move it to immediately after i'th element. 584 std::swap(Ops[i+1], Ops[j]); 585 ++i; // no need to rescan it. 586 if (i == e-2) return; // Done! 587 } 588 } 589 } 590 } 591 592 593 594 //===----------------------------------------------------------------------===// 595 // Simple SCEV method implementations 596 //===----------------------------------------------------------------------===// 597 598 /// BinomialCoefficient - Compute BC(It, K). The result has width W. 599 /// Assume, K > 0. 600 static const SCEV* BinomialCoefficient(const SCEV* It, unsigned K, 601 ScalarEvolution &SE, 602 const Type* ResultTy) { 603 // Handle the simplest case efficiently. 604 if (K == 1) 605 return SE.getTruncateOrZeroExtend(It, ResultTy); 606 607 // We are using the following formula for BC(It, K): 608 // 609 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! 610 // 611 // Suppose, W is the bitwidth of the return value. We must be prepared for 612 // overflow. Hence, we must assure that the result of our computation is 613 // equal to the accurate one modulo 2^W. Unfortunately, division isn't 614 // safe in modular arithmetic. 615 // 616 // However, this code doesn't use exactly that formula; the formula it uses 617 // is something like the following, where T is the number of factors of 2 in 618 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is 619 // exponentiation: 620 // 621 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) 622 // 623 // This formula is trivially equivalent to the previous formula. However, 624 // this formula can be implemented much more efficiently. The trick is that 625 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular 626 // arithmetic. To do exact division in modular arithmetic, all we have 627 // to do is multiply by the inverse. Therefore, this step can be done at 628 // width W. 629 // 630 // The next issue is how to safely do the division by 2^T. The way this 631 // is done is by doing the multiplication step at a width of at least W + T 632 // bits. This way, the bottom W+T bits of the product are accurate. Then, 633 // when we perform the division by 2^T (which is equivalent to a right shift 634 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get 635 // truncated out after the division by 2^T. 636 // 637 // In comparison to just directly using the first formula, this technique 638 // is much more efficient; using the first formula requires W * K bits, 639 // but this formula less than W + K bits. Also, the first formula requires 640 // a division step, whereas this formula only requires multiplies and shifts. 641 // 642 // It doesn't matter whether the subtraction step is done in the calculation 643 // width or the input iteration count's width; if the subtraction overflows, 644 // the result must be zero anyway. We prefer here to do it in the width of 645 // the induction variable because it helps a lot for certain cases; CodeGen 646 // isn't smart enough to ignore the overflow, which leads to much less 647 // efficient code if the width of the subtraction is wider than the native 648 // register width. 649 // 650 // (It's possible to not widen at all by pulling out factors of 2 before 651 // the multiplication; for example, K=2 can be calculated as 652 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires 653 // extra arithmetic, so it's not an obvious win, and it gets 654 // much more complicated for K > 3.) 655 656 // Protection from insane SCEVs; this bound is conservative, 657 // but it probably doesn't matter. 658 if (K > 1000) 659 return SE.getCouldNotCompute(); 660 661 unsigned W = SE.getTypeSizeInBits(ResultTy); 662 663 // Calculate K! / 2^T and T; we divide out the factors of two before 664 // multiplying for calculating K! / 2^T to avoid overflow. 665 // Other overflow doesn't matter because we only care about the bottom 666 // W bits of the result. 667 APInt OddFactorial(W, 1); 668 unsigned T = 1; 669 for (unsigned i = 3; i <= K; ++i) { 670 APInt Mult(W, i); 671 unsigned TwoFactors = Mult.countTrailingZeros(); 672 T += TwoFactors; 673 Mult = Mult.lshr(TwoFactors); 674 OddFactorial *= Mult; 675 } 676 677 // We need at least W + T bits for the multiplication step 678 unsigned CalculationBits = W + T; 679 680 // Calcuate 2^T, at width T+W. 681 APInt DivFactor = APInt(CalculationBits, 1).shl(T); 682 683 // Calculate the multiplicative inverse of K! / 2^T; 684 // this multiplication factor will perform the exact division by 685 // K! / 2^T. 686 APInt Mod = APInt::getSignedMinValue(W+1); 687 APInt MultiplyFactor = OddFactorial.zext(W+1); 688 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); 689 MultiplyFactor = MultiplyFactor.trunc(W); 690 691 // Calculate the product, at width T+W 692 const IntegerType *CalculationTy = IntegerType::get(CalculationBits); 693 const SCEV* Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); 694 for (unsigned i = 1; i != K; ++i) { 695 const SCEV* S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType())); 696 Dividend = SE.getMulExpr(Dividend, 697 SE.getTruncateOrZeroExtend(S, CalculationTy)); 698 } 699 700 // Divide by 2^T 701 const SCEV* DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); 702 703 // Truncate the result, and divide by K! / 2^T. 704 705 return SE.getMulExpr(SE.getConstant(MultiplyFactor), 706 SE.getTruncateOrZeroExtend(DivResult, ResultTy)); 707 } 708 709 /// evaluateAtIteration - Return the value of this chain of recurrences at 710 /// the specified iteration number. We can evaluate this recurrence by 711 /// multiplying each element in the chain by the binomial coefficient 712 /// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as: 713 /// 714 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) 715 /// 716 /// where BC(It, k) stands for binomial coefficient. 717 /// 718 const SCEV* SCEVAddRecExpr::evaluateAtIteration(const SCEV* It, 719 ScalarEvolution &SE) const { 720 const SCEV* Result = getStart(); 721 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 722 // The computation is correct in the face of overflow provided that the 723 // multiplication is performed _after_ the evaluation of the binomial 724 // coefficient. 725 const SCEV* Coeff = BinomialCoefficient(It, i, SE, getType()); 726 if (isa<SCEVCouldNotCompute>(Coeff)) 727 return Coeff; 728 729 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff)); 730 } 731 return Result; 732 } 733 734 //===----------------------------------------------------------------------===// 735 // SCEV Expression folder implementations 736 //===----------------------------------------------------------------------===// 737 738 const SCEV* ScalarEvolution::getTruncateExpr(const SCEV* Op, 739 const Type *Ty) { 740 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && 741 "This is not a truncating conversion!"); 742 assert(isSCEVable(Ty) && 743 "This is not a conversion to a SCEVable type!"); 744 Ty = getEffectiveSCEVType(Ty); 745 746 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 747 return getConstant( 748 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); 749 750 // trunc(trunc(x)) --> trunc(x) 751 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) 752 return getTruncateExpr(ST->getOperand(), Ty); 753 754 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing 755 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 756 return getTruncateOrSignExtend(SS->getOperand(), Ty); 757 758 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing 759 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 760 return getTruncateOrZeroExtend(SZ->getOperand(), Ty); 761 762 // If the input value is a chrec scev, truncate the chrec's operands. 763 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 764 SmallVector<const SCEV*, 4> Operands; 765 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 766 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty)); 767 return getAddRecExpr(Operands, AddRec->getLoop()); 768 } 769 770 FoldingSetNodeID ID; 771 ID.AddInteger(scTruncate); 772 ID.AddPointer(Op); 773 ID.AddPointer(Ty); 774 void *IP = 0; 775 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 776 SCEV *S = SCEVAllocator.Allocate<SCEVTruncateExpr>(); 777 new (S) SCEVTruncateExpr(Op, Ty); 778 UniqueSCEVs.InsertNode(S, IP); 779 return S; 780 } 781 782 const SCEV* ScalarEvolution::getZeroExtendExpr(const SCEV* Op, 783 const Type *Ty) { 784 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 785 "This is not an extending conversion!"); 786 assert(isSCEVable(Ty) && 787 "This is not a conversion to a SCEVable type!"); 788 Ty = getEffectiveSCEVType(Ty); 789 790 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) { 791 const Type *IntTy = getEffectiveSCEVType(Ty); 792 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy); 793 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty); 794 return getConstant(cast<ConstantInt>(C)); 795 } 796 797 // zext(zext(x)) --> zext(x) 798 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 799 return getZeroExtendExpr(SZ->getOperand(), Ty); 800 801 // If the input value is a chrec scev, and we can prove that the value 802 // did not overflow the old, smaller, value, we can zero extend all of the 803 // operands (often constants). This allows analysis of something like 804 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } 805 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 806 if (AR->isAffine()) { 807 // Check whether the backedge-taken count is SCEVCouldNotCompute. 808 // Note that this serves two purposes: It filters out loops that are 809 // simply not analyzable, and it covers the case where this code is 810 // being called from within backedge-taken count analysis, such that 811 // attempting to ask for the backedge-taken count would likely result 812 // in infinite recursion. In the later case, the analysis code will 813 // cope with a conservative value, and it will take care to purge 814 // that value once it has finished. 815 const SCEV* MaxBECount = getMaxBackedgeTakenCount(AR->getLoop()); 816 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 817 // Manually compute the final value for AR, checking for 818 // overflow. 819 const SCEV* Start = AR->getStart(); 820 const SCEV* Step = AR->getStepRecurrence(*this); 821 822 // Check whether the backedge-taken count can be losslessly casted to 823 // the addrec's type. The count is always unsigned. 824 const SCEV* CastedMaxBECount = 825 getTruncateOrZeroExtend(MaxBECount, Start->getType()); 826 const SCEV* RecastedMaxBECount = 827 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); 828 if (MaxBECount == RecastedMaxBECount) { 829 const Type *WideTy = 830 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2); 831 // Check whether Start+Step*MaxBECount has no unsigned overflow. 832 const SCEV* ZMul = 833 getMulExpr(CastedMaxBECount, 834 getTruncateOrZeroExtend(Step, Start->getType())); 835 const SCEV* Add = getAddExpr(Start, ZMul); 836 const SCEV* OperandExtendedAdd = 837 getAddExpr(getZeroExtendExpr(Start, WideTy), 838 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy), 839 getZeroExtendExpr(Step, WideTy))); 840 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd) 841 // Return the expression with the addrec on the outside. 842 return getAddRecExpr(getZeroExtendExpr(Start, Ty), 843 getZeroExtendExpr(Step, Ty), 844 AR->getLoop()); 845 846 // Similar to above, only this time treat the step value as signed. 847 // This covers loops that count down. 848 const SCEV* SMul = 849 getMulExpr(CastedMaxBECount, 850 getTruncateOrSignExtend(Step, Start->getType())); 851 Add = getAddExpr(Start, SMul); 852 OperandExtendedAdd = 853 getAddExpr(getZeroExtendExpr(Start, WideTy), 854 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy), 855 getSignExtendExpr(Step, WideTy))); 856 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd) 857 // Return the expression with the addrec on the outside. 858 return getAddRecExpr(getZeroExtendExpr(Start, Ty), 859 getSignExtendExpr(Step, Ty), 860 AR->getLoop()); 861 } 862 } 863 } 864 865 FoldingSetNodeID ID; 866 ID.AddInteger(scZeroExtend); 867 ID.AddPointer(Op); 868 ID.AddPointer(Ty); 869 void *IP = 0; 870 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 871 SCEV *S = SCEVAllocator.Allocate<SCEVZeroExtendExpr>(); 872 new (S) SCEVZeroExtendExpr(Op, Ty); 873 UniqueSCEVs.InsertNode(S, IP); 874 return S; 875 } 876 877 const SCEV* ScalarEvolution::getSignExtendExpr(const SCEV* Op, 878 const Type *Ty) { 879 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 880 "This is not an extending conversion!"); 881 assert(isSCEVable(Ty) && 882 "This is not a conversion to a SCEVable type!"); 883 Ty = getEffectiveSCEVType(Ty); 884 885 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) { 886 const Type *IntTy = getEffectiveSCEVType(Ty); 887 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy); 888 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty); 889 return getConstant(cast<ConstantInt>(C)); 890 } 891 892 // sext(sext(x)) --> sext(x) 893 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 894 return getSignExtendExpr(SS->getOperand(), Ty); 895 896 // If the input value is a chrec scev, and we can prove that the value 897 // did not overflow the old, smaller, value, we can sign extend all of the 898 // operands (often constants). This allows analysis of something like 899 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 900 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 901 if (AR->isAffine()) { 902 // Check whether the backedge-taken count is SCEVCouldNotCompute. 903 // Note that this serves two purposes: It filters out loops that are 904 // simply not analyzable, and it covers the case where this code is 905 // being called from within backedge-taken count analysis, such that 906 // attempting to ask for the backedge-taken count would likely result 907 // in infinite recursion. In the later case, the analysis code will 908 // cope with a conservative value, and it will take care to purge 909 // that value once it has finished. 910 const SCEV* MaxBECount = getMaxBackedgeTakenCount(AR->getLoop()); 911 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 912 // Manually compute the final value for AR, checking for 913 // overflow. 914 const SCEV* Start = AR->getStart(); 915 const SCEV* Step = AR->getStepRecurrence(*this); 916 917 // Check whether the backedge-taken count can be losslessly casted to 918 // the addrec's type. The count is always unsigned. 919 const SCEV* CastedMaxBECount = 920 getTruncateOrZeroExtend(MaxBECount, Start->getType()); 921 const SCEV* RecastedMaxBECount = 922 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); 923 if (MaxBECount == RecastedMaxBECount) { 924 const Type *WideTy = 925 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2); 926 // Check whether Start+Step*MaxBECount has no signed overflow. 927 const SCEV* SMul = 928 getMulExpr(CastedMaxBECount, 929 getTruncateOrSignExtend(Step, Start->getType())); 930 const SCEV* Add = getAddExpr(Start, SMul); 931 const SCEV* OperandExtendedAdd = 932 getAddExpr(getSignExtendExpr(Start, WideTy), 933 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy), 934 getSignExtendExpr(Step, WideTy))); 935 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd) 936 // Return the expression with the addrec on the outside. 937 return getAddRecExpr(getSignExtendExpr(Start, Ty), 938 getSignExtendExpr(Step, Ty), 939 AR->getLoop()); 940 } 941 } 942 } 943 944 FoldingSetNodeID ID; 945 ID.AddInteger(scSignExtend); 946 ID.AddPointer(Op); 947 ID.AddPointer(Ty); 948 void *IP = 0; 949 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 950 SCEV *S = SCEVAllocator.Allocate<SCEVSignExtendExpr>(); 951 new (S) SCEVSignExtendExpr(Op, Ty); 952 UniqueSCEVs.InsertNode(S, IP); 953 return S; 954 } 955 956 /// getAnyExtendExpr - Return a SCEV for the given operand extended with 957 /// unspecified bits out to the given type. 958 /// 959 const SCEV* ScalarEvolution::getAnyExtendExpr(const SCEV* Op, 960 const Type *Ty) { 961 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 962 "This is not an extending conversion!"); 963 assert(isSCEVable(Ty) && 964 "This is not a conversion to a SCEVable type!"); 965 Ty = getEffectiveSCEVType(Ty); 966 967 // Sign-extend negative constants. 968 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 969 if (SC->getValue()->getValue().isNegative()) 970 return getSignExtendExpr(Op, Ty); 971 972 // Peel off a truncate cast. 973 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { 974 const SCEV* NewOp = T->getOperand(); 975 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) 976 return getAnyExtendExpr(NewOp, Ty); 977 return getTruncateOrNoop(NewOp, Ty); 978 } 979 980 // Next try a zext cast. If the cast is folded, use it. 981 const SCEV* ZExt = getZeroExtendExpr(Op, Ty); 982 if (!isa<SCEVZeroExtendExpr>(ZExt)) 983 return ZExt; 984 985 // Next try a sext cast. If the cast is folded, use it. 986 const SCEV* SExt = getSignExtendExpr(Op, Ty); 987 if (!isa<SCEVSignExtendExpr>(SExt)) 988 return SExt; 989 990 // If the expression is obviously signed, use the sext cast value. 991 if (isa<SCEVSMaxExpr>(Op)) 992 return SExt; 993 994 // Absent any other information, use the zext cast value. 995 return ZExt; 996 } 997 998 /// CollectAddOperandsWithScales - Process the given Ops list, which is 999 /// a list of operands to be added under the given scale, update the given 1000 /// map. This is a helper function for getAddRecExpr. As an example of 1001 /// what it does, given a sequence of operands that would form an add 1002 /// expression like this: 1003 /// 1004 /// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r) 1005 /// 1006 /// where A and B are constants, update the map with these values: 1007 /// 1008 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) 1009 /// 1010 /// and add 13 + A*B*29 to AccumulatedConstant. 1011 /// This will allow getAddRecExpr to produce this: 1012 /// 1013 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) 1014 /// 1015 /// This form often exposes folding opportunities that are hidden in 1016 /// the original operand list. 1017 /// 1018 /// Return true iff it appears that any interesting folding opportunities 1019 /// may be exposed. This helps getAddRecExpr short-circuit extra work in 1020 /// the common case where no interesting opportunities are present, and 1021 /// is also used as a check to avoid infinite recursion. 1022 /// 1023 static bool 1024 CollectAddOperandsWithScales(DenseMap<const SCEV*, APInt> &M, 1025 SmallVector<const SCEV*, 8> &NewOps, 1026 APInt &AccumulatedConstant, 1027 const SmallVectorImpl<const SCEV*> &Ops, 1028 const APInt &Scale, 1029 ScalarEvolution &SE) { 1030 bool Interesting = false; 1031 1032 // Iterate over the add operands. 1033 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 1034 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); 1035 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { 1036 APInt NewScale = 1037 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue(); 1038 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { 1039 // A multiplication of a constant with another add; recurse. 1040 Interesting |= 1041 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 1042 cast<SCEVAddExpr>(Mul->getOperand(1)) 1043 ->getOperands(), 1044 NewScale, SE); 1045 } else { 1046 // A multiplication of a constant with some other value. Update 1047 // the map. 1048 SmallVector<const SCEV*, 4> MulOps(Mul->op_begin()+1, Mul->op_end()); 1049 const SCEV* Key = SE.getMulExpr(MulOps); 1050 std::pair<DenseMap<const SCEV*, APInt>::iterator, bool> Pair = 1051 M.insert(std::make_pair(Key, NewScale)); 1052 if (Pair.second) { 1053 NewOps.push_back(Pair.first->first); 1054 } else { 1055 Pair.first->second += NewScale; 1056 // The map already had an entry for this value, which may indicate 1057 // a folding opportunity. 1058 Interesting = true; 1059 } 1060 } 1061 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 1062 // Pull a buried constant out to the outside. 1063 if (Scale != 1 || AccumulatedConstant != 0 || C->isZero()) 1064 Interesting = true; 1065 AccumulatedConstant += Scale * C->getValue()->getValue(); 1066 } else { 1067 // An ordinary operand. Update the map. 1068 std::pair<DenseMap<const SCEV*, APInt>::iterator, bool> Pair = 1069 M.insert(std::make_pair(Ops[i], Scale)); 1070 if (Pair.second) { 1071 NewOps.push_back(Pair.first->first); 1072 } else { 1073 Pair.first->second += Scale; 1074 // The map already had an entry for this value, which may indicate 1075 // a folding opportunity. 1076 Interesting = true; 1077 } 1078 } 1079 } 1080 1081 return Interesting; 1082 } 1083 1084 namespace { 1085 struct APIntCompare { 1086 bool operator()(const APInt &LHS, const APInt &RHS) const { 1087 return LHS.ult(RHS); 1088 } 1089 }; 1090 } 1091 1092 /// getAddExpr - Get a canonical add expression, or something simpler if 1093 /// possible. 1094 const SCEV* ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV*> &Ops) { 1095 assert(!Ops.empty() && "Cannot get empty add!"); 1096 if (Ops.size() == 1) return Ops[0]; 1097 #ifndef NDEBUG 1098 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 1099 assert(getEffectiveSCEVType(Ops[i]->getType()) == 1100 getEffectiveSCEVType(Ops[0]->getType()) && 1101 "SCEVAddExpr operand types don't match!"); 1102 #endif 1103 1104 // Sort by complexity, this groups all similar expression types together. 1105 GroupByComplexity(Ops, LI); 1106 1107 // If there are any constants, fold them together. 1108 unsigned Idx = 0; 1109 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 1110 ++Idx; 1111 assert(Idx < Ops.size()); 1112 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 1113 // We found two constants, fold them together! 1114 Ops[0] = getConstant(LHSC->getValue()->getValue() + 1115 RHSC->getValue()->getValue()); 1116 if (Ops.size() == 2) return Ops[0]; 1117 Ops.erase(Ops.begin()+1); // Erase the folded element 1118 LHSC = cast<SCEVConstant>(Ops[0]); 1119 } 1120 1121 // If we are left with a constant zero being added, strip it off. 1122 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) { 1123 Ops.erase(Ops.begin()); 1124 --Idx; 1125 } 1126 } 1127 1128 if (Ops.size() == 1) return Ops[0]; 1129 1130 // Okay, check to see if the same value occurs in the operand list twice. If 1131 // so, merge them together into an multiply expression. Since we sorted the 1132 // list, these values are required to be adjacent. 1133 const Type *Ty = Ops[0]->getType(); 1134 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 1135 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 1136 // Found a match, merge the two values into a multiply, and add any 1137 // remaining values to the result. 1138 const SCEV* Two = getIntegerSCEV(2, Ty); 1139 const SCEV* Mul = getMulExpr(Ops[i], Two); 1140 if (Ops.size() == 2) 1141 return Mul; 1142 Ops.erase(Ops.begin()+i, Ops.begin()+i+2); 1143 Ops.push_back(Mul); 1144 return getAddExpr(Ops); 1145 } 1146 1147 // Check for truncates. If all the operands are truncated from the same 1148 // type, see if factoring out the truncate would permit the result to be 1149 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n) 1150 // if the contents of the resulting outer trunc fold to something simple. 1151 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) { 1152 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]); 1153 const Type *DstType = Trunc->getType(); 1154 const Type *SrcType = Trunc->getOperand()->getType(); 1155 SmallVector<const SCEV*, 8> LargeOps; 1156 bool Ok = true; 1157 // Check all the operands to see if they can be represented in the 1158 // source type of the truncate. 1159 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 1160 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 1161 if (T->getOperand()->getType() != SrcType) { 1162 Ok = false; 1163 break; 1164 } 1165 LargeOps.push_back(T->getOperand()); 1166 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 1167 // This could be either sign or zero extension, but sign extension 1168 // is much more likely to be foldable here. 1169 LargeOps.push_back(getSignExtendExpr(C, SrcType)); 1170 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 1171 SmallVector<const SCEV*, 8> LargeMulOps; 1172 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 1173 if (const SCEVTruncateExpr *T = 1174 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 1175 if (T->getOperand()->getType() != SrcType) { 1176 Ok = false; 1177 break; 1178 } 1179 LargeMulOps.push_back(T->getOperand()); 1180 } else if (const SCEVConstant *C = 1181 dyn_cast<SCEVConstant>(M->getOperand(j))) { 1182 // This could be either sign or zero extension, but sign extension 1183 // is much more likely to be foldable here. 1184 LargeMulOps.push_back(getSignExtendExpr(C, SrcType)); 1185 } else { 1186 Ok = false; 1187 break; 1188 } 1189 } 1190 if (Ok) 1191 LargeOps.push_back(getMulExpr(LargeMulOps)); 1192 } else { 1193 Ok = false; 1194 break; 1195 } 1196 } 1197 if (Ok) { 1198 // Evaluate the expression in the larger type. 1199 const SCEV* Fold = getAddExpr(LargeOps); 1200 // If it folds to something simple, use it. Otherwise, don't. 1201 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 1202 return getTruncateExpr(Fold, DstType); 1203 } 1204 } 1205 1206 // Skip past any other cast SCEVs. 1207 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 1208 ++Idx; 1209 1210 // If there are add operands they would be next. 1211 if (Idx < Ops.size()) { 1212 bool DeletedAdd = false; 1213 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 1214 // If we have an add, expand the add operands onto the end of the operands 1215 // list. 1216 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end()); 1217 Ops.erase(Ops.begin()+Idx); 1218 DeletedAdd = true; 1219 } 1220 1221 // If we deleted at least one add, we added operands to the end of the list, 1222 // and they are not necessarily sorted. Recurse to resort and resimplify 1223 // any operands we just aquired. 1224 if (DeletedAdd) 1225 return getAddExpr(Ops); 1226 } 1227 1228 // Skip over the add expression until we get to a multiply. 1229 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 1230 ++Idx; 1231 1232 // Check to see if there are any folding opportunities present with 1233 // operands multiplied by constant values. 1234 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 1235 uint64_t BitWidth = getTypeSizeInBits(Ty); 1236 DenseMap<const SCEV*, APInt> M; 1237 SmallVector<const SCEV*, 8> NewOps; 1238 APInt AccumulatedConstant(BitWidth, 0); 1239 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 1240 Ops, APInt(BitWidth, 1), *this)) { 1241 // Some interesting folding opportunity is present, so its worthwhile to 1242 // re-generate the operands list. Group the operands by constant scale, 1243 // to avoid multiplying by the same constant scale multiple times. 1244 std::map<APInt, SmallVector<const SCEV*, 4>, APIntCompare> MulOpLists; 1245 for (SmallVector<const SCEV*, 8>::iterator I = NewOps.begin(), 1246 E = NewOps.end(); I != E; ++I) 1247 MulOpLists[M.find(*I)->second].push_back(*I); 1248 // Re-generate the operands list. 1249 Ops.clear(); 1250 if (AccumulatedConstant != 0) 1251 Ops.push_back(getConstant(AccumulatedConstant)); 1252 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator 1253 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I) 1254 if (I->first != 0) 1255 Ops.push_back(getMulExpr(getConstant(I->first), 1256 getAddExpr(I->second))); 1257 if (Ops.empty()) 1258 return getIntegerSCEV(0, Ty); 1259 if (Ops.size() == 1) 1260 return Ops[0]; 1261 return getAddExpr(Ops); 1262 } 1263 } 1264 1265 // If we are adding something to a multiply expression, make sure the 1266 // something is not already an operand of the multiply. If so, merge it into 1267 // the multiply. 1268 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 1269 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 1270 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 1271 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 1272 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 1273 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(Ops[AddOp])) { 1274 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 1275 const SCEV* InnerMul = Mul->getOperand(MulOp == 0); 1276 if (Mul->getNumOperands() != 2) { 1277 // If the multiply has more than two operands, we must get the 1278 // Y*Z term. 1279 SmallVector<const SCEV*, 4> MulOps(Mul->op_begin(), Mul->op_end()); 1280 MulOps.erase(MulOps.begin()+MulOp); 1281 InnerMul = getMulExpr(MulOps); 1282 } 1283 const SCEV* One = getIntegerSCEV(1, Ty); 1284 const SCEV* AddOne = getAddExpr(InnerMul, One); 1285 const SCEV* OuterMul = getMulExpr(AddOne, Ops[AddOp]); 1286 if (Ops.size() == 2) return OuterMul; 1287 if (AddOp < Idx) { 1288 Ops.erase(Ops.begin()+AddOp); 1289 Ops.erase(Ops.begin()+Idx-1); 1290 } else { 1291 Ops.erase(Ops.begin()+Idx); 1292 Ops.erase(Ops.begin()+AddOp-1); 1293 } 1294 Ops.push_back(OuterMul); 1295 return getAddExpr(Ops); 1296 } 1297 1298 // Check this multiply against other multiplies being added together. 1299 for (unsigned OtherMulIdx = Idx+1; 1300 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 1301 ++OtherMulIdx) { 1302 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 1303 // If MulOp occurs in OtherMul, we can fold the two multiplies 1304 // together. 1305 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 1306 OMulOp != e; ++OMulOp) 1307 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 1308 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 1309 const SCEV* InnerMul1 = Mul->getOperand(MulOp == 0); 1310 if (Mul->getNumOperands() != 2) { 1311 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 1312 Mul->op_end()); 1313 MulOps.erase(MulOps.begin()+MulOp); 1314 InnerMul1 = getMulExpr(MulOps); 1315 } 1316 const SCEV* InnerMul2 = OtherMul->getOperand(OMulOp == 0); 1317 if (OtherMul->getNumOperands() != 2) { 1318 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 1319 OtherMul->op_end()); 1320 MulOps.erase(MulOps.begin()+OMulOp); 1321 InnerMul2 = getMulExpr(MulOps); 1322 } 1323 const SCEV* InnerMulSum = getAddExpr(InnerMul1,InnerMul2); 1324 const SCEV* OuterMul = getMulExpr(MulOpSCEV, InnerMulSum); 1325 if (Ops.size() == 2) return OuterMul; 1326 Ops.erase(Ops.begin()+Idx); 1327 Ops.erase(Ops.begin()+OtherMulIdx-1); 1328 Ops.push_back(OuterMul); 1329 return getAddExpr(Ops); 1330 } 1331 } 1332 } 1333 } 1334 1335 // If there are any add recurrences in the operands list, see if any other 1336 // added values are loop invariant. If so, we can fold them into the 1337 // recurrence. 1338 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 1339 ++Idx; 1340 1341 // Scan over all recurrences, trying to fold loop invariants into them. 1342 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 1343 // Scan all of the other operands to this add and add them to the vector if 1344 // they are loop invariant w.r.t. the recurrence. 1345 SmallVector<const SCEV*, 8> LIOps; 1346 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 1347 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 1348 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) { 1349 LIOps.push_back(Ops[i]); 1350 Ops.erase(Ops.begin()+i); 1351 --i; --e; 1352 } 1353 1354 // If we found some loop invariants, fold them into the recurrence. 1355 if (!LIOps.empty()) { 1356 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 1357 LIOps.push_back(AddRec->getStart()); 1358 1359 SmallVector<const SCEV*, 4> AddRecOps(AddRec->op_begin(), 1360 AddRec->op_end()); 1361 AddRecOps[0] = getAddExpr(LIOps); 1362 1363 const SCEV* NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop()); 1364 // If all of the other operands were loop invariant, we are done. 1365 if (Ops.size() == 1) return NewRec; 1366 1367 // Otherwise, add the folded AddRec by the non-liv parts. 1368 for (unsigned i = 0;; ++i) 1369 if (Ops[i] == AddRec) { 1370 Ops[i] = NewRec; 1371 break; 1372 } 1373 return getAddExpr(Ops); 1374 } 1375 1376 // Okay, if there weren't any loop invariants to be folded, check to see if 1377 // there are multiple AddRec's with the same loop induction variable being 1378 // added together. If so, we can fold them. 1379 for (unsigned OtherIdx = Idx+1; 1380 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx) 1381 if (OtherIdx != Idx) { 1382 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 1383 if (AddRec->getLoop() == OtherAddRec->getLoop()) { 1384 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D} 1385 SmallVector<const SCEV *, 4> NewOps(AddRec->op_begin(), 1386 AddRec->op_end()); 1387 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) { 1388 if (i >= NewOps.size()) { 1389 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i, 1390 OtherAddRec->op_end()); 1391 break; 1392 } 1393 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i)); 1394 } 1395 const SCEV* NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop()); 1396 1397 if (Ops.size() == 2) return NewAddRec; 1398 1399 Ops.erase(Ops.begin()+Idx); 1400 Ops.erase(Ops.begin()+OtherIdx-1); 1401 Ops.push_back(NewAddRec); 1402 return getAddExpr(Ops); 1403 } 1404 } 1405 1406 // Otherwise couldn't fold anything into this recurrence. Move onto the 1407 // next one. 1408 } 1409 1410 // Okay, it looks like we really DO need an add expr. Check to see if we 1411 // already have one, otherwise create a new one. 1412 FoldingSetNodeID ID; 1413 ID.AddInteger(scAddExpr); 1414 ID.AddInteger(Ops.size()); 1415 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 1416 ID.AddPointer(Ops[i]); 1417 void *IP = 0; 1418 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1419 SCEV *S = SCEVAllocator.Allocate<SCEVAddExpr>(); 1420 new (S) SCEVAddExpr(Ops); 1421 UniqueSCEVs.InsertNode(S, IP); 1422 return S; 1423 } 1424 1425 1426 /// getMulExpr - Get a canonical multiply expression, or something simpler if 1427 /// possible. 1428 const SCEV* ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV*> &Ops) { 1429 assert(!Ops.empty() && "Cannot get empty mul!"); 1430 #ifndef NDEBUG 1431 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 1432 assert(getEffectiveSCEVType(Ops[i]->getType()) == 1433 getEffectiveSCEVType(Ops[0]->getType()) && 1434 "SCEVMulExpr operand types don't match!"); 1435 #endif 1436 1437 // Sort by complexity, this groups all similar expression types together. 1438 GroupByComplexity(Ops, LI); 1439 1440 // If there are any constants, fold them together. 1441 unsigned Idx = 0; 1442 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 1443 1444 // C1*(C2+V) -> C1*C2 + C1*V 1445 if (Ops.size() == 2) 1446 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 1447 if (Add->getNumOperands() == 2 && 1448 isa<SCEVConstant>(Add->getOperand(0))) 1449 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)), 1450 getMulExpr(LHSC, Add->getOperand(1))); 1451 1452 1453 ++Idx; 1454 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 1455 // We found two constants, fold them together! 1456 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() * 1457 RHSC->getValue()->getValue()); 1458 Ops[0] = getConstant(Fold); 1459 Ops.erase(Ops.begin()+1); // Erase the folded element 1460 if (Ops.size() == 1) return Ops[0]; 1461 LHSC = cast<SCEVConstant>(Ops[0]); 1462 } 1463 1464 // If we are left with a constant one being multiplied, strip it off. 1465 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) { 1466 Ops.erase(Ops.begin()); 1467 --Idx; 1468 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) { 1469 // If we have a multiply of zero, it will always be zero. 1470 return Ops[0]; 1471 } 1472 } 1473 1474 // Skip over the add expression until we get to a multiply. 1475 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 1476 ++Idx; 1477 1478 if (Ops.size() == 1) 1479 return Ops[0]; 1480 1481 // If there are mul operands inline them all into this expression. 1482 if (Idx < Ops.size()) { 1483 bool DeletedMul = false; 1484 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 1485 // If we have an mul, expand the mul operands onto the end of the operands 1486 // list. 1487 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end()); 1488 Ops.erase(Ops.begin()+Idx); 1489 DeletedMul = true; 1490 } 1491 1492 // If we deleted at least one mul, we added operands to the end of the list, 1493 // and they are not necessarily sorted. Recurse to resort and resimplify 1494 // any operands we just aquired. 1495 if (DeletedMul) 1496 return getMulExpr(Ops); 1497 } 1498 1499 // If there are any add recurrences in the operands list, see if any other 1500 // added values are loop invariant. If so, we can fold them into the 1501 // recurrence. 1502 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 1503 ++Idx; 1504 1505 // Scan over all recurrences, trying to fold loop invariants into them. 1506 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 1507 // Scan all of the other operands to this mul and add them to the vector if 1508 // they are loop invariant w.r.t. the recurrence. 1509 SmallVector<const SCEV*, 8> LIOps; 1510 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 1511 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 1512 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) { 1513 LIOps.push_back(Ops[i]); 1514 Ops.erase(Ops.begin()+i); 1515 --i; --e; 1516 } 1517 1518 // If we found some loop invariants, fold them into the recurrence. 1519 if (!LIOps.empty()) { 1520 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 1521 SmallVector<const SCEV*, 4> NewOps; 1522 NewOps.reserve(AddRec->getNumOperands()); 1523 if (LIOps.size() == 1) { 1524 const SCEV *Scale = LIOps[0]; 1525 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 1526 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i))); 1527 } else { 1528 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 1529 SmallVector<const SCEV*, 4> MulOps(LIOps.begin(), LIOps.end()); 1530 MulOps.push_back(AddRec->getOperand(i)); 1531 NewOps.push_back(getMulExpr(MulOps)); 1532 } 1533 } 1534 1535 const SCEV* NewRec = getAddRecExpr(NewOps, AddRec->getLoop()); 1536 1537 // If all of the other operands were loop invariant, we are done. 1538 if (Ops.size() == 1) return NewRec; 1539 1540 // Otherwise, multiply the folded AddRec by the non-liv parts. 1541 for (unsigned i = 0;; ++i) 1542 if (Ops[i] == AddRec) { 1543 Ops[i] = NewRec; 1544 break; 1545 } 1546 return getMulExpr(Ops); 1547 } 1548 1549 // Okay, if there weren't any loop invariants to be folded, check to see if 1550 // there are multiple AddRec's with the same loop induction variable being 1551 // multiplied together. If so, we can fold them. 1552 for (unsigned OtherIdx = Idx+1; 1553 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx) 1554 if (OtherIdx != Idx) { 1555 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 1556 if (AddRec->getLoop() == OtherAddRec->getLoop()) { 1557 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D} 1558 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec; 1559 const SCEV* NewStart = getMulExpr(F->getStart(), 1560 G->getStart()); 1561 const SCEV* B = F->getStepRecurrence(*this); 1562 const SCEV* D = G->getStepRecurrence(*this); 1563 const SCEV* NewStep = getAddExpr(getMulExpr(F, D), 1564 getMulExpr(G, B), 1565 getMulExpr(B, D)); 1566 const SCEV* NewAddRec = getAddRecExpr(NewStart, NewStep, 1567 F->getLoop()); 1568 if (Ops.size() == 2) return NewAddRec; 1569 1570 Ops.erase(Ops.begin()+Idx); 1571 Ops.erase(Ops.begin()+OtherIdx-1); 1572 Ops.push_back(NewAddRec); 1573 return getMulExpr(Ops); 1574 } 1575 } 1576 1577 // Otherwise couldn't fold anything into this recurrence. Move onto the 1578 // next one. 1579 } 1580 1581 // Okay, it looks like we really DO need an mul expr. Check to see if we 1582 // already have one, otherwise create a new one. 1583 FoldingSetNodeID ID; 1584 ID.AddInteger(scMulExpr); 1585 ID.AddInteger(Ops.size()); 1586 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 1587 ID.AddPointer(Ops[i]); 1588 void *IP = 0; 1589 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1590 SCEV *S = SCEVAllocator.Allocate<SCEVMulExpr>(); 1591 new (S) SCEVMulExpr(Ops); 1592 UniqueSCEVs.InsertNode(S, IP); 1593 return S; 1594 } 1595 1596 /// getUDivExpr - Get a canonical multiply expression, or something simpler if 1597 /// possible. 1598 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 1599 const SCEV *RHS) { 1600 assert(getEffectiveSCEVType(LHS->getType()) == 1601 getEffectiveSCEVType(RHS->getType()) && 1602 "SCEVUDivExpr operand types don't match!"); 1603 1604 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 1605 if (RHSC->getValue()->equalsInt(1)) 1606 return LHS; // X udiv 1 --> x 1607 if (RHSC->isZero()) 1608 return getIntegerSCEV(0, LHS->getType()); // value is undefined 1609 1610 // Determine if the division can be folded into the operands of 1611 // its operands. 1612 // TODO: Generalize this to non-constants by using known-bits information. 1613 const Type *Ty = LHS->getType(); 1614 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros(); 1615 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ; 1616 // For non-power-of-two values, effectively round the value up to the 1617 // nearest power of two. 1618 if (!RHSC->getValue()->getValue().isPowerOf2()) 1619 ++MaxShiftAmt; 1620 const IntegerType *ExtTy = 1621 IntegerType::get(getTypeSizeInBits(Ty) + MaxShiftAmt); 1622 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 1623 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 1624 if (const SCEVConstant *Step = 1625 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) 1626 if (!Step->getValue()->getValue() 1627 .urem(RHSC->getValue()->getValue()) && 1628 getZeroExtendExpr(AR, ExtTy) == 1629 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 1630 getZeroExtendExpr(Step, ExtTy), 1631 AR->getLoop())) { 1632 SmallVector<const SCEV*, 4> Operands; 1633 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i) 1634 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS)); 1635 return getAddRecExpr(Operands, AR->getLoop()); 1636 } 1637 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 1638 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 1639 SmallVector<const SCEV*, 4> Operands; 1640 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) 1641 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy)); 1642 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 1643 // Find an operand that's safely divisible. 1644 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 1645 const SCEV* Op = M->getOperand(i); 1646 const SCEV* Div = getUDivExpr(Op, RHSC); 1647 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 1648 const SmallVectorImpl<const SCEV*> &MOperands = M->getOperands(); 1649 Operands = SmallVector<const SCEV*, 4>(MOperands.begin(), 1650 MOperands.end()); 1651 Operands[i] = Div; 1652 return getMulExpr(Operands); 1653 } 1654 } 1655 } 1656 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 1657 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) { 1658 SmallVector<const SCEV*, 4> Operands; 1659 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) 1660 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy)); 1661 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 1662 Operands.clear(); 1663 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 1664 const SCEV* Op = getUDivExpr(A->getOperand(i), RHS); 1665 if (isa<SCEVUDivExpr>(Op) || getMulExpr(Op, RHS) != A->getOperand(i)) 1666 break; 1667 Operands.push_back(Op); 1668 } 1669 if (Operands.size() == A->getNumOperands()) 1670 return getAddExpr(Operands); 1671 } 1672 } 1673 1674 // Fold if both operands are constant. 1675 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 1676 Constant *LHSCV = LHSC->getValue(); 1677 Constant *RHSCV = RHSC->getValue(); 1678 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 1679 RHSCV))); 1680 } 1681 } 1682 1683 FoldingSetNodeID ID; 1684 ID.AddInteger(scUDivExpr); 1685 ID.AddPointer(LHS); 1686 ID.AddPointer(RHS); 1687 void *IP = 0; 1688 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1689 SCEV *S = SCEVAllocator.Allocate<SCEVUDivExpr>(); 1690 new (S) SCEVUDivExpr(LHS, RHS); 1691 UniqueSCEVs.InsertNode(S, IP); 1692 return S; 1693 } 1694 1695 1696 /// getAddRecExpr - Get an add recurrence expression for the specified loop. 1697 /// Simplify the expression as much as possible. 1698 const SCEV* ScalarEvolution::getAddRecExpr(const SCEV* Start, 1699 const SCEV* Step, const Loop *L) { 1700 SmallVector<const SCEV*, 4> Operands; 1701 Operands.push_back(Start); 1702 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 1703 if (StepChrec->getLoop() == L) { 1704 Operands.insert(Operands.end(), StepChrec->op_begin(), 1705 StepChrec->op_end()); 1706 return getAddRecExpr(Operands, L); 1707 } 1708 1709 Operands.push_back(Step); 1710 return getAddRecExpr(Operands, L); 1711 } 1712 1713 /// getAddRecExpr - Get an add recurrence expression for the specified loop. 1714 /// Simplify the expression as much as possible. 1715 const SCEV * 1716 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV*> &Operands, 1717 const Loop *L) { 1718 if (Operands.size() == 1) return Operands[0]; 1719 #ifndef NDEBUG 1720 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 1721 assert(getEffectiveSCEVType(Operands[i]->getType()) == 1722 getEffectiveSCEVType(Operands[0]->getType()) && 1723 "SCEVAddRecExpr operand types don't match!"); 1724 #endif 1725 1726 if (Operands.back()->isZero()) { 1727 Operands.pop_back(); 1728 return getAddRecExpr(Operands, L); // {X,+,0} --> X 1729 } 1730 1731 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 1732 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 1733 const Loop* NestedLoop = NestedAR->getLoop(); 1734 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) { 1735 SmallVector<const SCEV*, 4> NestedOperands(NestedAR->op_begin(), 1736 NestedAR->op_end()); 1737 Operands[0] = NestedAR->getStart(); 1738 // AddRecs require their operands be loop-invariant with respect to their 1739 // loops. Don't perform this transformation if it would break this 1740 // requirement. 1741 bool AllInvariant = true; 1742 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 1743 if (!Operands[i]->isLoopInvariant(L)) { 1744 AllInvariant = false; 1745 break; 1746 } 1747 if (AllInvariant) { 1748 NestedOperands[0] = getAddRecExpr(Operands, L); 1749 AllInvariant = true; 1750 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i) 1751 if (!NestedOperands[i]->isLoopInvariant(NestedLoop)) { 1752 AllInvariant = false; 1753 break; 1754 } 1755 if (AllInvariant) 1756 // Ok, both add recurrences are valid after the transformation. 1757 return getAddRecExpr(NestedOperands, NestedLoop); 1758 } 1759 // Reset Operands to its original state. 1760 Operands[0] = NestedAR; 1761 } 1762 } 1763 1764 FoldingSetNodeID ID; 1765 ID.AddInteger(scAddRecExpr); 1766 ID.AddInteger(Operands.size()); 1767 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 1768 ID.AddPointer(Operands[i]); 1769 ID.AddPointer(L); 1770 void *IP = 0; 1771 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1772 SCEV *S = SCEVAllocator.Allocate<SCEVAddRecExpr>(); 1773 new (S) SCEVAddRecExpr(Operands, L); 1774 UniqueSCEVs.InsertNode(S, IP); 1775 return S; 1776 } 1777 1778 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, 1779 const SCEV *RHS) { 1780 SmallVector<const SCEV*, 2> Ops; 1781 Ops.push_back(LHS); 1782 Ops.push_back(RHS); 1783 return getSMaxExpr(Ops); 1784 } 1785 1786 const SCEV* 1787 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV*> &Ops) { 1788 assert(!Ops.empty() && "Cannot get empty smax!"); 1789 if (Ops.size() == 1) return Ops[0]; 1790 #ifndef NDEBUG 1791 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 1792 assert(getEffectiveSCEVType(Ops[i]->getType()) == 1793 getEffectiveSCEVType(Ops[0]->getType()) && 1794 "SCEVSMaxExpr operand types don't match!"); 1795 #endif 1796 1797 // Sort by complexity, this groups all similar expression types together. 1798 GroupByComplexity(Ops, LI); 1799 1800 // If there are any constants, fold them together. 1801 unsigned Idx = 0; 1802 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 1803 ++Idx; 1804 assert(Idx < Ops.size()); 1805 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 1806 // We found two constants, fold them together! 1807 ConstantInt *Fold = ConstantInt::get( 1808 APIntOps::smax(LHSC->getValue()->getValue(), 1809 RHSC->getValue()->getValue())); 1810 Ops[0] = getConstant(Fold); 1811 Ops.erase(Ops.begin()+1); // Erase the folded element 1812 if (Ops.size() == 1) return Ops[0]; 1813 LHSC = cast<SCEVConstant>(Ops[0]); 1814 } 1815 1816 // If we are left with a constant minimum-int, strip it off. 1817 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) { 1818 Ops.erase(Ops.begin()); 1819 --Idx; 1820 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) { 1821 // If we have an smax with a constant maximum-int, it will always be 1822 // maximum-int. 1823 return Ops[0]; 1824 } 1825 } 1826 1827 if (Ops.size() == 1) return Ops[0]; 1828 1829 // Find the first SMax 1830 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr) 1831 ++Idx; 1832 1833 // Check to see if one of the operands is an SMax. If so, expand its operands 1834 // onto our operand list, and recurse to simplify. 1835 if (Idx < Ops.size()) { 1836 bool DeletedSMax = false; 1837 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) { 1838 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end()); 1839 Ops.erase(Ops.begin()+Idx); 1840 DeletedSMax = true; 1841 } 1842 1843 if (DeletedSMax) 1844 return getSMaxExpr(Ops); 1845 } 1846 1847 // Okay, check to see if the same value occurs in the operand list twice. If 1848 // so, delete one. Since we sorted the list, these values are required to 1849 // be adjacent. 1850 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 1851 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y 1852 Ops.erase(Ops.begin()+i, Ops.begin()+i+1); 1853 --i; --e; 1854 } 1855 1856 if (Ops.size() == 1) return Ops[0]; 1857 1858 assert(!Ops.empty() && "Reduced smax down to nothing!"); 1859 1860 // Okay, it looks like we really DO need an smax expr. Check to see if we 1861 // already have one, otherwise create a new one. 1862 FoldingSetNodeID ID; 1863 ID.AddInteger(scSMaxExpr); 1864 ID.AddInteger(Ops.size()); 1865 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 1866 ID.AddPointer(Ops[i]); 1867 void *IP = 0; 1868 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1869 SCEV *S = SCEVAllocator.Allocate<SCEVSMaxExpr>(); 1870 new (S) SCEVSMaxExpr(Ops); 1871 UniqueSCEVs.InsertNode(S, IP); 1872 return S; 1873 } 1874 1875 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, 1876 const SCEV *RHS) { 1877 SmallVector<const SCEV*, 2> Ops; 1878 Ops.push_back(LHS); 1879 Ops.push_back(RHS); 1880 return getUMaxExpr(Ops); 1881 } 1882 1883 const SCEV* 1884 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV*> &Ops) { 1885 assert(!Ops.empty() && "Cannot get empty umax!"); 1886 if (Ops.size() == 1) return Ops[0]; 1887 #ifndef NDEBUG 1888 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 1889 assert(getEffectiveSCEVType(Ops[i]->getType()) == 1890 getEffectiveSCEVType(Ops[0]->getType()) && 1891 "SCEVUMaxExpr operand types don't match!"); 1892 #endif 1893 1894 // Sort by complexity, this groups all similar expression types together. 1895 GroupByComplexity(Ops, LI); 1896 1897 // If there are any constants, fold them together. 1898 unsigned Idx = 0; 1899 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 1900 ++Idx; 1901 assert(Idx < Ops.size()); 1902 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 1903 // We found two constants, fold them together! 1904 ConstantInt *Fold = ConstantInt::get( 1905 APIntOps::umax(LHSC->getValue()->getValue(), 1906 RHSC->getValue()->getValue())); 1907 Ops[0] = getConstant(Fold); 1908 Ops.erase(Ops.begin()+1); // Erase the folded element 1909 if (Ops.size() == 1) return Ops[0]; 1910 LHSC = cast<SCEVConstant>(Ops[0]); 1911 } 1912 1913 // If we are left with a constant minimum-int, strip it off. 1914 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) { 1915 Ops.erase(Ops.begin()); 1916 --Idx; 1917 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) { 1918 // If we have an umax with a constant maximum-int, it will always be 1919 // maximum-int. 1920 return Ops[0]; 1921 } 1922 } 1923 1924 if (Ops.size() == 1) return Ops[0]; 1925 1926 // Find the first UMax 1927 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr) 1928 ++Idx; 1929 1930 // Check to see if one of the operands is a UMax. If so, expand its operands 1931 // onto our operand list, and recurse to simplify. 1932 if (Idx < Ops.size()) { 1933 bool DeletedUMax = false; 1934 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) { 1935 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end()); 1936 Ops.erase(Ops.begin()+Idx); 1937 DeletedUMax = true; 1938 } 1939 1940 if (DeletedUMax) 1941 return getUMaxExpr(Ops); 1942 } 1943 1944 // Okay, check to see if the same value occurs in the operand list twice. If 1945 // so, delete one. Since we sorted the list, these values are required to 1946 // be adjacent. 1947 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) 1948 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y 1949 Ops.erase(Ops.begin()+i, Ops.begin()+i+1); 1950 --i; --e; 1951 } 1952 1953 if (Ops.size() == 1) return Ops[0]; 1954 1955 assert(!Ops.empty() && "Reduced umax down to nothing!"); 1956 1957 // Okay, it looks like we really DO need a umax expr. Check to see if we 1958 // already have one, otherwise create a new one. 1959 FoldingSetNodeID ID; 1960 ID.AddInteger(scUMaxExpr); 1961 ID.AddInteger(Ops.size()); 1962 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 1963 ID.AddPointer(Ops[i]); 1964 void *IP = 0; 1965 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1966 SCEV *S = SCEVAllocator.Allocate<SCEVUMaxExpr>(); 1967 new (S) SCEVUMaxExpr(Ops); 1968 UniqueSCEVs.InsertNode(S, IP); 1969 return S; 1970 } 1971 1972 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 1973 const SCEV *RHS) { 1974 // ~smax(~x, ~y) == smin(x, y). 1975 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS))); 1976 } 1977 1978 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, 1979 const SCEV *RHS) { 1980 // ~umax(~x, ~y) == umin(x, y) 1981 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS))); 1982 } 1983 1984 const SCEV* ScalarEvolution::getUnknown(Value *V) { 1985 // Don't attempt to do anything other than create a SCEVUnknown object 1986 // here. createSCEV only calls getUnknown after checking for all other 1987 // interesting possibilities, and any other code that calls getUnknown 1988 // is doing so in order to hide a value from SCEV canonicalization. 1989 1990 FoldingSetNodeID ID; 1991 ID.AddInteger(scUnknown); 1992 ID.AddPointer(V); 1993 void *IP = 0; 1994 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1995 SCEV *S = SCEVAllocator.Allocate<SCEVUnknown>(); 1996 new (S) SCEVUnknown(V); 1997 UniqueSCEVs.InsertNode(S, IP); 1998 return S; 1999 } 2000 2001 //===----------------------------------------------------------------------===// 2002 // Basic SCEV Analysis and PHI Idiom Recognition Code 2003 // 2004 2005 /// isSCEVable - Test if values of the given type are analyzable within 2006 /// the SCEV framework. This primarily includes integer types, and it 2007 /// can optionally include pointer types if the ScalarEvolution class 2008 /// has access to target-specific information. 2009 bool ScalarEvolution::isSCEVable(const Type *Ty) const { 2010 // Integers are always SCEVable. 2011 if (Ty->isInteger()) 2012 return true; 2013 2014 // Pointers are SCEVable if TargetData information is available 2015 // to provide pointer size information. 2016 if (isa<PointerType>(Ty)) 2017 return TD != NULL; 2018 2019 // Otherwise it's not SCEVable. 2020 return false; 2021 } 2022 2023 /// getTypeSizeInBits - Return the size in bits of the specified type, 2024 /// for which isSCEVable must return true. 2025 uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const { 2026 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 2027 2028 // If we have a TargetData, use it! 2029 if (TD) 2030 return TD->getTypeSizeInBits(Ty); 2031 2032 // Otherwise, we support only integer types. 2033 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!"); 2034 return Ty->getPrimitiveSizeInBits(); 2035 } 2036 2037 /// getEffectiveSCEVType - Return a type with the same bitwidth as 2038 /// the given type and which represents how SCEV will treat the given 2039 /// type, for which isSCEVable must return true. For pointer types, 2040 /// this is the pointer-sized integer type. 2041 const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const { 2042 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 2043 2044 if (Ty->isInteger()) 2045 return Ty; 2046 2047 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!"); 2048 return TD->getIntPtrType(); 2049 } 2050 2051 const SCEV* ScalarEvolution::getCouldNotCompute() { 2052 return &CouldNotCompute; 2053 } 2054 2055 /// hasSCEV - Return true if the SCEV for this value has already been 2056 /// computed. 2057 bool ScalarEvolution::hasSCEV(Value *V) const { 2058 return Scalars.count(V); 2059 } 2060 2061 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the 2062 /// expression and create a new one. 2063 const SCEV* ScalarEvolution::getSCEV(Value *V) { 2064 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 2065 2066 std::map<SCEVCallbackVH, const SCEV*>::iterator I = Scalars.find(V); 2067 if (I != Scalars.end()) return I->second; 2068 const SCEV* S = createSCEV(V); 2069 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S)); 2070 return S; 2071 } 2072 2073 /// getIntegerSCEV - Given a SCEVable type, create a constant for the 2074 /// specified signed integer value and return a SCEV for the constant. 2075 const SCEV* ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) { 2076 const IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty)); 2077 return getConstant(ConstantInt::get(ITy, Val)); 2078 } 2079 2080 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V 2081 /// 2082 const SCEV* ScalarEvolution::getNegativeSCEV(const SCEV* V) { 2083 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 2084 return getConstant(cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 2085 2086 const Type *Ty = V->getType(); 2087 Ty = getEffectiveSCEVType(Ty); 2088 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(Ty))); 2089 } 2090 2091 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V 2092 const SCEV* ScalarEvolution::getNotSCEV(const SCEV* V) { 2093 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 2094 return getConstant(cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 2095 2096 const Type *Ty = V->getType(); 2097 Ty = getEffectiveSCEVType(Ty); 2098 const SCEV* AllOnes = getConstant(ConstantInt::getAllOnesValue(Ty)); 2099 return getMinusSCEV(AllOnes, V); 2100 } 2101 2102 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS. 2103 /// 2104 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, 2105 const SCEV *RHS) { 2106 // X - Y --> X + -Y 2107 return getAddExpr(LHS, getNegativeSCEV(RHS)); 2108 } 2109 2110 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the 2111 /// input value to the specified type. If the type must be extended, it is zero 2112 /// extended. 2113 const SCEV* 2114 ScalarEvolution::getTruncateOrZeroExtend(const SCEV* V, 2115 const Type *Ty) { 2116 const Type *SrcTy = V->getType(); 2117 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) && 2118 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) && 2119 "Cannot truncate or zero extend with non-integer arguments!"); 2120 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 2121 return V; // No conversion 2122 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 2123 return getTruncateExpr(V, Ty); 2124 return getZeroExtendExpr(V, Ty); 2125 } 2126 2127 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the 2128 /// input value to the specified type. If the type must be extended, it is sign 2129 /// extended. 2130 const SCEV* 2131 ScalarEvolution::getTruncateOrSignExtend(const SCEV* V, 2132 const Type *Ty) { 2133 const Type *SrcTy = V->getType(); 2134 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) && 2135 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) && 2136 "Cannot truncate or zero extend with non-integer arguments!"); 2137 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 2138 return V; // No conversion 2139 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 2140 return getTruncateExpr(V, Ty); 2141 return getSignExtendExpr(V, Ty); 2142 } 2143 2144 /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the 2145 /// input value to the specified type. If the type must be extended, it is zero 2146 /// extended. The conversion must not be narrowing. 2147 const SCEV* 2148 ScalarEvolution::getNoopOrZeroExtend(const SCEV* V, const Type *Ty) { 2149 const Type *SrcTy = V->getType(); 2150 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) && 2151 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) && 2152 "Cannot noop or zero extend with non-integer arguments!"); 2153 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 2154 "getNoopOrZeroExtend cannot truncate!"); 2155 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 2156 return V; // No conversion 2157 return getZeroExtendExpr(V, Ty); 2158 } 2159 2160 /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the 2161 /// input value to the specified type. If the type must be extended, it is sign 2162 /// extended. The conversion must not be narrowing. 2163 const SCEV* 2164 ScalarEvolution::getNoopOrSignExtend(const SCEV* V, const Type *Ty) { 2165 const Type *SrcTy = V->getType(); 2166 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) && 2167 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) && 2168 "Cannot noop or sign extend with non-integer arguments!"); 2169 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 2170 "getNoopOrSignExtend cannot truncate!"); 2171 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 2172 return V; // No conversion 2173 return getSignExtendExpr(V, Ty); 2174 } 2175 2176 /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of 2177 /// the input value to the specified type. If the type must be extended, 2178 /// it is extended with unspecified bits. The conversion must not be 2179 /// narrowing. 2180 const SCEV* 2181 ScalarEvolution::getNoopOrAnyExtend(const SCEV* V, const Type *Ty) { 2182 const Type *SrcTy = V->getType(); 2183 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) && 2184 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) && 2185 "Cannot noop or any extend with non-integer arguments!"); 2186 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 2187 "getNoopOrAnyExtend cannot truncate!"); 2188 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 2189 return V; // No conversion 2190 return getAnyExtendExpr(V, Ty); 2191 } 2192 2193 /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the 2194 /// input value to the specified type. The conversion must not be widening. 2195 const SCEV* 2196 ScalarEvolution::getTruncateOrNoop(const SCEV* V, const Type *Ty) { 2197 const Type *SrcTy = V->getType(); 2198 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) && 2199 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) && 2200 "Cannot truncate or noop with non-integer arguments!"); 2201 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 2202 "getTruncateOrNoop cannot extend!"); 2203 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 2204 return V; // No conversion 2205 return getTruncateExpr(V, Ty); 2206 } 2207 2208 /// getUMaxFromMismatchedTypes - Promote the operands to the wider of 2209 /// the types using zero-extension, and then perform a umax operation 2210 /// with them. 2211 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 2212 const SCEV *RHS) { 2213 const SCEV* PromotedLHS = LHS; 2214 const SCEV* PromotedRHS = RHS; 2215 2216 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 2217 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 2218 else 2219 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 2220 2221 return getUMaxExpr(PromotedLHS, PromotedRHS); 2222 } 2223 2224 /// getUMinFromMismatchedTypes - Promote the operands to the wider of 2225 /// the types using zero-extension, and then perform a umin operation 2226 /// with them. 2227 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 2228 const SCEV *RHS) { 2229 const SCEV* PromotedLHS = LHS; 2230 const SCEV* PromotedRHS = RHS; 2231 2232 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 2233 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 2234 else 2235 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 2236 2237 return getUMinExpr(PromotedLHS, PromotedRHS); 2238 } 2239 2240 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for 2241 /// the specified instruction and replaces any references to the symbolic value 2242 /// SymName with the specified value. This is used during PHI resolution. 2243 void 2244 ScalarEvolution::ReplaceSymbolicValueWithConcrete(Instruction *I, 2245 const SCEV *SymName, 2246 const SCEV *NewVal) { 2247 std::map<SCEVCallbackVH, const SCEV*>::iterator SI = 2248 Scalars.find(SCEVCallbackVH(I, this)); 2249 if (SI == Scalars.end()) return; 2250 2251 const SCEV* NV = 2252 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this); 2253 if (NV == SI->second) return; // No change. 2254 2255 SI->second = NV; // Update the scalars map! 2256 2257 // Any instruction values that use this instruction might also need to be 2258 // updated! 2259 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); 2260 UI != E; ++UI) 2261 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal); 2262 } 2263 2264 /// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in 2265 /// a loop header, making it a potential recurrence, or it doesn't. 2266 /// 2267 const SCEV* ScalarEvolution::createNodeForPHI(PHINode *PN) { 2268 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized. 2269 if (const Loop *L = LI->getLoopFor(PN->getParent())) 2270 if (L->getHeader() == PN->getParent()) { 2271 // If it lives in the loop header, it has two incoming values, one 2272 // from outside the loop, and one from inside. 2273 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0)); 2274 unsigned BackEdge = IncomingEdge^1; 2275 2276 // While we are analyzing this PHI node, handle its value symbolically. 2277 const SCEV* SymbolicName = getUnknown(PN); 2278 assert(Scalars.find(PN) == Scalars.end() && 2279 "PHI node already processed?"); 2280 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName)); 2281 2282 // Using this symbolic name for the PHI, analyze the value coming around 2283 // the back-edge. 2284 const SCEV* BEValue = getSCEV(PN->getIncomingValue(BackEdge)); 2285 2286 // NOTE: If BEValue is loop invariant, we know that the PHI node just 2287 // has a special value for the first iteration of the loop. 2288 2289 // If the value coming around the backedge is an add with the symbolic 2290 // value we just inserted, then we found a simple induction variable! 2291 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 2292 // If there is a single occurrence of the symbolic value, replace it 2293 // with a recurrence. 2294 unsigned FoundIndex = Add->getNumOperands(); 2295 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 2296 if (Add->getOperand(i) == SymbolicName) 2297 if (FoundIndex == e) { 2298 FoundIndex = i; 2299 break; 2300 } 2301 2302 if (FoundIndex != Add->getNumOperands()) { 2303 // Create an add with everything but the specified operand. 2304 SmallVector<const SCEV*, 8> Ops; 2305 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 2306 if (i != FoundIndex) 2307 Ops.push_back(Add->getOperand(i)); 2308 const SCEV* Accum = getAddExpr(Ops); 2309 2310 // This is not a valid addrec if the step amount is varying each 2311 // loop iteration, but is not itself an addrec in this loop. 2312 if (Accum->isLoopInvariant(L) || 2313 (isa<SCEVAddRecExpr>(Accum) && 2314 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 2315 const SCEV *StartVal = 2316 getSCEV(PN->getIncomingValue(IncomingEdge)); 2317 const SCEV *PHISCEV = 2318 getAddRecExpr(StartVal, Accum, L); 2319 2320 // Okay, for the entire analysis of this edge we assumed the PHI 2321 // to be symbolic. We now need to go back and update all of the 2322 // entries for the scalars that use the PHI (except for the PHI 2323 // itself) to use the new analyzed value instead of the "symbolic" 2324 // value. 2325 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV); 2326 return PHISCEV; 2327 } 2328 } 2329 } else if (const SCEVAddRecExpr *AddRec = 2330 dyn_cast<SCEVAddRecExpr>(BEValue)) { 2331 // Otherwise, this could be a loop like this: 2332 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 2333 // In this case, j = {1,+,1} and BEValue is j. 2334 // Because the other in-value of i (0) fits the evolution of BEValue 2335 // i really is an addrec evolution. 2336 if (AddRec->getLoop() == L && AddRec->isAffine()) { 2337 const SCEV* StartVal = getSCEV(PN->getIncomingValue(IncomingEdge)); 2338 2339 // If StartVal = j.start - j.stride, we can use StartVal as the 2340 // initial step of the addrec evolution. 2341 if (StartVal == getMinusSCEV(AddRec->getOperand(0), 2342 AddRec->getOperand(1))) { 2343 const SCEV* PHISCEV = 2344 getAddRecExpr(StartVal, AddRec->getOperand(1), L); 2345 2346 // Okay, for the entire analysis of this edge we assumed the PHI 2347 // to be symbolic. We now need to go back and update all of the 2348 // entries for the scalars that use the PHI (except for the PHI 2349 // itself) to use the new analyzed value instead of the "symbolic" 2350 // value. 2351 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV); 2352 return PHISCEV; 2353 } 2354 } 2355 } 2356 2357 return SymbolicName; 2358 } 2359 2360 // If it's not a loop phi, we can't handle it yet. 2361 return getUnknown(PN); 2362 } 2363 2364 /// createNodeForGEP - Expand GEP instructions into add and multiply 2365 /// operations. This allows them to be analyzed by regular SCEV code. 2366 /// 2367 const SCEV* ScalarEvolution::createNodeForGEP(User *GEP) { 2368 2369 const Type *IntPtrTy = TD->getIntPtrType(); 2370 Value *Base = GEP->getOperand(0); 2371 // Don't attempt to analyze GEPs over unsized objects. 2372 if (!cast<PointerType>(Base->getType())->getElementType()->isSized()) 2373 return getUnknown(GEP); 2374 const SCEV* TotalOffset = getIntegerSCEV(0, IntPtrTy); 2375 gep_type_iterator GTI = gep_type_begin(GEP); 2376 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()), 2377 E = GEP->op_end(); 2378 I != E; ++I) { 2379 Value *Index = *I; 2380 // Compute the (potentially symbolic) offset in bytes for this index. 2381 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) { 2382 // For a struct, add the member offset. 2383 const StructLayout &SL = *TD->getStructLayout(STy); 2384 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue(); 2385 uint64_t Offset = SL.getElementOffset(FieldNo); 2386 TotalOffset = getAddExpr(TotalOffset, 2387 getIntegerSCEV(Offset, IntPtrTy)); 2388 } else { 2389 // For an array, add the element offset, explicitly scaled. 2390 const SCEV* LocalOffset = getSCEV(Index); 2391 if (!isa<PointerType>(LocalOffset->getType())) 2392 // Getelementptr indicies are signed. 2393 LocalOffset = getTruncateOrSignExtend(LocalOffset, 2394 IntPtrTy); 2395 LocalOffset = 2396 getMulExpr(LocalOffset, 2397 getIntegerSCEV(TD->getTypeAllocSize(*GTI), 2398 IntPtrTy)); 2399 TotalOffset = getAddExpr(TotalOffset, LocalOffset); 2400 } 2401 } 2402 return getAddExpr(getSCEV(Base), TotalOffset); 2403 } 2404 2405 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S is 2406 /// guaranteed to end in (at every loop iteration). It is, at the same time, 2407 /// the minimum number of times S is divisible by 2. For example, given {4,+,8} 2408 /// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S. 2409 uint32_t 2410 ScalarEvolution::GetMinTrailingZeros(const SCEV* S) { 2411 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 2412 return C->getValue()->getValue().countTrailingZeros(); 2413 2414 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 2415 return std::min(GetMinTrailingZeros(T->getOperand()), 2416 (uint32_t)getTypeSizeInBits(T->getType())); 2417 2418 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 2419 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 2420 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ? 2421 getTypeSizeInBits(E->getType()) : OpRes; 2422 } 2423 2424 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 2425 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 2426 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ? 2427 getTypeSizeInBits(E->getType()) : OpRes; 2428 } 2429 2430 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 2431 // The result is the min of all operands results. 2432 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 2433 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 2434 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 2435 return MinOpRes; 2436 } 2437 2438 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 2439 // The result is the sum of all operands results. 2440 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 2441 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 2442 for (unsigned i = 1, e = M->getNumOperands(); 2443 SumOpRes != BitWidth && i != e; ++i) 2444 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), 2445 BitWidth); 2446 return SumOpRes; 2447 } 2448 2449 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 2450 // The result is the min of all operands results. 2451 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 2452 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 2453 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 2454 return MinOpRes; 2455 } 2456 2457 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 2458 // The result is the min of all operands results. 2459 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 2460 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 2461 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 2462 return MinOpRes; 2463 } 2464 2465 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 2466 // The result is the min of all operands results. 2467 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 2468 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 2469 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 2470 return MinOpRes; 2471 } 2472 2473 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 2474 // For a SCEVUnknown, ask ValueTracking. 2475 unsigned BitWidth = getTypeSizeInBits(U->getType()); 2476 APInt Mask = APInt::getAllOnesValue(BitWidth); 2477 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0); 2478 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones); 2479 return Zeros.countTrailingOnes(); 2480 } 2481 2482 // SCEVUDivExpr 2483 return 0; 2484 } 2485 2486 uint32_t 2487 ScalarEvolution::GetMinLeadingZeros(const SCEV* S) { 2488 // TODO: Handle other SCEV expression types here. 2489 2490 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 2491 return C->getValue()->getValue().countLeadingZeros(); 2492 2493 if (const SCEVZeroExtendExpr *C = dyn_cast<SCEVZeroExtendExpr>(S)) { 2494 // A zero-extension cast adds zero bits. 2495 return GetMinLeadingZeros(C->getOperand()) + 2496 (getTypeSizeInBits(C->getType()) - 2497 getTypeSizeInBits(C->getOperand()->getType())); 2498 } 2499 2500 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 2501 // For a SCEVUnknown, ask ValueTracking. 2502 unsigned BitWidth = getTypeSizeInBits(U->getType()); 2503 APInt Mask = APInt::getAllOnesValue(BitWidth); 2504 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0); 2505 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD); 2506 return Zeros.countLeadingOnes(); 2507 } 2508 2509 return 1; 2510 } 2511 2512 uint32_t 2513 ScalarEvolution::GetMinSignBits(const SCEV* S) { 2514 // TODO: Handle other SCEV expression types here. 2515 2516 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) { 2517 const APInt &A = C->getValue()->getValue(); 2518 return A.isNegative() ? A.countLeadingOnes() : 2519 A.countLeadingZeros(); 2520 } 2521 2522 if (const SCEVSignExtendExpr *C = dyn_cast<SCEVSignExtendExpr>(S)) { 2523 // A sign-extension cast adds sign bits. 2524 return GetMinSignBits(C->getOperand()) + 2525 (getTypeSizeInBits(C->getType()) - 2526 getTypeSizeInBits(C->getOperand()->getType())); 2527 } 2528 2529 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 2530 unsigned BitWidth = getTypeSizeInBits(A->getType()); 2531 2532 // Special case decrementing a value (ADD X, -1): 2533 if (const SCEVConstant *CRHS = dyn_cast<SCEVConstant>(A->getOperand(0))) 2534 if (CRHS->isAllOnesValue()) { 2535 SmallVector<const SCEV *, 4> OtherOps(A->op_begin() + 1, A->op_end()); 2536 const SCEV *OtherOpsAdd = getAddExpr(OtherOps); 2537 unsigned LZ = GetMinLeadingZeros(OtherOpsAdd); 2538 2539 // If the input is known to be 0 or 1, the output is 0/-1, which is all 2540 // sign bits set. 2541 if (LZ == BitWidth - 1) 2542 return BitWidth; 2543 2544 // If we are subtracting one from a positive number, there is no carry 2545 // out of the result. 2546 if (LZ > 0) 2547 return GetMinSignBits(OtherOpsAdd); 2548 } 2549 2550 // Add can have at most one carry bit. Thus we know that the output 2551 // is, at worst, one more bit than the inputs. 2552 unsigned Min = BitWidth; 2553 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 2554 unsigned N = GetMinSignBits(A->getOperand(i)); 2555 Min = std::min(Min, N) - 1; 2556 if (Min == 0) return 1; 2557 } 2558 return 1; 2559 } 2560 2561 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 2562 // For a SCEVUnknown, ask ValueTracking. 2563 return ComputeNumSignBits(U->getValue(), TD); 2564 } 2565 2566 return 1; 2567 } 2568 2569 /// createSCEV - We know that there is no SCEV for the specified value. 2570 /// Analyze the expression. 2571 /// 2572 const SCEV* ScalarEvolution::createSCEV(Value *V) { 2573 if (!isSCEVable(V->getType())) 2574 return getUnknown(V); 2575 2576 unsigned Opcode = Instruction::UserOp1; 2577 if (Instruction *I = dyn_cast<Instruction>(V)) 2578 Opcode = I->getOpcode(); 2579 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) 2580 Opcode = CE->getOpcode(); 2581 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 2582 return getConstant(CI); 2583 else if (isa<ConstantPointerNull>(V)) 2584 return getIntegerSCEV(0, V->getType()); 2585 else if (isa<UndefValue>(V)) 2586 return getIntegerSCEV(0, V->getType()); 2587 else 2588 return getUnknown(V); 2589 2590 User *U = cast<User>(V); 2591 switch (Opcode) { 2592 case Instruction::Add: 2593 return getAddExpr(getSCEV(U->getOperand(0)), 2594 getSCEV(U->getOperand(1))); 2595 case Instruction::Mul: 2596 return getMulExpr(getSCEV(U->getOperand(0)), 2597 getSCEV(U->getOperand(1))); 2598 case Instruction::UDiv: 2599 return getUDivExpr(getSCEV(U->getOperand(0)), 2600 getSCEV(U->getOperand(1))); 2601 case Instruction::Sub: 2602 return getMinusSCEV(getSCEV(U->getOperand(0)), 2603 getSCEV(U->getOperand(1))); 2604 case Instruction::And: 2605 // For an expression like x&255 that merely masks off the high bits, 2606 // use zext(trunc(x)) as the SCEV expression. 2607 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) { 2608 if (CI->isNullValue()) 2609 return getSCEV(U->getOperand(1)); 2610 if (CI->isAllOnesValue()) 2611 return getSCEV(U->getOperand(0)); 2612 const APInt &A = CI->getValue(); 2613 2614 // Instcombine's ShrinkDemandedConstant may strip bits out of 2615 // constants, obscuring what would otherwise be a low-bits mask. 2616 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant 2617 // knew about to reconstruct a low-bits mask value. 2618 unsigned LZ = A.countLeadingZeros(); 2619 unsigned BitWidth = A.getBitWidth(); 2620 APInt AllOnes = APInt::getAllOnesValue(BitWidth); 2621 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0); 2622 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD); 2623 2624 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ); 2625 2626 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask)) 2627 return 2628 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)), 2629 IntegerType::get(BitWidth - LZ)), 2630 U->getType()); 2631 } 2632 break; 2633 2634 case Instruction::Or: 2635 // If the RHS of the Or is a constant, we may have something like: 2636 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 2637 // optimizations will transparently handle this case. 2638 // 2639 // In order for this transformation to be safe, the LHS must be of the 2640 // form X*(2^n) and the Or constant must be less than 2^n. 2641 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) { 2642 const SCEV* LHS = getSCEV(U->getOperand(0)); 2643 const APInt &CIVal = CI->getValue(); 2644 if (GetMinTrailingZeros(LHS) >= 2645 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) 2646 return getAddExpr(LHS, getSCEV(U->getOperand(1))); 2647 } 2648 break; 2649 case Instruction::Xor: 2650 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) { 2651 // If the RHS of the xor is a signbit, then this is just an add. 2652 // Instcombine turns add of signbit into xor as a strength reduction step. 2653 if (CI->getValue().isSignBit()) 2654 return getAddExpr(getSCEV(U->getOperand(0)), 2655 getSCEV(U->getOperand(1))); 2656 2657 // If the RHS of xor is -1, then this is a not operation. 2658 if (CI->isAllOnesValue()) 2659 return getNotSCEV(getSCEV(U->getOperand(0))); 2660 2661 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 2662 // This is a variant of the check for xor with -1, and it handles 2663 // the case where instcombine has trimmed non-demanded bits out 2664 // of an xor with -1. 2665 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0))) 2666 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1))) 2667 if (BO->getOpcode() == Instruction::And && 2668 LCI->getValue() == CI->getValue()) 2669 if (const SCEVZeroExtendExpr *Z = 2670 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) { 2671 const Type *UTy = U->getType(); 2672 const SCEV* Z0 = Z->getOperand(); 2673 const Type *Z0Ty = Z0->getType(); 2674 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 2675 2676 // If C is a low-bits mask, the zero extend is zerving to 2677 // mask off the high bits. Complement the operand and 2678 // re-apply the zext. 2679 if (APIntOps::isMask(Z0TySize, CI->getValue())) 2680 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 2681 2682 // If C is a single bit, it may be in the sign-bit position 2683 // before the zero-extend. In this case, represent the xor 2684 // using an add, which is equivalent, and re-apply the zext. 2685 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize); 2686 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() && 2687 Trunc.isSignBit()) 2688 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 2689 UTy); 2690 } 2691 } 2692 break; 2693 2694 case Instruction::Shl: 2695 // Turn shift left of a constant amount into a multiply. 2696 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) { 2697 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth(); 2698 Constant *X = ConstantInt::get( 2699 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth))); 2700 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X)); 2701 } 2702 break; 2703 2704 case Instruction::LShr: 2705 // Turn logical shift right of a constant into a unsigned divide. 2706 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) { 2707 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth(); 2708 Constant *X = ConstantInt::get( 2709 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth))); 2710 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X)); 2711 } 2712 break; 2713 2714 case Instruction::AShr: 2715 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression. 2716 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) 2717 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0))) 2718 if (L->getOpcode() == Instruction::Shl && 2719 L->getOperand(1) == U->getOperand(1)) { 2720 unsigned BitWidth = getTypeSizeInBits(U->getType()); 2721 uint64_t Amt = BitWidth - CI->getZExtValue(); 2722 if (Amt == BitWidth) 2723 return getSCEV(L->getOperand(0)); // shift by zero --> noop 2724 if (Amt > BitWidth) 2725 return getIntegerSCEV(0, U->getType()); // value is undefined 2726 return 2727 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)), 2728 IntegerType::get(Amt)), 2729 U->getType()); 2730 } 2731 break; 2732 2733 case Instruction::Trunc: 2734 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 2735 2736 case Instruction::ZExt: 2737 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 2738 2739 case Instruction::SExt: 2740 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 2741 2742 case Instruction::BitCast: 2743 // BitCasts are no-op casts so we just eliminate the cast. 2744 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 2745 return getSCEV(U->getOperand(0)); 2746 break; 2747 2748 case Instruction::IntToPtr: 2749 if (!TD) break; // Without TD we can't analyze pointers. 2750 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)), 2751 TD->getIntPtrType()); 2752 2753 case Instruction::PtrToInt: 2754 if (!TD) break; // Without TD we can't analyze pointers. 2755 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)), 2756 U->getType()); 2757 2758 case Instruction::GetElementPtr: 2759 if (!TD) break; // Without TD we can't analyze pointers. 2760 return createNodeForGEP(U); 2761 2762 case Instruction::PHI: 2763 return createNodeForPHI(cast<PHINode>(U)); 2764 2765 case Instruction::Select: 2766 // This could be a smax or umax that was lowered earlier. 2767 // Try to recover it. 2768 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) { 2769 Value *LHS = ICI->getOperand(0); 2770 Value *RHS = ICI->getOperand(1); 2771 switch (ICI->getPredicate()) { 2772 case ICmpInst::ICMP_SLT: 2773 case ICmpInst::ICMP_SLE: 2774 std::swap(LHS, RHS); 2775 // fall through 2776 case ICmpInst::ICMP_SGT: 2777 case ICmpInst::ICMP_SGE: 2778 if (LHS == U->getOperand(1) && RHS == U->getOperand(2)) 2779 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS)); 2780 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1)) 2781 return getSMinExpr(getSCEV(LHS), getSCEV(RHS)); 2782 break; 2783 case ICmpInst::ICMP_ULT: 2784 case ICmpInst::ICMP_ULE: 2785 std::swap(LHS, RHS); 2786 // fall through 2787 case ICmpInst::ICMP_UGT: 2788 case ICmpInst::ICMP_UGE: 2789 if (LHS == U->getOperand(1) && RHS == U->getOperand(2)) 2790 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS)); 2791 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1)) 2792 return getUMinExpr(getSCEV(LHS), getSCEV(RHS)); 2793 break; 2794 case ICmpInst::ICMP_NE: 2795 // n != 0 ? n : 1 -> umax(n, 1) 2796 if (LHS == U->getOperand(1) && 2797 isa<ConstantInt>(U->getOperand(2)) && 2798 cast<ConstantInt>(U->getOperand(2))->isOne() && 2799 isa<ConstantInt>(RHS) && 2800 cast<ConstantInt>(RHS)->isZero()) 2801 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(2))); 2802 break; 2803 case ICmpInst::ICMP_EQ: 2804 // n == 0 ? 1 : n -> umax(n, 1) 2805 if (LHS == U->getOperand(2) && 2806 isa<ConstantInt>(U->getOperand(1)) && 2807 cast<ConstantInt>(U->getOperand(1))->isOne() && 2808 isa<ConstantInt>(RHS) && 2809 cast<ConstantInt>(RHS)->isZero()) 2810 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(1))); 2811 break; 2812 default: 2813 break; 2814 } 2815 } 2816 2817 default: // We cannot analyze this expression. 2818 break; 2819 } 2820 2821 return getUnknown(V); 2822 } 2823 2824 2825 2826 //===----------------------------------------------------------------------===// 2827 // Iteration Count Computation Code 2828 // 2829 2830 /// getBackedgeTakenCount - If the specified loop has a predictable 2831 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute 2832 /// object. The backedge-taken count is the number of times the loop header 2833 /// will be branched to from within the loop. This is one less than the 2834 /// trip count of the loop, since it doesn't count the first iteration, 2835 /// when the header is branched to from outside the loop. 2836 /// 2837 /// Note that it is not valid to call this method on a loop without a 2838 /// loop-invariant backedge-taken count (see 2839 /// hasLoopInvariantBackedgeTakenCount). 2840 /// 2841 const SCEV* ScalarEvolution::getBackedgeTakenCount(const Loop *L) { 2842 return getBackedgeTakenInfo(L).Exact; 2843 } 2844 2845 /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except 2846 /// return the least SCEV value that is known never to be less than the 2847 /// actual backedge taken count. 2848 const SCEV* ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) { 2849 return getBackedgeTakenInfo(L).Max; 2850 } 2851 2852 const ScalarEvolution::BackedgeTakenInfo & 2853 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 2854 // Initially insert a CouldNotCompute for this loop. If the insertion 2855 // succeeds, procede to actually compute a backedge-taken count and 2856 // update the value. The temporary CouldNotCompute value tells SCEV 2857 // code elsewhere that it shouldn't attempt to request a new 2858 // backedge-taken count, which could result in infinite recursion. 2859 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair = 2860 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute())); 2861 if (Pair.second) { 2862 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L); 2863 if (ItCount.Exact != getCouldNotCompute()) { 2864 assert(ItCount.Exact->isLoopInvariant(L) && 2865 ItCount.Max->isLoopInvariant(L) && 2866 "Computed trip count isn't loop invariant for loop!"); 2867 ++NumTripCountsComputed; 2868 2869 // Update the value in the map. 2870 Pair.first->second = ItCount; 2871 } else { 2872 if (ItCount.Max != getCouldNotCompute()) 2873 // Update the value in the map. 2874 Pair.first->second = ItCount; 2875 if (isa<PHINode>(L->getHeader()->begin())) 2876 // Only count loops that have phi nodes as not being computable. 2877 ++NumTripCountsNotComputed; 2878 } 2879 2880 // Now that we know more about the trip count for this loop, forget any 2881 // existing SCEV values for PHI nodes in this loop since they are only 2882 // conservative estimates made without the benefit 2883 // of trip count information. 2884 if (ItCount.hasAnyInfo()) 2885 forgetLoopPHIs(L); 2886 } 2887 return Pair.first->second; 2888 } 2889 2890 /// forgetLoopBackedgeTakenCount - This method should be called by the 2891 /// client when it has changed a loop in a way that may effect 2892 /// ScalarEvolution's ability to compute a trip count, or if the loop 2893 /// is deleted. 2894 void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) { 2895 BackedgeTakenCounts.erase(L); 2896 forgetLoopPHIs(L); 2897 } 2898 2899 /// forgetLoopPHIs - Delete the memoized SCEVs associated with the 2900 /// PHI nodes in the given loop. This is used when the trip count of 2901 /// the loop may have changed. 2902 void ScalarEvolution::forgetLoopPHIs(const Loop *L) { 2903 BasicBlock *Header = L->getHeader(); 2904 2905 // Push all Loop-header PHIs onto the Worklist stack, except those 2906 // that are presently represented via a SCEVUnknown. SCEVUnknown for 2907 // a PHI either means that it has an unrecognized structure, or it's 2908 // a PHI that's in the progress of being computed by createNodeForPHI. 2909 // In the former case, additional loop trip count information isn't 2910 // going to change anything. In the later case, createNodeForPHI will 2911 // perform the necessary updates on its own when it gets to that point. 2912 SmallVector<Instruction *, 16> Worklist; 2913 for (BasicBlock::iterator I = Header->begin(); 2914 PHINode *PN = dyn_cast<PHINode>(I); ++I) { 2915 std::map<SCEVCallbackVH, const SCEV*>::iterator It = 2916 Scalars.find((Value*)I); 2917 if (It != Scalars.end() && !isa<SCEVUnknown>(It->second)) 2918 Worklist.push_back(PN); 2919 } 2920 2921 while (!Worklist.empty()) { 2922 Instruction *I = Worklist.pop_back_val(); 2923 if (Scalars.erase(I)) 2924 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); 2925 UI != UE; ++UI) 2926 Worklist.push_back(cast<Instruction>(UI)); 2927 } 2928 } 2929 2930 /// ComputeBackedgeTakenCount - Compute the number of times the backedge 2931 /// of the specified loop will execute. 2932 ScalarEvolution::BackedgeTakenInfo 2933 ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) { 2934 SmallVector<BasicBlock*, 8> ExitingBlocks; 2935 L->getExitingBlocks(ExitingBlocks); 2936 2937 // Examine all exits and pick the most conservative values. 2938 const SCEV* BECount = getCouldNotCompute(); 2939 const SCEV* MaxBECount = getCouldNotCompute(); 2940 bool CouldNotComputeBECount = false; 2941 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 2942 BackedgeTakenInfo NewBTI = 2943 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]); 2944 2945 if (NewBTI.Exact == getCouldNotCompute()) { 2946 // We couldn't compute an exact value for this exit, so 2947 // we won't be able to compute an exact value for the loop. 2948 CouldNotComputeBECount = true; 2949 BECount = getCouldNotCompute(); 2950 } else if (!CouldNotComputeBECount) { 2951 if (BECount == getCouldNotCompute()) 2952 BECount = NewBTI.Exact; 2953 else 2954 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact); 2955 } 2956 if (MaxBECount == getCouldNotCompute()) 2957 MaxBECount = NewBTI.Max; 2958 else if (NewBTI.Max != getCouldNotCompute()) 2959 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max); 2960 } 2961 2962 return BackedgeTakenInfo(BECount, MaxBECount); 2963 } 2964 2965 /// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge 2966 /// of the specified loop will execute if it exits via the specified block. 2967 ScalarEvolution::BackedgeTakenInfo 2968 ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L, 2969 BasicBlock *ExitingBlock) { 2970 2971 // Okay, we've chosen an exiting block. See what condition causes us to 2972 // exit at this block. 2973 // 2974 // FIXME: we should be able to handle switch instructions (with a single exit) 2975 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator()); 2976 if (ExitBr == 0) return getCouldNotCompute(); 2977 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!"); 2978 2979 // At this point, we know we have a conditional branch that determines whether 2980 // the loop is exited. However, we don't know if the branch is executed each 2981 // time through the loop. If not, then the execution count of the branch will 2982 // not be equal to the trip count of the loop. 2983 // 2984 // Currently we check for this by checking to see if the Exit branch goes to 2985 // the loop header. If so, we know it will always execute the same number of 2986 // times as the loop. We also handle the case where the exit block *is* the 2987 // loop header. This is common for un-rotated loops. 2988 // 2989 // If both of those tests fail, walk up the unique predecessor chain to the 2990 // header, stopping if there is an edge that doesn't exit the loop. If the 2991 // header is reached, the execution count of the branch will be equal to the 2992 // trip count of the loop. 2993 // 2994 // More extensive analysis could be done to handle more cases here. 2995 // 2996 if (ExitBr->getSuccessor(0) != L->getHeader() && 2997 ExitBr->getSuccessor(1) != L->getHeader() && 2998 ExitBr->getParent() != L->getHeader()) { 2999 // The simple checks failed, try climbing the unique predecessor chain 3000 // up to the header. 3001 bool Ok = false; 3002 for (BasicBlock *BB = ExitBr->getParent(); BB; ) { 3003 BasicBlock *Pred = BB->getUniquePredecessor(); 3004 if (!Pred) 3005 return getCouldNotCompute(); 3006 TerminatorInst *PredTerm = Pred->getTerminator(); 3007 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) { 3008 BasicBlock *PredSucc = PredTerm->getSuccessor(i); 3009 if (PredSucc == BB) 3010 continue; 3011 // If the predecessor has a successor that isn't BB and isn't 3012 // outside the loop, assume the worst. 3013 if (L->contains(PredSucc)) 3014 return getCouldNotCompute(); 3015 } 3016 if (Pred == L->getHeader()) { 3017 Ok = true; 3018 break; 3019 } 3020 BB = Pred; 3021 } 3022 if (!Ok) 3023 return getCouldNotCompute(); 3024 } 3025 3026 // Procede to the next level to examine the exit condition expression. 3027 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(), 3028 ExitBr->getSuccessor(0), 3029 ExitBr->getSuccessor(1)); 3030 } 3031 3032 /// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the 3033 /// backedge of the specified loop will execute if its exit condition 3034 /// were a conditional branch of ExitCond, TBB, and FBB. 3035 ScalarEvolution::BackedgeTakenInfo 3036 ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L, 3037 Value *ExitCond, 3038 BasicBlock *TBB, 3039 BasicBlock *FBB) { 3040 // Check if the controlling expression for this loop is an And or Or. 3041 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) { 3042 if (BO->getOpcode() == Instruction::And) { 3043 // Recurse on the operands of the and. 3044 BackedgeTakenInfo BTI0 = 3045 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB); 3046 BackedgeTakenInfo BTI1 = 3047 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB); 3048 const SCEV* BECount = getCouldNotCompute(); 3049 const SCEV* MaxBECount = getCouldNotCompute(); 3050 if (L->contains(TBB)) { 3051 // Both conditions must be true for the loop to continue executing. 3052 // Choose the less conservative count. 3053 if (BTI0.Exact == getCouldNotCompute() || 3054 BTI1.Exact == getCouldNotCompute()) 3055 BECount = getCouldNotCompute(); 3056 else 3057 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact); 3058 if (BTI0.Max == getCouldNotCompute()) 3059 MaxBECount = BTI1.Max; 3060 else if (BTI1.Max == getCouldNotCompute()) 3061 MaxBECount = BTI0.Max; 3062 else 3063 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max); 3064 } else { 3065 // Both conditions must be true for the loop to exit. 3066 assert(L->contains(FBB) && "Loop block has no successor in loop!"); 3067 if (BTI0.Exact != getCouldNotCompute() && 3068 BTI1.Exact != getCouldNotCompute()) 3069 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact); 3070 if (BTI0.Max != getCouldNotCompute() && 3071 BTI1.Max != getCouldNotCompute()) 3072 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max); 3073 } 3074 3075 return BackedgeTakenInfo(BECount, MaxBECount); 3076 } 3077 if (BO->getOpcode() == Instruction::Or) { 3078 // Recurse on the operands of the or. 3079 BackedgeTakenInfo BTI0 = 3080 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB); 3081 BackedgeTakenInfo BTI1 = 3082 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB); 3083 const SCEV* BECount = getCouldNotCompute(); 3084 const SCEV* MaxBECount = getCouldNotCompute(); 3085 if (L->contains(FBB)) { 3086 // Both conditions must be false for the loop to continue executing. 3087 // Choose the less conservative count. 3088 if (BTI0.Exact == getCouldNotCompute() || 3089 BTI1.Exact == getCouldNotCompute()) 3090 BECount = getCouldNotCompute(); 3091 else 3092 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact); 3093 if (BTI0.Max == getCouldNotCompute()) 3094 MaxBECount = BTI1.Max; 3095 else if (BTI1.Max == getCouldNotCompute()) 3096 MaxBECount = BTI0.Max; 3097 else 3098 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max); 3099 } else { 3100 // Both conditions must be false for the loop to exit. 3101 assert(L->contains(TBB) && "Loop block has no successor in loop!"); 3102 if (BTI0.Exact != getCouldNotCompute() && 3103 BTI1.Exact != getCouldNotCompute()) 3104 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact); 3105 if (BTI0.Max != getCouldNotCompute() && 3106 BTI1.Max != getCouldNotCompute()) 3107 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max); 3108 } 3109 3110 return BackedgeTakenInfo(BECount, MaxBECount); 3111 } 3112 } 3113 3114 // With an icmp, it may be feasible to compute an exact backedge-taken count. 3115 // Procede to the next level to examine the icmp. 3116 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) 3117 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB); 3118 3119 // If it's not an integer or pointer comparison then compute it the hard way. 3120 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB)); 3121 } 3122 3123 /// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the 3124 /// backedge of the specified loop will execute if its exit condition 3125 /// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB. 3126 ScalarEvolution::BackedgeTakenInfo 3127 ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L, 3128 ICmpInst *ExitCond, 3129 BasicBlock *TBB, 3130 BasicBlock *FBB) { 3131 3132 // If the condition was exit on true, convert the condition to exit on false 3133 ICmpInst::Predicate Cond; 3134 if (!L->contains(FBB)) 3135 Cond = ExitCond->getPredicate(); 3136 else 3137 Cond = ExitCond->getInversePredicate(); 3138 3139 // Handle common loops like: for (X = "string"; *X; ++X) 3140 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 3141 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 3142 const SCEV* ItCnt = 3143 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond); 3144 if (!isa<SCEVCouldNotCompute>(ItCnt)) { 3145 unsigned BitWidth = getTypeSizeInBits(ItCnt->getType()); 3146 return BackedgeTakenInfo(ItCnt, 3147 isa<SCEVConstant>(ItCnt) ? ItCnt : 3148 getConstant(APInt::getMaxValue(BitWidth)-1)); 3149 } 3150 } 3151 3152 const SCEV* LHS = getSCEV(ExitCond->getOperand(0)); 3153 const SCEV* RHS = getSCEV(ExitCond->getOperand(1)); 3154 3155 // Try to evaluate any dependencies out of the loop. 3156 LHS = getSCEVAtScope(LHS, L); 3157 RHS = getSCEVAtScope(RHS, L); 3158 3159 // At this point, we would like to compute how many iterations of the 3160 // loop the predicate will return true for these inputs. 3161 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) { 3162 // If there is a loop-invariant, force it into the RHS. 3163 std::swap(LHS, RHS); 3164 Cond = ICmpInst::getSwappedPredicate(Cond); 3165 } 3166 3167 // If we have a comparison of a chrec against a constant, try to use value 3168 // ranges to answer this query. 3169 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 3170 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 3171 if (AddRec->getLoop() == L) { 3172 // Form the constant range. 3173 ConstantRange CompRange( 3174 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue())); 3175 3176 const SCEV* Ret = AddRec->getNumIterationsInRange(CompRange, *this); 3177 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 3178 } 3179 3180 switch (Cond) { 3181 case ICmpInst::ICMP_NE: { // while (X != Y) 3182 // Convert to: while (X-Y != 0) 3183 const SCEV* TC = HowFarToZero(getMinusSCEV(LHS, RHS), L); 3184 if (!isa<SCEVCouldNotCompute>(TC)) return TC; 3185 break; 3186 } 3187 case ICmpInst::ICMP_EQ: { 3188 // Convert to: while (X-Y == 0) // while (X == Y) 3189 const SCEV* TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L); 3190 if (!isa<SCEVCouldNotCompute>(TC)) return TC; 3191 break; 3192 } 3193 case ICmpInst::ICMP_SLT: { 3194 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true); 3195 if (BTI.hasAnyInfo()) return BTI; 3196 break; 3197 } 3198 case ICmpInst::ICMP_SGT: { 3199 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS), 3200 getNotSCEV(RHS), L, true); 3201 if (BTI.hasAnyInfo()) return BTI; 3202 break; 3203 } 3204 case ICmpInst::ICMP_ULT: { 3205 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false); 3206 if (BTI.hasAnyInfo()) return BTI; 3207 break; 3208 } 3209 case ICmpInst::ICMP_UGT: { 3210 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS), 3211 getNotSCEV(RHS), L, false); 3212 if (BTI.hasAnyInfo()) return BTI; 3213 break; 3214 } 3215 default: 3216 #if 0 3217 errs() << "ComputeBackedgeTakenCount "; 3218 if (ExitCond->getOperand(0)->getType()->isUnsigned()) 3219 errs() << "[unsigned] "; 3220 errs() << *LHS << " " 3221 << Instruction::getOpcodeName(Instruction::ICmp) 3222 << " " << *RHS << "\n"; 3223 #endif 3224 break; 3225 } 3226 return 3227 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB)); 3228 } 3229 3230 static ConstantInt * 3231 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 3232 ScalarEvolution &SE) { 3233 const SCEV* InVal = SE.getConstant(C); 3234 const SCEV* Val = AddRec->evaluateAtIteration(InVal, SE); 3235 assert(isa<SCEVConstant>(Val) && 3236 "Evaluation of SCEV at constant didn't fold correctly?"); 3237 return cast<SCEVConstant>(Val)->getValue(); 3238 } 3239 3240 /// GetAddressedElementFromGlobal - Given a global variable with an initializer 3241 /// and a GEP expression (missing the pointer index) indexing into it, return 3242 /// the addressed element of the initializer or null if the index expression is 3243 /// invalid. 3244 static Constant * 3245 GetAddressedElementFromGlobal(GlobalVariable *GV, 3246 const std::vector<ConstantInt*> &Indices) { 3247 Constant *Init = GV->getInitializer(); 3248 for (unsigned i = 0, e = Indices.size(); i != e; ++i) { 3249 uint64_t Idx = Indices[i]->getZExtValue(); 3250 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) { 3251 assert(Idx < CS->getNumOperands() && "Bad struct index!"); 3252 Init = cast<Constant>(CS->getOperand(Idx)); 3253 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) { 3254 if (Idx >= CA->getNumOperands()) return 0; // Bogus program 3255 Init = cast<Constant>(CA->getOperand(Idx)); 3256 } else if (isa<ConstantAggregateZero>(Init)) { 3257 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) { 3258 assert(Idx < STy->getNumElements() && "Bad struct index!"); 3259 Init = Constant::getNullValue(STy->getElementType(Idx)); 3260 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) { 3261 if (Idx >= ATy->getNumElements()) return 0; // Bogus program 3262 Init = Constant::getNullValue(ATy->getElementType()); 3263 } else { 3264 assert(0 && "Unknown constant aggregate type!"); 3265 } 3266 return 0; 3267 } else { 3268 return 0; // Unknown initializer type 3269 } 3270 } 3271 return Init; 3272 } 3273 3274 /// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of 3275 /// 'icmp op load X, cst', try to see if we can compute the backedge 3276 /// execution count. 3277 const SCEV * 3278 ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount( 3279 LoadInst *LI, 3280 Constant *RHS, 3281 const Loop *L, 3282 ICmpInst::Predicate predicate) { 3283 if (LI->isVolatile()) return getCouldNotCompute(); 3284 3285 // Check to see if the loaded pointer is a getelementptr of a global. 3286 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 3287 if (!GEP) return getCouldNotCompute(); 3288 3289 // Make sure that it is really a constant global we are gepping, with an 3290 // initializer, and make sure the first IDX is really 0. 3291 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 3292 if (!GV || !GV->isConstant() || !GV->hasInitializer() || 3293 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 3294 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 3295 return getCouldNotCompute(); 3296 3297 // Okay, we allow one non-constant index into the GEP instruction. 3298 Value *VarIdx = 0; 3299 std::vector<ConstantInt*> Indexes; 3300 unsigned VarIdxNum = 0; 3301 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 3302 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 3303 Indexes.push_back(CI); 3304 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 3305 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. 3306 VarIdx = GEP->getOperand(i); 3307 VarIdxNum = i-2; 3308 Indexes.push_back(0); 3309 } 3310 3311 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 3312 // Check to see if X is a loop variant variable value now. 3313 const SCEV* Idx = getSCEV(VarIdx); 3314 Idx = getSCEVAtScope(Idx, L); 3315 3316 // We can only recognize very limited forms of loop index expressions, in 3317 // particular, only affine AddRec's like {C1,+,C2}. 3318 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 3319 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) || 3320 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 3321 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 3322 return getCouldNotCompute(); 3323 3324 unsigned MaxSteps = MaxBruteForceIterations; 3325 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 3326 ConstantInt *ItCst = 3327 ConstantInt::get(cast<IntegerType>(IdxExpr->getType()), IterationNum); 3328 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 3329 3330 // Form the GEP offset. 3331 Indexes[VarIdxNum] = Val; 3332 3333 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes); 3334 if (Result == 0) break; // Cannot compute! 3335 3336 // Evaluate the condition for this iteration. 3337 Result = ConstantExpr::getICmp(predicate, Result, RHS); 3338 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 3339 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 3340 #if 0 3341 errs() << "\n***\n*** Computed loop count " << *ItCst 3342 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader() 3343 << "***\n"; 3344 #endif 3345 ++NumArrayLenItCounts; 3346 return getConstant(ItCst); // Found terminating iteration! 3347 } 3348 } 3349 return getCouldNotCompute(); 3350 } 3351 3352 3353 /// CanConstantFold - Return true if we can constant fold an instruction of the 3354 /// specified type, assuming that all operands were constants. 3355 static bool CanConstantFold(const Instruction *I) { 3356 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 3357 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I)) 3358 return true; 3359 3360 if (const CallInst *CI = dyn_cast<CallInst>(I)) 3361 if (const Function *F = CI->getCalledFunction()) 3362 return canConstantFoldCallTo(F); 3363 return false; 3364 } 3365 3366 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 3367 /// in the loop that V is derived from. We allow arbitrary operations along the 3368 /// way, but the operands of an operation must either be constants or a value 3369 /// derived from a constant PHI. If this expression does not fit with these 3370 /// constraints, return null. 3371 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 3372 // If this is not an instruction, or if this is an instruction outside of the 3373 // loop, it can't be derived from a loop PHI. 3374 Instruction *I = dyn_cast<Instruction>(V); 3375 if (I == 0 || !L->contains(I->getParent())) return 0; 3376 3377 if (PHINode *PN = dyn_cast<PHINode>(I)) { 3378 if (L->getHeader() == I->getParent()) 3379 return PN; 3380 else 3381 // We don't currently keep track of the control flow needed to evaluate 3382 // PHIs, so we cannot handle PHIs inside of loops. 3383 return 0; 3384 } 3385 3386 // If we won't be able to constant fold this expression even if the operands 3387 // are constants, return early. 3388 if (!CanConstantFold(I)) return 0; 3389 3390 // Otherwise, we can evaluate this instruction if all of its operands are 3391 // constant or derived from a PHI node themselves. 3392 PHINode *PHI = 0; 3393 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op) 3394 if (!(isa<Constant>(I->getOperand(Op)) || 3395 isa<GlobalValue>(I->getOperand(Op)))) { 3396 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L); 3397 if (P == 0) return 0; // Not evolving from PHI 3398 if (PHI == 0) 3399 PHI = P; 3400 else if (PHI != P) 3401 return 0; // Evolving from multiple different PHIs. 3402 } 3403 3404 // This is a expression evolving from a constant PHI! 3405 return PHI; 3406 } 3407 3408 /// EvaluateExpression - Given an expression that passes the 3409 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 3410 /// in the loop has the value PHIVal. If we can't fold this expression for some 3411 /// reason, return null. 3412 static Constant *EvaluateExpression(Value *V, Constant *PHIVal) { 3413 if (isa<PHINode>(V)) return PHIVal; 3414 if (Constant *C = dyn_cast<Constant>(V)) return C; 3415 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV; 3416 Instruction *I = cast<Instruction>(V); 3417 3418 std::vector<Constant*> Operands; 3419 Operands.resize(I->getNumOperands()); 3420 3421 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 3422 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal); 3423 if (Operands[i] == 0) return 0; 3424 } 3425 3426 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 3427 return ConstantFoldCompareInstOperands(CI->getPredicate(), 3428 &Operands[0], Operands.size()); 3429 else 3430 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), 3431 &Operands[0], Operands.size()); 3432 } 3433 3434 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 3435 /// in the header of its containing loop, we know the loop executes a 3436 /// constant number of times, and the PHI node is just a recurrence 3437 /// involving constants, fold it. 3438 Constant * 3439 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 3440 const APInt& BEs, 3441 const Loop *L) { 3442 std::map<PHINode*, Constant*>::iterator I = 3443 ConstantEvolutionLoopExitValue.find(PN); 3444 if (I != ConstantEvolutionLoopExitValue.end()) 3445 return I->second; 3446 3447 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations))) 3448 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it. 3449 3450 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 3451 3452 // Since the loop is canonicalized, the PHI node must have two entries. One 3453 // entry must be a constant (coming in from outside of the loop), and the 3454 // second must be derived from the same PHI. 3455 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1)); 3456 Constant *StartCST = 3457 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge)); 3458 if (StartCST == 0) 3459 return RetVal = 0; // Must be a constant. 3460 3461 Value *BEValue = PN->getIncomingValue(SecondIsBackedge); 3462 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L); 3463 if (PN2 != PN) 3464 return RetVal = 0; // Not derived from same PHI. 3465 3466 // Execute the loop symbolically to determine the exit value. 3467 if (BEs.getActiveBits() >= 32) 3468 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it! 3469 3470 unsigned NumIterations = BEs.getZExtValue(); // must be in range 3471 unsigned IterationNum = 0; 3472 for (Constant *PHIVal = StartCST; ; ++IterationNum) { 3473 if (IterationNum == NumIterations) 3474 return RetVal = PHIVal; // Got exit value! 3475 3476 // Compute the value of the PHI node for the next iteration. 3477 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal); 3478 if (NextPHI == PHIVal) 3479 return RetVal = NextPHI; // Stopped evolving! 3480 if (NextPHI == 0) 3481 return 0; // Couldn't evaluate! 3482 PHIVal = NextPHI; 3483 } 3484 } 3485 3486 /// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a 3487 /// constant number of times (the condition evolves only from constants), 3488 /// try to evaluate a few iterations of the loop until we get the exit 3489 /// condition gets a value of ExitWhen (true or false). If we cannot 3490 /// evaluate the trip count of the loop, return getCouldNotCompute(). 3491 const SCEV * 3492 ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L, 3493 Value *Cond, 3494 bool ExitWhen) { 3495 PHINode *PN = getConstantEvolvingPHI(Cond, L); 3496 if (PN == 0) return getCouldNotCompute(); 3497 3498 // Since the loop is canonicalized, the PHI node must have two entries. One 3499 // entry must be a constant (coming in from outside of the loop), and the 3500 // second must be derived from the same PHI. 3501 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1)); 3502 Constant *StartCST = 3503 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge)); 3504 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant. 3505 3506 Value *BEValue = PN->getIncomingValue(SecondIsBackedge); 3507 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L); 3508 if (PN2 != PN) return getCouldNotCompute(); // Not derived from same PHI. 3509 3510 // Okay, we find a PHI node that defines the trip count of this loop. Execute 3511 // the loop symbolically to determine when the condition gets a value of 3512 // "ExitWhen". 3513 unsigned IterationNum = 0; 3514 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 3515 for (Constant *PHIVal = StartCST; 3516 IterationNum != MaxIterations; ++IterationNum) { 3517 ConstantInt *CondVal = 3518 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal)); 3519 3520 // Couldn't symbolically evaluate. 3521 if (!CondVal) return getCouldNotCompute(); 3522 3523 if (CondVal->getValue() == uint64_t(ExitWhen)) { 3524 ConstantEvolutionLoopExitValue[PN] = PHIVal; 3525 ++NumBruteForceTripCountsComputed; 3526 return getConstant(Type::Int32Ty, IterationNum); 3527 } 3528 3529 // Compute the value of the PHI node for the next iteration. 3530 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal); 3531 if (NextPHI == 0 || NextPHI == PHIVal) 3532 return getCouldNotCompute();// Couldn't evaluate or not making progress... 3533 PHIVal = NextPHI; 3534 } 3535 3536 // Too many iterations were needed to evaluate. 3537 return getCouldNotCompute(); 3538 } 3539 3540 /// getSCEVAtScope - Return a SCEV expression handle for the specified value 3541 /// at the specified scope in the program. The L value specifies a loop 3542 /// nest to evaluate the expression at, where null is the top-level or a 3543 /// specified loop is immediately inside of the loop. 3544 /// 3545 /// This method can be used to compute the exit value for a variable defined 3546 /// in a loop by querying what the value will hold in the parent loop. 3547 /// 3548 /// In the case that a relevant loop exit value cannot be computed, the 3549 /// original value V is returned. 3550 const SCEV* ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 3551 // FIXME: this should be turned into a virtual method on SCEV! 3552 3553 if (isa<SCEVConstant>(V)) return V; 3554 3555 // If this instruction is evolved from a constant-evolving PHI, compute the 3556 // exit value from the loop without using SCEVs. 3557 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 3558 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 3559 const Loop *LI = (*this->LI)[I->getParent()]; 3560 if (LI && LI->getParentLoop() == L) // Looking for loop exit value. 3561 if (PHINode *PN = dyn_cast<PHINode>(I)) 3562 if (PN->getParent() == LI->getHeader()) { 3563 // Okay, there is no closed form solution for the PHI node. Check 3564 // to see if the loop that contains it has a known backedge-taken 3565 // count. If so, we may be able to force computation of the exit 3566 // value. 3567 const SCEV* BackedgeTakenCount = getBackedgeTakenCount(LI); 3568 if (const SCEVConstant *BTCC = 3569 dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 3570 // Okay, we know how many times the containing loop executes. If 3571 // this is a constant evolving PHI node, get the final value at 3572 // the specified iteration number. 3573 Constant *RV = getConstantEvolutionLoopExitValue(PN, 3574 BTCC->getValue()->getValue(), 3575 LI); 3576 if (RV) return getUnknown(RV); 3577 } 3578 } 3579 3580 // Okay, this is an expression that we cannot symbolically evaluate 3581 // into a SCEV. Check to see if it's possible to symbolically evaluate 3582 // the arguments into constants, and if so, try to constant propagate the 3583 // result. This is particularly useful for computing loop exit values. 3584 if (CanConstantFold(I)) { 3585 // Check to see if we've folded this instruction at this loop before. 3586 std::map<const Loop *, Constant *> &Values = ValuesAtScopes[I]; 3587 std::pair<std::map<const Loop *, Constant *>::iterator, bool> Pair = 3588 Values.insert(std::make_pair(L, static_cast<Constant *>(0))); 3589 if (!Pair.second) 3590 return Pair.first->second ? &*getUnknown(Pair.first->second) : V; 3591 3592 std::vector<Constant*> Operands; 3593 Operands.reserve(I->getNumOperands()); 3594 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 3595 Value *Op = I->getOperand(i); 3596 if (Constant *C = dyn_cast<Constant>(Op)) { 3597 Operands.push_back(C); 3598 } else { 3599 // If any of the operands is non-constant and if they are 3600 // non-integer and non-pointer, don't even try to analyze them 3601 // with scev techniques. 3602 if (!isSCEVable(Op->getType())) 3603 return V; 3604 3605 const SCEV* OpV = getSCEVAtScope(getSCEV(Op), L); 3606 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) { 3607 Constant *C = SC->getValue(); 3608 if (C->getType() != Op->getType()) 3609 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 3610 Op->getType(), 3611 false), 3612 C, Op->getType()); 3613 Operands.push_back(C); 3614 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) { 3615 if (Constant *C = dyn_cast<Constant>(SU->getValue())) { 3616 if (C->getType() != Op->getType()) 3617 C = 3618 ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 3619 Op->getType(), 3620 false), 3621 C, Op->getType()); 3622 Operands.push_back(C); 3623 } else 3624 return V; 3625 } else { 3626 return V; 3627 } 3628 } 3629 } 3630 3631 Constant *C; 3632 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 3633 C = ConstantFoldCompareInstOperands(CI->getPredicate(), 3634 &Operands[0], Operands.size()); 3635 else 3636 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(), 3637 &Operands[0], Operands.size()); 3638 Pair.first->second = C; 3639 return getUnknown(C); 3640 } 3641 } 3642 3643 // This is some other type of SCEVUnknown, just return it. 3644 return V; 3645 } 3646 3647 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 3648 // Avoid performing the look-up in the common case where the specified 3649 // expression has no loop-variant portions. 3650 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 3651 const SCEV* OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 3652 if (OpAtScope != Comm->getOperand(i)) { 3653 // Okay, at least one of these operands is loop variant but might be 3654 // foldable. Build a new instance of the folded commutative expression. 3655 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 3656 Comm->op_begin()+i); 3657 NewOps.push_back(OpAtScope); 3658 3659 for (++i; i != e; ++i) { 3660 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 3661 NewOps.push_back(OpAtScope); 3662 } 3663 if (isa<SCEVAddExpr>(Comm)) 3664 return getAddExpr(NewOps); 3665 if (isa<SCEVMulExpr>(Comm)) 3666 return getMulExpr(NewOps); 3667 if (isa<SCEVSMaxExpr>(Comm)) 3668 return getSMaxExpr(NewOps); 3669 if (isa<SCEVUMaxExpr>(Comm)) 3670 return getUMaxExpr(NewOps); 3671 assert(0 && "Unknown commutative SCEV type!"); 3672 } 3673 } 3674 // If we got here, all operands are loop invariant. 3675 return Comm; 3676 } 3677 3678 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 3679 const SCEV* LHS = getSCEVAtScope(Div->getLHS(), L); 3680 const SCEV* RHS = getSCEVAtScope(Div->getRHS(), L); 3681 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 3682 return Div; // must be loop invariant 3683 return getUDivExpr(LHS, RHS); 3684 } 3685 3686 // If this is a loop recurrence for a loop that does not contain L, then we 3687 // are dealing with the final value computed by the loop. 3688 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 3689 if (!L || !AddRec->getLoop()->contains(L->getHeader())) { 3690 // To evaluate this recurrence, we need to know how many times the AddRec 3691 // loop iterates. Compute this now. 3692 const SCEV* BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 3693 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 3694 3695 // Then, evaluate the AddRec. 3696 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 3697 } 3698 return AddRec; 3699 } 3700 3701 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 3702 const SCEV* Op = getSCEVAtScope(Cast->getOperand(), L); 3703 if (Op == Cast->getOperand()) 3704 return Cast; // must be loop invariant 3705 return getZeroExtendExpr(Op, Cast->getType()); 3706 } 3707 3708 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 3709 const SCEV* Op = getSCEVAtScope(Cast->getOperand(), L); 3710 if (Op == Cast->getOperand()) 3711 return Cast; // must be loop invariant 3712 return getSignExtendExpr(Op, Cast->getType()); 3713 } 3714 3715 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 3716 const SCEV* Op = getSCEVAtScope(Cast->getOperand(), L); 3717 if (Op == Cast->getOperand()) 3718 return Cast; // must be loop invariant 3719 return getTruncateExpr(Op, Cast->getType()); 3720 } 3721 3722 assert(0 && "Unknown SCEV type!"); 3723 return 0; 3724 } 3725 3726 /// getSCEVAtScope - This is a convenience function which does 3727 /// getSCEVAtScope(getSCEV(V), L). 3728 const SCEV* ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 3729 return getSCEVAtScope(getSCEV(V), L); 3730 } 3731 3732 /// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the 3733 /// following equation: 3734 /// 3735 /// A * X = B (mod N) 3736 /// 3737 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 3738 /// A and B isn't important. 3739 /// 3740 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 3741 static const SCEV* SolveLinEquationWithOverflow(const APInt &A, const APInt &B, 3742 ScalarEvolution &SE) { 3743 uint32_t BW = A.getBitWidth(); 3744 assert(BW == B.getBitWidth() && "Bit widths must be the same."); 3745 assert(A != 0 && "A must be non-zero."); 3746 3747 // 1. D = gcd(A, N) 3748 // 3749 // The gcd of A and N may have only one prime factor: 2. The number of 3750 // trailing zeros in A is its multiplicity 3751 uint32_t Mult2 = A.countTrailingZeros(); 3752 // D = 2^Mult2 3753 3754 // 2. Check if B is divisible by D. 3755 // 3756 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 3757 // is not less than multiplicity of this prime factor for D. 3758 if (B.countTrailingZeros() < Mult2) 3759 return SE.getCouldNotCompute(); 3760 3761 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 3762 // modulo (N / D). 3763 // 3764 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this 3765 // bit width during computations. 3766 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 3767 APInt Mod(BW + 1, 0); 3768 Mod.set(BW - Mult2); // Mod = N / D 3769 APInt I = AD.multiplicativeInverse(Mod); 3770 3771 // 4. Compute the minimum unsigned root of the equation: 3772 // I * (B / D) mod (N / D) 3773 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod); 3774 3775 // The result is guaranteed to be less than 2^BW so we may truncate it to BW 3776 // bits. 3777 return SE.getConstant(Result.trunc(BW)); 3778 } 3779 3780 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the 3781 /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which 3782 /// might be the same) or two SCEVCouldNotCompute objects. 3783 /// 3784 static std::pair<const SCEV*,const SCEV*> 3785 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 3786 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 3787 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 3788 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 3789 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 3790 3791 // We currently can only solve this if the coefficients are constants. 3792 if (!LC || !MC || !NC) { 3793 const SCEV *CNC = SE.getCouldNotCompute(); 3794 return std::make_pair(CNC, CNC); 3795 } 3796 3797 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth(); 3798 const APInt &L = LC->getValue()->getValue(); 3799 const APInt &M = MC->getValue()->getValue(); 3800 const APInt &N = NC->getValue()->getValue(); 3801 APInt Two(BitWidth, 2); 3802 APInt Four(BitWidth, 4); 3803 3804 { 3805 using namespace APIntOps; 3806 const APInt& C = L; 3807 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C 3808 // The B coefficient is M-N/2 3809 APInt B(M); 3810 B -= sdiv(N,Two); 3811 3812 // The A coefficient is N/2 3813 APInt A(N.sdiv(Two)); 3814 3815 // Compute the B^2-4ac term. 3816 APInt SqrtTerm(B); 3817 SqrtTerm *= B; 3818 SqrtTerm -= Four * (A * C); 3819 3820 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest 3821 // integer value or else APInt::sqrt() will assert. 3822 APInt SqrtVal(SqrtTerm.sqrt()); 3823 3824 // Compute the two solutions for the quadratic formula. 3825 // The divisions must be performed as signed divisions. 3826 APInt NegB(-B); 3827 APInt TwoA( A << 1 ); 3828 if (TwoA.isMinValue()) { 3829 const SCEV *CNC = SE.getCouldNotCompute(); 3830 return std::make_pair(CNC, CNC); 3831 } 3832 3833 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA)); 3834 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA)); 3835 3836 return std::make_pair(SE.getConstant(Solution1), 3837 SE.getConstant(Solution2)); 3838 } // end APIntOps namespace 3839 } 3840 3841 /// HowFarToZero - Return the number of times a backedge comparing the specified 3842 /// value to zero will execute. If not computable, return CouldNotCompute. 3843 const SCEV* ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) { 3844 // If the value is a constant 3845 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 3846 // If the value is already zero, the branch will execute zero times. 3847 if (C->getValue()->isZero()) return C; 3848 return getCouldNotCompute(); // Otherwise it will loop infinitely. 3849 } 3850 3851 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V); 3852 if (!AddRec || AddRec->getLoop() != L) 3853 return getCouldNotCompute(); 3854 3855 if (AddRec->isAffine()) { 3856 // If this is an affine expression, the execution count of this branch is 3857 // the minimum unsigned root of the following equation: 3858 // 3859 // Start + Step*N = 0 (mod 2^BW) 3860 // 3861 // equivalent to: 3862 // 3863 // Step*N = -Start (mod 2^BW) 3864 // 3865 // where BW is the common bit width of Start and Step. 3866 3867 // Get the initial value for the loop. 3868 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), 3869 L->getParentLoop()); 3870 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), 3871 L->getParentLoop()); 3872 3873 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) { 3874 // For now we handle only constant steps. 3875 3876 // First, handle unitary steps. 3877 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so: 3878 return getNegativeSCEV(Start); // N = -Start (as unsigned) 3879 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so: 3880 return Start; // N = Start (as unsigned) 3881 3882 // Then, try to solve the above equation provided that Start is constant. 3883 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) 3884 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(), 3885 -StartC->getValue()->getValue(), 3886 *this); 3887 } 3888 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) { 3889 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 3890 // the quadratic equation to solve it. 3891 std::pair<const SCEV*,const SCEV*> Roots = SolveQuadraticEquation(AddRec, 3892 *this); 3893 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first); 3894 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second); 3895 if (R1) { 3896 #if 0 3897 errs() << "HFTZ: " << *V << " - sol#1: " << *R1 3898 << " sol#2: " << *R2 << "\n"; 3899 #endif 3900 // Pick the smallest positive root value. 3901 if (ConstantInt *CB = 3902 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT, 3903 R1->getValue(), R2->getValue()))) { 3904 if (CB->getZExtValue() == false) 3905 std::swap(R1, R2); // R1 is the minimum root now. 3906 3907 // We can only use this value if the chrec ends up with an exact zero 3908 // value at this index. When solving for "X*X != 5", for example, we 3909 // should not accept a root of 2. 3910 const SCEV* Val = AddRec->evaluateAtIteration(R1, *this); 3911 if (Val->isZero()) 3912 return R1; // We found a quadratic root! 3913 } 3914 } 3915 } 3916 3917 return getCouldNotCompute(); 3918 } 3919 3920 /// HowFarToNonZero - Return the number of times a backedge checking the 3921 /// specified value for nonzero will execute. If not computable, return 3922 /// CouldNotCompute 3923 const SCEV* ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) { 3924 // Loops that look like: while (X == 0) are very strange indeed. We don't 3925 // handle them yet except for the trivial case. This could be expanded in the 3926 // future as needed. 3927 3928 // If the value is a constant, check to see if it is known to be non-zero 3929 // already. If so, the backedge will execute zero times. 3930 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 3931 if (!C->getValue()->isNullValue()) 3932 return getIntegerSCEV(0, C->getType()); 3933 return getCouldNotCompute(); // Otherwise it will loop infinitely. 3934 } 3935 3936 // We could implement others, but I really doubt anyone writes loops like 3937 // this, and if they did, they would already be constant folded. 3938 return getCouldNotCompute(); 3939 } 3940 3941 /// getLoopPredecessor - If the given loop's header has exactly one unique 3942 /// predecessor outside the loop, return it. Otherwise return null. 3943 /// 3944 BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) { 3945 BasicBlock *Header = L->getHeader(); 3946 BasicBlock *Pred = 0; 3947 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header); 3948 PI != E; ++PI) 3949 if (!L->contains(*PI)) { 3950 if (Pred && Pred != *PI) return 0; // Multiple predecessors. 3951 Pred = *PI; 3952 } 3953 return Pred; 3954 } 3955 3956 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB 3957 /// (which may not be an immediate predecessor) which has exactly one 3958 /// successor from which BB is reachable, or null if no such block is 3959 /// found. 3960 /// 3961 BasicBlock * 3962 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) { 3963 // If the block has a unique predecessor, then there is no path from the 3964 // predecessor to the block that does not go through the direct edge 3965 // from the predecessor to the block. 3966 if (BasicBlock *Pred = BB->getSinglePredecessor()) 3967 return Pred; 3968 3969 // A loop's header is defined to be a block that dominates the loop. 3970 // If the header has a unique predecessor outside the loop, it must be 3971 // a block that has exactly one successor that can reach the loop. 3972 if (Loop *L = LI->getLoopFor(BB)) 3973 return getLoopPredecessor(L); 3974 3975 return 0; 3976 } 3977 3978 /// HasSameValue - SCEV structural equivalence is usually sufficient for 3979 /// testing whether two expressions are equal, however for the purposes of 3980 /// looking for a condition guarding a loop, it can be useful to be a little 3981 /// more general, since a front-end may have replicated the controlling 3982 /// expression. 3983 /// 3984 static bool HasSameValue(const SCEV* A, const SCEV* B) { 3985 // Quick check to see if they are the same SCEV. 3986 if (A == B) return true; 3987 3988 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 3989 // two different instructions with the same value. Check for this case. 3990 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 3991 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 3992 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 3993 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 3994 if (AI->isIdenticalTo(BI)) 3995 return true; 3996 3997 // Otherwise assume they may have a different value. 3998 return false; 3999 } 4000 4001 /// isLoopGuardedByCond - Test whether entry to the loop is protected by 4002 /// a conditional between LHS and RHS. This is used to help avoid max 4003 /// expressions in loop trip counts. 4004 bool ScalarEvolution::isLoopGuardedByCond(const Loop *L, 4005 ICmpInst::Predicate Pred, 4006 const SCEV *LHS, const SCEV *RHS) { 4007 // Interpret a null as meaning no loop, where there is obviously no guard 4008 // (interprocedural conditions notwithstanding). 4009 if (!L) return false; 4010 4011 BasicBlock *Predecessor = getLoopPredecessor(L); 4012 BasicBlock *PredecessorDest = L->getHeader(); 4013 4014 // Starting at the loop predecessor, climb up the predecessor chain, as long 4015 // as there are predecessors that can be found that have unique successors 4016 // leading to the original header. 4017 for (; Predecessor; 4018 PredecessorDest = Predecessor, 4019 Predecessor = getPredecessorWithUniqueSuccessorForBB(Predecessor)) { 4020 4021 BranchInst *LoopEntryPredicate = 4022 dyn_cast<BranchInst>(Predecessor->getTerminator()); 4023 if (!LoopEntryPredicate || 4024 LoopEntryPredicate->isUnconditional()) 4025 continue; 4026 4027 if (isNecessaryCond(LoopEntryPredicate->getCondition(), Pred, LHS, RHS, 4028 LoopEntryPredicate->getSuccessor(0) != PredecessorDest)) 4029 return true; 4030 } 4031 4032 return false; 4033 } 4034 4035 /// isNecessaryCond - Test whether the given CondValue value is a condition 4036 /// which is at least as strict as the one described by Pred, LHS, and RHS. 4037 bool ScalarEvolution::isNecessaryCond(Value *CondValue, 4038 ICmpInst::Predicate Pred, 4039 const SCEV *LHS, const SCEV *RHS, 4040 bool Inverse) { 4041 // Recursivly handle And and Or conditions. 4042 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CondValue)) { 4043 if (BO->getOpcode() == Instruction::And) { 4044 if (!Inverse) 4045 return isNecessaryCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) || 4046 isNecessaryCond(BO->getOperand(1), Pred, LHS, RHS, Inverse); 4047 } else if (BO->getOpcode() == Instruction::Or) { 4048 if (Inverse) 4049 return isNecessaryCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) || 4050 isNecessaryCond(BO->getOperand(1), Pred, LHS, RHS, Inverse); 4051 } 4052 } 4053 4054 ICmpInst *ICI = dyn_cast<ICmpInst>(CondValue); 4055 if (!ICI) return false; 4056 4057 // Now that we found a conditional branch that dominates the loop, check to 4058 // see if it is the comparison we are looking for. 4059 Value *PreCondLHS = ICI->getOperand(0); 4060 Value *PreCondRHS = ICI->getOperand(1); 4061 ICmpInst::Predicate Cond; 4062 if (Inverse) 4063 Cond = ICI->getInversePredicate(); 4064 else 4065 Cond = ICI->getPredicate(); 4066 4067 if (Cond == Pred) 4068 ; // An exact match. 4069 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE) 4070 ; // The actual condition is beyond sufficient. 4071 else 4072 // Check a few special cases. 4073 switch (Cond) { 4074 case ICmpInst::ICMP_UGT: 4075 if (Pred == ICmpInst::ICMP_ULT) { 4076 std::swap(PreCondLHS, PreCondRHS); 4077 Cond = ICmpInst::ICMP_ULT; 4078 break; 4079 } 4080 return false; 4081 case ICmpInst::ICMP_SGT: 4082 if (Pred == ICmpInst::ICMP_SLT) { 4083 std::swap(PreCondLHS, PreCondRHS); 4084 Cond = ICmpInst::ICMP_SLT; 4085 break; 4086 } 4087 return false; 4088 case ICmpInst::ICMP_NE: 4089 // Expressions like (x >u 0) are often canonicalized to (x != 0), 4090 // so check for this case by checking if the NE is comparing against 4091 // a minimum or maximum constant. 4092 if (!ICmpInst::isTrueWhenEqual(Pred)) 4093 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) { 4094 const APInt &A = CI->getValue(); 4095 switch (Pred) { 4096 case ICmpInst::ICMP_SLT: 4097 if (A.isMaxSignedValue()) break; 4098 return false; 4099 case ICmpInst::ICMP_SGT: 4100 if (A.isMinSignedValue()) break; 4101 return false; 4102 case ICmpInst::ICMP_ULT: 4103 if (A.isMaxValue()) break; 4104 return false; 4105 case ICmpInst::ICMP_UGT: 4106 if (A.isMinValue()) break; 4107 return false; 4108 default: 4109 return false; 4110 } 4111 Cond = ICmpInst::ICMP_NE; 4112 // NE is symmetric but the original comparison may not be. Swap 4113 // the operands if necessary so that they match below. 4114 if (isa<SCEVConstant>(LHS)) 4115 std::swap(PreCondLHS, PreCondRHS); 4116 break; 4117 } 4118 return false; 4119 default: 4120 // We weren't able to reconcile the condition. 4121 return false; 4122 } 4123 4124 if (!PreCondLHS->getType()->isInteger()) return false; 4125 4126 const SCEV *PreCondLHSSCEV = getSCEV(PreCondLHS); 4127 const SCEV *PreCondRHSSCEV = getSCEV(PreCondRHS); 4128 return (HasSameValue(LHS, PreCondLHSSCEV) && 4129 HasSameValue(RHS, PreCondRHSSCEV)) || 4130 (HasSameValue(LHS, getNotSCEV(PreCondRHSSCEV)) && 4131 HasSameValue(RHS, getNotSCEV(PreCondLHSSCEV))); 4132 } 4133 4134 /// getBECount - Subtract the end and start values and divide by the step, 4135 /// rounding up, to get the number of times the backedge is executed. Return 4136 /// CouldNotCompute if an intermediate computation overflows. 4137 const SCEV* ScalarEvolution::getBECount(const SCEV* Start, 4138 const SCEV* End, 4139 const SCEV* Step) { 4140 const Type *Ty = Start->getType(); 4141 const SCEV* NegOne = getIntegerSCEV(-1, Ty); 4142 const SCEV* Diff = getMinusSCEV(End, Start); 4143 const SCEV* RoundUp = getAddExpr(Step, NegOne); 4144 4145 // Add an adjustment to the difference between End and Start so that 4146 // the division will effectively round up. 4147 const SCEV* Add = getAddExpr(Diff, RoundUp); 4148 4149 // Check Add for unsigned overflow. 4150 // TODO: More sophisticated things could be done here. 4151 const Type *WideTy = IntegerType::get(getTypeSizeInBits(Ty) + 1); 4152 const SCEV* OperandExtendedAdd = 4153 getAddExpr(getZeroExtendExpr(Diff, WideTy), 4154 getZeroExtendExpr(RoundUp, WideTy)); 4155 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd) 4156 return getCouldNotCompute(); 4157 4158 return getUDivExpr(Add, Step); 4159 } 4160 4161 /// HowManyLessThans - Return the number of times a backedge containing the 4162 /// specified less-than comparison will execute. If not computable, return 4163 /// CouldNotCompute. 4164 ScalarEvolution::BackedgeTakenInfo 4165 ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS, 4166 const Loop *L, bool isSigned) { 4167 // Only handle: "ADDREC < LoopInvariant". 4168 if (!RHS->isLoopInvariant(L)) return getCouldNotCompute(); 4169 4170 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS); 4171 if (!AddRec || AddRec->getLoop() != L) 4172 return getCouldNotCompute(); 4173 4174 if (AddRec->isAffine()) { 4175 // FORNOW: We only support unit strides. 4176 unsigned BitWidth = getTypeSizeInBits(AddRec->getType()); 4177 const SCEV* Step = AddRec->getStepRecurrence(*this); 4178 4179 // TODO: handle non-constant strides. 4180 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step); 4181 if (!CStep || CStep->isZero()) 4182 return getCouldNotCompute(); 4183 if (CStep->isOne()) { 4184 // With unit stride, the iteration never steps past the limit value. 4185 } else if (CStep->getValue()->getValue().isStrictlyPositive()) { 4186 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) { 4187 // Test whether a positive iteration iteration can step past the limit 4188 // value and past the maximum value for its type in a single step. 4189 if (isSigned) { 4190 APInt Max = APInt::getSignedMaxValue(BitWidth); 4191 if ((Max - CStep->getValue()->getValue()) 4192 .slt(CLimit->getValue()->getValue())) 4193 return getCouldNotCompute(); 4194 } else { 4195 APInt Max = APInt::getMaxValue(BitWidth); 4196 if ((Max - CStep->getValue()->getValue()) 4197 .ult(CLimit->getValue()->getValue())) 4198 return getCouldNotCompute(); 4199 } 4200 } else 4201 // TODO: handle non-constant limit values below. 4202 return getCouldNotCompute(); 4203 } else 4204 // TODO: handle negative strides below. 4205 return getCouldNotCompute(); 4206 4207 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant 4208 // m. So, we count the number of iterations in which {n,+,s} < m is true. 4209 // Note that we cannot simply return max(m-n,0)/s because it's not safe to 4210 // treat m-n as signed nor unsigned due to overflow possibility. 4211 4212 // First, we get the value of the LHS in the first iteration: n 4213 const SCEV* Start = AddRec->getOperand(0); 4214 4215 // Determine the minimum constant start value. 4216 const SCEV *MinStart = isa<SCEVConstant>(Start) ? Start : 4217 getConstant(isSigned ? APInt::getSignedMinValue(BitWidth) : 4218 APInt::getMinValue(BitWidth)); 4219 4220 // If we know that the condition is true in order to enter the loop, 4221 // then we know that it will run exactly (m-n)/s times. Otherwise, we 4222 // only know that it will execute (max(m,n)-n)/s times. In both cases, 4223 // the division must round up. 4224 const SCEV* End = RHS; 4225 if (!isLoopGuardedByCond(L, 4226 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT, 4227 getMinusSCEV(Start, Step), RHS)) 4228 End = isSigned ? getSMaxExpr(RHS, Start) 4229 : getUMaxExpr(RHS, Start); 4230 4231 // Determine the maximum constant end value. 4232 const SCEV* MaxEnd = 4233 isa<SCEVConstant>(End) ? End : 4234 getConstant(isSigned ? APInt::getSignedMaxValue(BitWidth) 4235 .ashr(GetMinSignBits(End) - 1) : 4236 APInt::getMaxValue(BitWidth) 4237 .lshr(GetMinLeadingZeros(End))); 4238 4239 // Finally, we subtract these two values and divide, rounding up, to get 4240 // the number of times the backedge is executed. 4241 const SCEV* BECount = getBECount(Start, End, Step); 4242 4243 // The maximum backedge count is similar, except using the minimum start 4244 // value and the maximum end value. 4245 const SCEV* MaxBECount = getBECount(MinStart, MaxEnd, Step);; 4246 4247 return BackedgeTakenInfo(BECount, MaxBECount); 4248 } 4249 4250 return getCouldNotCompute(); 4251 } 4252 4253 /// getNumIterationsInRange - Return the number of iterations of this loop that 4254 /// produce values in the specified constant range. Another way of looking at 4255 /// this is that it returns the first iteration number where the value is not in 4256 /// the condition, thus computing the exit count. If the iteration count can't 4257 /// be computed, an instance of SCEVCouldNotCompute is returned. 4258 const SCEV* SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range, 4259 ScalarEvolution &SE) const { 4260 if (Range.isFullSet()) // Infinite loop. 4261 return SE.getCouldNotCompute(); 4262 4263 // If the start is a non-zero constant, shift the range to simplify things. 4264 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 4265 if (!SC->getValue()->isZero()) { 4266 SmallVector<const SCEV*, 4> Operands(op_begin(), op_end()); 4267 Operands[0] = SE.getIntegerSCEV(0, SC->getType()); 4268 const SCEV* Shifted = SE.getAddRecExpr(Operands, getLoop()); 4269 if (const SCEVAddRecExpr *ShiftedAddRec = 4270 dyn_cast<SCEVAddRecExpr>(Shifted)) 4271 return ShiftedAddRec->getNumIterationsInRange( 4272 Range.subtract(SC->getValue()->getValue()), SE); 4273 // This is strange and shouldn't happen. 4274 return SE.getCouldNotCompute(); 4275 } 4276 4277 // The only time we can solve this is when we have all constant indices. 4278 // Otherwise, we cannot determine the overflow conditions. 4279 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) 4280 if (!isa<SCEVConstant>(getOperand(i))) 4281 return SE.getCouldNotCompute(); 4282 4283 4284 // Okay at this point we know that all elements of the chrec are constants and 4285 // that the start element is zero. 4286 4287 // First check to see if the range contains zero. If not, the first 4288 // iteration exits. 4289 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 4290 if (!Range.contains(APInt(BitWidth, 0))) 4291 return SE.getIntegerSCEV(0, getType()); 4292 4293 if (isAffine()) { 4294 // If this is an affine expression then we have this situation: 4295 // Solve {0,+,A} in Range === Ax in Range 4296 4297 // We know that zero is in the range. If A is positive then we know that 4298 // the upper value of the range must be the first possible exit value. 4299 // If A is negative then the lower of the range is the last possible loop 4300 // value. Also note that we already checked for a full range. 4301 APInt One(BitWidth,1); 4302 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue(); 4303 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower(); 4304 4305 // The exit value should be (End+A)/A. 4306 APInt ExitVal = (End + A).udiv(A); 4307 ConstantInt *ExitValue = ConstantInt::get(ExitVal); 4308 4309 // Evaluate at the exit value. If we really did fall out of the valid 4310 // range, then we computed our trip count, otherwise wrap around or other 4311 // things must have happened. 4312 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 4313 if (Range.contains(Val->getValue())) 4314 return SE.getCouldNotCompute(); // Something strange happened 4315 4316 // Ensure that the previous value is in the range. This is a sanity check. 4317 assert(Range.contains( 4318 EvaluateConstantChrecAtConstant(this, 4319 ConstantInt::get(ExitVal - One), SE)->getValue()) && 4320 "Linear scev computation is off in a bad way!"); 4321 return SE.getConstant(ExitValue); 4322 } else if (isQuadratic()) { 4323 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the 4324 // quadratic equation to solve it. To do this, we must frame our problem in 4325 // terms of figuring out when zero is crossed, instead of when 4326 // Range.getUpper() is crossed. 4327 SmallVector<const SCEV*, 4> NewOps(op_begin(), op_end()); 4328 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper())); 4329 const SCEV* NewAddRec = SE.getAddRecExpr(NewOps, getLoop()); 4330 4331 // Next, solve the constructed addrec 4332 std::pair<const SCEV*,const SCEV*> Roots = 4333 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE); 4334 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first); 4335 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second); 4336 if (R1) { 4337 // Pick the smallest positive root value. 4338 if (ConstantInt *CB = 4339 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT, 4340 R1->getValue(), R2->getValue()))) { 4341 if (CB->getZExtValue() == false) 4342 std::swap(R1, R2); // R1 is the minimum root now. 4343 4344 // Make sure the root is not off by one. The returned iteration should 4345 // not be in the range, but the previous one should be. When solving 4346 // for "X*X < 5", for example, we should not return a root of 2. 4347 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this, 4348 R1->getValue(), 4349 SE); 4350 if (Range.contains(R1Val->getValue())) { 4351 // The next iteration must be out of the range... 4352 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1); 4353 4354 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); 4355 if (!Range.contains(R1Val->getValue())) 4356 return SE.getConstant(NextVal); 4357 return SE.getCouldNotCompute(); // Something strange happened 4358 } 4359 4360 // If R1 was not in the range, then it is a good return value. Make 4361 // sure that R1-1 WAS in the range though, just in case. 4362 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1); 4363 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); 4364 if (Range.contains(R1Val->getValue())) 4365 return R1; 4366 return SE.getCouldNotCompute(); // Something strange happened 4367 } 4368 } 4369 } 4370 4371 return SE.getCouldNotCompute(); 4372 } 4373 4374 4375 4376 //===----------------------------------------------------------------------===// 4377 // SCEVCallbackVH Class Implementation 4378 //===----------------------------------------------------------------------===// 4379 4380 void ScalarEvolution::SCEVCallbackVH::deleted() { 4381 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!"); 4382 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 4383 SE->ConstantEvolutionLoopExitValue.erase(PN); 4384 if (Instruction *I = dyn_cast<Instruction>(getValPtr())) 4385 SE->ValuesAtScopes.erase(I); 4386 SE->Scalars.erase(getValPtr()); 4387 // this now dangles! 4388 } 4389 4390 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *) { 4391 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!"); 4392 4393 // Forget all the expressions associated with users of the old value, 4394 // so that future queries will recompute the expressions using the new 4395 // value. 4396 SmallVector<User *, 16> Worklist; 4397 Value *Old = getValPtr(); 4398 bool DeleteOld = false; 4399 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end(); 4400 UI != UE; ++UI) 4401 Worklist.push_back(*UI); 4402 while (!Worklist.empty()) { 4403 User *U = Worklist.pop_back_val(); 4404 // Deleting the Old value will cause this to dangle. Postpone 4405 // that until everything else is done. 4406 if (U == Old) { 4407 DeleteOld = true; 4408 continue; 4409 } 4410 if (PHINode *PN = dyn_cast<PHINode>(U)) 4411 SE->ConstantEvolutionLoopExitValue.erase(PN); 4412 if (Instruction *I = dyn_cast<Instruction>(U)) 4413 SE->ValuesAtScopes.erase(I); 4414 if (SE->Scalars.erase(U)) 4415 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end(); 4416 UI != UE; ++UI) 4417 Worklist.push_back(*UI); 4418 } 4419 if (DeleteOld) { 4420 if (PHINode *PN = dyn_cast<PHINode>(Old)) 4421 SE->ConstantEvolutionLoopExitValue.erase(PN); 4422 if (Instruction *I = dyn_cast<Instruction>(Old)) 4423 SE->ValuesAtScopes.erase(I); 4424 SE->Scalars.erase(Old); 4425 // this now dangles! 4426 } 4427 // this may dangle! 4428 } 4429 4430 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 4431 : CallbackVH(V), SE(se) {} 4432 4433 //===----------------------------------------------------------------------===// 4434 // ScalarEvolution Class Implementation 4435 //===----------------------------------------------------------------------===// 4436 4437 ScalarEvolution::ScalarEvolution() 4438 : FunctionPass(&ID) { 4439 } 4440 4441 bool ScalarEvolution::runOnFunction(Function &F) { 4442 this->F = &F; 4443 LI = &getAnalysis<LoopInfo>(); 4444 TD = getAnalysisIfAvailable<TargetData>(); 4445 return false; 4446 } 4447 4448 void ScalarEvolution::releaseMemory() { 4449 Scalars.clear(); 4450 BackedgeTakenCounts.clear(); 4451 ConstantEvolutionLoopExitValue.clear(); 4452 ValuesAtScopes.clear(); 4453 UniqueSCEVs.clear(); 4454 SCEVAllocator.Reset(); 4455 } 4456 4457 void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const { 4458 AU.setPreservesAll(); 4459 AU.addRequiredTransitive<LoopInfo>(); 4460 } 4461 4462 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 4463 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 4464 } 4465 4466 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 4467 const Loop *L) { 4468 // Print all inner loops first 4469 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I) 4470 PrintLoopInfo(OS, SE, *I); 4471 4472 OS << "Loop " << L->getHeader()->getName() << ": "; 4473 4474 SmallVector<BasicBlock*, 8> ExitBlocks; 4475 L->getExitBlocks(ExitBlocks); 4476 if (ExitBlocks.size() != 1) 4477 OS << "<multiple exits> "; 4478 4479 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 4480 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L); 4481 } else { 4482 OS << "Unpredictable backedge-taken count. "; 4483 } 4484 4485 OS << "\n"; 4486 OS << "Loop " << L->getHeader()->getName() << ": "; 4487 4488 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) { 4489 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L); 4490 } else { 4491 OS << "Unpredictable max backedge-taken count. "; 4492 } 4493 4494 OS << "\n"; 4495 } 4496 4497 void ScalarEvolution::print(raw_ostream &OS, const Module* ) const { 4498 // ScalarEvolution's implementaiton of the print method is to print 4499 // out SCEV values of all instructions that are interesting. Doing 4500 // this potentially causes it to create new SCEV objects though, 4501 // which technically conflicts with the const qualifier. This isn't 4502 // observable from outside the class though (the hasSCEV function 4503 // notwithstanding), so casting away the const isn't dangerous. 4504 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this); 4505 4506 OS << "Classifying expressions for: " << F->getName() << "\n"; 4507 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) 4508 if (isSCEVable(I->getType())) { 4509 OS << *I; 4510 OS << " --> "; 4511 const SCEV* SV = SE.getSCEV(&*I); 4512 SV->print(OS); 4513 4514 const Loop *L = LI->getLoopFor((*I).getParent()); 4515 4516 const SCEV* AtUse = SE.getSCEVAtScope(SV, L); 4517 if (AtUse != SV) { 4518 OS << " --> "; 4519 AtUse->print(OS); 4520 } 4521 4522 if (L) { 4523 OS << "\t\t" "Exits: "; 4524 const SCEV* ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 4525 if (!ExitValue->isLoopInvariant(L)) { 4526 OS << "<<Unknown>>"; 4527 } else { 4528 OS << *ExitValue; 4529 } 4530 } 4531 4532 OS << "\n"; 4533 } 4534 4535 OS << "Determining loop execution counts for: " << F->getName() << "\n"; 4536 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I) 4537 PrintLoopInfo(OS, &SE, *I); 4538 } 4539 4540 void ScalarEvolution::print(std::ostream &o, const Module *M) const { 4541 raw_os_ostream OS(o); 4542 print(OS, M); 4543 } 4544