blob: fc7d286aaf9a957e7a8d8259e1ab0f83a8351084 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
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
Dan Gohman161ea032009-07-07 17:06:11 +000017// can handle. These classes are reference counted, managed by the const SCEV *
Dan Gohmanf17a25c2007-07-18 16:29:46 +000018// class. We only create one SCEV of a particular shape, so pointer-comparisons
19// for equality are legal.
20//
21// One important aspect of the SCEV objects is that they are never cyclic, even
22// if there is a cycle in the dataflow for an expression (ie, a PHI node). If
23// the PHI node is one of the idioms that we can represent (e.g., a polynomial
24// recurrence) then we represent it directly as a recurrence node, otherwise we
25// represent it as a SCEVUnknown node.
26//
27// In addition to being able to represent expressions of various types, we also
28// have folders that are used to build the *canonical* representation for a
29// particular expression. These folders are capable of using a variety of
30// rewrite rules to simplify the expressions.
31//
32// Once the folders are defined, we can implement the more interesting
33// higher-level code, such as the code that recognizes PHI nodes of various
34// types, computes the execution count of a loop, etc.
35//
36// TODO: We should use these routines and value representations to implement
37// dependence analysis!
38//
39//===----------------------------------------------------------------------===//
40//
41// There are several good references for the techniques used in this analysis.
42//
43// Chains of recurrences -- a method to expedite the evaluation
44// of closed-form functions
45// Olaf Bachmann, Paul S. Wang, Eugene V. Zima
46//
47// On computational properties of chains of recurrences
48// Eugene V. Zima
49//
50// Symbolic Evaluation of Chains of Recurrences for Loop Optimization
51// Robert A. van Engelen
52//
53// Efficient Symbolic Analysis for Optimizing Compilers
54// Robert A. van Engelen
55//
56// Using the chains of recurrences algebra for data dependence testing and
57// induction variable substitution
58// MS Thesis, Johnie Birch
59//
60//===----------------------------------------------------------------------===//
61
62#define DEBUG_TYPE "scalar-evolution"
63#include "llvm/Analysis/ScalarEvolutionExpressions.h"
64#include "llvm/Constants.h"
65#include "llvm/DerivedTypes.h"
66#include "llvm/GlobalVariable.h"
67#include "llvm/Instructions.h"
Owen Andersone755b092009-07-06 22:37:39 +000068#include "llvm/LLVMContext.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000069#include "llvm/Analysis/ConstantFolding.h"
Evan Cheng98c073b2009-02-17 00:13:06 +000070#include "llvm/Analysis/Dominators.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000071#include "llvm/Analysis/LoopInfo.h"
Dan Gohmana7726c32009-06-16 19:52:01 +000072#include "llvm/Analysis/ValueTracking.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000073#include "llvm/Assembly/Writer.h"
Dan Gohman01c2ee72009-04-16 03:18:22 +000074#include "llvm/Target/TargetData.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000075#include "llvm/Support/CommandLine.h"
76#include "llvm/Support/Compiler.h"
77#include "llvm/Support/ConstantRange.h"
Edwin Török675d5622009-07-11 20:10:48 +000078#include "llvm/Support/ErrorHandling.h"
Dan Gohman01c2ee72009-04-16 03:18:22 +000079#include "llvm/Support/GetElementPtrTypeIterator.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000080#include "llvm/Support/InstIterator.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000081#include "llvm/Support/MathExtras.h"
Dan Gohman13058cc2009-04-21 00:47:46 +000082#include "llvm/Support/raw_ostream.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000083#include "llvm/ADT/Statistic.h"
Dan Gohman01c2ee72009-04-16 03:18:22 +000084#include "llvm/ADT/STLExtras.h"
Dan Gohmanb7d04aa2009-07-08 19:23:34 +000085#include "llvm/ADT/SmallPtrSet.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000086#include <algorithm>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000087using namespace llvm;
88
Dan Gohmanf17a25c2007-07-18 16:29:46 +000089STATISTIC(NumArrayLenItCounts,
90 "Number of trip counts computed with array length");
91STATISTIC(NumTripCountsComputed,
92 "Number of loops with predictable loop counts");
93STATISTIC(NumTripCountsNotComputed,
94 "Number of loops without predictable loop counts");
95STATISTIC(NumBruteForceTripCountsComputed,
96 "Number of loops with trip counts computed by force");
97
Dan Gohman089efff2008-05-13 00:00:25 +000098static cl::opt<unsigned>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000099MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
100 cl::desc("Maximum number of iterations SCEV will "
Dan Gohman9bc642f2009-06-24 04:48:43 +0000101 "symbolically execute a constant "
102 "derived loop"),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000103 cl::init(100));
104
Dan Gohman089efff2008-05-13 00:00:25 +0000105static RegisterPass<ScalarEvolution>
106R("scalar-evolution", "Scalar Evolution Analysis", false, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000107char ScalarEvolution::ID = 0;
108
109//===----------------------------------------------------------------------===//
110// SCEV class definitions
111//===----------------------------------------------------------------------===//
112
113//===----------------------------------------------------------------------===//
114// Implementation of the SCEV class.
115//
Dan Gohmanc86c0df2009-06-30 20:13:32 +0000116
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000117SCEV::~SCEV() {}
Dan Gohmanc86c0df2009-06-30 20:13:32 +0000118
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000119void SCEV::dump() const {
Dan Gohman13058cc2009-04-21 00:47:46 +0000120 print(errs());
121 errs() << '\n';
122}
123
124void SCEV::print(std::ostream &o) const {
125 raw_os_ostream OS(o);
126 print(OS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000127}
128
Dan Gohman7b560c42008-06-18 16:23:07 +0000129bool SCEV::isZero() const {
130 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
131 return SC->getValue()->isZero();
132 return false;
133}
134
Dan Gohmanf8bc8e82009-05-18 15:22:39 +0000135bool SCEV::isOne() const {
136 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
137 return SC->getValue()->isOne();
138 return false;
139}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000140
Dan Gohmanf05118e2009-06-24 00:30:26 +0000141bool SCEV::isAllOnesValue() const {
142 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
143 return SC->getValue()->isAllOnesValue();
144 return false;
145}
146
Owen Andersonb70139d2009-06-22 21:57:23 +0000147SCEVCouldNotCompute::SCEVCouldNotCompute() :
148 SCEV(scCouldNotCompute) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000149
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000150void SCEVCouldNotCompute::Profile(FoldingSetNodeID &ID) const {
Edwin Török675d5622009-07-11 20:10:48 +0000151 LLVM_UNREACHABLE("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000152}
153
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000154bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
Edwin Török675d5622009-07-11 20:10:48 +0000155 LLVM_UNREACHABLE("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000156 return false;
157}
158
159const Type *SCEVCouldNotCompute::getType() const {
Edwin Török675d5622009-07-11 20:10:48 +0000160 LLVM_UNREACHABLE("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000161 return 0;
162}
163
164bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
Edwin Török675d5622009-07-11 20:10:48 +0000165 LLVM_UNREACHABLE("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000166 return false;
167}
168
Dan Gohman9bc642f2009-06-24 04:48:43 +0000169const SCEV *
170SCEVCouldNotCompute::replaceSymbolicValuesWithConcrete(
171 const SCEV *Sym,
172 const SCEV *Conc,
173 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000174 return this;
175}
176
Dan Gohman13058cc2009-04-21 00:47:46 +0000177void SCEVCouldNotCompute::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000178 OS << "***COULDNOTCOMPUTE***";
179}
180
181bool SCEVCouldNotCompute::classof(const SCEV *S) {
182 return S->getSCEVType() == scCouldNotCompute;
183}
184
Dan Gohman161ea032009-07-07 17:06:11 +0000185const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000186 FoldingSetNodeID ID;
187 ID.AddInteger(scConstant);
188 ID.AddPointer(V);
189 void *IP = 0;
190 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
191 SCEV *S = SCEVAllocator.Allocate<SCEVConstant>();
192 new (S) SCEVConstant(V);
193 UniqueSCEVs.InsertNode(S, IP);
194 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000195}
196
Dan Gohman161ea032009-07-07 17:06:11 +0000197const SCEV *ScalarEvolution::getConstant(const APInt& Val) {
Dan Gohman89f85052007-10-22 18:31:58 +0000198 return getConstant(ConstantInt::get(Val));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000199}
200
Dan Gohman161ea032009-07-07 17:06:11 +0000201const SCEV *
Dan Gohman8fd520a2009-06-15 22:12:54 +0000202ScalarEvolution::getConstant(const Type *Ty, uint64_t V, bool isSigned) {
203 return getConstant(ConstantInt::get(cast<IntegerType>(Ty), V, isSigned));
204}
205
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000206void SCEVConstant::Profile(FoldingSetNodeID &ID) const {
207 ID.AddInteger(scConstant);
208 ID.AddPointer(V);
209}
210
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000211const Type *SCEVConstant::getType() const { return V->getType(); }
212
Dan Gohman13058cc2009-04-21 00:47:46 +0000213void SCEVConstant::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000214 WriteAsOperand(OS, V, false);
215}
216
Dan Gohman2a381532009-04-21 01:25:57 +0000217SCEVCastExpr::SCEVCastExpr(unsigned SCEVTy,
Dan Gohman161ea032009-07-07 17:06:11 +0000218 const SCEV *op, const Type *ty)
Owen Andersonb70139d2009-06-22 21:57:23 +0000219 : SCEV(SCEVTy), Op(op), Ty(ty) {}
Dan Gohman2a381532009-04-21 01:25:57 +0000220
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000221void SCEVCastExpr::Profile(FoldingSetNodeID &ID) const {
222 ID.AddInteger(getSCEVType());
223 ID.AddPointer(Op);
224 ID.AddPointer(Ty);
225}
226
Dan Gohman2a381532009-04-21 01:25:57 +0000227bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
228 return Op->dominates(BB, DT);
229}
230
Dan Gohman161ea032009-07-07 17:06:11 +0000231SCEVTruncateExpr::SCEVTruncateExpr(const SCEV *op, const Type *ty)
Owen Andersonb70139d2009-06-22 21:57:23 +0000232 : SCEVCastExpr(scTruncate, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000233 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
234 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000235 "Cannot truncate non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000236}
237
Dan Gohman13058cc2009-04-21 00:47:46 +0000238void SCEVTruncateExpr::print(raw_ostream &OS) const {
Dan Gohmanc9119222009-04-29 20:27:52 +0000239 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000240}
241
Dan Gohman161ea032009-07-07 17:06:11 +0000242SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEV *op, const Type *ty)
Owen Andersonb70139d2009-06-22 21:57:23 +0000243 : SCEVCastExpr(scZeroExtend, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000244 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
245 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000246 "Cannot zero extend non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000247}
248
Dan Gohman13058cc2009-04-21 00:47:46 +0000249void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
Dan Gohmanc9119222009-04-29 20:27:52 +0000250 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000251}
252
Dan Gohman161ea032009-07-07 17:06:11 +0000253SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEV *op, const Type *ty)
Owen Andersonb70139d2009-06-22 21:57:23 +0000254 : SCEVCastExpr(scSignExtend, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000255 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
256 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000257 "Cannot sign extend non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000258}
259
Dan Gohman13058cc2009-04-21 00:47:46 +0000260void SCEVSignExtendExpr::print(raw_ostream &OS) const {
Dan Gohmanc9119222009-04-29 20:27:52 +0000261 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000262}
263
Dan Gohman13058cc2009-04-21 00:47:46 +0000264void SCEVCommutativeExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000265 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
266 const char *OpStr = getOperationStr();
267 OS << "(" << *Operands[0];
268 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
269 OS << OpStr << *Operands[i];
270 OS << ")";
271}
272
Dan Gohman9bc642f2009-06-24 04:48:43 +0000273const SCEV *
274SCEVCommutativeExpr::replaceSymbolicValuesWithConcrete(
275 const SCEV *Sym,
276 const SCEV *Conc,
277 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000278 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman161ea032009-07-07 17:06:11 +0000279 const SCEV *H =
Dan Gohman89f85052007-10-22 18:31:58 +0000280 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000281 if (H != getOperand(i)) {
Dan Gohman161ea032009-07-07 17:06:11 +0000282 SmallVector<const SCEV *, 8> NewOps;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000283 NewOps.reserve(getNumOperands());
284 for (unsigned j = 0; j != i; ++j)
285 NewOps.push_back(getOperand(j));
286 NewOps.push_back(H);
287 for (++i; i != e; ++i)
288 NewOps.push_back(getOperand(i)->
Dan Gohman89f85052007-10-22 18:31:58 +0000289 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000290
291 if (isa<SCEVAddExpr>(this))
Dan Gohman89f85052007-10-22 18:31:58 +0000292 return SE.getAddExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000293 else if (isa<SCEVMulExpr>(this))
Dan Gohman89f85052007-10-22 18:31:58 +0000294 return SE.getMulExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +0000295 else if (isa<SCEVSMaxExpr>(this))
296 return SE.getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000297 else if (isa<SCEVUMaxExpr>(this))
298 return SE.getUMaxExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000299 else
Edwin Török675d5622009-07-11 20:10:48 +0000300 LLVM_UNREACHABLE("Unknown commutative expr!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000301 }
302 }
303 return this;
304}
305
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000306void SCEVNAryExpr::Profile(FoldingSetNodeID &ID) const {
307 ID.AddInteger(getSCEVType());
308 ID.AddInteger(Operands.size());
309 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
310 ID.AddPointer(Operands[i]);
311}
312
Dan Gohman72a8a022009-05-07 14:00:19 +0000313bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
Evan Cheng98c073b2009-02-17 00:13:06 +0000314 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
315 if (!getOperand(i)->dominates(BB, DT))
316 return false;
317 }
318 return true;
319}
320
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000321void SCEVUDivExpr::Profile(FoldingSetNodeID &ID) const {
322 ID.AddInteger(scUDivExpr);
323 ID.AddPointer(LHS);
324 ID.AddPointer(RHS);
325}
326
Evan Cheng98c073b2009-02-17 00:13:06 +0000327bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
328 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
329}
330
Dan Gohman13058cc2009-04-21 00:47:46 +0000331void SCEVUDivExpr::print(raw_ostream &OS) const {
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000332 OS << "(" << *LHS << " /u " << *RHS << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000333}
334
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000335const Type *SCEVUDivExpr::getType() const {
Dan Gohman140f08f2009-05-26 17:44:05 +0000336 // In most cases the types of LHS and RHS will be the same, but in some
337 // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
338 // depend on the type for correctness, but handling types carefully can
339 // avoid extra casts in the SCEVExpander. The LHS is more likely to be
340 // a pointer type than the RHS, so use the RHS' type here.
341 return RHS->getType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000342}
343
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000344void SCEVAddRecExpr::Profile(FoldingSetNodeID &ID) const {
345 ID.AddInteger(scAddRecExpr);
346 ID.AddInteger(Operands.size());
347 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
348 ID.AddPointer(Operands[i]);
349 ID.AddPointer(L);
350}
351
Dan Gohman9bc642f2009-06-24 04:48:43 +0000352const SCEV *
353SCEVAddRecExpr::replaceSymbolicValuesWithConcrete(const SCEV *Sym,
354 const SCEV *Conc,
355 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000356 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman161ea032009-07-07 17:06:11 +0000357 const SCEV *H =
Dan Gohman89f85052007-10-22 18:31:58 +0000358 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000359 if (H != getOperand(i)) {
Dan Gohman161ea032009-07-07 17:06:11 +0000360 SmallVector<const SCEV *, 8> NewOps;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000361 NewOps.reserve(getNumOperands());
362 for (unsigned j = 0; j != i; ++j)
363 NewOps.push_back(getOperand(j));
364 NewOps.push_back(H);
365 for (++i; i != e; ++i)
366 NewOps.push_back(getOperand(i)->
Dan Gohman89f85052007-10-22 18:31:58 +0000367 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000368
Dan Gohman89f85052007-10-22 18:31:58 +0000369 return SE.getAddRecExpr(NewOps, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000370 }
371 }
372 return this;
373}
374
375
376bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
Dan Gohmanae1eaae2009-05-20 01:01:24 +0000377 // Add recurrences are never invariant in the function-body (null loop).
Dan Gohman2d888d82009-06-26 22:17:21 +0000378 if (!QueryLoop)
379 return false;
380
381 // This recurrence is variant w.r.t. QueryLoop if QueryLoop contains L.
382 if (QueryLoop->contains(L->getHeader()))
383 return false;
384
385 // This recurrence is variant w.r.t. QueryLoop if any of its operands
386 // are variant.
387 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
388 if (!getOperand(i)->isLoopInvariant(QueryLoop))
389 return false;
390
391 // Otherwise it's loop-invariant.
392 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000393}
394
Dan Gohman13058cc2009-04-21 00:47:46 +0000395void SCEVAddRecExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000396 OS << "{" << *Operands[0];
397 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
398 OS << ",+," << *Operands[i];
399 OS << "}<" << L->getHeader()->getName() + ">";
400}
401
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000402void SCEVUnknown::Profile(FoldingSetNodeID &ID) const {
403 ID.AddInteger(scUnknown);
404 ID.AddPointer(V);
405}
406
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000407bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
408 // All non-instruction values are loop invariant. All instructions are loop
409 // invariant if they are not contained in the specified loop.
Dan Gohmanae1eaae2009-05-20 01:01:24 +0000410 // Instructions are never considered invariant in the function body
411 // (null loop) because they are defined within the "loop".
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000412 if (Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmanae1eaae2009-05-20 01:01:24 +0000413 return L && !L->contains(I->getParent());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000414 return true;
415}
416
Evan Cheng98c073b2009-02-17 00:13:06 +0000417bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
418 if (Instruction *I = dyn_cast<Instruction>(getValue()))
419 return DT->dominates(I->getParent(), BB);
420 return true;
421}
422
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000423const Type *SCEVUnknown::getType() const {
424 return V->getType();
425}
426
Dan Gohman13058cc2009-04-21 00:47:46 +0000427void SCEVUnknown::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000428 WriteAsOperand(OS, V, false);
429}
430
431//===----------------------------------------------------------------------===//
432// SCEV Utilities
433//===----------------------------------------------------------------------===//
434
435namespace {
436 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
437 /// than the complexity of the RHS. This comparator is used to canonicalize
438 /// expressions.
Dan Gohman5d486452009-05-07 14:39:04 +0000439 class VISIBILITY_HIDDEN SCEVComplexityCompare {
440 LoopInfo *LI;
441 public:
442 explicit SCEVComplexityCompare(LoopInfo *li) : LI(li) {}
443
Dan Gohmanc0c69cf2008-04-14 18:23:56 +0000444 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman5d486452009-05-07 14:39:04 +0000445 // Primarily, sort the SCEVs by their getSCEVType().
446 if (LHS->getSCEVType() != RHS->getSCEVType())
447 return LHS->getSCEVType() < RHS->getSCEVType();
448
449 // Aside from the getSCEVType() ordering, the particular ordering
450 // isn't very important except that it's beneficial to be consistent,
451 // so that (a + b) and (b + a) don't end up as different expressions.
452
453 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
454 // not as complete as it could be.
455 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
456 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
457
Dan Gohmand0c01232009-05-19 02:15:55 +0000458 // Order pointer values after integer values. This helps SCEVExpander
459 // form GEPs.
460 if (isa<PointerType>(LU->getType()) && !isa<PointerType>(RU->getType()))
461 return false;
462 if (isa<PointerType>(RU->getType()) && !isa<PointerType>(LU->getType()))
463 return true;
464
Dan Gohman5d486452009-05-07 14:39:04 +0000465 // Compare getValueID values.
466 if (LU->getValue()->getValueID() != RU->getValue()->getValueID())
467 return LU->getValue()->getValueID() < RU->getValue()->getValueID();
468
469 // Sort arguments by their position.
470 if (const Argument *LA = dyn_cast<Argument>(LU->getValue())) {
471 const Argument *RA = cast<Argument>(RU->getValue());
472 return LA->getArgNo() < RA->getArgNo();
473 }
474
475 // For instructions, compare their loop depth, and their opcode.
476 // This is pretty loose.
477 if (Instruction *LV = dyn_cast<Instruction>(LU->getValue())) {
478 Instruction *RV = cast<Instruction>(RU->getValue());
479
480 // Compare loop depths.
481 if (LI->getLoopDepth(LV->getParent()) !=
482 LI->getLoopDepth(RV->getParent()))
483 return LI->getLoopDepth(LV->getParent()) <
484 LI->getLoopDepth(RV->getParent());
485
486 // Compare opcodes.
487 if (LV->getOpcode() != RV->getOpcode())
488 return LV->getOpcode() < RV->getOpcode();
489
490 // Compare the number of operands.
491 if (LV->getNumOperands() != RV->getNumOperands())
492 return LV->getNumOperands() < RV->getNumOperands();
493 }
494
495 return false;
496 }
497
Dan Gohman56fc8f12009-06-14 22:51:25 +0000498 // Compare constant values.
499 if (const SCEVConstant *LC = dyn_cast<SCEVConstant>(LHS)) {
500 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
Nick Lewycky9bb14052009-07-04 17:24:52 +0000501 if (LC->getValue()->getBitWidth() != RC->getValue()->getBitWidth())
502 return LC->getValue()->getBitWidth() < RC->getValue()->getBitWidth();
Dan Gohman56fc8f12009-06-14 22:51:25 +0000503 return LC->getValue()->getValue().ult(RC->getValue()->getValue());
504 }
505
506 // Compare addrec loop depths.
507 if (const SCEVAddRecExpr *LA = dyn_cast<SCEVAddRecExpr>(LHS)) {
508 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
509 if (LA->getLoop()->getLoopDepth() != RA->getLoop()->getLoopDepth())
510 return LA->getLoop()->getLoopDepth() < RA->getLoop()->getLoopDepth();
511 }
Dan Gohman5d486452009-05-07 14:39:04 +0000512
513 // Lexicographically compare n-ary expressions.
514 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
515 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
516 for (unsigned i = 0, e = LC->getNumOperands(); i != e; ++i) {
517 if (i >= RC->getNumOperands())
518 return false;
519 if (operator()(LC->getOperand(i), RC->getOperand(i)))
520 return true;
521 if (operator()(RC->getOperand(i), LC->getOperand(i)))
522 return false;
523 }
524 return LC->getNumOperands() < RC->getNumOperands();
525 }
526
Dan Gohman6e10db12009-05-07 19:23:21 +0000527 // Lexicographically compare udiv expressions.
528 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
529 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
530 if (operator()(LC->getLHS(), RC->getLHS()))
531 return true;
532 if (operator()(RC->getLHS(), LC->getLHS()))
533 return false;
534 if (operator()(LC->getRHS(), RC->getRHS()))
535 return true;
536 if (operator()(RC->getRHS(), LC->getRHS()))
537 return false;
538 return false;
539 }
540
Dan Gohman5d486452009-05-07 14:39:04 +0000541 // Compare cast expressions by operand.
542 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
543 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
544 return operator()(LC->getOperand(), RC->getOperand());
545 }
546
Edwin Török675d5622009-07-11 20:10:48 +0000547 LLVM_UNREACHABLE("Unknown SCEV kind!");
Dan Gohman5d486452009-05-07 14:39:04 +0000548 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000549 }
550 };
551}
552
553/// GroupByComplexity - Given a list of SCEV objects, order them by their
554/// complexity, and group objects of the same complexity together by value.
555/// When this routine is finished, we know that any duplicates in the vector are
556/// consecutive and that complexity is monotonically increasing.
557///
558/// Note that we go take special precautions to ensure that we get determinstic
559/// results from this routine. In other words, we don't want the results of
560/// this to depend on where the addresses of various SCEV objects happened to
561/// land in memory.
562///
Dan Gohman161ea032009-07-07 17:06:11 +0000563static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
Dan Gohman5d486452009-05-07 14:39:04 +0000564 LoopInfo *LI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000565 if (Ops.size() < 2) return; // Noop
566 if (Ops.size() == 2) {
567 // This is the common case, which also happens to be trivially simple.
568 // Special case it.
Dan Gohman5d486452009-05-07 14:39:04 +0000569 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000570 std::swap(Ops[0], Ops[1]);
571 return;
572 }
573
574 // Do the rough sort by complexity.
Dan Gohman5d486452009-05-07 14:39:04 +0000575 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000576
577 // Now that we are sorted by complexity, group elements of the same
578 // complexity. Note that this is, at worst, N^2, but the vector is likely to
579 // be extremely short in practice. Note that we take this approach because we
580 // do not want to depend on the addresses of the objects we are grouping.
581 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Dan Gohmanbff6b582009-05-04 22:30:44 +0000582 const SCEV *S = Ops[i];
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000583 unsigned Complexity = S->getSCEVType();
584
585 // If there are any objects of the same complexity and same value as this
586 // one, group them.
587 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
588 if (Ops[j] == S) { // Found a duplicate.
589 // Move it to immediately after i'th element.
590 std::swap(Ops[i+1], Ops[j]);
591 ++i; // no need to rescan it.
592 if (i == e-2) return; // Done!
593 }
594 }
595 }
596}
597
598
599
600//===----------------------------------------------------------------------===//
601// Simple SCEV method implementations
602//===----------------------------------------------------------------------===//
603
Eli Friedman7489ec92008-08-04 23:49:06 +0000604/// BinomialCoefficient - Compute BC(It, K). The result has width W.
Dan Gohmanc8a29272009-05-24 23:45:28 +0000605/// Assume, K > 0.
Dan Gohman161ea032009-07-07 17:06:11 +0000606static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
Eli Friedman7489ec92008-08-04 23:49:06 +0000607 ScalarEvolution &SE,
Dan Gohman01c2ee72009-04-16 03:18:22 +0000608 const Type* ResultTy) {
Eli Friedman7489ec92008-08-04 23:49:06 +0000609 // Handle the simplest case efficiently.
610 if (K == 1)
611 return SE.getTruncateOrZeroExtend(It, ResultTy);
612
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000613 // We are using the following formula for BC(It, K):
614 //
615 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
616 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000617 // Suppose, W is the bitwidth of the return value. We must be prepared for
618 // overflow. Hence, we must assure that the result of our computation is
619 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
620 // safe in modular arithmetic.
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000621 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000622 // However, this code doesn't use exactly that formula; the formula it uses
Dan Gohman9bc642f2009-06-24 04:48:43 +0000623 // is something like the following, where T is the number of factors of 2 in
Eli Friedman7489ec92008-08-04 23:49:06 +0000624 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
625 // exponentiation:
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000626 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000627 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000628 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000629 // This formula is trivially equivalent to the previous formula. However,
630 // this formula can be implemented much more efficiently. The trick is that
631 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
632 // arithmetic. To do exact division in modular arithmetic, all we have
633 // to do is multiply by the inverse. Therefore, this step can be done at
634 // width W.
Dan Gohman9bc642f2009-06-24 04:48:43 +0000635 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000636 // The next issue is how to safely do the division by 2^T. The way this
637 // is done is by doing the multiplication step at a width of at least W + T
638 // bits. This way, the bottom W+T bits of the product are accurate. Then,
639 // when we perform the division by 2^T (which is equivalent to a right shift
640 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
641 // truncated out after the division by 2^T.
642 //
643 // In comparison to just directly using the first formula, this technique
644 // is much more efficient; using the first formula requires W * K bits,
645 // but this formula less than W + K bits. Also, the first formula requires
646 // a division step, whereas this formula only requires multiplies and shifts.
647 //
648 // It doesn't matter whether the subtraction step is done in the calculation
649 // width or the input iteration count's width; if the subtraction overflows,
650 // the result must be zero anyway. We prefer here to do it in the width of
651 // the induction variable because it helps a lot for certain cases; CodeGen
652 // isn't smart enough to ignore the overflow, which leads to much less
653 // efficient code if the width of the subtraction is wider than the native
654 // register width.
655 //
656 // (It's possible to not widen at all by pulling out factors of 2 before
657 // the multiplication; for example, K=2 can be calculated as
658 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
659 // extra arithmetic, so it's not an obvious win, and it gets
660 // much more complicated for K > 3.)
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000661
Eli Friedman7489ec92008-08-04 23:49:06 +0000662 // Protection from insane SCEVs; this bound is conservative,
663 // but it probably doesn't matter.
664 if (K > 1000)
Dan Gohman0ad08b02009-04-18 17:58:19 +0000665 return SE.getCouldNotCompute();
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000666
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000667 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000668
Eli Friedman7489ec92008-08-04 23:49:06 +0000669 // Calculate K! / 2^T and T; we divide out the factors of two before
670 // multiplying for calculating K! / 2^T to avoid overflow.
671 // Other overflow doesn't matter because we only care about the bottom
672 // W bits of the result.
673 APInt OddFactorial(W, 1);
674 unsigned T = 1;
675 for (unsigned i = 3; i <= K; ++i) {
676 APInt Mult(W, i);
677 unsigned TwoFactors = Mult.countTrailingZeros();
678 T += TwoFactors;
679 Mult = Mult.lshr(TwoFactors);
680 OddFactorial *= Mult;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000681 }
Nick Lewyckydbaa60a2008-06-13 04:38:55 +0000682
Eli Friedman7489ec92008-08-04 23:49:06 +0000683 // We need at least W + T bits for the multiplication step
nicholas9e3e5fd2009-01-25 08:16:27 +0000684 unsigned CalculationBits = W + T;
Eli Friedman7489ec92008-08-04 23:49:06 +0000685
686 // Calcuate 2^T, at width T+W.
687 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
688
689 // Calculate the multiplicative inverse of K! / 2^T;
690 // this multiplication factor will perform the exact division by
691 // K! / 2^T.
692 APInt Mod = APInt::getSignedMinValue(W+1);
693 APInt MultiplyFactor = OddFactorial.zext(W+1);
694 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
695 MultiplyFactor = MultiplyFactor.trunc(W);
696
697 // Calculate the product, at width T+W
698 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
Dan Gohman161ea032009-07-07 17:06:11 +0000699 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
Eli Friedman7489ec92008-08-04 23:49:06 +0000700 for (unsigned i = 1; i != K; ++i) {
Dan Gohman161ea032009-07-07 17:06:11 +0000701 const SCEV *S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
Eli Friedman7489ec92008-08-04 23:49:06 +0000702 Dividend = SE.getMulExpr(Dividend,
703 SE.getTruncateOrZeroExtend(S, CalculationTy));
704 }
705
706 // Divide by 2^T
Dan Gohman161ea032009-07-07 17:06:11 +0000707 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
Eli Friedman7489ec92008-08-04 23:49:06 +0000708
709 // Truncate the result, and divide by K! / 2^T.
710
711 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
712 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000713}
714
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000715/// evaluateAtIteration - Return the value of this chain of recurrences at
716/// the specified iteration number. We can evaluate this recurrence by
717/// multiplying each element in the chain by the binomial coefficient
718/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
719///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000720/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000721///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000722/// where BC(It, k) stands for binomial coefficient.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000723///
Dan Gohman161ea032009-07-07 17:06:11 +0000724const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
Dan Gohman89f85052007-10-22 18:31:58 +0000725 ScalarEvolution &SE) const {
Dan Gohman161ea032009-07-07 17:06:11 +0000726 const SCEV *Result = getStart();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000727 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000728 // The computation is correct in the face of overflow provided that the
729 // multiplication is performed _after_ the evaluation of the binomial
730 // coefficient.
Dan Gohman161ea032009-07-07 17:06:11 +0000731 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckyb6218e02008-10-13 03:58:02 +0000732 if (isa<SCEVCouldNotCompute>(Coeff))
733 return Coeff;
734
735 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000736 }
737 return Result;
738}
739
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000740//===----------------------------------------------------------------------===//
741// SCEV Expression folder implementations
742//===----------------------------------------------------------------------===//
743
Dan Gohman161ea032009-07-07 17:06:11 +0000744const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
Dan Gohman9c8abcc2009-05-01 16:44:56 +0000745 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000746 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000747 "This is not a truncating conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000748 assert(isSCEVable(Ty) &&
749 "This is not a conversion to a SCEVable type!");
750 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000751
Dan Gohmanc86c0df2009-06-30 20:13:32 +0000752 // Fold if the operand is constant.
Dan Gohmanc76b5452009-05-04 22:02:23 +0000753 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman55788cf2009-06-24 00:38:39 +0000754 return getConstant(
755 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000756
Dan Gohman1a5c4992009-04-22 16:20:48 +0000757 // trunc(trunc(x)) --> trunc(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000758 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000759 return getTruncateExpr(ST->getOperand(), Ty);
760
Nick Lewycky37d04642009-04-23 05:15:08 +0000761 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohmanc76b5452009-05-04 22:02:23 +0000762 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewycky37d04642009-04-23 05:15:08 +0000763 return getTruncateOrSignExtend(SS->getOperand(), Ty);
764
765 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohmanc76b5452009-05-04 22:02:23 +0000766 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewycky37d04642009-04-23 05:15:08 +0000767 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
768
Dan Gohman1c0aa2c2009-06-18 16:24:47 +0000769 // If the input value is a chrec scev, truncate the chrec's operands.
Dan Gohmanc76b5452009-05-04 22:02:23 +0000770 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohman161ea032009-07-07 17:06:11 +0000771 SmallVector<const SCEV *, 4> Operands;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000772 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman45b3b542009-05-08 21:03:19 +0000773 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
774 return getAddRecExpr(Operands, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000775 }
776
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000777 FoldingSetNodeID ID;
778 ID.AddInteger(scTruncate);
779 ID.AddPointer(Op);
780 ID.AddPointer(Ty);
781 void *IP = 0;
782 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
783 SCEV *S = SCEVAllocator.Allocate<SCEVTruncateExpr>();
784 new (S) SCEVTruncateExpr(Op, Ty);
785 UniqueSCEVs.InsertNode(S, IP);
786 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000787}
788
Dan Gohman161ea032009-07-07 17:06:11 +0000789const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
Dan Gohman36d40922009-04-16 19:25:55 +0000790 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000791 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman36d40922009-04-16 19:25:55 +0000792 "This is not an extending conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000793 assert(isSCEVable(Ty) &&
794 "This is not a conversion to a SCEVable type!");
795 Ty = getEffectiveSCEVType(Ty);
Dan Gohman36d40922009-04-16 19:25:55 +0000796
Dan Gohmanc86c0df2009-06-30 20:13:32 +0000797 // Fold if the operand is constant.
Dan Gohmanc76b5452009-05-04 22:02:23 +0000798 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000799 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000800 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
801 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
Dan Gohman55788cf2009-06-24 00:38:39 +0000802 return getConstant(cast<ConstantInt>(C));
Dan Gohman01c2ee72009-04-16 03:18:22 +0000803 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000804
Dan Gohman1a5c4992009-04-22 16:20:48 +0000805 // zext(zext(x)) --> zext(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000806 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000807 return getZeroExtendExpr(SZ->getOperand(), Ty);
808
Dan Gohmana9dba962009-04-27 20:16:15 +0000809 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000810 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohmana9dba962009-04-27 20:16:15 +0000811 // operands (often constants). This allows analysis of something like
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000812 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmanc76b5452009-05-04 22:02:23 +0000813 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohmana9dba962009-04-27 20:16:15 +0000814 if (AR->isAffine()) {
815 // Check whether the backedge-taken count is SCEVCouldNotCompute.
816 // Note that this serves two purposes: It filters out loops that are
817 // simply not analyzable, and it covers the case where this code is
818 // being called from within backedge-taken count analysis, such that
819 // attempting to ask for the backedge-taken count would likely result
820 // in infinite recursion. In the later case, the analysis code will
821 // cope with a conservative value, and it will take care to purge
822 // that value once it has finished.
Nick Lewycky9425be92009-07-11 20:38:25 +0000823 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000824 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman4ada77f2009-04-29 01:54:20 +0000825 // Manually compute the final value for AR, checking for
Dan Gohman3ded5b22009-04-29 22:28:28 +0000826 // overflow.
Nick Lewycky9425be92009-07-11 20:38:25 +0000827 const SCEV *Start = AR->getStart();
828 const SCEV *Step = AR->getStepRecurrence(*this);
Dan Gohmana9dba962009-04-27 20:16:15 +0000829
830 // Check whether the backedge-taken count can be losslessly casted to
831 // the addrec's type. The count is always unsigned.
Dan Gohman161ea032009-07-07 17:06:11 +0000832 const SCEV *CastedMaxBECount =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000833 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman161ea032009-07-07 17:06:11 +0000834 const SCEV *RecastedMaxBECount =
Dan Gohman3bb37f52009-05-18 15:58:39 +0000835 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
836 if (MaxBECount == RecastedMaxBECount) {
Nick Lewycky9425be92009-07-11 20:38:25 +0000837 const Type *WideTy =
838 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000839 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohman161ea032009-07-07 17:06:11 +0000840 const SCEV *ZMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000841 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000842 getTruncateOrZeroExtend(Step, Start->getType()));
Dan Gohman161ea032009-07-07 17:06:11 +0000843 const SCEV *Add = getAddExpr(Start, ZMul);
844 const SCEV *OperandExtendedAdd =
Dan Gohman3bb37f52009-05-18 15:58:39 +0000845 getAddExpr(getZeroExtendExpr(Start, WideTy),
846 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
847 getZeroExtendExpr(Step, WideTy)));
848 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman3ded5b22009-04-29 22:28:28 +0000849 // Return the expression with the addrec on the outside.
850 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
851 getZeroExtendExpr(Step, Ty),
Nick Lewycky9425be92009-07-11 20:38:25 +0000852 AR->getLoop());
Dan Gohmana9dba962009-04-27 20:16:15 +0000853
854 // Similar to above, only this time treat the step value as signed.
855 // This covers loops that count down.
Dan Gohman161ea032009-07-07 17:06:11 +0000856 const SCEV *SMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000857 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000858 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohman3ded5b22009-04-29 22:28:28 +0000859 Add = getAddExpr(Start, SMul);
Dan Gohman3bb37f52009-05-18 15:58:39 +0000860 OperandExtendedAdd =
861 getAddExpr(getZeroExtendExpr(Start, WideTy),
862 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
863 getSignExtendExpr(Step, WideTy)));
864 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman3ded5b22009-04-29 22:28:28 +0000865 // Return the expression with the addrec on the outside.
866 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
867 getSignExtendExpr(Step, Ty),
Nick Lewycky9425be92009-07-11 20:38:25 +0000868 AR->getLoop());
Dan Gohmana9dba962009-04-27 20:16:15 +0000869 }
870 }
871 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000872
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000873 FoldingSetNodeID ID;
874 ID.AddInteger(scZeroExtend);
875 ID.AddPointer(Op);
876 ID.AddPointer(Ty);
877 void *IP = 0;
878 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
879 SCEV *S = SCEVAllocator.Allocate<SCEVZeroExtendExpr>();
880 new (S) SCEVZeroExtendExpr(Op, Ty);
881 UniqueSCEVs.InsertNode(S, IP);
882 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000883}
884
Dan Gohman161ea032009-07-07 17:06:11 +0000885const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
Dan Gohmana9dba962009-04-27 20:16:15 +0000886 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000887 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000888 "This is not an extending conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000889 assert(isSCEVable(Ty) &&
890 "This is not a conversion to a SCEVable type!");
891 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000892
Dan Gohmanc86c0df2009-06-30 20:13:32 +0000893 // Fold if the operand is constant.
Dan Gohmanc76b5452009-05-04 22:02:23 +0000894 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000895 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000896 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
897 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
Dan Gohman55788cf2009-06-24 00:38:39 +0000898 return getConstant(cast<ConstantInt>(C));
Dan Gohman01c2ee72009-04-16 03:18:22 +0000899 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000900
Dan Gohman1a5c4992009-04-22 16:20:48 +0000901 // sext(sext(x)) --> sext(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000902 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000903 return getSignExtendExpr(SS->getOperand(), Ty);
904
Dan Gohmana9dba962009-04-27 20:16:15 +0000905 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000906 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohmana9dba962009-04-27 20:16:15 +0000907 // operands (often constants). This allows analysis of something like
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000908 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmanc76b5452009-05-04 22:02:23 +0000909 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohmana9dba962009-04-27 20:16:15 +0000910 if (AR->isAffine()) {
911 // Check whether the backedge-taken count is SCEVCouldNotCompute.
912 // Note that this serves two purposes: It filters out loops that are
913 // simply not analyzable, and it covers the case where this code is
914 // being called from within backedge-taken count analysis, such that
915 // attempting to ask for the backedge-taken count would likely result
916 // in infinite recursion. In the later case, the analysis code will
917 // cope with a conservative value, and it will take care to purge
918 // that value once it has finished.
Nick Lewycky9425be92009-07-11 20:38:25 +0000919 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000920 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman4ada77f2009-04-29 01:54:20 +0000921 // Manually compute the final value for AR, checking for
Dan Gohman3ded5b22009-04-29 22:28:28 +0000922 // overflow.
Nick Lewycky9425be92009-07-11 20:38:25 +0000923 const SCEV *Start = AR->getStart();
924 const SCEV *Step = AR->getStepRecurrence(*this);
Dan Gohmana9dba962009-04-27 20:16:15 +0000925
926 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohman3ded5b22009-04-29 22:28:28 +0000927 // the addrec's type. The count is always unsigned.
Dan Gohman161ea032009-07-07 17:06:11 +0000928 const SCEV *CastedMaxBECount =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000929 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman161ea032009-07-07 17:06:11 +0000930 const SCEV *RecastedMaxBECount =
Dan Gohman3bb37f52009-05-18 15:58:39 +0000931 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
932 if (MaxBECount == RecastedMaxBECount) {
Nick Lewycky9425be92009-07-11 20:38:25 +0000933 const Type *WideTy =
934 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000935 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman161ea032009-07-07 17:06:11 +0000936 const SCEV *SMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000937 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000938 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohman161ea032009-07-07 17:06:11 +0000939 const SCEV *Add = getAddExpr(Start, SMul);
940 const SCEV *OperandExtendedAdd =
Dan Gohman3bb37f52009-05-18 15:58:39 +0000941 getAddExpr(getSignExtendExpr(Start, WideTy),
942 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
943 getSignExtendExpr(Step, WideTy)));
944 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman3ded5b22009-04-29 22:28:28 +0000945 // Return the expression with the addrec on the outside.
946 return getAddRecExpr(getSignExtendExpr(Start, Ty),
947 getSignExtendExpr(Step, Ty),
Nick Lewycky9425be92009-07-11 20:38:25 +0000948 AR->getLoop());
Dan Gohmana9dba962009-04-27 20:16:15 +0000949 }
950 }
951 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000952
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000953 FoldingSetNodeID ID;
954 ID.AddInteger(scSignExtend);
955 ID.AddPointer(Op);
956 ID.AddPointer(Ty);
957 void *IP = 0;
958 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
959 SCEV *S = SCEVAllocator.Allocate<SCEVSignExtendExpr>();
960 new (S) SCEVSignExtendExpr(Op, Ty);
961 UniqueSCEVs.InsertNode(S, IP);
962 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000963}
964
Dan Gohmane1ca7e82009-06-13 15:56:47 +0000965/// getAnyExtendExpr - Return a SCEV for the given operand extended with
966/// unspecified bits out to the given type.
967///
Dan Gohman161ea032009-07-07 17:06:11 +0000968const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
Dan Gohmane1ca7e82009-06-13 15:56:47 +0000969 const Type *Ty) {
970 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
971 "This is not an extending conversion!");
972 assert(isSCEVable(Ty) &&
973 "This is not a conversion to a SCEVable type!");
974 Ty = getEffectiveSCEVType(Ty);
975
976 // Sign-extend negative constants.
977 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
978 if (SC->getValue()->getValue().isNegative())
979 return getSignExtendExpr(Op, Ty);
980
981 // Peel off a truncate cast.
982 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
Dan Gohman161ea032009-07-07 17:06:11 +0000983 const SCEV *NewOp = T->getOperand();
Dan Gohmane1ca7e82009-06-13 15:56:47 +0000984 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
985 return getAnyExtendExpr(NewOp, Ty);
986 return getTruncateOrNoop(NewOp, Ty);
987 }
988
989 // Next try a zext cast. If the cast is folded, use it.
Dan Gohman161ea032009-07-07 17:06:11 +0000990 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
Dan Gohmane1ca7e82009-06-13 15:56:47 +0000991 if (!isa<SCEVZeroExtendExpr>(ZExt))
992 return ZExt;
993
994 // Next try a sext cast. If the cast is folded, use it.
Dan Gohman161ea032009-07-07 17:06:11 +0000995 const SCEV *SExt = getSignExtendExpr(Op, Ty);
Dan Gohmane1ca7e82009-06-13 15:56:47 +0000996 if (!isa<SCEVSignExtendExpr>(SExt))
997 return SExt;
998
999 // If the expression is obviously signed, use the sext cast value.
1000 if (isa<SCEVSMaxExpr>(Op))
1001 return SExt;
1002
1003 // Absent any other information, use the zext cast value.
1004 return ZExt;
1005}
1006
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001007/// CollectAddOperandsWithScales - Process the given Ops list, which is
1008/// a list of operands to be added under the given scale, update the given
1009/// map. This is a helper function for getAddRecExpr. As an example of
1010/// what it does, given a sequence of operands that would form an add
1011/// expression like this:
1012///
1013/// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1014///
1015/// where A and B are constants, update the map with these values:
1016///
1017/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1018///
1019/// and add 13 + A*B*29 to AccumulatedConstant.
1020/// This will allow getAddRecExpr to produce this:
1021///
1022/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1023///
1024/// This form often exposes folding opportunities that are hidden in
1025/// the original operand list.
1026///
1027/// Return true iff it appears that any interesting folding opportunities
1028/// may be exposed. This helps getAddRecExpr short-circuit extra work in
1029/// the common case where no interesting opportunities are present, and
1030/// is also used as a check to avoid infinite recursion.
1031///
1032static bool
Dan Gohman161ea032009-07-07 17:06:11 +00001033CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1034 SmallVector<const SCEV *, 8> &NewOps,
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001035 APInt &AccumulatedConstant,
Dan Gohman161ea032009-07-07 17:06:11 +00001036 const SmallVectorImpl<const SCEV *> &Ops,
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001037 const APInt &Scale,
1038 ScalarEvolution &SE) {
1039 bool Interesting = false;
1040
1041 // Iterate over the add operands.
1042 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1043 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1044 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1045 APInt NewScale =
1046 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1047 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1048 // A multiplication of a constant with another add; recurse.
1049 Interesting |=
1050 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1051 cast<SCEVAddExpr>(Mul->getOperand(1))
1052 ->getOperands(),
1053 NewScale, SE);
1054 } else {
1055 // A multiplication of a constant with some other value. Update
1056 // the map.
Dan Gohman161ea032009-07-07 17:06:11 +00001057 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1058 const SCEV *Key = SE.getMulExpr(MulOps);
1059 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman3bf01f02009-06-29 18:25:52 +00001060 M.insert(std::make_pair(Key, NewScale));
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001061 if (Pair.second) {
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001062 NewOps.push_back(Pair.first->first);
1063 } else {
1064 Pair.first->second += NewScale;
1065 // The map already had an entry for this value, which may indicate
1066 // a folding opportunity.
1067 Interesting = true;
1068 }
1069 }
1070 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1071 // Pull a buried constant out to the outside.
1072 if (Scale != 1 || AccumulatedConstant != 0 || C->isZero())
1073 Interesting = true;
1074 AccumulatedConstant += Scale * C->getValue()->getValue();
1075 } else {
1076 // An ordinary operand. Update the map.
Dan Gohman161ea032009-07-07 17:06:11 +00001077 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman3bf01f02009-06-29 18:25:52 +00001078 M.insert(std::make_pair(Ops[i], Scale));
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001079 if (Pair.second) {
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001080 NewOps.push_back(Pair.first->first);
1081 } else {
1082 Pair.first->second += Scale;
1083 // The map already had an entry for this value, which may indicate
1084 // a folding opportunity.
1085 Interesting = true;
1086 }
1087 }
1088 }
1089
1090 return Interesting;
1091}
1092
1093namespace {
1094 struct APIntCompare {
1095 bool operator()(const APInt &LHS, const APInt &RHS) const {
1096 return LHS.ult(RHS);
1097 }
1098 };
1099}
1100
Dan Gohmanc8a29272009-05-24 23:45:28 +00001101/// getAddExpr - Get a canonical add expression, or something simpler if
1102/// possible.
Dan Gohman161ea032009-07-07 17:06:11 +00001103const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001104 assert(!Ops.empty() && "Cannot get empty add!");
1105 if (Ops.size() == 1) return Ops[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001106#ifndef NDEBUG
1107 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1108 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1109 getEffectiveSCEVType(Ops[0]->getType()) &&
1110 "SCEVAddExpr operand types don't match!");
1111#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001112
1113 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001114 GroupByComplexity(Ops, LI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001115
1116 // If there are any constants, fold them together.
1117 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001118 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001119 ++Idx;
1120 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001121 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001122 // We found two constants, fold them together!
Dan Gohman02ff9392009-06-14 22:47:23 +00001123 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1124 RHSC->getValue()->getValue());
Dan Gohman68f23e82009-06-14 22:53:57 +00001125 if (Ops.size() == 2) return Ops[0];
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001126 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001127 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001128 }
1129
1130 // If we are left with a constant zero being added, strip it off.
1131 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1132 Ops.erase(Ops.begin());
1133 --Idx;
1134 }
1135 }
1136
1137 if (Ops.size() == 1) return Ops[0];
1138
1139 // Okay, check to see if the same value occurs in the operand list twice. If
1140 // so, merge them together into an multiply expression. Since we sorted the
1141 // list, these values are required to be adjacent.
1142 const Type *Ty = Ops[0]->getType();
1143 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1144 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1145 // Found a match, merge the two values into a multiply, and add any
1146 // remaining values to the result.
Dan Gohman161ea032009-07-07 17:06:11 +00001147 const SCEV *Two = getIntegerSCEV(2, Ty);
1148 const SCEV *Mul = getMulExpr(Ops[i], Two);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001149 if (Ops.size() == 2)
1150 return Mul;
1151 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
1152 Ops.push_back(Mul);
Dan Gohman89f85052007-10-22 18:31:58 +00001153 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001154 }
1155
Dan Gohman45b3b542009-05-08 21:03:19 +00001156 // Check for truncates. If all the operands are truncated from the same
1157 // type, see if factoring out the truncate would permit the result to be
1158 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1159 // if the contents of the resulting outer trunc fold to something simple.
1160 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1161 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1162 const Type *DstType = Trunc->getType();
1163 const Type *SrcType = Trunc->getOperand()->getType();
Dan Gohman161ea032009-07-07 17:06:11 +00001164 SmallVector<const SCEV *, 8> LargeOps;
Dan Gohman45b3b542009-05-08 21:03:19 +00001165 bool Ok = true;
1166 // Check all the operands to see if they can be represented in the
1167 // source type of the truncate.
1168 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1169 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1170 if (T->getOperand()->getType() != SrcType) {
1171 Ok = false;
1172 break;
1173 }
1174 LargeOps.push_back(T->getOperand());
1175 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1176 // This could be either sign or zero extension, but sign extension
1177 // is much more likely to be foldable here.
1178 LargeOps.push_back(getSignExtendExpr(C, SrcType));
1179 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Dan Gohman161ea032009-07-07 17:06:11 +00001180 SmallVector<const SCEV *, 8> LargeMulOps;
Dan Gohman45b3b542009-05-08 21:03:19 +00001181 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1182 if (const SCEVTruncateExpr *T =
1183 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1184 if (T->getOperand()->getType() != SrcType) {
1185 Ok = false;
1186 break;
1187 }
1188 LargeMulOps.push_back(T->getOperand());
1189 } else if (const SCEVConstant *C =
1190 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1191 // This could be either sign or zero extension, but sign extension
1192 // is much more likely to be foldable here.
1193 LargeMulOps.push_back(getSignExtendExpr(C, SrcType));
1194 } else {
1195 Ok = false;
1196 break;
1197 }
1198 }
1199 if (Ok)
1200 LargeOps.push_back(getMulExpr(LargeMulOps));
1201 } else {
1202 Ok = false;
1203 break;
1204 }
1205 }
1206 if (Ok) {
1207 // Evaluate the expression in the larger type.
Dan Gohman161ea032009-07-07 17:06:11 +00001208 const SCEV *Fold = getAddExpr(LargeOps);
Dan Gohman45b3b542009-05-08 21:03:19 +00001209 // If it folds to something simple, use it. Otherwise, don't.
1210 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1211 return getTruncateExpr(Fold, DstType);
1212 }
1213 }
1214
1215 // Skip past any other cast SCEVs.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001216 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1217 ++Idx;
1218
1219 // If there are add operands they would be next.
1220 if (Idx < Ops.size()) {
1221 bool DeletedAdd = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001222 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001223 // If we have an add, expand the add operands onto the end of the operands
1224 // list.
1225 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
1226 Ops.erase(Ops.begin()+Idx);
1227 DeletedAdd = true;
1228 }
1229
1230 // If we deleted at least one add, we added operands to the end of the list,
1231 // and they are not necessarily sorted. Recurse to resort and resimplify
1232 // any operands we just aquired.
1233 if (DeletedAdd)
Dan Gohman89f85052007-10-22 18:31:58 +00001234 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001235 }
1236
1237 // Skip over the add expression until we get to a multiply.
1238 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1239 ++Idx;
1240
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001241 // Check to see if there are any folding opportunities present with
1242 // operands multiplied by constant values.
1243 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1244 uint64_t BitWidth = getTypeSizeInBits(Ty);
Dan Gohman161ea032009-07-07 17:06:11 +00001245 DenseMap<const SCEV *, APInt> M;
1246 SmallVector<const SCEV *, 8> NewOps;
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001247 APInt AccumulatedConstant(BitWidth, 0);
1248 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1249 Ops, APInt(BitWidth, 1), *this)) {
1250 // Some interesting folding opportunity is present, so its worthwhile to
1251 // re-generate the operands list. Group the operands by constant scale,
1252 // to avoid multiplying by the same constant scale multiple times.
Dan Gohman161ea032009-07-07 17:06:11 +00001253 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
1254 for (SmallVector<const SCEV *, 8>::iterator I = NewOps.begin(),
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001255 E = NewOps.end(); I != E; ++I)
1256 MulOpLists[M.find(*I)->second].push_back(*I);
1257 // Re-generate the operands list.
1258 Ops.clear();
1259 if (AccumulatedConstant != 0)
1260 Ops.push_back(getConstant(AccumulatedConstant));
Dan Gohman9bc642f2009-06-24 04:48:43 +00001261 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1262 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001263 if (I->first != 0)
Dan Gohman9bc642f2009-06-24 04:48:43 +00001264 Ops.push_back(getMulExpr(getConstant(I->first),
1265 getAddExpr(I->second)));
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001266 if (Ops.empty())
1267 return getIntegerSCEV(0, Ty);
1268 if (Ops.size() == 1)
1269 return Ops[0];
1270 return getAddExpr(Ops);
1271 }
1272 }
1273
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001274 // If we are adding something to a multiply expression, make sure the
1275 // something is not already an operand of the multiply. If so, merge it into
1276 // the multiply.
1277 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001278 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001279 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001280 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001281 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohman02ff9392009-06-14 22:47:23 +00001282 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(Ops[AddOp])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001283 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Dan Gohman161ea032009-07-07 17:06:11 +00001284 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001285 if (Mul->getNumOperands() != 2) {
1286 // If the multiply has more than two operands, we must get the
1287 // Y*Z term.
Dan Gohman161ea032009-07-07 17:06:11 +00001288 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), Mul->op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001289 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001290 InnerMul = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001291 }
Dan Gohman161ea032009-07-07 17:06:11 +00001292 const SCEV *One = getIntegerSCEV(1, Ty);
1293 const SCEV *AddOne = getAddExpr(InnerMul, One);
1294 const SCEV *OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001295 if (Ops.size() == 2) return OuterMul;
1296 if (AddOp < Idx) {
1297 Ops.erase(Ops.begin()+AddOp);
1298 Ops.erase(Ops.begin()+Idx-1);
1299 } else {
1300 Ops.erase(Ops.begin()+Idx);
1301 Ops.erase(Ops.begin()+AddOp-1);
1302 }
1303 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +00001304 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001305 }
1306
1307 // Check this multiply against other multiplies being added together.
1308 for (unsigned OtherMulIdx = Idx+1;
1309 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1310 ++OtherMulIdx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001311 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001312 // If MulOp occurs in OtherMul, we can fold the two multiplies
1313 // together.
1314 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1315 OMulOp != e; ++OMulOp)
1316 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1317 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Dan Gohman161ea032009-07-07 17:06:11 +00001318 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001319 if (Mul->getNumOperands() != 2) {
Dan Gohman9bc642f2009-06-24 04:48:43 +00001320 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1321 Mul->op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001322 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001323 InnerMul1 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001324 }
Dan Gohman161ea032009-07-07 17:06:11 +00001325 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001326 if (OtherMul->getNumOperands() != 2) {
Dan Gohman9bc642f2009-06-24 04:48:43 +00001327 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
1328 OtherMul->op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001329 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001330 InnerMul2 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001331 }
Dan Gohman161ea032009-07-07 17:06:11 +00001332 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1333 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001334 if (Ops.size() == 2) return OuterMul;
1335 Ops.erase(Ops.begin()+Idx);
1336 Ops.erase(Ops.begin()+OtherMulIdx-1);
1337 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +00001338 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001339 }
1340 }
1341 }
1342 }
1343
1344 // If there are any add recurrences in the operands list, see if any other
1345 // added values are loop invariant. If so, we can fold them into the
1346 // recurrence.
1347 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1348 ++Idx;
1349
1350 // Scan over all recurrences, trying to fold loop invariants into them.
1351 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1352 // Scan all of the other operands to this add and add them to the vector if
1353 // they are loop invariant w.r.t. the recurrence.
Dan Gohman161ea032009-07-07 17:06:11 +00001354 SmallVector<const SCEV *, 8> LIOps;
Dan Gohmanbff6b582009-05-04 22:30:44 +00001355 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001356 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1357 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1358 LIOps.push_back(Ops[i]);
1359 Ops.erase(Ops.begin()+i);
1360 --i; --e;
1361 }
1362
1363 // If we found some loop invariants, fold them into the recurrence.
1364 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001365 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001366 LIOps.push_back(AddRec->getStart());
1367
Dan Gohman161ea032009-07-07 17:06:11 +00001368 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
Dan Gohman02ff9392009-06-14 22:47:23 +00001369 AddRec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001370 AddRecOps[0] = getAddExpr(LIOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001371
Dan Gohman161ea032009-07-07 17:06:11 +00001372 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001373 // If all of the other operands were loop invariant, we are done.
1374 if (Ops.size() == 1) return NewRec;
1375
1376 // Otherwise, add the folded AddRec by the non-liv parts.
1377 for (unsigned i = 0;; ++i)
1378 if (Ops[i] == AddRec) {
1379 Ops[i] = NewRec;
1380 break;
1381 }
Dan Gohman89f85052007-10-22 18:31:58 +00001382 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001383 }
1384
1385 // Okay, if there weren't any loop invariants to be folded, check to see if
1386 // there are multiple AddRec's with the same loop induction variable being
1387 // added together. If so, we can fold them.
1388 for (unsigned OtherIdx = Idx+1;
1389 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1390 if (OtherIdx != Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001391 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001392 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1393 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
Dan Gohman9bc642f2009-06-24 04:48:43 +00001394 SmallVector<const SCEV *, 4> NewOps(AddRec->op_begin(),
1395 AddRec->op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001396 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1397 if (i >= NewOps.size()) {
1398 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1399 OtherAddRec->op_end());
1400 break;
1401 }
Dan Gohman89f85052007-10-22 18:31:58 +00001402 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001403 }
Dan Gohman161ea032009-07-07 17:06:11 +00001404 const SCEV *NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001405
1406 if (Ops.size() == 2) return NewAddRec;
1407
1408 Ops.erase(Ops.begin()+Idx);
1409 Ops.erase(Ops.begin()+OtherIdx-1);
1410 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001411 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001412 }
1413 }
1414
1415 // Otherwise couldn't fold anything into this recurrence. Move onto the
1416 // next one.
1417 }
1418
1419 // Okay, it looks like we really DO need an add expr. Check to see if we
1420 // already have one, otherwise create a new one.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001421 FoldingSetNodeID ID;
1422 ID.AddInteger(scAddExpr);
1423 ID.AddInteger(Ops.size());
1424 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1425 ID.AddPointer(Ops[i]);
1426 void *IP = 0;
1427 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1428 SCEV *S = SCEVAllocator.Allocate<SCEVAddExpr>();
1429 new (S) SCEVAddExpr(Ops);
1430 UniqueSCEVs.InsertNode(S, IP);
1431 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001432}
1433
1434
Dan Gohmanc8a29272009-05-24 23:45:28 +00001435/// getMulExpr - Get a canonical multiply expression, or something simpler if
1436/// possible.
Dan Gohman161ea032009-07-07 17:06:11 +00001437const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001438 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohmana77b3d42009-05-18 15:44:58 +00001439#ifndef NDEBUG
1440 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1441 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1442 getEffectiveSCEVType(Ops[0]->getType()) &&
1443 "SCEVMulExpr operand types don't match!");
1444#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001445
1446 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001447 GroupByComplexity(Ops, LI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001448
1449 // If there are any constants, fold them together.
1450 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001451 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001452
1453 // C1*(C2+V) -> C1*C2 + C1*V
1454 if (Ops.size() == 2)
Dan Gohmanc76b5452009-05-04 22:02:23 +00001455 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001456 if (Add->getNumOperands() == 2 &&
1457 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman89f85052007-10-22 18:31:58 +00001458 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1459 getMulExpr(LHSC, Add->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001460
1461
1462 ++Idx;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001463 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001464 // We found two constants, fold them together!
Dan Gohman9bc642f2009-06-24 04:48:43 +00001465 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001466 RHSC->getValue()->getValue());
1467 Ops[0] = getConstant(Fold);
1468 Ops.erase(Ops.begin()+1); // Erase the folded element
1469 if (Ops.size() == 1) return Ops[0];
1470 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001471 }
1472
1473 // If we are left with a constant one being multiplied, strip it off.
1474 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1475 Ops.erase(Ops.begin());
1476 --Idx;
1477 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1478 // If we have a multiply of zero, it will always be zero.
1479 return Ops[0];
1480 }
1481 }
1482
1483 // Skip over the add expression until we get to a multiply.
1484 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1485 ++Idx;
1486
1487 if (Ops.size() == 1)
1488 return Ops[0];
1489
1490 // If there are mul operands inline them all into this expression.
1491 if (Idx < Ops.size()) {
1492 bool DeletedMul = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001493 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001494 // If we have an mul, expand the mul operands onto the end of the operands
1495 // list.
1496 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1497 Ops.erase(Ops.begin()+Idx);
1498 DeletedMul = true;
1499 }
1500
1501 // If we deleted at least one mul, we added operands to the end of the list,
1502 // and they are not necessarily sorted. Recurse to resort and resimplify
1503 // any operands we just aquired.
1504 if (DeletedMul)
Dan Gohman89f85052007-10-22 18:31:58 +00001505 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001506 }
1507
1508 // If there are any add recurrences in the operands list, see if any other
1509 // added values are loop invariant. If so, we can fold them into the
1510 // recurrence.
1511 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1512 ++Idx;
1513
1514 // Scan over all recurrences, trying to fold loop invariants into them.
1515 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1516 // Scan all of the other operands to this mul and add them to the vector if
1517 // they are loop invariant w.r.t. the recurrence.
Dan Gohman161ea032009-07-07 17:06:11 +00001518 SmallVector<const SCEV *, 8> LIOps;
Dan Gohmanbff6b582009-05-04 22:30:44 +00001519 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001520 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1521 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1522 LIOps.push_back(Ops[i]);
1523 Ops.erase(Ops.begin()+i);
1524 --i; --e;
1525 }
1526
1527 // If we found some loop invariants, fold them into the recurrence.
1528 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001529 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohman161ea032009-07-07 17:06:11 +00001530 SmallVector<const SCEV *, 4> NewOps;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001531 NewOps.reserve(AddRec->getNumOperands());
1532 if (LIOps.size() == 1) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001533 const SCEV *Scale = LIOps[0];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001534 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman89f85052007-10-22 18:31:58 +00001535 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001536 } else {
1537 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
Dan Gohman161ea032009-07-07 17:06:11 +00001538 SmallVector<const SCEV *, 4> MulOps(LIOps.begin(), LIOps.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001539 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman89f85052007-10-22 18:31:58 +00001540 NewOps.push_back(getMulExpr(MulOps));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001541 }
1542 }
1543
Dan Gohman161ea032009-07-07 17:06:11 +00001544 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001545
1546 // If all of the other operands were loop invariant, we are done.
1547 if (Ops.size() == 1) return NewRec;
1548
1549 // Otherwise, multiply the folded AddRec by the non-liv parts.
1550 for (unsigned i = 0;; ++i)
1551 if (Ops[i] == AddRec) {
1552 Ops[i] = NewRec;
1553 break;
1554 }
Dan Gohman89f85052007-10-22 18:31:58 +00001555 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001556 }
1557
1558 // Okay, if there weren't any loop invariants to be folded, check to see if
1559 // there are multiple AddRec's with the same loop induction variable being
1560 // multiplied together. If so, we can fold them.
1561 for (unsigned OtherIdx = Idx+1;
1562 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1563 if (OtherIdx != Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001564 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001565 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1566 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
Dan Gohmanbff6b582009-05-04 22:30:44 +00001567 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman161ea032009-07-07 17:06:11 +00001568 const SCEV *NewStart = getMulExpr(F->getStart(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001569 G->getStart());
Dan Gohman161ea032009-07-07 17:06:11 +00001570 const SCEV *B = F->getStepRecurrence(*this);
1571 const SCEV *D = G->getStepRecurrence(*this);
1572 const SCEV *NewStep = getAddExpr(getMulExpr(F, D),
Dan Gohman89f85052007-10-22 18:31:58 +00001573 getMulExpr(G, B),
1574 getMulExpr(B, D));
Dan Gohman161ea032009-07-07 17:06:11 +00001575 const SCEV *NewAddRec = getAddRecExpr(NewStart, NewStep,
Dan Gohman89f85052007-10-22 18:31:58 +00001576 F->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001577 if (Ops.size() == 2) return NewAddRec;
1578
1579 Ops.erase(Ops.begin()+Idx);
1580 Ops.erase(Ops.begin()+OtherIdx-1);
1581 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001582 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001583 }
1584 }
1585
1586 // Otherwise couldn't fold anything into this recurrence. Move onto the
1587 // next one.
1588 }
1589
1590 // Okay, it looks like we really DO need an mul expr. Check to see if we
1591 // already have one, otherwise create a new one.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001592 FoldingSetNodeID ID;
1593 ID.AddInteger(scMulExpr);
1594 ID.AddInteger(Ops.size());
1595 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1596 ID.AddPointer(Ops[i]);
1597 void *IP = 0;
1598 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1599 SCEV *S = SCEVAllocator.Allocate<SCEVMulExpr>();
1600 new (S) SCEVMulExpr(Ops);
1601 UniqueSCEVs.InsertNode(S, IP);
1602 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001603}
1604
Dan Gohmanc8a29272009-05-24 23:45:28 +00001605/// getUDivExpr - Get a canonical multiply expression, or something simpler if
1606/// possible.
Dan Gohman8c4f20b2009-06-24 14:49:00 +00001607const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
1608 const SCEV *RHS) {
Dan Gohmana77b3d42009-05-18 15:44:58 +00001609 assert(getEffectiveSCEVType(LHS->getType()) ==
1610 getEffectiveSCEVType(RHS->getType()) &&
1611 "SCEVUDivExpr operand types don't match!");
1612
Dan Gohmanc76b5452009-05-04 22:02:23 +00001613 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001614 if (RHSC->getValue()->equalsInt(1))
Nick Lewycky35b56022009-01-13 09:18:58 +00001615 return LHS; // X udiv 1 --> x
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001616 if (RHSC->isZero())
1617 return getIntegerSCEV(0, LHS->getType()); // value is undefined
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001618
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001619 // Determine if the division can be folded into the operands of
1620 // its operands.
1621 // TODO: Generalize this to non-constants by using known-bits information.
1622 const Type *Ty = LHS->getType();
1623 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1624 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1625 // For non-power-of-two values, effectively round the value up to the
1626 // nearest power of two.
1627 if (!RHSC->getValue()->getValue().isPowerOf2())
1628 ++MaxShiftAmt;
1629 const IntegerType *ExtTy =
1630 IntegerType::get(getTypeSizeInBits(Ty) + MaxShiftAmt);
1631 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1632 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1633 if (const SCEVConstant *Step =
1634 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1635 if (!Step->getValue()->getValue()
1636 .urem(RHSC->getValue()->getValue()) &&
Dan Gohman14374d32009-05-08 23:11:16 +00001637 getZeroExtendExpr(AR, ExtTy) ==
1638 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1639 getZeroExtendExpr(Step, ExtTy),
1640 AR->getLoop())) {
Dan Gohman161ea032009-07-07 17:06:11 +00001641 SmallVector<const SCEV *, 4> Operands;
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001642 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1643 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1644 return getAddRecExpr(Operands, AR->getLoop());
1645 }
1646 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
Dan Gohman14374d32009-05-08 23:11:16 +00001647 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
Dan Gohman161ea032009-07-07 17:06:11 +00001648 SmallVector<const SCEV *, 4> Operands;
Dan Gohman14374d32009-05-08 23:11:16 +00001649 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1650 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1651 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001652 // Find an operand that's safely divisible.
1653 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
Dan Gohman161ea032009-07-07 17:06:11 +00001654 const SCEV *Op = M->getOperand(i);
1655 const SCEV *Div = getUDivExpr(Op, RHSC);
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001656 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
Dan Gohman161ea032009-07-07 17:06:11 +00001657 const SmallVectorImpl<const SCEV *> &MOperands = M->getOperands();
1658 Operands = SmallVector<const SCEV *, 4>(MOperands.begin(),
Dan Gohman02ff9392009-06-14 22:47:23 +00001659 MOperands.end());
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001660 Operands[i] = Div;
1661 return getMulExpr(Operands);
1662 }
1663 }
Dan Gohman14374d32009-05-08 23:11:16 +00001664 }
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001665 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
Dan Gohman14374d32009-05-08 23:11:16 +00001666 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
Dan Gohman161ea032009-07-07 17:06:11 +00001667 SmallVector<const SCEV *, 4> Operands;
Dan Gohman14374d32009-05-08 23:11:16 +00001668 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1669 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1670 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1671 Operands.clear();
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001672 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
Dan Gohman161ea032009-07-07 17:06:11 +00001673 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001674 if (isa<SCEVUDivExpr>(Op) || getMulExpr(Op, RHS) != A->getOperand(i))
1675 break;
1676 Operands.push_back(Op);
1677 }
1678 if (Operands.size() == A->getNumOperands())
1679 return getAddExpr(Operands);
1680 }
Dan Gohman14374d32009-05-08 23:11:16 +00001681 }
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001682
1683 // Fold if both operands are constant.
Dan Gohmanc76b5452009-05-04 22:02:23 +00001684 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001685 Constant *LHSCV = LHSC->getValue();
1686 Constant *RHSCV = RHSC->getValue();
Dan Gohman55788cf2009-06-24 00:38:39 +00001687 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
1688 RHSCV)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001689 }
1690 }
1691
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001692 FoldingSetNodeID ID;
1693 ID.AddInteger(scUDivExpr);
1694 ID.AddPointer(LHS);
1695 ID.AddPointer(RHS);
1696 void *IP = 0;
1697 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1698 SCEV *S = SCEVAllocator.Allocate<SCEVUDivExpr>();
1699 new (S) SCEVUDivExpr(LHS, RHS);
1700 UniqueSCEVs.InsertNode(S, IP);
1701 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001702}
1703
1704
Dan Gohmanc8a29272009-05-24 23:45:28 +00001705/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1706/// Simplify the expression as much as possible.
Dan Gohman161ea032009-07-07 17:06:11 +00001707const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start,
1708 const SCEV *Step, const Loop *L) {
1709 SmallVector<const SCEV *, 4> Operands;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001710 Operands.push_back(Start);
Dan Gohmanc76b5452009-05-04 22:02:23 +00001711 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001712 if (StepChrec->getLoop() == L) {
1713 Operands.insert(Operands.end(), StepChrec->op_begin(),
1714 StepChrec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001715 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001716 }
1717
1718 Operands.push_back(Step);
Dan Gohman89f85052007-10-22 18:31:58 +00001719 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001720}
1721
Dan Gohmanc8a29272009-05-24 23:45:28 +00001722/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1723/// Simplify the expression as much as possible.
Dan Gohman9bc642f2009-06-24 04:48:43 +00001724const SCEV *
Dan Gohman161ea032009-07-07 17:06:11 +00001725ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
Dan Gohman9bc642f2009-06-24 04:48:43 +00001726 const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001727 if (Operands.size() == 1) return Operands[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001728#ifndef NDEBUG
1729 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1730 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
1731 getEffectiveSCEVType(Operands[0]->getType()) &&
1732 "SCEVAddRecExpr operand types don't match!");
1733#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001734
Dan Gohman7b560c42008-06-18 16:23:07 +00001735 if (Operands.back()->isZero()) {
1736 Operands.pop_back();
Dan Gohmanabe991f2008-09-14 17:21:12 +00001737 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohman7b560c42008-06-18 16:23:07 +00001738 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001739
Dan Gohman42936882008-08-08 18:33:12 +00001740 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohmanc76b5452009-05-04 22:02:23 +00001741 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohman42936882008-08-08 18:33:12 +00001742 const Loop* NestedLoop = NestedAR->getLoop();
1743 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
Dan Gohman161ea032009-07-07 17:06:11 +00001744 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohman02ff9392009-06-14 22:47:23 +00001745 NestedAR->op_end());
Dan Gohman42936882008-08-08 18:33:12 +00001746 Operands[0] = NestedAR->getStart();
Dan Gohman08c4c072009-06-26 22:36:20 +00001747 // AddRecs require their operands be loop-invariant with respect to their
1748 // loops. Don't perform this transformation if it would break this
1749 // requirement.
1750 bool AllInvariant = true;
1751 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1752 if (!Operands[i]->isLoopInvariant(L)) {
1753 AllInvariant = false;
1754 break;
1755 }
1756 if (AllInvariant) {
1757 NestedOperands[0] = getAddRecExpr(Operands, L);
1758 AllInvariant = true;
1759 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
1760 if (!NestedOperands[i]->isLoopInvariant(NestedLoop)) {
1761 AllInvariant = false;
1762 break;
1763 }
1764 if (AllInvariant)
1765 // Ok, both add recurrences are valid after the transformation.
1766 return getAddRecExpr(NestedOperands, NestedLoop);
1767 }
1768 // Reset Operands to its original state.
1769 Operands[0] = NestedAR;
Dan Gohman42936882008-08-08 18:33:12 +00001770 }
1771 }
1772
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001773 FoldingSetNodeID ID;
1774 ID.AddInteger(scAddRecExpr);
1775 ID.AddInteger(Operands.size());
1776 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1777 ID.AddPointer(Operands[i]);
1778 ID.AddPointer(L);
1779 void *IP = 0;
1780 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1781 SCEV *S = SCEVAllocator.Allocate<SCEVAddRecExpr>();
1782 new (S) SCEVAddRecExpr(Operands, L);
1783 UniqueSCEVs.InsertNode(S, IP);
1784 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001785}
1786
Dan Gohman8c4f20b2009-06-24 14:49:00 +00001787const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
1788 const SCEV *RHS) {
Dan Gohman161ea032009-07-07 17:06:11 +00001789 SmallVector<const SCEV *, 2> Ops;
Nick Lewycky711640a2007-11-25 22:41:31 +00001790 Ops.push_back(LHS);
1791 Ops.push_back(RHS);
1792 return getSMaxExpr(Ops);
1793}
1794
Dan Gohman161ea032009-07-07 17:06:11 +00001795const SCEV *
1796ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001797 assert(!Ops.empty() && "Cannot get empty smax!");
1798 if (Ops.size() == 1) return Ops[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001799#ifndef NDEBUG
1800 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1801 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1802 getEffectiveSCEVType(Ops[0]->getType()) &&
1803 "SCEVSMaxExpr operand types don't match!");
1804#endif
Nick Lewycky711640a2007-11-25 22:41:31 +00001805
1806 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001807 GroupByComplexity(Ops, LI);
Nick Lewycky711640a2007-11-25 22:41:31 +00001808
1809 // If there are any constants, fold them together.
1810 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001811 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001812 ++Idx;
1813 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001814 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001815 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001816 ConstantInt *Fold = ConstantInt::get(
Nick Lewycky711640a2007-11-25 22:41:31 +00001817 APIntOps::smax(LHSC->getValue()->getValue(),
1818 RHSC->getValue()->getValue()));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001819 Ops[0] = getConstant(Fold);
1820 Ops.erase(Ops.begin()+1); // Erase the folded element
1821 if (Ops.size() == 1) return Ops[0];
1822 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewycky711640a2007-11-25 22:41:31 +00001823 }
1824
Dan Gohmand156c092009-06-24 14:46:22 +00001825 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky711640a2007-11-25 22:41:31 +00001826 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1827 Ops.erase(Ops.begin());
1828 --Idx;
Dan Gohmand156c092009-06-24 14:46:22 +00001829 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
1830 // If we have an smax with a constant maximum-int, it will always be
1831 // maximum-int.
1832 return Ops[0];
Nick Lewycky711640a2007-11-25 22:41:31 +00001833 }
1834 }
1835
1836 if (Ops.size() == 1) return Ops[0];
1837
1838 // Find the first SMax
1839 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1840 ++Idx;
1841
1842 // Check to see if one of the operands is an SMax. If so, expand its operands
1843 // onto our operand list, and recurse to simplify.
1844 if (Idx < Ops.size()) {
1845 bool DeletedSMax = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001846 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001847 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1848 Ops.erase(Ops.begin()+Idx);
1849 DeletedSMax = true;
1850 }
1851
1852 if (DeletedSMax)
1853 return getSMaxExpr(Ops);
1854 }
1855
1856 // Okay, check to see if the same value occurs in the operand list twice. If
1857 // so, delete one. Since we sorted the list, these values are required to
1858 // be adjacent.
1859 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1860 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1861 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1862 --i; --e;
1863 }
1864
1865 if (Ops.size() == 1) return Ops[0];
1866
1867 assert(!Ops.empty() && "Reduced smax down to nothing!");
1868
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001869 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewycky711640a2007-11-25 22:41:31 +00001870 // already have one, otherwise create a new one.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001871 FoldingSetNodeID ID;
1872 ID.AddInteger(scSMaxExpr);
1873 ID.AddInteger(Ops.size());
1874 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1875 ID.AddPointer(Ops[i]);
1876 void *IP = 0;
1877 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1878 SCEV *S = SCEVAllocator.Allocate<SCEVSMaxExpr>();
1879 new (S) SCEVSMaxExpr(Ops);
1880 UniqueSCEVs.InsertNode(S, IP);
1881 return S;
Nick Lewycky711640a2007-11-25 22:41:31 +00001882}
1883
Dan Gohman8c4f20b2009-06-24 14:49:00 +00001884const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
1885 const SCEV *RHS) {
Dan Gohman161ea032009-07-07 17:06:11 +00001886 SmallVector<const SCEV *, 2> Ops;
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001887 Ops.push_back(LHS);
1888 Ops.push_back(RHS);
1889 return getUMaxExpr(Ops);
1890}
1891
Dan Gohman161ea032009-07-07 17:06:11 +00001892const SCEV *
1893ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001894 assert(!Ops.empty() && "Cannot get empty umax!");
1895 if (Ops.size() == 1) return Ops[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001896#ifndef NDEBUG
1897 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1898 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1899 getEffectiveSCEVType(Ops[0]->getType()) &&
1900 "SCEVUMaxExpr operand types don't match!");
1901#endif
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001902
1903 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001904 GroupByComplexity(Ops, LI);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001905
1906 // If there are any constants, fold them together.
1907 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001908 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001909 ++Idx;
1910 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001911 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001912 // We found two constants, fold them together!
1913 ConstantInt *Fold = ConstantInt::get(
1914 APIntOps::umax(LHSC->getValue()->getValue(),
1915 RHSC->getValue()->getValue()));
1916 Ops[0] = getConstant(Fold);
1917 Ops.erase(Ops.begin()+1); // Erase the folded element
1918 if (Ops.size() == 1) return Ops[0];
1919 LHSC = cast<SCEVConstant>(Ops[0]);
1920 }
1921
Dan Gohmand156c092009-06-24 14:46:22 +00001922 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001923 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1924 Ops.erase(Ops.begin());
1925 --Idx;
Dan Gohmand156c092009-06-24 14:46:22 +00001926 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
1927 // If we have an umax with a constant maximum-int, it will always be
1928 // maximum-int.
1929 return Ops[0];
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001930 }
1931 }
1932
1933 if (Ops.size() == 1) return Ops[0];
1934
1935 // Find the first UMax
1936 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1937 ++Idx;
1938
1939 // Check to see if one of the operands is a UMax. If so, expand its operands
1940 // onto our operand list, and recurse to simplify.
1941 if (Idx < Ops.size()) {
1942 bool DeletedUMax = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001943 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001944 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1945 Ops.erase(Ops.begin()+Idx);
1946 DeletedUMax = true;
1947 }
1948
1949 if (DeletedUMax)
1950 return getUMaxExpr(Ops);
1951 }
1952
1953 // Okay, check to see if the same value occurs in the operand list twice. If
1954 // so, delete one. Since we sorted the list, these values are required to
1955 // be adjacent.
1956 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1957 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1958 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1959 --i; --e;
1960 }
1961
1962 if (Ops.size() == 1) return Ops[0];
1963
1964 assert(!Ops.empty() && "Reduced umax down to nothing!");
1965
1966 // Okay, it looks like we really DO need a umax expr. Check to see if we
1967 // already have one, otherwise create a new one.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001968 FoldingSetNodeID ID;
1969 ID.AddInteger(scUMaxExpr);
1970 ID.AddInteger(Ops.size());
1971 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1972 ID.AddPointer(Ops[i]);
1973 void *IP = 0;
1974 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1975 SCEV *S = SCEVAllocator.Allocate<SCEVUMaxExpr>();
1976 new (S) SCEVUMaxExpr(Ops);
1977 UniqueSCEVs.InsertNode(S, IP);
1978 return S;
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001979}
1980
Dan Gohman8c4f20b2009-06-24 14:49:00 +00001981const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
1982 const SCEV *RHS) {
Dan Gohmand01fff82009-06-22 03:18:45 +00001983 // ~smax(~x, ~y) == smin(x, y).
1984 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
1985}
1986
Dan Gohman8c4f20b2009-06-24 14:49:00 +00001987const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
1988 const SCEV *RHS) {
Dan Gohmand01fff82009-06-22 03:18:45 +00001989 // ~umax(~x, ~y) == umin(x, y)
1990 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
1991}
1992
Dan Gohman161ea032009-07-07 17:06:11 +00001993const SCEV *ScalarEvolution::getUnknown(Value *V) {
Dan Gohman984c78a2009-06-24 00:54:57 +00001994 // Don't attempt to do anything other than create a SCEVUnknown object
1995 // here. createSCEV only calls getUnknown after checking for all other
1996 // interesting possibilities, and any other code that calls getUnknown
1997 // is doing so in order to hide a value from SCEV canonicalization.
1998
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001999 FoldingSetNodeID ID;
2000 ID.AddInteger(scUnknown);
2001 ID.AddPointer(V);
2002 void *IP = 0;
2003 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2004 SCEV *S = SCEVAllocator.Allocate<SCEVUnknown>();
2005 new (S) SCEVUnknown(V);
2006 UniqueSCEVs.InsertNode(S, IP);
2007 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002008}
2009
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002010//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002011// Basic SCEV Analysis and PHI Idiom Recognition Code
2012//
2013
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002014/// isSCEVable - Test if values of the given type are analyzable within
2015/// the SCEV framework. This primarily includes integer types, and it
2016/// can optionally include pointer types if the ScalarEvolution class
2017/// has access to target-specific information.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002018bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002019 // Integers are always SCEVable.
2020 if (Ty->isInteger())
2021 return true;
2022
2023 // Pointers are SCEVable if TargetData information is available
2024 // to provide pointer size information.
2025 if (isa<PointerType>(Ty))
2026 return TD != NULL;
2027
2028 // Otherwise it's not SCEVable.
2029 return false;
2030}
2031
2032/// getTypeSizeInBits - Return the size in bits of the specified type,
2033/// for which isSCEVable must return true.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002034uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002035 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2036
2037 // If we have a TargetData, use it!
2038 if (TD)
2039 return TD->getTypeSizeInBits(Ty);
2040
2041 // Otherwise, we support only integer types.
2042 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
2043 return Ty->getPrimitiveSizeInBits();
2044}
2045
2046/// getEffectiveSCEVType - Return a type with the same bitwidth as
2047/// the given type and which represents how SCEV will treat the given
2048/// type, for which isSCEVable must return true. For pointer types,
2049/// this is the pointer-sized integer type.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002050const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002051 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2052
2053 if (Ty->isInteger())
2054 return Ty;
2055
2056 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
2057 return TD->getIntPtrType();
Dan Gohman01c2ee72009-04-16 03:18:22 +00002058}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002059
Dan Gohman161ea032009-07-07 17:06:11 +00002060const SCEV *ScalarEvolution::getCouldNotCompute() {
Dan Gohmanc6475cb2009-06-27 21:21:31 +00002061 return &CouldNotCompute;
Dan Gohman0ad08b02009-04-18 17:58:19 +00002062}
2063
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002064/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2065/// expression and create a new one.
Dan Gohman161ea032009-07-07 17:06:11 +00002066const SCEV *ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002067 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002068
Dan Gohman161ea032009-07-07 17:06:11 +00002069 std::map<SCEVCallbackVH, const SCEV *>::iterator I = Scalars.find(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002070 if (I != Scalars.end()) return I->second;
Dan Gohman161ea032009-07-07 17:06:11 +00002071 const SCEV *S = createSCEV(V);
Dan Gohmanbff6b582009-05-04 22:30:44 +00002072 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002073 return S;
2074}
2075
Dan Gohman984c78a2009-06-24 00:54:57 +00002076/// getIntegerSCEV - Given a SCEVable type, create a constant for the
Dan Gohman01c2ee72009-04-16 03:18:22 +00002077/// specified signed integer value and return a SCEV for the constant.
Dan Gohman161ea032009-07-07 17:06:11 +00002078const SCEV *ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
Dan Gohman984c78a2009-06-24 00:54:57 +00002079 const IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
2080 return getConstant(ConstantInt::get(ITy, Val));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002081}
2082
2083/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2084///
Dan Gohman161ea032009-07-07 17:06:11 +00002085const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00002086 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson15b39322009-07-13 04:09:18 +00002087 return getConstant(
2088 cast<ConstantInt>(Context->getConstantExprNeg(VC->getValue())));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002089
2090 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002091 Ty = getEffectiveSCEVType(Ty);
2092 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(Ty)));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002093}
2094
2095/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohman161ea032009-07-07 17:06:11 +00002096const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00002097 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohman55788cf2009-06-24 00:38:39 +00002098 return getConstant(cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002099
2100 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002101 Ty = getEffectiveSCEVType(Ty);
Dan Gohman161ea032009-07-07 17:06:11 +00002102 const SCEV *AllOnes = getConstant(ConstantInt::getAllOnesValue(Ty));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002103 return getMinusSCEV(AllOnes, V);
2104}
2105
2106/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2107///
Dan Gohman8c4f20b2009-06-24 14:49:00 +00002108const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS,
2109 const SCEV *RHS) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00002110 // X - Y --> X + -Y
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002111 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002112}
2113
2114/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2115/// input value to the specified type. If the type must be extended, it is zero
2116/// extended.
Dan Gohman161ea032009-07-07 17:06:11 +00002117const SCEV *
2118ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V,
Nick Lewycky37d04642009-04-23 05:15:08 +00002119 const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00002120 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002121 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2122 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00002123 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002124 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00002125 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002126 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002127 return getTruncateExpr(V, Ty);
2128 return getZeroExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002129}
2130
2131/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2132/// input value to the specified type. If the type must be extended, it is sign
2133/// extended.
Dan Gohman161ea032009-07-07 17:06:11 +00002134const SCEV *
2135ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
Nick Lewycky37d04642009-04-23 05:15:08 +00002136 const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00002137 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002138 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2139 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00002140 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002141 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00002142 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002143 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002144 return getTruncateExpr(V, Ty);
2145 return getSignExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002146}
2147
Dan Gohmanac959332009-05-13 03:46:30 +00002148/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2149/// input value to the specified type. If the type must be extended, it is zero
2150/// extended. The conversion must not be narrowing.
Dan Gohman161ea032009-07-07 17:06:11 +00002151const SCEV *
2152ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, const Type *Ty) {
Dan Gohmanac959332009-05-13 03:46:30 +00002153 const Type *SrcTy = V->getType();
2154 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2155 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2156 "Cannot noop or zero extend with non-integer arguments!");
2157 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2158 "getNoopOrZeroExtend cannot truncate!");
2159 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2160 return V; // No conversion
2161 return getZeroExtendExpr(V, Ty);
2162}
2163
2164/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2165/// input value to the specified type. If the type must be extended, it is sign
2166/// extended. The conversion must not be narrowing.
Dan Gohman161ea032009-07-07 17:06:11 +00002167const SCEV *
2168ScalarEvolution::getNoopOrSignExtend(const SCEV *V, const Type *Ty) {
Dan Gohmanac959332009-05-13 03:46:30 +00002169 const Type *SrcTy = V->getType();
2170 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2171 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2172 "Cannot noop or sign extend with non-integer arguments!");
2173 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2174 "getNoopOrSignExtend cannot truncate!");
2175 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2176 return V; // No conversion
2177 return getSignExtendExpr(V, Ty);
2178}
2179
Dan Gohmane1ca7e82009-06-13 15:56:47 +00002180/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2181/// the input value to the specified type. If the type must be extended,
2182/// it is extended with unspecified bits. The conversion must not be
2183/// narrowing.
Dan Gohman161ea032009-07-07 17:06:11 +00002184const SCEV *
2185ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, const Type *Ty) {
Dan Gohmane1ca7e82009-06-13 15:56:47 +00002186 const Type *SrcTy = V->getType();
2187 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2188 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2189 "Cannot noop or any extend with non-integer arguments!");
2190 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2191 "getNoopOrAnyExtend cannot truncate!");
2192 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2193 return V; // No conversion
2194 return getAnyExtendExpr(V, Ty);
2195}
2196
Dan Gohmanac959332009-05-13 03:46:30 +00002197/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2198/// input value to the specified type. The conversion must not be widening.
Dan Gohman161ea032009-07-07 17:06:11 +00002199const SCEV *
2200ScalarEvolution::getTruncateOrNoop(const SCEV *V, const Type *Ty) {
Dan Gohmanac959332009-05-13 03:46:30 +00002201 const Type *SrcTy = V->getType();
2202 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2203 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2204 "Cannot truncate or noop with non-integer arguments!");
2205 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2206 "getTruncateOrNoop cannot extend!");
2207 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2208 return V; // No conversion
2209 return getTruncateExpr(V, Ty);
2210}
2211
Dan Gohman8e8b5232009-06-22 00:31:57 +00002212/// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2213/// the types using zero-extension, and then perform a umax operation
2214/// with them.
Dan Gohman8c4f20b2009-06-24 14:49:00 +00002215const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2216 const SCEV *RHS) {
Dan Gohman161ea032009-07-07 17:06:11 +00002217 const SCEV *PromotedLHS = LHS;
2218 const SCEV *PromotedRHS = RHS;
Dan Gohman8e8b5232009-06-22 00:31:57 +00002219
2220 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2221 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2222 else
2223 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2224
2225 return getUMaxExpr(PromotedLHS, PromotedRHS);
2226}
2227
Dan Gohman9e62bb02009-06-22 15:03:27 +00002228/// getUMinFromMismatchedTypes - Promote the operands to the wider of
2229/// the types using zero-extension, and then perform a umin operation
2230/// with them.
Dan Gohman8c4f20b2009-06-24 14:49:00 +00002231const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2232 const SCEV *RHS) {
Dan Gohman161ea032009-07-07 17:06:11 +00002233 const SCEV *PromotedLHS = LHS;
2234 const SCEV *PromotedRHS = RHS;
Dan Gohman9e62bb02009-06-22 15:03:27 +00002235
2236 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2237 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2238 else
2239 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2240
2241 return getUMinExpr(PromotedLHS, PromotedRHS);
2242}
2243
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002244/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
2245/// the specified instruction and replaces any references to the symbolic value
2246/// SymName with the specified value. This is used during PHI resolution.
Dan Gohman9bc642f2009-06-24 04:48:43 +00002247void
2248ScalarEvolution::ReplaceSymbolicValueWithConcrete(Instruction *I,
2249 const SCEV *SymName,
2250 const SCEV *NewVal) {
Dan Gohman161ea032009-07-07 17:06:11 +00002251 std::map<SCEVCallbackVH, const SCEV *>::iterator SI =
Dan Gohmanbff6b582009-05-04 22:30:44 +00002252 Scalars.find(SCEVCallbackVH(I, this));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002253 if (SI == Scalars.end()) return;
2254
Dan Gohman161ea032009-07-07 17:06:11 +00002255 const SCEV *NV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002256 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002257 if (NV == SI->second) return; // No change.
2258
2259 SI->second = NV; // Update the scalars map!
2260
2261 // Any instruction values that use this instruction might also need to be
2262 // updated!
2263 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
2264 UI != E; ++UI)
2265 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
2266}
2267
2268/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2269/// a loop header, making it a potential recurrence, or it doesn't.
2270///
Dan Gohman161ea032009-07-07 17:06:11 +00002271const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002272 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002273 if (const Loop *L = LI->getLoopFor(PN->getParent()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002274 if (L->getHeader() == PN->getParent()) {
2275 // If it lives in the loop header, it has two incoming values, one
2276 // from outside the loop, and one from inside.
2277 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
2278 unsigned BackEdge = IncomingEdge^1;
2279
2280 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohman161ea032009-07-07 17:06:11 +00002281 const SCEV *SymbolicName = getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002282 assert(Scalars.find(PN) == Scalars.end() &&
2283 "PHI node already processed?");
Dan Gohmanbff6b582009-05-04 22:30:44 +00002284 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002285
2286 // Using this symbolic name for the PHI, analyze the value coming around
2287 // the back-edge.
Dan Gohman161ea032009-07-07 17:06:11 +00002288 const SCEV *BEValue = getSCEV(PN->getIncomingValue(BackEdge));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002289
2290 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2291 // has a special value for the first iteration of the loop.
2292
2293 // If the value coming around the backedge is an add with the symbolic
2294 // value we just inserted, then we found a simple induction variable!
Dan Gohmanc76b5452009-05-04 22:02:23 +00002295 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002296 // If there is a single occurrence of the symbolic value, replace it
2297 // with a recurrence.
2298 unsigned FoundIndex = Add->getNumOperands();
2299 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2300 if (Add->getOperand(i) == SymbolicName)
2301 if (FoundIndex == e) {
2302 FoundIndex = i;
2303 break;
2304 }
2305
2306 if (FoundIndex != Add->getNumOperands()) {
2307 // Create an add with everything but the specified operand.
Dan Gohman161ea032009-07-07 17:06:11 +00002308 SmallVector<const SCEV *, 8> Ops;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002309 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2310 if (i != FoundIndex)
2311 Ops.push_back(Add->getOperand(i));
Dan Gohman161ea032009-07-07 17:06:11 +00002312 const SCEV *Accum = getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002313
2314 // This is not a valid addrec if the step amount is varying each
2315 // loop iteration, but is not itself an addrec in this loop.
2316 if (Accum->isLoopInvariant(L) ||
2317 (isa<SCEVAddRecExpr>(Accum) &&
2318 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
Dan Gohman9bc642f2009-06-24 04:48:43 +00002319 const SCEV *StartVal =
2320 getSCEV(PN->getIncomingValue(IncomingEdge));
2321 const SCEV *PHISCEV =
2322 getAddRecExpr(StartVal, Accum, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002323
2324 // Okay, for the entire analysis of this edge we assumed the PHI
2325 // to be symbolic. We now need to go back and update all of the
2326 // entries for the scalars that use the PHI (except for the PHI
2327 // itself) to use the new analyzed value instead of the "symbolic"
2328 // value.
2329 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
2330 return PHISCEV;
2331 }
2332 }
Dan Gohmanc76b5452009-05-04 22:02:23 +00002333 } else if (const SCEVAddRecExpr *AddRec =
2334 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002335 // Otherwise, this could be a loop like this:
2336 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2337 // In this case, j = {1,+,1} and BEValue is j.
2338 // Because the other in-value of i (0) fits the evolution of BEValue
2339 // i really is an addrec evolution.
2340 if (AddRec->getLoop() == L && AddRec->isAffine()) {
Dan Gohman161ea032009-07-07 17:06:11 +00002341 const SCEV *StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002342
2343 // If StartVal = j.start - j.stride, we can use StartVal as the
2344 // initial step of the addrec evolution.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002345 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman89f85052007-10-22 18:31:58 +00002346 AddRec->getOperand(1))) {
Dan Gohman161ea032009-07-07 17:06:11 +00002347 const SCEV *PHISCEV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002348 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002349
2350 // Okay, for the entire analysis of this edge we assumed the PHI
2351 // to be symbolic. We now need to go back and update all of the
2352 // entries for the scalars that use the PHI (except for the PHI
2353 // itself) to use the new analyzed value instead of the "symbolic"
2354 // value.
2355 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
2356 return PHISCEV;
2357 }
2358 }
2359 }
2360
2361 return SymbolicName;
2362 }
2363
2364 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002365 return getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002366}
2367
Dan Gohman509cf4d2009-05-08 20:26:55 +00002368/// createNodeForGEP - Expand GEP instructions into add and multiply
2369/// operations. This allows them to be analyzed by regular SCEV code.
2370///
Dan Gohman161ea032009-07-07 17:06:11 +00002371const SCEV *ScalarEvolution::createNodeForGEP(User *GEP) {
Dan Gohman509cf4d2009-05-08 20:26:55 +00002372
2373 const Type *IntPtrTy = TD->getIntPtrType();
Dan Gohmanc7034fa2009-05-08 20:36:47 +00002374 Value *Base = GEP->getOperand(0);
Dan Gohmand586a4f2009-05-09 00:14:52 +00002375 // Don't attempt to analyze GEPs over unsized objects.
2376 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2377 return getUnknown(GEP);
Dan Gohman161ea032009-07-07 17:06:11 +00002378 const SCEV *TotalOffset = getIntegerSCEV(0, IntPtrTy);
Dan Gohmanc7034fa2009-05-08 20:36:47 +00002379 gep_type_iterator GTI = gep_type_begin(GEP);
2380 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
2381 E = GEP->op_end();
Dan Gohman509cf4d2009-05-08 20:26:55 +00002382 I != E; ++I) {
2383 Value *Index = *I;
2384 // Compute the (potentially symbolic) offset in bytes for this index.
2385 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2386 // For a struct, add the member offset.
2387 const StructLayout &SL = *TD->getStructLayout(STy);
2388 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
2389 uint64_t Offset = SL.getElementOffset(FieldNo);
Nick Lewycky9425be92009-07-11 20:38:25 +00002390 TotalOffset = getAddExpr(TotalOffset,
2391 getIntegerSCEV(Offset, IntPtrTy));
Dan Gohman509cf4d2009-05-08 20:26:55 +00002392 } else {
2393 // For an array, add the element offset, explicitly scaled.
Dan Gohman161ea032009-07-07 17:06:11 +00002394 const SCEV *LocalOffset = getSCEV(Index);
Dan Gohman509cf4d2009-05-08 20:26:55 +00002395 if (!isa<PointerType>(LocalOffset->getType()))
2396 // Getelementptr indicies are signed.
Nick Lewycky9425be92009-07-11 20:38:25 +00002397 LocalOffset = getTruncateOrSignExtend(LocalOffset,
2398 IntPtrTy);
Dan Gohman509cf4d2009-05-08 20:26:55 +00002399 LocalOffset =
2400 getMulExpr(LocalOffset,
Nick Lewycky9425be92009-07-11 20:38:25 +00002401 getIntegerSCEV(TD->getTypeAllocSize(*GTI),
2402 IntPtrTy));
Dan Gohman509cf4d2009-05-08 20:26:55 +00002403 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
2404 }
2405 }
2406 return getAddExpr(getSCEV(Base), TotalOffset);
2407}
2408
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002409/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2410/// guaranteed to end in (at every loop iteration). It is, at the same time,
2411/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2412/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohman6e923a72009-06-19 23:29:04 +00002413uint32_t
Dan Gohman161ea032009-07-07 17:06:11 +00002414ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00002415 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner6ecce2a2007-11-23 22:36:49 +00002416 return C->getValue()->getValue().countTrailingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002417
Dan Gohmanc76b5452009-05-04 22:02:23 +00002418 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohman6e923a72009-06-19 23:29:04 +00002419 return std::min(GetMinTrailingZeros(T->getOperand()),
2420 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002421
Dan Gohmanc76b5452009-05-04 22:02:23 +00002422 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohman6e923a72009-06-19 23:29:04 +00002423 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2424 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2425 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002426 }
2427
Dan Gohmanc76b5452009-05-04 22:02:23 +00002428 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohman6e923a72009-06-19 23:29:04 +00002429 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2430 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2431 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002432 }
2433
Dan Gohmanc76b5452009-05-04 22:02:23 +00002434 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002435 // The result is the min of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002436 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002437 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002438 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002439 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002440 }
2441
Dan Gohmanc76b5452009-05-04 22:02:23 +00002442 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002443 // The result is the sum of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002444 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2445 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002446 for (unsigned i = 1, e = M->getNumOperands();
2447 SumOpRes != BitWidth && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002448 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002449 BitWidth);
2450 return SumOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002451 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002452
Dan Gohmanc76b5452009-05-04 22:02:23 +00002453 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002454 // The result is the min of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002455 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002456 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002457 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002458 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002459 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002460
Dan Gohmanc76b5452009-05-04 22:02:23 +00002461 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewycky711640a2007-11-25 22:41:31 +00002462 // The result is the min of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002463 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky711640a2007-11-25 22:41:31 +00002464 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002465 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky711640a2007-11-25 22:41:31 +00002466 return MinOpRes;
2467 }
2468
Dan Gohmanc76b5452009-05-04 22:02:23 +00002469 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002470 // The result is the min of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002471 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002472 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002473 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002474 return MinOpRes;
2475 }
2476
Dan Gohman6e923a72009-06-19 23:29:04 +00002477 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2478 // For a SCEVUnknown, ask ValueTracking.
2479 unsigned BitWidth = getTypeSizeInBits(U->getType());
2480 APInt Mask = APInt::getAllOnesValue(BitWidth);
2481 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2482 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2483 return Zeros.countTrailingOnes();
2484 }
2485
2486 // SCEVUDivExpr
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002487 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002488}
2489
Nick Lewycky9425be92009-07-11 20:38:25 +00002490uint32_t
2491ScalarEvolution::GetMinLeadingZeros(const SCEV *S) {
2492 // TODO: Handle other SCEV expression types here.
Dan Gohman6e923a72009-06-19 23:29:04 +00002493
2494 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Nick Lewycky9425be92009-07-11 20:38:25 +00002495 return C->getValue()->getValue().countLeadingZeros();
Dan Gohman6e923a72009-06-19 23:29:04 +00002496
Nick Lewycky9425be92009-07-11 20:38:25 +00002497 if (const SCEVZeroExtendExpr *C = dyn_cast<SCEVZeroExtendExpr>(S)) {
2498 // A zero-extension cast adds zero bits.
2499 return GetMinLeadingZeros(C->getOperand()) +
2500 (getTypeSizeInBits(C->getType()) -
2501 getTypeSizeInBits(C->getOperand()->getType()));
Dan Gohman6e923a72009-06-19 23:29:04 +00002502 }
2503
2504 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2505 // For a SCEVUnknown, ask ValueTracking.
2506 unsigned BitWidth = getTypeSizeInBits(U->getType());
2507 APInt Mask = APInt::getAllOnesValue(BitWidth);
2508 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2509 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
Nick Lewycky9425be92009-07-11 20:38:25 +00002510 return Zeros.countLeadingOnes();
Dan Gohman6e923a72009-06-19 23:29:04 +00002511 }
2512
Nick Lewycky9425be92009-07-11 20:38:25 +00002513 return 1;
Dan Gohman6e923a72009-06-19 23:29:04 +00002514}
2515
Nick Lewycky9425be92009-07-11 20:38:25 +00002516uint32_t
2517ScalarEvolution::GetMinSignBits(const SCEV *S) {
2518 // TODO: Handle other SCEV expression types here.
Dan Gohman6e923a72009-06-19 23:29:04 +00002519
Nick Lewycky9425be92009-07-11 20:38:25 +00002520 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
2521 const APInt &A = C->getValue()->getValue();
2522 return A.isNegative() ? A.countLeadingOnes() :
2523 A.countLeadingZeros();
Dan Gohman6e923a72009-06-19 23:29:04 +00002524 }
2525
Nick Lewycky9425be92009-07-11 20:38:25 +00002526 if (const SCEVSignExtendExpr *C = dyn_cast<SCEVSignExtendExpr>(S)) {
2527 // A sign-extension cast adds sign bits.
2528 return GetMinSignBits(C->getOperand()) +
2529 (getTypeSizeInBits(C->getType()) -
2530 getTypeSizeInBits(C->getOperand()->getType()));
Dan Gohman6e923a72009-06-19 23:29:04 +00002531 }
2532
Nick Lewycky9425be92009-07-11 20:38:25 +00002533 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
2534 unsigned BitWidth = getTypeSizeInBits(A->getType());
Dan Gohman61e0c4c2009-06-24 01:05:09 +00002535
Nick Lewycky9425be92009-07-11 20:38:25 +00002536 // Special case decrementing a value (ADD X, -1):
2537 if (const SCEVConstant *CRHS = dyn_cast<SCEVConstant>(A->getOperand(0)))
2538 if (CRHS->isAllOnesValue()) {
2539 SmallVector<const SCEV *, 4> OtherOps(A->op_begin() + 1, A->op_end());
2540 const SCEV *OtherOpsAdd = getAddExpr(OtherOps);
2541 unsigned LZ = GetMinLeadingZeros(OtherOpsAdd);
Dan Gohman61e0c4c2009-06-24 01:05:09 +00002542
Nick Lewycky9425be92009-07-11 20:38:25 +00002543 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2544 // sign bits set.
2545 if (LZ == BitWidth - 1)
2546 return BitWidth;
Dan Gohman61e0c4c2009-06-24 01:05:09 +00002547
Nick Lewycky9425be92009-07-11 20:38:25 +00002548 // If we are subtracting one from a positive number, there is no carry
2549 // out of the result.
2550 if (LZ > 0)
2551 return GetMinSignBits(OtherOpsAdd);
Dan Gohman61e0c4c2009-06-24 01:05:09 +00002552 }
Nick Lewycky9425be92009-07-11 20:38:25 +00002553
2554 // Add can have at most one carry bit. Thus we know that the output
2555 // is, at worst, one more bit than the inputs.
2556 unsigned Min = BitWidth;
2557 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
2558 unsigned N = GetMinSignBits(A->getOperand(i));
2559 Min = std::min(Min, N) - 1;
2560 if (Min == 0) return 1;
Dan Gohman61e0c4c2009-06-24 01:05:09 +00002561 }
Nick Lewycky9425be92009-07-11 20:38:25 +00002562 return 1;
Dan Gohman61e0c4c2009-06-24 01:05:09 +00002563 }
2564
Dan Gohman6e923a72009-06-19 23:29:04 +00002565 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2566 // For a SCEVUnknown, ask ValueTracking.
Nick Lewycky9425be92009-07-11 20:38:25 +00002567 return ComputeNumSignBits(U->getValue(), TD);
Dan Gohman6e923a72009-06-19 23:29:04 +00002568 }
2569
Nick Lewycky9425be92009-07-11 20:38:25 +00002570 return 1;
Dan Gohman6e923a72009-06-19 23:29:04 +00002571}
2572
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002573/// createSCEV - We know that there is no SCEV for the specified value.
2574/// Analyze the expression.
2575///
Dan Gohman161ea032009-07-07 17:06:11 +00002576const SCEV *ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002577 if (!isSCEVable(V->getType()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002578 return getUnknown(V);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002579
Dan Gohman3996f472008-06-22 19:56:46 +00002580 unsigned Opcode = Instruction::UserOp1;
2581 if (Instruction *I = dyn_cast<Instruction>(V))
2582 Opcode = I->getOpcode();
2583 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
2584 Opcode = CE->getOpcode();
Dan Gohman984c78a2009-06-24 00:54:57 +00002585 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2586 return getConstant(CI);
2587 else if (isa<ConstantPointerNull>(V))
2588 return getIntegerSCEV(0, V->getType());
2589 else if (isa<UndefValue>(V))
2590 return getIntegerSCEV(0, V->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002591 else
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002592 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002593
Dan Gohman3996f472008-06-22 19:56:46 +00002594 User *U = cast<User>(V);
2595 switch (Opcode) {
2596 case Instruction::Add:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002597 return getAddExpr(getSCEV(U->getOperand(0)),
2598 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002599 case Instruction::Mul:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002600 return getMulExpr(getSCEV(U->getOperand(0)),
2601 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002602 case Instruction::UDiv:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002603 return getUDivExpr(getSCEV(U->getOperand(0)),
2604 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002605 case Instruction::Sub:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002606 return getMinusSCEV(getSCEV(U->getOperand(0)),
2607 getSCEV(U->getOperand(1)));
Dan Gohman53bf64a2009-04-21 02:26:00 +00002608 case Instruction::And:
2609 // For an expression like x&255 that merely masks off the high bits,
2610 // use zext(trunc(x)) as the SCEV expression.
2611 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman91ae1e72009-04-25 17:05:40 +00002612 if (CI->isNullValue())
2613 return getSCEV(U->getOperand(1));
Dan Gohmanc7ebba12009-04-27 01:41:10 +00002614 if (CI->isAllOnesValue())
2615 return getSCEV(U->getOperand(0));
Dan Gohman53bf64a2009-04-21 02:26:00 +00002616 const APInt &A = CI->getValue();
Dan Gohmana7726c32009-06-16 19:52:01 +00002617
2618 // Instcombine's ShrinkDemandedConstant may strip bits out of
2619 // constants, obscuring what would otherwise be a low-bits mask.
2620 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
2621 // knew about to reconstruct a low-bits mask value.
2622 unsigned LZ = A.countLeadingZeros();
2623 unsigned BitWidth = A.getBitWidth();
2624 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
2625 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2626 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
2627
2628 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
2629
Dan Gohmanae1d7dd2009-06-17 23:54:37 +00002630 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
Dan Gohman53bf64a2009-04-21 02:26:00 +00002631 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002632 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
Dan Gohmana7726c32009-06-16 19:52:01 +00002633 IntegerType::get(BitWidth - LZ)),
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002634 U->getType());
Dan Gohman53bf64a2009-04-21 02:26:00 +00002635 }
2636 break;
Dan Gohmana7726c32009-06-16 19:52:01 +00002637
Dan Gohman3996f472008-06-22 19:56:46 +00002638 case Instruction::Or:
2639 // If the RHS of the Or is a constant, we may have something like:
2640 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
2641 // optimizations will transparently handle this case.
2642 //
2643 // In order for this transformation to be safe, the LHS must be of the
2644 // form X*(2^n) and the Or constant must be less than 2^n.
2645 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman161ea032009-07-07 17:06:11 +00002646 const SCEV *LHS = getSCEV(U->getOperand(0));
Dan Gohman3996f472008-06-22 19:56:46 +00002647 const APInt &CIVal = CI->getValue();
Dan Gohman6e923a72009-06-19 23:29:04 +00002648 if (GetMinTrailingZeros(LHS) >=
Dan Gohman3996f472008-06-22 19:56:46 +00002649 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002650 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002651 }
Dan Gohman3996f472008-06-22 19:56:46 +00002652 break;
2653 case Instruction::Xor:
Dan Gohman3996f472008-06-22 19:56:46 +00002654 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky7fd27892008-07-07 06:15:49 +00002655 // If the RHS of the xor is a signbit, then this is just an add.
2656 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman3996f472008-06-22 19:56:46 +00002657 if (CI->getValue().isSignBit())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002658 return getAddExpr(getSCEV(U->getOperand(0)),
2659 getSCEV(U->getOperand(1)));
Nick Lewycky7fd27892008-07-07 06:15:49 +00002660
2661 // If the RHS of xor is -1, then this is a not operation.
Dan Gohmanc897f752009-05-18 16:17:44 +00002662 if (CI->isAllOnesValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002663 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohmanfc78cff2009-05-18 16:29:04 +00002664
2665 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
2666 // This is a variant of the check for xor with -1, and it handles
2667 // the case where instcombine has trimmed non-demanded bits out
2668 // of an xor with -1.
2669 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
2670 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
2671 if (BO->getOpcode() == Instruction::And &&
2672 LCI->getValue() == CI->getValue())
2673 if (const SCEVZeroExtendExpr *Z =
Dan Gohmane49ae432009-06-17 01:22:39 +00002674 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
Dan Gohmaned1d8bb2009-06-18 00:00:20 +00002675 const Type *UTy = U->getType();
Dan Gohman161ea032009-07-07 17:06:11 +00002676 const SCEV *Z0 = Z->getOperand();
Dan Gohmaned1d8bb2009-06-18 00:00:20 +00002677 const Type *Z0Ty = Z0->getType();
2678 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
2679
2680 // If C is a low-bits mask, the zero extend is zerving to
2681 // mask off the high bits. Complement the operand and
2682 // re-apply the zext.
2683 if (APIntOps::isMask(Z0TySize, CI->getValue()))
2684 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
2685
2686 // If C is a single bit, it may be in the sign-bit position
2687 // before the zero-extend. In this case, represent the xor
2688 // using an add, which is equivalent, and re-apply the zext.
2689 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
2690 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
2691 Trunc.isSignBit())
2692 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
2693 UTy);
Dan Gohmane49ae432009-06-17 01:22:39 +00002694 }
Dan Gohman3996f472008-06-22 19:56:46 +00002695 }
2696 break;
2697
2698 case Instruction::Shl:
2699 // Turn shift left of a constant amount into a multiply.
2700 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2701 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2702 Constant *X = ConstantInt::get(
2703 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002704 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman3996f472008-06-22 19:56:46 +00002705 }
2706 break;
2707
Nick Lewycky7fd27892008-07-07 06:15:49 +00002708 case Instruction::LShr:
Nick Lewycky35b56022009-01-13 09:18:58 +00002709 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky7fd27892008-07-07 06:15:49 +00002710 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2711 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2712 Constant *X = ConstantInt::get(
2713 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002714 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky7fd27892008-07-07 06:15:49 +00002715 }
2716 break;
2717
Dan Gohman53bf64a2009-04-21 02:26:00 +00002718 case Instruction::AShr:
2719 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
2720 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
2721 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
2722 if (L->getOpcode() == Instruction::Shl &&
2723 L->getOperand(1) == U->getOperand(1)) {
Dan Gohman91ae1e72009-04-25 17:05:40 +00002724 unsigned BitWidth = getTypeSizeInBits(U->getType());
2725 uint64_t Amt = BitWidth - CI->getZExtValue();
2726 if (Amt == BitWidth)
2727 return getSCEV(L->getOperand(0)); // shift by zero --> noop
2728 if (Amt > BitWidth)
2729 return getIntegerSCEV(0, U->getType()); // value is undefined
Dan Gohman53bf64a2009-04-21 02:26:00 +00002730 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002731 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohman91ae1e72009-04-25 17:05:40 +00002732 IntegerType::get(Amt)),
Dan Gohman53bf64a2009-04-21 02:26:00 +00002733 U->getType());
2734 }
2735 break;
2736
Dan Gohman3996f472008-06-22 19:56:46 +00002737 case Instruction::Trunc:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002738 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002739
2740 case Instruction::ZExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002741 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002742
2743 case Instruction::SExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002744 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002745
2746 case Instruction::BitCast:
2747 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002748 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman3996f472008-06-22 19:56:46 +00002749 return getSCEV(U->getOperand(0));
2750 break;
2751
Dan Gohman01c2ee72009-04-16 03:18:22 +00002752 case Instruction::IntToPtr:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002753 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00002754 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002755 TD->getIntPtrType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00002756
2757 case Instruction::PtrToInt:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002758 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00002759 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
2760 U->getType());
2761
Dan Gohman509cf4d2009-05-08 20:26:55 +00002762 case Instruction::GetElementPtr:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002763 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohmanca5a39e2009-05-08 20:58:38 +00002764 return createNodeForGEP(U);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002765
Dan Gohman3996f472008-06-22 19:56:46 +00002766 case Instruction::PHI:
2767 return createNodeForPHI(cast<PHINode>(U));
2768
2769 case Instruction::Select:
2770 // This could be a smax or umax that was lowered earlier.
2771 // Try to recover it.
2772 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2773 Value *LHS = ICI->getOperand(0);
2774 Value *RHS = ICI->getOperand(1);
2775 switch (ICI->getPredicate()) {
2776 case ICmpInst::ICMP_SLT:
2777 case ICmpInst::ICMP_SLE:
2778 std::swap(LHS, RHS);
2779 // fall through
2780 case ICmpInst::ICMP_SGT:
2781 case ICmpInst::ICMP_SGE:
2782 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002783 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002784 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmand01fff82009-06-22 03:18:45 +00002785 return getSMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002786 break;
2787 case ICmpInst::ICMP_ULT:
2788 case ICmpInst::ICMP_ULE:
2789 std::swap(LHS, RHS);
2790 // fall through
2791 case ICmpInst::ICMP_UGT:
2792 case ICmpInst::ICMP_UGE:
2793 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002794 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002795 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmand01fff82009-06-22 03:18:45 +00002796 return getUMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002797 break;
Dan Gohmanf27dc692009-06-18 20:21:07 +00002798 case ICmpInst::ICMP_NE:
2799 // n != 0 ? n : 1 -> umax(n, 1)
2800 if (LHS == U->getOperand(1) &&
2801 isa<ConstantInt>(U->getOperand(2)) &&
2802 cast<ConstantInt>(U->getOperand(2))->isOne() &&
2803 isa<ConstantInt>(RHS) &&
2804 cast<ConstantInt>(RHS)->isZero())
2805 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(2)));
2806 break;
2807 case ICmpInst::ICMP_EQ:
2808 // n == 0 ? 1 : n -> umax(n, 1)
2809 if (LHS == U->getOperand(2) &&
2810 isa<ConstantInt>(U->getOperand(1)) &&
2811 cast<ConstantInt>(U->getOperand(1))->isOne() &&
2812 isa<ConstantInt>(RHS) &&
2813 cast<ConstantInt>(RHS)->isZero())
2814 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(1)));
2815 break;
Dan Gohman3996f472008-06-22 19:56:46 +00002816 default:
2817 break;
2818 }
2819 }
2820
2821 default: // We cannot analyze this expression.
2822 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002823 }
2824
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002825 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002826}
2827
2828
2829
2830//===----------------------------------------------------------------------===//
2831// Iteration Count Computation Code
2832//
2833
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002834/// getBackedgeTakenCount - If the specified loop has a predictable
2835/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
2836/// object. The backedge-taken count is the number of times the loop header
2837/// will be branched to from within the loop. This is one less than the
2838/// trip count of the loop, since it doesn't count the first iteration,
2839/// when the header is branched to from outside the loop.
2840///
2841/// Note that it is not valid to call this method on a loop without a
2842/// loop-invariant backedge-taken count (see
2843/// hasLoopInvariantBackedgeTakenCount).
2844///
Dan Gohman161ea032009-07-07 17:06:11 +00002845const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002846 return getBackedgeTakenInfo(L).Exact;
2847}
2848
2849/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
2850/// return the least SCEV value that is known never to be less than the
2851/// actual backedge taken count.
Dan Gohman161ea032009-07-07 17:06:11 +00002852const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002853 return getBackedgeTakenInfo(L).Max;
2854}
2855
Dan Gohmanb7d04aa2009-07-08 19:23:34 +00002856/// PushLoopPHIs - Push PHI nodes in the header of the given loop
2857/// onto the given Worklist.
2858static void
2859PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
2860 BasicBlock *Header = L->getHeader();
2861
2862 // Push all Loop-header PHIs onto the Worklist stack.
2863 for (BasicBlock::iterator I = Header->begin();
2864 PHINode *PN = dyn_cast<PHINode>(I); ++I)
2865 Worklist.push_back(PN);
2866}
2867
2868/// PushDefUseChildren - Push users of the given Instruction
2869/// onto the given Worklist.
2870static void
2871PushDefUseChildren(Instruction *I,
2872 SmallVectorImpl<Instruction *> &Worklist) {
2873 // Push the def-use children onto the Worklist stack.
2874 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2875 UI != UE; ++UI)
2876 Worklist.push_back(cast<Instruction>(UI));
2877}
2878
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002879const ScalarEvolution::BackedgeTakenInfo &
2880ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohmana9dba962009-04-27 20:16:15 +00002881 // Initially insert a CouldNotCompute for this loop. If the insertion
2882 // succeeds, procede to actually compute a backedge-taken count and
2883 // update the value. The temporary CouldNotCompute value tells SCEV
2884 // code elsewhere that it shouldn't attempt to request a new
2885 // backedge-taken count, which could result in infinite recursion.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002886 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohmana9dba962009-04-27 20:16:15 +00002887 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
2888 if (Pair.second) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002889 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00002890 if (ItCount.Exact != getCouldNotCompute()) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002891 assert(ItCount.Exact->isLoopInvariant(L) &&
2892 ItCount.Max->isLoopInvariant(L) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002893 "Computed trip count isn't loop invariant for loop!");
2894 ++NumTripCountsComputed;
Dan Gohmana9dba962009-04-27 20:16:15 +00002895
Dan Gohmana9dba962009-04-27 20:16:15 +00002896 // Update the value in the map.
2897 Pair.first->second = ItCount;
Dan Gohman8e8b5232009-06-22 00:31:57 +00002898 } else {
Dan Gohmanc6475cb2009-06-27 21:21:31 +00002899 if (ItCount.Max != getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00002900 // Update the value in the map.
2901 Pair.first->second = ItCount;
2902 if (isa<PHINode>(L->getHeader()->begin()))
2903 // Only count loops that have phi nodes as not being computable.
2904 ++NumTripCountsNotComputed;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002905 }
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002906
2907 // Now that we know more about the trip count for this loop, forget any
2908 // existing SCEV values for PHI nodes in this loop since they are only
Dan Gohmanb7d04aa2009-07-08 19:23:34 +00002909 // conservative estimates made without the benefit of trip count
2910 // information. This is similar to the code in
2911 // forgetLoopBackedgeTakenCount, except that it handles SCEVUnknown PHI
2912 // nodes specially.
2913 if (ItCount.hasAnyInfo()) {
2914 SmallVector<Instruction *, 16> Worklist;
2915 PushLoopPHIs(L, Worklist);
2916
2917 SmallPtrSet<Instruction *, 8> Visited;
2918 while (!Worklist.empty()) {
2919 Instruction *I = Worklist.pop_back_val();
2920 if (!Visited.insert(I)) continue;
2921
2922 std::map<SCEVCallbackVH, const SCEV*>::iterator It =
2923 Scalars.find(static_cast<Value *>(I));
2924 if (It != Scalars.end()) {
2925 // SCEVUnknown for a PHI either means that it has an unrecognized
2926 // structure, or it's a PHI that's in the progress of being computed
2927 // by createNodeForPHI. In the former case, additional loop trip count
2928 // information isn't going to change anything. In the later case,
2929 // createNodeForPHI will perform the necessary updates on its own when
2930 // it gets to that point.
2931 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(It->second))
2932 Scalars.erase(It);
2933 ValuesAtScopes.erase(I);
2934 if (PHINode *PN = dyn_cast<PHINode>(I))
2935 ConstantEvolutionLoopExitValue.erase(PN);
2936 }
2937
2938 PushDefUseChildren(I, Worklist);
2939 }
2940 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002941 }
Dan Gohmana9dba962009-04-27 20:16:15 +00002942 return Pair.first->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002943}
2944
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002945/// forgetLoopBackedgeTakenCount - This method should be called by the
Dan Gohmanf3a060a2009-02-17 20:49:49 +00002946/// client when it has changed a loop in a way that may effect
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002947/// ScalarEvolution's ability to compute a trip count, or if the loop
2948/// is deleted.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002949void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002950 BackedgeTakenCounts.erase(L);
Dan Gohman94623022009-05-02 17:43:35 +00002951
Dan Gohmanbff6b582009-05-04 22:30:44 +00002952 SmallVector<Instruction *, 16> Worklist;
Dan Gohmanb7d04aa2009-07-08 19:23:34 +00002953 PushLoopPHIs(L, Worklist);
Dan Gohmanbff6b582009-05-04 22:30:44 +00002954
Dan Gohmanb7d04aa2009-07-08 19:23:34 +00002955 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohmanbff6b582009-05-04 22:30:44 +00002956 while (!Worklist.empty()) {
2957 Instruction *I = Worklist.pop_back_val();
Dan Gohmanb7d04aa2009-07-08 19:23:34 +00002958 if (!Visited.insert(I)) continue;
2959
2960 std::map<SCEVCallbackVH, const SCEV*>::iterator It =
2961 Scalars.find(static_cast<Value *>(I));
2962 if (It != Scalars.end()) {
2963 Scalars.erase(It);
2964 ValuesAtScopes.erase(I);
2965 if (PHINode *PN = dyn_cast<PHINode>(I))
2966 ConstantEvolutionLoopExitValue.erase(PN);
2967 }
2968
2969 PushDefUseChildren(I, Worklist);
Dan Gohmanbff6b582009-05-04 22:30:44 +00002970 }
Dan Gohmanf3a060a2009-02-17 20:49:49 +00002971}
2972
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002973/// ComputeBackedgeTakenCount - Compute the number of times the backedge
2974/// of the specified loop will execute.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002975ScalarEvolution::BackedgeTakenInfo
2976ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohman8e8b5232009-06-22 00:31:57 +00002977 SmallVector<BasicBlock*, 8> ExitingBlocks;
2978 L->getExitingBlocks(ExitingBlocks);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002979
Dan Gohman8e8b5232009-06-22 00:31:57 +00002980 // Examine all exits and pick the most conservative values.
Dan Gohman161ea032009-07-07 17:06:11 +00002981 const SCEV *BECount = getCouldNotCompute();
2982 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohman8e8b5232009-06-22 00:31:57 +00002983 bool CouldNotComputeBECount = false;
Dan Gohman8e8b5232009-06-22 00:31:57 +00002984 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
2985 BackedgeTakenInfo NewBTI =
2986 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002987
Dan Gohmanc6475cb2009-06-27 21:21:31 +00002988 if (NewBTI.Exact == getCouldNotCompute()) {
Dan Gohman8e8b5232009-06-22 00:31:57 +00002989 // We couldn't compute an exact value for this exit, so
Dan Gohmanc6e8c832009-06-22 21:10:22 +00002990 // we won't be able to compute an exact value for the loop.
Dan Gohman8e8b5232009-06-22 00:31:57 +00002991 CouldNotComputeBECount = true;
Dan Gohmanc6475cb2009-06-27 21:21:31 +00002992 BECount = getCouldNotCompute();
Dan Gohman8e8b5232009-06-22 00:31:57 +00002993 } else if (!CouldNotComputeBECount) {
Dan Gohmanc6475cb2009-06-27 21:21:31 +00002994 if (BECount == getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00002995 BECount = NewBTI.Exact;
Dan Gohman8e8b5232009-06-22 00:31:57 +00002996 else
Dan Gohman423ed6c2009-06-24 01:18:18 +00002997 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
Dan Gohman8e8b5232009-06-22 00:31:57 +00002998 }
Dan Gohmanc6475cb2009-06-27 21:21:31 +00002999 if (MaxBECount == getCouldNotCompute())
Dan Gohman423ed6c2009-06-24 01:18:18 +00003000 MaxBECount = NewBTI.Max;
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003001 else if (NewBTI.Max != getCouldNotCompute())
Dan Gohman423ed6c2009-06-24 01:18:18 +00003002 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
Dan Gohman8e8b5232009-06-22 00:31:57 +00003003 }
3004
3005 return BackedgeTakenInfo(BECount, MaxBECount);
3006}
3007
3008/// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
3009/// of the specified loop will execute if it exits via the specified block.
3010ScalarEvolution::BackedgeTakenInfo
3011ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
3012 BasicBlock *ExitingBlock) {
3013
3014 // Okay, we've chosen an exiting block. See what condition causes us to
3015 // exit at this block.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003016 //
3017 // FIXME: we should be able to handle switch instructions (with a single exit)
3018 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003019 if (ExitBr == 0) return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003020 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Dan Gohman9bc642f2009-06-24 04:48:43 +00003021
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003022 // At this point, we know we have a conditional branch that determines whether
3023 // the loop is exited. However, we don't know if the branch is executed each
3024 // time through the loop. If not, then the execution count of the branch will
3025 // not be equal to the trip count of the loop.
3026 //
3027 // Currently we check for this by checking to see if the Exit branch goes to
3028 // the loop header. If so, we know it will always execute the same number of
3029 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohman8e8b5232009-06-22 00:31:57 +00003030 // loop header. This is common for un-rotated loops.
3031 //
3032 // If both of those tests fail, walk up the unique predecessor chain to the
3033 // header, stopping if there is an edge that doesn't exit the loop. If the
3034 // header is reached, the execution count of the branch will be equal to the
3035 // trip count of the loop.
3036 //
3037 // More extensive analysis could be done to handle more cases here.
3038 //
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003039 if (ExitBr->getSuccessor(0) != L->getHeader() &&
3040 ExitBr->getSuccessor(1) != L->getHeader() &&
Dan Gohman8e8b5232009-06-22 00:31:57 +00003041 ExitBr->getParent() != L->getHeader()) {
3042 // The simple checks failed, try climbing the unique predecessor chain
3043 // up to the header.
3044 bool Ok = false;
3045 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
3046 BasicBlock *Pred = BB->getUniquePredecessor();
3047 if (!Pred)
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003048 return getCouldNotCompute();
Dan Gohman8e8b5232009-06-22 00:31:57 +00003049 TerminatorInst *PredTerm = Pred->getTerminator();
3050 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
3051 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
3052 if (PredSucc == BB)
3053 continue;
3054 // If the predecessor has a successor that isn't BB and isn't
3055 // outside the loop, assume the worst.
3056 if (L->contains(PredSucc))
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003057 return getCouldNotCompute();
Dan Gohman8e8b5232009-06-22 00:31:57 +00003058 }
3059 if (Pred == L->getHeader()) {
3060 Ok = true;
3061 break;
3062 }
3063 BB = Pred;
3064 }
3065 if (!Ok)
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003066 return getCouldNotCompute();
Dan Gohman8e8b5232009-06-22 00:31:57 +00003067 }
3068
3069 // Procede to the next level to examine the exit condition expression.
3070 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
3071 ExitBr->getSuccessor(0),
3072 ExitBr->getSuccessor(1));
3073}
3074
3075/// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
3076/// backedge of the specified loop will execute if its exit condition
3077/// were a conditional branch of ExitCond, TBB, and FBB.
3078ScalarEvolution::BackedgeTakenInfo
3079ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
3080 Value *ExitCond,
3081 BasicBlock *TBB,
3082 BasicBlock *FBB) {
Dan Gohman423ed6c2009-06-24 01:18:18 +00003083 // Check if the controlling expression for this loop is an And or Or.
Dan Gohman8e8b5232009-06-22 00:31:57 +00003084 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
3085 if (BO->getOpcode() == Instruction::And) {
3086 // Recurse on the operands of the and.
3087 BackedgeTakenInfo BTI0 =
3088 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3089 BackedgeTakenInfo BTI1 =
3090 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman161ea032009-07-07 17:06:11 +00003091 const SCEV *BECount = getCouldNotCompute();
3092 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohman8e8b5232009-06-22 00:31:57 +00003093 if (L->contains(TBB)) {
3094 // Both conditions must be true for the loop to continue executing.
3095 // Choose the less conservative count.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003096 if (BTI0.Exact == getCouldNotCompute() ||
3097 BTI1.Exact == getCouldNotCompute())
3098 BECount = getCouldNotCompute();
Dan Gohmanac958b32009-06-22 15:09:28 +00003099 else
3100 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003101 if (BTI0.Max == getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003102 MaxBECount = BTI1.Max;
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003103 else if (BTI1.Max == getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003104 MaxBECount = BTI0.Max;
Dan Gohmanac958b32009-06-22 15:09:28 +00003105 else
3106 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohman8e8b5232009-06-22 00:31:57 +00003107 } else {
3108 // Both conditions must be true for the loop to exit.
3109 assert(L->contains(FBB) && "Loop block has no successor in loop!");
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003110 if (BTI0.Exact != getCouldNotCompute() &&
3111 BTI1.Exact != getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003112 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003113 if (BTI0.Max != getCouldNotCompute() &&
3114 BTI1.Max != getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003115 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3116 }
3117
3118 return BackedgeTakenInfo(BECount, MaxBECount);
3119 }
3120 if (BO->getOpcode() == Instruction::Or) {
3121 // Recurse on the operands of the or.
3122 BackedgeTakenInfo BTI0 =
3123 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3124 BackedgeTakenInfo BTI1 =
3125 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman161ea032009-07-07 17:06:11 +00003126 const SCEV *BECount = getCouldNotCompute();
3127 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohman8e8b5232009-06-22 00:31:57 +00003128 if (L->contains(FBB)) {
3129 // Both conditions must be false for the loop to continue executing.
3130 // Choose the less conservative count.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003131 if (BTI0.Exact == getCouldNotCompute() ||
3132 BTI1.Exact == getCouldNotCompute())
3133 BECount = getCouldNotCompute();
Dan Gohmanac958b32009-06-22 15:09:28 +00003134 else
3135 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003136 if (BTI0.Max == getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003137 MaxBECount = BTI1.Max;
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003138 else if (BTI1.Max == getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003139 MaxBECount = BTI0.Max;
Dan Gohmanac958b32009-06-22 15:09:28 +00003140 else
3141 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohman8e8b5232009-06-22 00:31:57 +00003142 } else {
3143 // Both conditions must be false for the loop to exit.
3144 assert(L->contains(TBB) && "Loop block has no successor in loop!");
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003145 if (BTI0.Exact != getCouldNotCompute() &&
3146 BTI1.Exact != getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003147 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003148 if (BTI0.Max != getCouldNotCompute() &&
3149 BTI1.Max != getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003150 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3151 }
3152
3153 return BackedgeTakenInfo(BECount, MaxBECount);
3154 }
3155 }
3156
3157 // With an icmp, it may be feasible to compute an exact backedge-taken count.
3158 // Procede to the next level to examine the icmp.
3159 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
3160 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003161
Eli Friedman459d7292009-05-09 12:32:42 +00003162 // If it's not an integer or pointer comparison then compute it the hard way.
Dan Gohman8e8b5232009-06-22 00:31:57 +00003163 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3164}
3165
3166/// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
3167/// backedge of the specified loop will execute if its exit condition
3168/// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
3169ScalarEvolution::BackedgeTakenInfo
3170ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
3171 ICmpInst *ExitCond,
3172 BasicBlock *TBB,
3173 BasicBlock *FBB) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003174
3175 // If the condition was exit on true, convert the condition to exit on false
3176 ICmpInst::Predicate Cond;
Dan Gohman8e8b5232009-06-22 00:31:57 +00003177 if (!L->contains(FBB))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003178 Cond = ExitCond->getPredicate();
3179 else
3180 Cond = ExitCond->getInversePredicate();
3181
3182 // Handle common loops like: for (X = "string"; *X; ++X)
3183 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
3184 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Dan Gohman161ea032009-07-07 17:06:11 +00003185 const SCEV *ItCnt =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003186 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohman8e8b5232009-06-22 00:31:57 +00003187 if (!isa<SCEVCouldNotCompute>(ItCnt)) {
3188 unsigned BitWidth = getTypeSizeInBits(ItCnt->getType());
3189 return BackedgeTakenInfo(ItCnt,
3190 isa<SCEVConstant>(ItCnt) ? ItCnt :
3191 getConstant(APInt::getMaxValue(BitWidth)-1));
3192 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003193 }
3194
Dan Gohman161ea032009-07-07 17:06:11 +00003195 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
3196 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003197
3198 // Try to evaluate any dependencies out of the loop.
Dan Gohmanaff14d62009-05-24 23:25:42 +00003199 LHS = getSCEVAtScope(LHS, L);
3200 RHS = getSCEVAtScope(RHS, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003201
Dan Gohman9bc642f2009-06-24 04:48:43 +00003202 // At this point, we would like to compute how many iterations of the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003203 // loop the predicate will return true for these inputs.
Dan Gohman2d96e352008-09-16 18:52:57 +00003204 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
3205 // If there is a loop-invariant, force it into the RHS.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003206 std::swap(LHS, RHS);
3207 Cond = ICmpInst::getSwappedPredicate(Cond);
3208 }
3209
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003210 // If we have a comparison of a chrec against a constant, try to use value
3211 // ranges to answer this query.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003212 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
3213 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003214 if (AddRec->getLoop() == L) {
Eli Friedman459d7292009-05-09 12:32:42 +00003215 // Form the constant range.
3216 ConstantRange CompRange(
3217 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003218
Dan Gohman161ea032009-07-07 17:06:11 +00003219 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedman459d7292009-05-09 12:32:42 +00003220 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003221 }
3222
3223 switch (Cond) {
3224 case ICmpInst::ICMP_NE: { // while (X != Y)
3225 // Convert to: while (X-Y != 0)
Dan Gohman161ea032009-07-07 17:06:11 +00003226 const SCEV *TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003227 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
3228 break;
3229 }
3230 case ICmpInst::ICMP_EQ: {
3231 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohman161ea032009-07-07 17:06:11 +00003232 const SCEV *TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003233 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
3234 break;
3235 }
3236 case ICmpInst::ICMP_SLT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003237 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
3238 if (BTI.hasAnyInfo()) return BTI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003239 break;
3240 }
3241 case ICmpInst::ICMP_SGT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003242 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3243 getNotSCEV(RHS), L, true);
3244 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyb7c28942007-08-06 19:21:00 +00003245 break;
3246 }
3247 case ICmpInst::ICMP_ULT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003248 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
3249 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyb7c28942007-08-06 19:21:00 +00003250 break;
3251 }
3252 case ICmpInst::ICMP_UGT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003253 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3254 getNotSCEV(RHS), L, false);
3255 if (BTI.hasAnyInfo()) return BTI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003256 break;
3257 }
3258 default:
3259#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00003260 errs() << "ComputeBackedgeTakenCount ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003261 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Dan Gohman13058cc2009-04-21 00:47:46 +00003262 errs() << "[unsigned] ";
3263 errs() << *LHS << " "
Dan Gohman9bc642f2009-06-24 04:48:43 +00003264 << Instruction::getOpcodeName(Instruction::ICmp)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003265 << " " << *RHS << "\n";
3266#endif
3267 break;
3268 }
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003269 return
Dan Gohman8e8b5232009-06-22 00:31:57 +00003270 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003271}
3272
3273static ConstantInt *
Dan Gohman89f85052007-10-22 18:31:58 +00003274EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
3275 ScalarEvolution &SE) {
Dan Gohman161ea032009-07-07 17:06:11 +00003276 const SCEV *InVal = SE.getConstant(C);
3277 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003278 assert(isa<SCEVConstant>(Val) &&
3279 "Evaluation of SCEV at constant didn't fold correctly?");
3280 return cast<SCEVConstant>(Val)->getValue();
3281}
3282
3283/// GetAddressedElementFromGlobal - Given a global variable with an initializer
3284/// and a GEP expression (missing the pointer index) indexing into it, return
3285/// the addressed element of the initializer or null if the index expression is
3286/// invalid.
3287static Constant *
Owen Anderson15b39322009-07-13 04:09:18 +00003288GetAddressedElementFromGlobal(LLVMContext *Context, GlobalVariable *GV,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003289 const std::vector<ConstantInt*> &Indices) {
3290 Constant *Init = GV->getInitializer();
3291 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
3292 uint64_t Idx = Indices[i]->getZExtValue();
3293 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
3294 assert(Idx < CS->getNumOperands() && "Bad struct index!");
3295 Init = cast<Constant>(CS->getOperand(Idx));
3296 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
3297 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
3298 Init = cast<Constant>(CA->getOperand(Idx));
3299 } else if (isa<ConstantAggregateZero>(Init)) {
3300 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
3301 assert(Idx < STy->getNumElements() && "Bad struct index!");
Owen Anderson15b39322009-07-13 04:09:18 +00003302 Init = Context->getNullValue(STy->getElementType(Idx));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003303 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
3304 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
Owen Anderson15b39322009-07-13 04:09:18 +00003305 Init = Context->getNullValue(ATy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003306 } else {
Edwin Török675d5622009-07-11 20:10:48 +00003307 LLVM_UNREACHABLE("Unknown constant aggregate type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003308 }
3309 return 0;
3310 } else {
3311 return 0; // Unknown initializer type
3312 }
3313 }
3314 return Init;
3315}
3316
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003317/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
3318/// 'icmp op load X, cst', try to see if we can compute the backedge
3319/// execution count.
Dan Gohman9bc642f2009-06-24 04:48:43 +00003320const SCEV *
3321ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
3322 LoadInst *LI,
3323 Constant *RHS,
3324 const Loop *L,
3325 ICmpInst::Predicate predicate) {
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003326 if (LI->isVolatile()) return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003327
3328 // Check to see if the loaded pointer is a getelementptr of a global.
3329 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003330 if (!GEP) return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003331
3332 // Make sure that it is really a constant global we are gepping, with an
3333 // initializer, and make sure the first IDX is really 0.
3334 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
3335 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
3336 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
3337 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003338 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003339
3340 // Okay, we allow one non-constant index into the GEP instruction.
3341 Value *VarIdx = 0;
3342 std::vector<ConstantInt*> Indexes;
3343 unsigned VarIdxNum = 0;
3344 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
3345 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
3346 Indexes.push_back(CI);
3347 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003348 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003349 VarIdx = GEP->getOperand(i);
3350 VarIdxNum = i-2;
3351 Indexes.push_back(0);
3352 }
3353
3354 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
3355 // Check to see if X is a loop variant variable value now.
Dan Gohman161ea032009-07-07 17:06:11 +00003356 const SCEV *Idx = getSCEV(VarIdx);
Dan Gohmanaff14d62009-05-24 23:25:42 +00003357 Idx = getSCEVAtScope(Idx, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003358
3359 // We can only recognize very limited forms of loop index expressions, in
3360 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohmanbff6b582009-05-04 22:30:44 +00003361 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003362 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
3363 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
3364 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003365 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003366
3367 unsigned MaxSteps = MaxBruteForceIterations;
3368 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
3369 ConstantInt *ItCst =
Dan Gohman8fd520a2009-06-15 22:12:54 +00003370 ConstantInt::get(cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003371 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003372
3373 // Form the GEP offset.
3374 Indexes[VarIdxNum] = Val;
3375
Owen Anderson15b39322009-07-13 04:09:18 +00003376 Constant *Result = GetAddressedElementFromGlobal(Context, GV, Indexes);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003377 if (Result == 0) break; // Cannot compute!
3378
3379 // Evaluate the condition for this iteration.
3380 Result = ConstantExpr::getICmp(predicate, Result, RHS);
3381 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
3382 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
3383#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00003384 errs() << "\n***\n*** Computed loop count " << *ItCst
3385 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
3386 << "***\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003387#endif
3388 ++NumArrayLenItCounts;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003389 return getConstant(ItCst); // Found terminating iteration!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003390 }
3391 }
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003392 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003393}
3394
3395
3396/// CanConstantFold - Return true if we can constant fold an instruction of the
3397/// specified type, assuming that all operands were constants.
3398static bool CanConstantFold(const Instruction *I) {
3399 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
3400 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
3401 return true;
3402
3403 if (const CallInst *CI = dyn_cast<CallInst>(I))
3404 if (const Function *F = CI->getCalledFunction())
Dan Gohmane6e001f2008-01-31 01:05:10 +00003405 return canConstantFoldCallTo(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003406 return false;
3407}
3408
3409/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
3410/// in the loop that V is derived from. We allow arbitrary operations along the
3411/// way, but the operands of an operation must either be constants or a value
3412/// derived from a constant PHI. If this expression does not fit with these
3413/// constraints, return null.
3414static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
3415 // If this is not an instruction, or if this is an instruction outside of the
3416 // loop, it can't be derived from a loop PHI.
3417 Instruction *I = dyn_cast<Instruction>(V);
3418 if (I == 0 || !L->contains(I->getParent())) return 0;
3419
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00003420 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003421 if (L->getHeader() == I->getParent())
3422 return PN;
3423 else
3424 // We don't currently keep track of the control flow needed to evaluate
3425 // PHIs, so we cannot handle PHIs inside of loops.
3426 return 0;
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00003427 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003428
3429 // If we won't be able to constant fold this expression even if the operands
3430 // are constants, return early.
3431 if (!CanConstantFold(I)) return 0;
3432
3433 // Otherwise, we can evaluate this instruction if all of its operands are
3434 // constant or derived from a PHI node themselves.
3435 PHINode *PHI = 0;
3436 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
3437 if (!(isa<Constant>(I->getOperand(Op)) ||
3438 isa<GlobalValue>(I->getOperand(Op)))) {
3439 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
3440 if (P == 0) return 0; // Not evolving from PHI
3441 if (PHI == 0)
3442 PHI = P;
3443 else if (PHI != P)
3444 return 0; // Evolving from multiple different PHIs.
3445 }
3446
3447 // This is a expression evolving from a constant PHI!
3448 return PHI;
3449}
3450
3451/// EvaluateExpression - Given an expression that passes the
3452/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
3453/// in the loop has the value PHIVal. If we can't fold this expression for some
3454/// reason, return null.
3455static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
3456 if (isa<PHINode>(V)) return PHIVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003457 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman01c2ee72009-04-16 03:18:22 +00003458 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003459 Instruction *I = cast<Instruction>(V);
Owen Anderson5349f052009-07-06 23:00:19 +00003460 LLVMContext *Context = I->getParent()->getContext();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003461
3462 std::vector<Constant*> Operands;
3463 Operands.resize(I->getNumOperands());
3464
3465 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3466 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
3467 if (Operands[i] == 0) return 0;
3468 }
3469
Chris Lattnerd6e56912007-12-10 22:53:04 +00003470 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3471 return ConstantFoldCompareInstOperands(CI->getPredicate(),
Owen Andersond4d90a02009-07-06 18:42:36 +00003472 &Operands[0], Operands.size(),
3473 Context);
Chris Lattnerd6e56912007-12-10 22:53:04 +00003474 else
3475 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Owen Andersond4d90a02009-07-06 18:42:36 +00003476 &Operands[0], Operands.size(),
3477 Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003478}
3479
3480/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
3481/// in the header of its containing loop, we know the loop executes a
3482/// constant number of times, and the PHI node is just a recurrence
3483/// involving constants, fold it.
Dan Gohman9bc642f2009-06-24 04:48:43 +00003484Constant *
3485ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
3486 const APInt& BEs,
3487 const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003488 std::map<PHINode*, Constant*>::iterator I =
3489 ConstantEvolutionLoopExitValue.find(PN);
3490 if (I != ConstantEvolutionLoopExitValue.end())
3491 return I->second;
3492
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003493 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003494 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
3495
3496 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
3497
3498 // Since the loop is canonicalized, the PHI node must have two entries. One
3499 // entry must be a constant (coming in from outside of the loop), and the
3500 // second must be derived from the same PHI.
3501 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3502 Constant *StartCST =
3503 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
3504 if (StartCST == 0)
3505 return RetVal = 0; // Must be a constant.
3506
3507 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3508 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
3509 if (PN2 != PN)
3510 return RetVal = 0; // Not derived from same PHI.
3511
3512 // Execute the loop symbolically to determine the exit value.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003513 if (BEs.getActiveBits() >= 32)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003514 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
3515
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003516 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003517 unsigned IterationNum = 0;
3518 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
3519 if (IterationNum == NumIterations)
3520 return RetVal = PHIVal; // Got exit value!
3521
3522 // Compute the value of the PHI node for the next iteration.
3523 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3524 if (NextPHI == PHIVal)
3525 return RetVal = NextPHI; // Stopped evolving!
3526 if (NextPHI == 0)
3527 return 0; // Couldn't evaluate!
3528 PHIVal = NextPHI;
3529 }
3530}
3531
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003532/// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003533/// constant number of times (the condition evolves only from constants),
3534/// try to evaluate a few iterations of the loop until we get the exit
3535/// condition gets a value of ExitWhen (true or false). If we cannot
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003536/// evaluate the trip count of the loop, return getCouldNotCompute().
Dan Gohman9bc642f2009-06-24 04:48:43 +00003537const SCEV *
3538ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
3539 Value *Cond,
3540 bool ExitWhen) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003541 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003542 if (PN == 0) return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003543
3544 // Since the loop is canonicalized, the PHI node must have two entries. One
3545 // entry must be a constant (coming in from outside of the loop), and the
3546 // second must be derived from the same PHI.
3547 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3548 Constant *StartCST =
3549 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003550 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003551
3552 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3553 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003554 if (PN2 != PN) return getCouldNotCompute(); // Not derived from same PHI.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003555
3556 // Okay, we find a PHI node that defines the trip count of this loop. Execute
3557 // the loop symbolically to determine when the condition gets a value of
3558 // "ExitWhen".
3559 unsigned IterationNum = 0;
3560 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
3561 for (Constant *PHIVal = StartCST;
3562 IterationNum != MaxIterations; ++IterationNum) {
3563 ConstantInt *CondVal =
3564 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
3565
3566 // Couldn't symbolically evaluate.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003567 if (!CondVal) return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003568
3569 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003570 ++NumBruteForceTripCountsComputed;
Dan Gohman8fd520a2009-06-15 22:12:54 +00003571 return getConstant(Type::Int32Ty, IterationNum);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003572 }
3573
3574 // Compute the value of the PHI node for the next iteration.
3575 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3576 if (NextPHI == 0 || NextPHI == PHIVal)
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003577 return getCouldNotCompute();// Couldn't evaluate or not making progress...
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003578 PHIVal = NextPHI;
3579 }
3580
3581 // Too many iterations were needed to evaluate.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003582 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003583}
3584
Dan Gohmandd40e9a2009-05-08 20:38:54 +00003585/// getSCEVAtScope - Return a SCEV expression handle for the specified value
3586/// at the specified scope in the program. The L value specifies a loop
3587/// nest to evaluate the expression at, where null is the top-level or a
3588/// specified loop is immediately inside of the loop.
3589///
3590/// This method can be used to compute the exit value for a variable defined
3591/// in a loop by querying what the value will hold in the parent loop.
3592///
Dan Gohmanaff14d62009-05-24 23:25:42 +00003593/// In the case that a relevant loop exit value cannot be computed, the
3594/// original value V is returned.
Dan Gohman161ea032009-07-07 17:06:11 +00003595const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003596 // FIXME: this should be turned into a virtual method on SCEV!
3597
3598 if (isa<SCEVConstant>(V)) return V;
3599
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00003600 // If this instruction is evolved from a constant-evolving PHI, compute the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003601 // exit value from the loop without using SCEVs.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003602 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003603 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003604 const Loop *LI = (*this->LI)[I->getParent()];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003605 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
3606 if (PHINode *PN = dyn_cast<PHINode>(I))
3607 if (PN->getParent() == LI->getHeader()) {
3608 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003609 // to see if the loop that contains it has a known backedge-taken
3610 // count. If so, we may be able to force computation of the exit
3611 // value.
Dan Gohman161ea032009-07-07 17:06:11 +00003612 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohmanc76b5452009-05-04 22:02:23 +00003613 if (const SCEVConstant *BTCC =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003614 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003615 // Okay, we know how many times the containing loop executes. If
3616 // this is a constant evolving PHI node, get the final value at
3617 // the specified iteration number.
3618 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003619 BTCC->getValue()->getValue(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003620 LI);
Dan Gohman652caf12009-06-29 21:31:18 +00003621 if (RV) return getSCEV(RV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003622 }
3623 }
3624
3625 // Okay, this is an expression that we cannot symbolically evaluate
3626 // into a SCEV. Check to see if it's possible to symbolically evaluate
3627 // the arguments into constants, and if so, try to constant propagate the
3628 // result. This is particularly useful for computing loop exit values.
3629 if (CanConstantFold(I)) {
Dan Gohmanda0071e2009-05-08 20:47:27 +00003630 // Check to see if we've folded this instruction at this loop before.
3631 std::map<const Loop *, Constant *> &Values = ValuesAtScopes[I];
3632 std::pair<std::map<const Loop *, Constant *>::iterator, bool> Pair =
3633 Values.insert(std::make_pair(L, static_cast<Constant *>(0)));
3634 if (!Pair.second)
Dan Gohman652caf12009-06-29 21:31:18 +00003635 return Pair.first->second ? &*getSCEV(Pair.first->second) : V;
Dan Gohmanda0071e2009-05-08 20:47:27 +00003636
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003637 std::vector<Constant*> Operands;
3638 Operands.reserve(I->getNumOperands());
3639 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3640 Value *Op = I->getOperand(i);
3641 if (Constant *C = dyn_cast<Constant>(Op)) {
3642 Operands.push_back(C);
3643 } else {
Chris Lattner3fff4642007-11-23 08:46:22 +00003644 // If any of the operands is non-constant and if they are
Dan Gohman01c2ee72009-04-16 03:18:22 +00003645 // non-integer and non-pointer, don't even try to analyze them
3646 // with scev techniques.
Dan Gohman5e4eb762009-04-30 16:40:30 +00003647 if (!isSCEVable(Op->getType()))
Chris Lattner3fff4642007-11-23 08:46:22 +00003648 return V;
Dan Gohman01c2ee72009-04-16 03:18:22 +00003649
Nick Lewycky9425be92009-07-11 20:38:25 +00003650 const SCEV *OpV = getSCEVAtScope(getSCEV(Op), L);
Dan Gohmanc76b5452009-05-04 22:02:23 +00003651 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
Dan Gohman5e4eb762009-04-30 16:40:30 +00003652 Constant *C = SC->getValue();
3653 if (C->getType() != Op->getType())
3654 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3655 Op->getType(),
3656 false),
3657 C, Op->getType());
3658 Operands.push_back(C);
Dan Gohmanc76b5452009-05-04 22:02:23 +00003659 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
Dan Gohman5e4eb762009-04-30 16:40:30 +00003660 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
3661 if (C->getType() != Op->getType())
3662 C =
3663 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3664 Op->getType(),
3665 false),
3666 C, Op->getType());
3667 Operands.push_back(C);
3668 } else
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003669 return V;
3670 } else {
3671 return V;
3672 }
3673 }
3674 }
Dan Gohman9bc642f2009-06-24 04:48:43 +00003675
Chris Lattnerd6e56912007-12-10 22:53:04 +00003676 Constant *C;
3677 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3678 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
Owen Andersond4d90a02009-07-06 18:42:36 +00003679 &Operands[0], Operands.size(),
3680 Context);
Chris Lattnerd6e56912007-12-10 22:53:04 +00003681 else
3682 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Owen Andersond4d90a02009-07-06 18:42:36 +00003683 &Operands[0], Operands.size(), Context);
Dan Gohmanda0071e2009-05-08 20:47:27 +00003684 Pair.first->second = C;
Dan Gohman652caf12009-06-29 21:31:18 +00003685 return getSCEV(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003686 }
3687 }
3688
3689 // This is some other type of SCEVUnknown, just return it.
3690 return V;
3691 }
3692
Dan Gohmanc76b5452009-05-04 22:02:23 +00003693 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003694 // Avoid performing the look-up in the common case where the specified
3695 // expression has no loop-variant portions.
3696 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Dan Gohman161ea032009-07-07 17:06:11 +00003697 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003698 if (OpAtScope != Comm->getOperand(i)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003699 // Okay, at least one of these operands is loop variant but might be
3700 // foldable. Build a new instance of the folded commutative expression.
Dan Gohman9bc642f2009-06-24 04:48:43 +00003701 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
3702 Comm->op_begin()+i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003703 NewOps.push_back(OpAtScope);
3704
3705 for (++i; i != e; ++i) {
3706 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003707 NewOps.push_back(OpAtScope);
3708 }
3709 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003710 return getAddExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00003711 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003712 return getMulExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00003713 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003714 return getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00003715 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003716 return getUMaxExpr(NewOps);
Edwin Török675d5622009-07-11 20:10:48 +00003717 LLVM_UNREACHABLE("Unknown commutative SCEV type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003718 }
3719 }
3720 // If we got here, all operands are loop invariant.
3721 return Comm;
3722 }
3723
Dan Gohmanc76b5452009-05-04 22:02:23 +00003724 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Dan Gohman161ea032009-07-07 17:06:11 +00003725 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
3726 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky35b56022009-01-13 09:18:58 +00003727 if (LHS == Div->getLHS() && RHS == Div->getRHS())
3728 return Div; // must be loop invariant
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003729 return getUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003730 }
3731
3732 // If this is a loop recurrence for a loop that does not contain L, then we
3733 // are dealing with the final value computed by the loop.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003734 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003735 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
3736 // To evaluate this recurrence, we need to know how many times the AddRec
3737 // loop iterates. Compute this now.
Dan Gohman161ea032009-07-07 17:06:11 +00003738 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003739 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003740
Eli Friedman7489ec92008-08-04 23:49:06 +00003741 // Then, evaluate the AddRec.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003742 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003743 }
Dan Gohmanaff14d62009-05-24 23:25:42 +00003744 return AddRec;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003745 }
3746
Dan Gohmanc76b5452009-05-04 22:02:23 +00003747 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohman161ea032009-07-07 17:06:11 +00003748 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman78d63c82009-04-29 22:29:01 +00003749 if (Op == Cast->getOperand())
3750 return Cast; // must be loop invariant
3751 return getZeroExtendExpr(Op, Cast->getType());
3752 }
3753
Dan Gohmanc76b5452009-05-04 22:02:23 +00003754 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohman161ea032009-07-07 17:06:11 +00003755 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman78d63c82009-04-29 22:29:01 +00003756 if (Op == Cast->getOperand())
3757 return Cast; // must be loop invariant
3758 return getSignExtendExpr(Op, Cast->getType());
3759 }
3760
Dan Gohmanc76b5452009-05-04 22:02:23 +00003761 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohman161ea032009-07-07 17:06:11 +00003762 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman78d63c82009-04-29 22:29:01 +00003763 if (Op == Cast->getOperand())
3764 return Cast; // must be loop invariant
3765 return getTruncateExpr(Op, Cast->getType());
3766 }
3767
Edwin Török675d5622009-07-11 20:10:48 +00003768 LLVM_UNREACHABLE("Unknown SCEV type!");
Daniel Dunbara95d96c2009-05-18 16:43:04 +00003769 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003770}
3771
Dan Gohmandd40e9a2009-05-08 20:38:54 +00003772/// getSCEVAtScope - This is a convenience function which does
3773/// getSCEVAtScope(getSCEV(V), L).
Dan Gohman161ea032009-07-07 17:06:11 +00003774const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003775 return getSCEVAtScope(getSCEV(V), L);
3776}
3777
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003778/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
3779/// following equation:
3780///
3781/// A * X = B (mod N)
3782///
3783/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
3784/// A and B isn't important.
3785///
3786/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Dan Gohman161ea032009-07-07 17:06:11 +00003787static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003788 ScalarEvolution &SE) {
3789 uint32_t BW = A.getBitWidth();
3790 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
3791 assert(A != 0 && "A must be non-zero.");
3792
3793 // 1. D = gcd(A, N)
3794 //
3795 // The gcd of A and N may have only one prime factor: 2. The number of
3796 // trailing zeros in A is its multiplicity
3797 uint32_t Mult2 = A.countTrailingZeros();
3798 // D = 2^Mult2
3799
3800 // 2. Check if B is divisible by D.
3801 //
3802 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
3803 // is not less than multiplicity of this prime factor for D.
3804 if (B.countTrailingZeros() < Mult2)
Dan Gohman0ad08b02009-04-18 17:58:19 +00003805 return SE.getCouldNotCompute();
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003806
3807 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
3808 // modulo (N / D).
3809 //
3810 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
3811 // bit width during computations.
3812 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
3813 APInt Mod(BW + 1, 0);
3814 Mod.set(BW - Mult2); // Mod = N / D
3815 APInt I = AD.multiplicativeInverse(Mod);
3816
3817 // 4. Compute the minimum unsigned root of the equation:
3818 // I * (B / D) mod (N / D)
3819 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
3820
3821 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
3822 // bits.
3823 return SE.getConstant(Result.trunc(BW));
3824}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003825
3826/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
3827/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
3828/// might be the same) or two SCEVCouldNotCompute objects.
3829///
Dan Gohman161ea032009-07-07 17:06:11 +00003830static std::pair<const SCEV *,const SCEV *>
Dan Gohman89f85052007-10-22 18:31:58 +00003831SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003832 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohmanbff6b582009-05-04 22:30:44 +00003833 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
3834 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
3835 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003836
3837 // We currently can only solve this if the coefficients are constants.
3838 if (!LC || !MC || !NC) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00003839 const SCEV *CNC = SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003840 return std::make_pair(CNC, CNC);
3841 }
3842
3843 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
3844 const APInt &L = LC->getValue()->getValue();
3845 const APInt &M = MC->getValue()->getValue();
3846 const APInt &N = NC->getValue()->getValue();
3847 APInt Two(BitWidth, 2);
3848 APInt Four(BitWidth, 4);
3849
Dan Gohman9bc642f2009-06-24 04:48:43 +00003850 {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003851 using namespace APIntOps;
3852 const APInt& C = L;
3853 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
3854 // The B coefficient is M-N/2
3855 APInt B(M);
3856 B -= sdiv(N,Two);
3857
3858 // The A coefficient is N/2
3859 APInt A(N.sdiv(Two));
3860
3861 // Compute the B^2-4ac term.
3862 APInt SqrtTerm(B);
3863 SqrtTerm *= B;
3864 SqrtTerm -= Four * (A * C);
3865
3866 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
3867 // integer value or else APInt::sqrt() will assert.
3868 APInt SqrtVal(SqrtTerm.sqrt());
3869
Dan Gohman9bc642f2009-06-24 04:48:43 +00003870 // Compute the two solutions for the quadratic formula.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003871 // The divisions must be performed as signed divisions.
3872 APInt NegB(-B);
3873 APInt TwoA( A << 1 );
Nick Lewycky35776692008-11-03 02:43:49 +00003874 if (TwoA.isMinValue()) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00003875 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky35776692008-11-03 02:43:49 +00003876 return std::make_pair(CNC, CNC);
3877 }
3878
Owen Andersone755b092009-07-06 22:37:39 +00003879 LLVMContext *Context = SE.getContext();
3880
3881 ConstantInt *Solution1 =
3882 Context->getConstantInt((NegB + SqrtVal).sdiv(TwoA));
3883 ConstantInt *Solution2 =
3884 Context->getConstantInt((NegB - SqrtVal).sdiv(TwoA));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003885
Dan Gohman9bc642f2009-06-24 04:48:43 +00003886 return std::make_pair(SE.getConstant(Solution1),
Dan Gohman89f85052007-10-22 18:31:58 +00003887 SE.getConstant(Solution2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003888 } // end APIntOps namespace
3889}
3890
3891/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman0c850912009-06-06 14:37:11 +00003892/// value to zero will execute. If not computable, return CouldNotCompute.
Dan Gohman161ea032009-07-07 17:06:11 +00003893const SCEV *ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003894 // If the value is a constant
Dan Gohmanc76b5452009-05-04 22:02:23 +00003895 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003896 // If the value is already zero, the branch will execute zero times.
3897 if (C->getValue()->isZero()) return C;
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003898 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003899 }
3900
Dan Gohmanbff6b582009-05-04 22:30:44 +00003901 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003902 if (!AddRec || AddRec->getLoop() != L)
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003903 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003904
3905 if (AddRec->isAffine()) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003906 // If this is an affine expression, the execution count of this branch is
3907 // the minimum unsigned root of the following equation:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003908 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003909 // Start + Step*N = 0 (mod 2^BW)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003910 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003911 // equivalent to:
3912 //
3913 // Step*N = -Start (mod 2^BW)
3914 //
3915 // where BW is the common bit width of Start and Step.
3916
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003917 // Get the initial value for the loop.
Dan Gohman9bc642f2009-06-24 04:48:43 +00003918 const SCEV *Start = getSCEVAtScope(AddRec->getStart(),
3919 L->getParentLoop());
3920 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1),
3921 L->getParentLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003922
Dan Gohmanc76b5452009-05-04 22:02:23 +00003923 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003924 // For now we handle only constant steps.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003925
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003926 // First, handle unitary steps.
3927 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003928 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003929 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
3930 return Start; // N = Start (as unsigned)
3931
3932 // Then, try to solve the above equation provided that Start is constant.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003933 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003934 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003935 -StartC->getValue()->getValue(),
3936 *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003937 }
3938 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
3939 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
3940 // the quadratic equation to solve it.
Dan Gohman161ea032009-07-07 17:06:11 +00003941 std::pair<const SCEV *,const SCEV *> Roots = SolveQuadraticEquation(AddRec,
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003942 *this);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003943 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3944 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003945 if (R1) {
3946#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00003947 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
3948 << " sol#2: " << *R2 << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003949#endif
3950 // Pick the smallest positive root value.
3951 if (ConstantInt *CB =
Owen Andersone755b092009-07-06 22:37:39 +00003952 dyn_cast<ConstantInt>(Context->getConstantExprICmp(ICmpInst::ICMP_ULT,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003953 R1->getValue(), R2->getValue()))) {
3954 if (CB->getZExtValue() == false)
3955 std::swap(R1, R2); // R1 is the minimum root now.
3956
3957 // We can only use this value if the chrec ends up with an exact zero
3958 // value at this index. When solving for "X*X != 5", for example, we
3959 // should not accept a root of 2.
Dan Gohman161ea032009-07-07 17:06:11 +00003960 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohman7b560c42008-06-18 16:23:07 +00003961 if (Val->isZero())
3962 return R1; // We found a quadratic root!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003963 }
3964 }
3965 }
3966
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003967 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003968}
3969
3970/// HowFarToNonZero - Return the number of times a backedge checking the
3971/// specified value for nonzero will execute. If not computable, return
Dan Gohman0c850912009-06-06 14:37:11 +00003972/// CouldNotCompute
Dan Gohman161ea032009-07-07 17:06:11 +00003973const SCEV *ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003974 // Loops that look like: while (X == 0) are very strange indeed. We don't
3975 // handle them yet except for the trivial case. This could be expanded in the
3976 // future as needed.
3977
3978 // If the value is a constant, check to see if it is known to be non-zero
3979 // already. If so, the backedge will execute zero times.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003980 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewyckyf6805182008-02-21 09:14:53 +00003981 if (!C->getValue()->isNullValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003982 return getIntegerSCEV(0, C->getType());
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003983 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003984 }
3985
3986 // We could implement others, but I really doubt anyone writes loops like
3987 // this, and if they did, they would already be constant folded.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003988 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003989}
3990
Dan Gohmanab157b22009-05-18 15:36:09 +00003991/// getLoopPredecessor - If the given loop's header has exactly one unique
3992/// predecessor outside the loop, return it. Otherwise return null.
3993///
3994BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) {
3995 BasicBlock *Header = L->getHeader();
3996 BasicBlock *Pred = 0;
3997 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header);
3998 PI != E; ++PI)
3999 if (!L->contains(*PI)) {
4000 if (Pred && Pred != *PI) return 0; // Multiple predecessors.
4001 Pred = *PI;
4002 }
4003 return Pred;
4004}
4005
Dan Gohman1cddf972008-09-15 22:18:04 +00004006/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
4007/// (which may not be an immediate predecessor) which has exactly one
4008/// successor from which BB is reachable, or null if no such block is
4009/// found.
4010///
4011BasicBlock *
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004012ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman1116ea72009-04-30 20:48:53 +00004013 // If the block has a unique predecessor, then there is no path from the
4014 // predecessor to the block that does not go through the direct edge
4015 // from the predecessor to the block.
Dan Gohman1cddf972008-09-15 22:18:04 +00004016 if (BasicBlock *Pred = BB->getSinglePredecessor())
4017 return Pred;
4018
4019 // A loop's header is defined to be a block that dominates the loop.
Dan Gohmanab157b22009-05-18 15:36:09 +00004020 // If the header has a unique predecessor outside the loop, it must be
4021 // a block that has exactly one successor that can reach the loop.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004022 if (Loop *L = LI->getLoopFor(BB))
Dan Gohmanab157b22009-05-18 15:36:09 +00004023 return getLoopPredecessor(L);
Dan Gohman1cddf972008-09-15 22:18:04 +00004024
4025 return 0;
4026}
4027
Dan Gohmanbc1e3472009-06-20 00:35:32 +00004028/// HasSameValue - SCEV structural equivalence is usually sufficient for
4029/// testing whether two expressions are equal, however for the purposes of
4030/// looking for a condition guarding a loop, it can be useful to be a little
4031/// more general, since a front-end may have replicated the controlling
4032/// expression.
4033///
Dan Gohman161ea032009-07-07 17:06:11 +00004034static bool HasSameValue(const SCEV *A, const SCEV *B) {
Dan Gohmanbc1e3472009-06-20 00:35:32 +00004035 // Quick check to see if they are the same SCEV.
4036 if (A == B) return true;
4037
4038 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
4039 // two different instructions with the same value. Check for this case.
4040 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
4041 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
4042 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
4043 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
4044 if (AI->isIdenticalTo(BI))
4045 return true;
4046
4047 // Otherwise assume they may have a different value.
4048 return false;
4049}
4050
Nick Lewycky9425be92009-07-11 20:38:25 +00004051/// isLoopGuardedByCond - Test whether entry to the loop is protected by
4052/// a conditional between LHS and RHS. This is used to help avoid max
4053/// expressions in loop trip counts.
4054bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
4055 ICmpInst::Predicate Pred,
4056 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman8b938182009-05-18 16:03:58 +00004057 // Interpret a null as meaning no loop, where there is obviously no guard
4058 // (interprocedural conditions notwithstanding).
4059 if (!L) return false;
4060
Dan Gohmanab157b22009-05-18 15:36:09 +00004061 BasicBlock *Predecessor = getLoopPredecessor(L);
4062 BasicBlock *PredecessorDest = L->getHeader();
Nick Lewycky1b020bf2008-07-12 07:41:32 +00004063
Dan Gohmanab157b22009-05-18 15:36:09 +00004064 // Starting at the loop predecessor, climb up the predecessor chain, as long
4065 // as there are predecessors that can be found that have unique successors
Dan Gohman1cddf972008-09-15 22:18:04 +00004066 // leading to the original header.
Dan Gohmanab157b22009-05-18 15:36:09 +00004067 for (; Predecessor;
4068 PredecessorDest = Predecessor,
4069 Predecessor = getPredecessorWithUniqueSuccessorForBB(Predecessor)) {
Dan Gohmanab678fb2008-08-12 20:17:31 +00004070
4071 BranchInst *LoopEntryPredicate =
Dan Gohmanab157b22009-05-18 15:36:09 +00004072 dyn_cast<BranchInst>(Predecessor->getTerminator());
Dan Gohmanab678fb2008-08-12 20:17:31 +00004073 if (!LoopEntryPredicate ||
4074 LoopEntryPredicate->isUnconditional())
4075 continue;
4076
Dan Gohman423ed6c2009-06-24 01:18:18 +00004077 if (isNecessaryCond(LoopEntryPredicate->getCondition(), Pred, LHS, RHS,
4078 LoopEntryPredicate->getSuccessor(0) != PredecessorDest))
Dan Gohmanab678fb2008-08-12 20:17:31 +00004079 return true;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00004080 }
4081
Dan Gohmanab678fb2008-08-12 20:17:31 +00004082 return false;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00004083}
4084
Nick Lewycky9425be92009-07-11 20:38:25 +00004085/// isNecessaryCond - Test whether the given CondValue value is a condition
4086/// which is at least as strict as the one described by Pred, LHS, and RHS.
Dan Gohman423ed6c2009-06-24 01:18:18 +00004087bool ScalarEvolution::isNecessaryCond(Value *CondValue,
4088 ICmpInst::Predicate Pred,
4089 const SCEV *LHS, const SCEV *RHS,
4090 bool Inverse) {
4091 // Recursivly handle And and Or conditions.
4092 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CondValue)) {
4093 if (BO->getOpcode() == Instruction::And) {
4094 if (!Inverse)
4095 return isNecessaryCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4096 isNecessaryCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
4097 } else if (BO->getOpcode() == Instruction::Or) {
4098 if (Inverse)
4099 return isNecessaryCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4100 isNecessaryCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
4101 }
4102 }
4103
4104 ICmpInst *ICI = dyn_cast<ICmpInst>(CondValue);
4105 if (!ICI) return false;
4106
4107 // Now that we found a conditional branch that dominates the loop, check to
4108 // see if it is the comparison we are looking for.
4109 Value *PreCondLHS = ICI->getOperand(0);
4110 Value *PreCondRHS = ICI->getOperand(1);
Nick Lewycky9425be92009-07-11 20:38:25 +00004111 ICmpInst::Predicate Cond;
Dan Gohman423ed6c2009-06-24 01:18:18 +00004112 if (Inverse)
Nick Lewycky9425be92009-07-11 20:38:25 +00004113 Cond = ICI->getInversePredicate();
Dan Gohman423ed6c2009-06-24 01:18:18 +00004114 else
Nick Lewycky9425be92009-07-11 20:38:25 +00004115 Cond = ICI->getPredicate();
Dan Gohman423ed6c2009-06-24 01:18:18 +00004116
Nick Lewycky9425be92009-07-11 20:38:25 +00004117 if (Cond == Pred)
Dan Gohman423ed6c2009-06-24 01:18:18 +00004118 ; // An exact match.
Nick Lewycky9425be92009-07-11 20:38:25 +00004119 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
4120 ; // The actual condition is beyond sufficient.
4121 else
Dan Gohman423ed6c2009-06-24 01:18:18 +00004122 // Check a few special cases.
Nick Lewycky9425be92009-07-11 20:38:25 +00004123 switch (Cond) {
Dan Gohman423ed6c2009-06-24 01:18:18 +00004124 case ICmpInst::ICMP_UGT:
4125 if (Pred == ICmpInst::ICMP_ULT) {
4126 std::swap(PreCondLHS, PreCondRHS);
Nick Lewycky9425be92009-07-11 20:38:25 +00004127 Cond = ICmpInst::ICMP_ULT;
Dan Gohman423ed6c2009-06-24 01:18:18 +00004128 break;
4129 }
4130 return false;
4131 case ICmpInst::ICMP_SGT:
4132 if (Pred == ICmpInst::ICMP_SLT) {
4133 std::swap(PreCondLHS, PreCondRHS);
Nick Lewycky9425be92009-07-11 20:38:25 +00004134 Cond = ICmpInst::ICMP_SLT;
Dan Gohman423ed6c2009-06-24 01:18:18 +00004135 break;
4136 }
4137 return false;
4138 case ICmpInst::ICMP_NE:
4139 // Expressions like (x >u 0) are often canonicalized to (x != 0),
4140 // so check for this case by checking if the NE is comparing against
4141 // a minimum or maximum constant.
4142 if (!ICmpInst::isTrueWhenEqual(Pred))
Nick Lewycky9425be92009-07-11 20:38:25 +00004143 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
4144 const APInt &A = CI->getValue();
Dan Gohman423ed6c2009-06-24 01:18:18 +00004145 switch (Pred) {
4146 case ICmpInst::ICMP_SLT:
4147 if (A.isMaxSignedValue()) break;
4148 return false;
4149 case ICmpInst::ICMP_SGT:
4150 if (A.isMinSignedValue()) break;
4151 return false;
4152 case ICmpInst::ICMP_ULT:
4153 if (A.isMaxValue()) break;
4154 return false;
4155 case ICmpInst::ICMP_UGT:
4156 if (A.isMinValue()) break;
4157 return false;
4158 default:
4159 return false;
4160 }
Nick Lewycky9425be92009-07-11 20:38:25 +00004161 Cond = ICmpInst::ICMP_NE;
Dan Gohman423ed6c2009-06-24 01:18:18 +00004162 // NE is symmetric but the original comparison may not be. Swap
4163 // the operands if necessary so that they match below.
4164 if (isa<SCEVConstant>(LHS))
4165 std::swap(PreCondLHS, PreCondRHS);
4166 break;
4167 }
4168 return false;
4169 default:
4170 // We weren't able to reconcile the condition.
4171 return false;
4172 }
4173
Nick Lewycky9425be92009-07-11 20:38:25 +00004174 if (!PreCondLHS->getType()->isInteger()) return false;
Dan Gohman423ed6c2009-06-24 01:18:18 +00004175
Nick Lewycky9425be92009-07-11 20:38:25 +00004176 const SCEV *PreCondLHSSCEV = getSCEV(PreCondLHS);
4177 const SCEV *PreCondRHSSCEV = getSCEV(PreCondRHS);
4178 return (HasSameValue(LHS, PreCondLHSSCEV) &&
4179 HasSameValue(RHS, PreCondRHSSCEV)) ||
4180 (HasSameValue(LHS, getNotSCEV(PreCondRHSSCEV)) &&
4181 HasSameValue(RHS, getNotSCEV(PreCondLHSSCEV)));
Dan Gohman423ed6c2009-06-24 01:18:18 +00004182}
4183
Dan Gohmand2b62c42009-06-21 23:46:38 +00004184/// getBECount - Subtract the end and start values and divide by the step,
4185/// rounding up, to get the number of times the backedge is executed. Return
4186/// CouldNotCompute if an intermediate computation overflows.
Dan Gohman161ea032009-07-07 17:06:11 +00004187const SCEV *ScalarEvolution::getBECount(const SCEV *Start,
4188 const SCEV *End,
4189 const SCEV *Step) {
Dan Gohmand2b62c42009-06-21 23:46:38 +00004190 const Type *Ty = Start->getType();
Dan Gohman161ea032009-07-07 17:06:11 +00004191 const SCEV *NegOne = getIntegerSCEV(-1, Ty);
4192 const SCEV *Diff = getMinusSCEV(End, Start);
4193 const SCEV *RoundUp = getAddExpr(Step, NegOne);
Dan Gohmand2b62c42009-06-21 23:46:38 +00004194
4195 // Add an adjustment to the difference between End and Start so that
4196 // the division will effectively round up.
Dan Gohman161ea032009-07-07 17:06:11 +00004197 const SCEV *Add = getAddExpr(Diff, RoundUp);
Dan Gohmand2b62c42009-06-21 23:46:38 +00004198
4199 // Check Add for unsigned overflow.
4200 // TODO: More sophisticated things could be done here.
Owen Andersone755b092009-07-06 22:37:39 +00004201 const Type *WideTy = Context->getIntegerType(getTypeSizeInBits(Ty) + 1);
Dan Gohman161ea032009-07-07 17:06:11 +00004202 const SCEV *OperandExtendedAdd =
Dan Gohmand2b62c42009-06-21 23:46:38 +00004203 getAddExpr(getZeroExtendExpr(Diff, WideTy),
4204 getZeroExtendExpr(RoundUp, WideTy));
4205 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004206 return getCouldNotCompute();
Dan Gohmand2b62c42009-06-21 23:46:38 +00004207
4208 return getUDivExpr(Add, Step);
4209}
4210
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004211/// HowManyLessThans - Return the number of times a backedge containing the
4212/// specified less-than comparison will execute. If not computable, return
Dan Gohman0c850912009-06-06 14:37:11 +00004213/// CouldNotCompute.
Dan Gohman9bc642f2009-06-24 04:48:43 +00004214ScalarEvolution::BackedgeTakenInfo
4215ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
4216 const Loop *L, bool isSigned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004217 // Only handle: "ADDREC < LoopInvariant".
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004218 if (!RHS->isLoopInvariant(L)) return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004219
Dan Gohmanbff6b582009-05-04 22:30:44 +00004220 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004221 if (!AddRec || AddRec->getLoop() != L)
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004222 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004223
4224 if (AddRec->isAffine()) {
Nick Lewycky35b56022009-01-13 09:18:58 +00004225 // FORNOW: We only support unit strides.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004226 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
Dan Gohman161ea032009-07-07 17:06:11 +00004227 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004228
4229 // TODO: handle non-constant strides.
4230 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
4231 if (!CStep || CStep->isZero())
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004232 return getCouldNotCompute();
Dan Gohmanf8bc8e82009-05-18 15:22:39 +00004233 if (CStep->isOne()) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004234 // With unit stride, the iteration never steps past the limit value.
4235 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
4236 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
4237 // Test whether a positive iteration iteration can step past the limit
4238 // value and past the maximum value for its type in a single step.
4239 if (isSigned) {
4240 APInt Max = APInt::getSignedMaxValue(BitWidth);
4241 if ((Max - CStep->getValue()->getValue())
4242 .slt(CLimit->getValue()->getValue()))
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004243 return getCouldNotCompute();
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004244 } else {
4245 APInt Max = APInt::getMaxValue(BitWidth);
4246 if ((Max - CStep->getValue()->getValue())
4247 .ult(CLimit->getValue()->getValue()))
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004248 return getCouldNotCompute();
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004249 }
4250 } else
4251 // TODO: handle non-constant limit values below.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004252 return getCouldNotCompute();
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004253 } else
4254 // TODO: handle negative strides below.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004255 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004256
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004257 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
4258 // m. So, we count the number of iterations in which {n,+,s} < m is true.
4259 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicz1377a542008-02-13 12:21:32 +00004260 // treat m-n as signed nor unsigned due to overflow possibility.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004261
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00004262 // First, we get the value of the LHS in the first iteration: n
Dan Gohman161ea032009-07-07 17:06:11 +00004263 const SCEV *Start = AddRec->getOperand(0);
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00004264
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004265 // Determine the minimum constant start value.
Nick Lewycky9425be92009-07-11 20:38:25 +00004266 const SCEV *MinStart = isa<SCEVConstant>(Start) ? Start :
4267 getConstant(isSigned ? APInt::getSignedMinValue(BitWidth) :
4268 APInt::getMinValue(BitWidth));
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00004269
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004270 // If we know that the condition is true in order to enter the loop,
4271 // then we know that it will run exactly (m-n)/s times. Otherwise, we
Dan Gohmanc8a29272009-05-24 23:45:28 +00004272 // only know that it will execute (max(m,n)-n)/s times. In both cases,
4273 // the division must round up.
Dan Gohman161ea032009-07-07 17:06:11 +00004274 const SCEV *End = RHS;
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004275 if (!isLoopGuardedByCond(L,
Nick Lewycky9425be92009-07-11 20:38:25 +00004276 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004277 getMinusSCEV(Start, Step), RHS))
4278 End = isSigned ? getSMaxExpr(RHS, Start)
4279 : getUMaxExpr(RHS, Start);
4280
4281 // Determine the maximum constant end value.
Nick Lewycky9425be92009-07-11 20:38:25 +00004282 const SCEV *MaxEnd =
4283 isa<SCEVConstant>(End) ? End :
4284 getConstant(isSigned ? APInt::getSignedMaxValue(BitWidth)
4285 .ashr(GetMinSignBits(End) - 1) :
4286 APInt::getMaxValue(BitWidth)
4287 .lshr(GetMinLeadingZeros(End)));
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004288
4289 // Finally, we subtract these two values and divide, rounding up, to get
4290 // the number of times the backedge is executed.
Dan Gohman161ea032009-07-07 17:06:11 +00004291 const SCEV *BECount = getBECount(Start, End, Step);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004292
4293 // The maximum backedge count is similar, except using the minimum start
4294 // value and the maximum end value.
Dan Gohman161ea032009-07-07 17:06:11 +00004295 const SCEV *MaxBECount = getBECount(MinStart, MaxEnd, Step);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004296
4297 return BackedgeTakenInfo(BECount, MaxBECount);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004298 }
4299
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004300 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004301}
4302
4303/// getNumIterationsInRange - Return the number of iterations of this loop that
4304/// produce values in the specified constant range. Another way of looking at
4305/// this is that it returns the first iteration number where the value is not in
4306/// the condition, thus computing the exit count. If the iteration count can't
4307/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman161ea032009-07-07 17:06:11 +00004308const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
Dan Gohman9bc642f2009-06-24 04:48:43 +00004309 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004310 if (Range.isFullSet()) // Infinite loop.
Dan Gohman0ad08b02009-04-18 17:58:19 +00004311 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004312
4313 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohmanc76b5452009-05-04 22:02:23 +00004314 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004315 if (!SC->getValue()->isZero()) {
Dan Gohman161ea032009-07-07 17:06:11 +00004316 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00004317 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
Dan Gohman161ea032009-07-07 17:06:11 +00004318 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohmanc76b5452009-05-04 22:02:23 +00004319 if (const SCEVAddRecExpr *ShiftedAddRec =
4320 dyn_cast<SCEVAddRecExpr>(Shifted))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004321 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman89f85052007-10-22 18:31:58 +00004322 Range.subtract(SC->getValue()->getValue()), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004323 // This is strange and shouldn't happen.
Dan Gohman0ad08b02009-04-18 17:58:19 +00004324 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004325 }
4326
4327 // The only time we can solve this is when we have all constant indices.
4328 // Otherwise, we cannot determine the overflow conditions.
4329 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
4330 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohman0ad08b02009-04-18 17:58:19 +00004331 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004332
4333
4334 // Okay at this point we know that all elements of the chrec are constants and
4335 // that the start element is zero.
4336
4337 // First check to see if the range contains zero. If not, the first
4338 // iteration exits.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00004339 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00004340 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman8fd520a2009-06-15 22:12:54 +00004341 return SE.getIntegerSCEV(0, getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004342
4343 if (isAffine()) {
4344 // If this is an affine expression then we have this situation:
4345 // Solve {0,+,A} in Range === Ax in Range
4346
4347 // We know that zero is in the range. If A is positive then we know that
4348 // the upper value of the range must be the first possible exit value.
4349 // If A is negative then the lower of the range is the last possible loop
4350 // value. Also note that we already checked for a full range.
Dan Gohman01c2ee72009-04-16 03:18:22 +00004351 APInt One(BitWidth,1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004352 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
4353 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
4354
4355 // The exit value should be (End+A)/A.
Nick Lewyckya0facae2007-09-27 14:12:54 +00004356 APInt ExitVal = (End + A).udiv(A);
Owen Andersone755b092009-07-06 22:37:39 +00004357 ConstantInt *ExitValue = SE.getContext()->getConstantInt(ExitVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004358
4359 // Evaluate at the exit value. If we really did fall out of the valid
4360 // range, then we computed our trip count, otherwise wrap around or other
4361 // things must have happened.
Dan Gohman89f85052007-10-22 18:31:58 +00004362 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004363 if (Range.contains(Val->getValue()))
Dan Gohman0ad08b02009-04-18 17:58:19 +00004364 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004365
4366 // Ensure that the previous value is in the range. This is a sanity check.
4367 assert(Range.contains(
Dan Gohman9bc642f2009-06-24 04:48:43 +00004368 EvaluateConstantChrecAtConstant(this,
Owen Andersone755b092009-07-06 22:37:39 +00004369 SE.getContext()->getConstantInt(ExitVal - One), SE)->getValue()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004370 "Linear scev computation is off in a bad way!");
Dan Gohman89f85052007-10-22 18:31:58 +00004371 return SE.getConstant(ExitValue);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004372 } else if (isQuadratic()) {
4373 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
4374 // quadratic equation to solve it. To do this, we must frame our problem in
4375 // terms of figuring out when zero is crossed, instead of when
4376 // Range.getUpper() is crossed.
Dan Gohman161ea032009-07-07 17:06:11 +00004377 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00004378 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Dan Gohman161ea032009-07-07 17:06:11 +00004379 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004380
4381 // Next, solve the constructed addrec
Dan Gohman161ea032009-07-07 17:06:11 +00004382 std::pair<const SCEV *,const SCEV *> Roots =
Dan Gohman89f85052007-10-22 18:31:58 +00004383 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohmanbff6b582009-05-04 22:30:44 +00004384 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4385 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004386 if (R1) {
4387 // Pick the smallest positive root value.
4388 if (ConstantInt *CB =
Owen Andersone755b092009-07-06 22:37:39 +00004389 dyn_cast<ConstantInt>(
4390 SE.getContext()->getConstantExprICmp(ICmpInst::ICMP_ULT,
4391 R1->getValue(), R2->getValue()))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004392 if (CB->getZExtValue() == false)
4393 std::swap(R1, R2); // R1 is the minimum root now.
4394
4395 // Make sure the root is not off by one. The returned iteration should
4396 // not be in the range, but the previous one should be. When solving
4397 // for "X*X < 5", for example, we should not return a root of 2.
4398 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00004399 R1->getValue(),
4400 SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004401 if (Range.contains(R1Val->getValue())) {
4402 // The next iteration must be out of the range...
Owen Andersone755b092009-07-06 22:37:39 +00004403 ConstantInt *NextVal =
4404 SE.getContext()->getConstantInt(R1->getValue()->getValue()+1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004405
Dan Gohman89f85052007-10-22 18:31:58 +00004406 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004407 if (!Range.contains(R1Val->getValue()))
Dan Gohman89f85052007-10-22 18:31:58 +00004408 return SE.getConstant(NextVal);
Dan Gohman0ad08b02009-04-18 17:58:19 +00004409 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004410 }
4411
4412 // If R1 was not in the range, then it is a good return value. Make
4413 // sure that R1-1 WAS in the range though, just in case.
Owen Andersone755b092009-07-06 22:37:39 +00004414 ConstantInt *NextVal =
4415 SE.getContext()->getConstantInt(R1->getValue()->getValue()-1);
Dan Gohman89f85052007-10-22 18:31:58 +00004416 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004417 if (Range.contains(R1Val->getValue()))
4418 return R1;
Dan Gohman0ad08b02009-04-18 17:58:19 +00004419 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004420 }
4421 }
4422 }
4423
Dan Gohman0ad08b02009-04-18 17:58:19 +00004424 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004425}
4426
4427
4428
4429//===----------------------------------------------------------------------===//
Dan Gohmanbff6b582009-05-04 22:30:44 +00004430// SCEVCallbackVH Class Implementation
4431//===----------------------------------------------------------------------===//
4432
Dan Gohman999d14e2009-05-19 19:22:47 +00004433void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmanbff6b582009-05-04 22:30:44 +00004434 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
4435 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
4436 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00004437 if (Instruction *I = dyn_cast<Instruction>(getValPtr()))
4438 SE->ValuesAtScopes.erase(I);
Dan Gohmanbff6b582009-05-04 22:30:44 +00004439 SE->Scalars.erase(getValPtr());
4440 // this now dangles!
4441}
4442
Dan Gohman999d14e2009-05-19 19:22:47 +00004443void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00004444 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
4445
4446 // Forget all the expressions associated with users of the old value,
4447 // so that future queries will recompute the expressions using the new
4448 // value.
4449 SmallVector<User *, 16> Worklist;
4450 Value *Old = getValPtr();
4451 bool DeleteOld = false;
4452 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
4453 UI != UE; ++UI)
4454 Worklist.push_back(*UI);
4455 while (!Worklist.empty()) {
4456 User *U = Worklist.pop_back_val();
4457 // Deleting the Old value will cause this to dangle. Postpone
4458 // that until everything else is done.
4459 if (U == Old) {
4460 DeleteOld = true;
4461 continue;
4462 }
4463 if (PHINode *PN = dyn_cast<PHINode>(U))
4464 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00004465 if (Instruction *I = dyn_cast<Instruction>(U))
4466 SE->ValuesAtScopes.erase(I);
Dan Gohmanbff6b582009-05-04 22:30:44 +00004467 if (SE->Scalars.erase(U))
4468 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
4469 UI != UE; ++UI)
4470 Worklist.push_back(*UI);
4471 }
4472 if (DeleteOld) {
4473 if (PHINode *PN = dyn_cast<PHINode>(Old))
4474 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00004475 if (Instruction *I = dyn_cast<Instruction>(Old))
4476 SE->ValuesAtScopes.erase(I);
Dan Gohmanbff6b582009-05-04 22:30:44 +00004477 SE->Scalars.erase(Old);
4478 // this now dangles!
4479 }
4480 // this may dangle!
4481}
4482
Dan Gohman999d14e2009-05-19 19:22:47 +00004483ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohmanbff6b582009-05-04 22:30:44 +00004484 : CallbackVH(V), SE(se) {}
4485
4486//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004487// ScalarEvolution Class Implementation
4488//===----------------------------------------------------------------------===//
4489
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004490ScalarEvolution::ScalarEvolution()
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004491 : FunctionPass(&ID) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004492}
4493
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004494bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004495 this->F = &F;
4496 LI = &getAnalysis<LoopInfo>();
4497 TD = getAnalysisIfAvailable<TargetData>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004498 return false;
4499}
4500
4501void ScalarEvolution::releaseMemory() {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004502 Scalars.clear();
4503 BackedgeTakenCounts.clear();
4504 ConstantEvolutionLoopExitValue.clear();
Dan Gohmanda0071e2009-05-08 20:47:27 +00004505 ValuesAtScopes.clear();
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004506 UniqueSCEVs.clear();
4507 SCEVAllocator.Reset();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004508}
4509
4510void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
4511 AU.setPreservesAll();
4512 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman01c2ee72009-04-16 03:18:22 +00004513}
4514
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004515bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00004516 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004517}
4518
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004519static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004520 const Loop *L) {
4521 // Print all inner loops first
4522 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
4523 PrintLoopInfo(OS, SE, *I);
4524
Nick Lewyckye5da1912008-01-02 02:49:20 +00004525 OS << "Loop " << L->getHeader()->getName() << ": ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004526
Devang Patel02451fa2007-08-21 00:31:24 +00004527 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004528 L->getExitBlocks(ExitBlocks);
4529 if (ExitBlocks.size() != 1)
Nick Lewyckye5da1912008-01-02 02:49:20 +00004530 OS << "<multiple exits> ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004531
Dan Gohman76d5a0d2009-02-24 18:55:53 +00004532 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
4533 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004534 } else {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00004535 OS << "Unpredictable backedge-taken count. ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004536 }
4537
Nick Lewyckye5da1912008-01-02 02:49:20 +00004538 OS << "\n";
Dan Gohmanb6b9e9e2009-06-24 00:33:16 +00004539 OS << "Loop " << L->getHeader()->getName() << ": ";
4540
4541 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
4542 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
4543 } else {
4544 OS << "Unpredictable max backedge-taken count. ";
4545 }
4546
4547 OS << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004548}
4549
Dan Gohman13058cc2009-04-21 00:47:46 +00004550void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004551 // ScalarEvolution's implementaiton of the print method is to print
4552 // out SCEV values of all instructions that are interesting. Doing
4553 // this potentially causes it to create new SCEV objects though,
4554 // which technically conflicts with the const qualifier. This isn't
Dan Gohmanac2a9d62009-07-10 20:25:29 +00004555 // observable from outside the class though, so casting away the
4556 // const isn't dangerous.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004557 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004558
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004559 OS << "Classifying expressions for: " << F->getName() << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004560 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohman43d37e92009-04-30 01:30:18 +00004561 if (isSCEVable(I->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004562 OS << *I;
Dan Gohmanabe991f2008-09-14 17:21:12 +00004563 OS << " --> ";
Dan Gohman161ea032009-07-07 17:06:11 +00004564 const SCEV *SV = SE.getSCEV(&*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004565 SV->print(OS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004566
Dan Gohman8db598a2009-06-19 17:49:54 +00004567 const Loop *L = LI->getLoopFor((*I).getParent());
4568
Dan Gohman161ea032009-07-07 17:06:11 +00004569 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohman8db598a2009-06-19 17:49:54 +00004570 if (AtUse != SV) {
4571 OS << " --> ";
4572 AtUse->print(OS);
4573 }
4574
4575 if (L) {
Dan Gohmane5b60842009-06-18 00:37:45 +00004576 OS << "\t\t" "Exits: ";
Dan Gohman161ea032009-07-07 17:06:11 +00004577 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohmanaff14d62009-05-24 23:25:42 +00004578 if (!ExitValue->isLoopInvariant(L)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004579 OS << "<<Unknown>>";
4580 } else {
4581 OS << *ExitValue;
4582 }
4583 }
4584
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004585 OS << "\n";
4586 }
4587
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004588 OS << "Determining loop execution counts for: " << F->getName() << "\n";
4589 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
4590 PrintLoopInfo(OS, &SE, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004591}
Dan Gohman13058cc2009-04-21 00:47:46 +00004592
4593void ScalarEvolution::print(std::ostream &o, const Module *M) const {
4594 raw_os_ostream OS(o);
4595 print(OS, M);
4596}