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