blob: a16779202412e61da3cbc7d0329c4aa13af4c4d7 [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))
Dan Gohman55788cf2009-06-24 00:38:39 +00002087 return getConstant(cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002088
2089 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002090 Ty = getEffectiveSCEVType(Ty);
2091 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(Ty)));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002092}
2093
2094/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohman161ea032009-07-07 17:06:11 +00002095const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00002096 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohman55788cf2009-06-24 00:38:39 +00002097 return getConstant(cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002098
2099 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002100 Ty = getEffectiveSCEVType(Ty);
Dan Gohman161ea032009-07-07 17:06:11 +00002101 const SCEV *AllOnes = getConstant(ConstantInt::getAllOnesValue(Ty));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002102 return getMinusSCEV(AllOnes, V);
2103}
2104
2105/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2106///
Dan Gohman8c4f20b2009-06-24 14:49:00 +00002107const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS,
2108 const SCEV *RHS) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00002109 // X - Y --> X + -Y
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002110 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002111}
2112
2113/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2114/// input value to the specified type. If the type must be extended, it is zero
2115/// extended.
Dan Gohman161ea032009-07-07 17:06:11 +00002116const SCEV *
2117ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V,
Nick Lewycky37d04642009-04-23 05:15:08 +00002118 const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00002119 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002120 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2121 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00002122 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002123 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00002124 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002125 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002126 return getTruncateExpr(V, Ty);
2127 return getZeroExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002128}
2129
2130/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2131/// input value to the specified type. If the type must be extended, it is sign
2132/// extended.
Dan Gohman161ea032009-07-07 17:06:11 +00002133const SCEV *
2134ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
Nick Lewycky37d04642009-04-23 05:15:08 +00002135 const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00002136 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002137 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2138 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00002139 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002140 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00002141 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002142 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002143 return getTruncateExpr(V, Ty);
2144 return getSignExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002145}
2146
Dan Gohmanac959332009-05-13 03:46:30 +00002147/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2148/// input value to the specified type. If the type must be extended, it is zero
2149/// extended. The conversion must not be narrowing.
Dan Gohman161ea032009-07-07 17:06:11 +00002150const SCEV *
2151ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, const Type *Ty) {
Dan Gohmanac959332009-05-13 03:46:30 +00002152 const Type *SrcTy = V->getType();
2153 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2154 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2155 "Cannot noop or zero extend with non-integer arguments!");
2156 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2157 "getNoopOrZeroExtend cannot truncate!");
2158 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2159 return V; // No conversion
2160 return getZeroExtendExpr(V, Ty);
2161}
2162
2163/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2164/// input value to the specified type. If the type must be extended, it is sign
2165/// extended. The conversion must not be narrowing.
Dan Gohman161ea032009-07-07 17:06:11 +00002166const SCEV *
2167ScalarEvolution::getNoopOrSignExtend(const SCEV *V, const Type *Ty) {
Dan Gohmanac959332009-05-13 03:46:30 +00002168 const Type *SrcTy = V->getType();
2169 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2170 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2171 "Cannot noop or sign extend with non-integer arguments!");
2172 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2173 "getNoopOrSignExtend cannot truncate!");
2174 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2175 return V; // No conversion
2176 return getSignExtendExpr(V, Ty);
2177}
2178
Dan Gohmane1ca7e82009-06-13 15:56:47 +00002179/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2180/// the input value to the specified type. If the type must be extended,
2181/// it is extended with unspecified bits. The conversion must not be
2182/// narrowing.
Dan Gohman161ea032009-07-07 17:06:11 +00002183const SCEV *
2184ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, const Type *Ty) {
Dan Gohmane1ca7e82009-06-13 15:56:47 +00002185 const Type *SrcTy = V->getType();
2186 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2187 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2188 "Cannot noop or any extend with non-integer arguments!");
2189 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2190 "getNoopOrAnyExtend cannot truncate!");
2191 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2192 return V; // No conversion
2193 return getAnyExtendExpr(V, Ty);
2194}
2195
Dan Gohmanac959332009-05-13 03:46:30 +00002196/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2197/// input value to the specified type. The conversion must not be widening.
Dan Gohman161ea032009-07-07 17:06:11 +00002198const SCEV *
2199ScalarEvolution::getTruncateOrNoop(const SCEV *V, const Type *Ty) {
Dan Gohmanac959332009-05-13 03:46:30 +00002200 const Type *SrcTy = V->getType();
2201 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2202 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2203 "Cannot truncate or noop with non-integer arguments!");
2204 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2205 "getTruncateOrNoop cannot extend!");
2206 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2207 return V; // No conversion
2208 return getTruncateExpr(V, Ty);
2209}
2210
Dan Gohman8e8b5232009-06-22 00:31:57 +00002211/// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2212/// the types using zero-extension, and then perform a umax operation
2213/// with them.
Dan Gohman8c4f20b2009-06-24 14:49:00 +00002214const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2215 const SCEV *RHS) {
Dan Gohman161ea032009-07-07 17:06:11 +00002216 const SCEV *PromotedLHS = LHS;
2217 const SCEV *PromotedRHS = RHS;
Dan Gohman8e8b5232009-06-22 00:31:57 +00002218
2219 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2220 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2221 else
2222 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2223
2224 return getUMaxExpr(PromotedLHS, PromotedRHS);
2225}
2226
Dan Gohman9e62bb02009-06-22 15:03:27 +00002227/// getUMinFromMismatchedTypes - Promote the operands to the wider of
2228/// the types using zero-extension, and then perform a umin operation
2229/// with them.
Dan Gohman8c4f20b2009-06-24 14:49:00 +00002230const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2231 const SCEV *RHS) {
Dan Gohman161ea032009-07-07 17:06:11 +00002232 const SCEV *PromotedLHS = LHS;
2233 const SCEV *PromotedRHS = RHS;
Dan Gohman9e62bb02009-06-22 15:03:27 +00002234
2235 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2236 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2237 else
2238 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2239
2240 return getUMinExpr(PromotedLHS, PromotedRHS);
2241}
2242
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002243/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
2244/// the specified instruction and replaces any references to the symbolic value
2245/// SymName with the specified value. This is used during PHI resolution.
Dan Gohman9bc642f2009-06-24 04:48:43 +00002246void
2247ScalarEvolution::ReplaceSymbolicValueWithConcrete(Instruction *I,
2248 const SCEV *SymName,
2249 const SCEV *NewVal) {
Dan Gohman161ea032009-07-07 17:06:11 +00002250 std::map<SCEVCallbackVH, const SCEV *>::iterator SI =
Dan Gohmanbff6b582009-05-04 22:30:44 +00002251 Scalars.find(SCEVCallbackVH(I, this));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002252 if (SI == Scalars.end()) return;
2253
Dan Gohman161ea032009-07-07 17:06:11 +00002254 const SCEV *NV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002255 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002256 if (NV == SI->second) return; // No change.
2257
2258 SI->second = NV; // Update the scalars map!
2259
2260 // Any instruction values that use this instruction might also need to be
2261 // updated!
2262 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
2263 UI != E; ++UI)
2264 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
2265}
2266
2267/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2268/// a loop header, making it a potential recurrence, or it doesn't.
2269///
Dan Gohman161ea032009-07-07 17:06:11 +00002270const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002271 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002272 if (const Loop *L = LI->getLoopFor(PN->getParent()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002273 if (L->getHeader() == PN->getParent()) {
2274 // If it lives in the loop header, it has two incoming values, one
2275 // from outside the loop, and one from inside.
2276 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
2277 unsigned BackEdge = IncomingEdge^1;
2278
2279 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohman161ea032009-07-07 17:06:11 +00002280 const SCEV *SymbolicName = getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002281 assert(Scalars.find(PN) == Scalars.end() &&
2282 "PHI node already processed?");
Dan Gohmanbff6b582009-05-04 22:30:44 +00002283 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002284
2285 // Using this symbolic name for the PHI, analyze the value coming around
2286 // the back-edge.
Dan Gohman161ea032009-07-07 17:06:11 +00002287 const SCEV *BEValue = getSCEV(PN->getIncomingValue(BackEdge));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002288
2289 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2290 // has a special value for the first iteration of the loop.
2291
2292 // If the value coming around the backedge is an add with the symbolic
2293 // value we just inserted, then we found a simple induction variable!
Dan Gohmanc76b5452009-05-04 22:02:23 +00002294 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002295 // If there is a single occurrence of the symbolic value, replace it
2296 // with a recurrence.
2297 unsigned FoundIndex = Add->getNumOperands();
2298 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2299 if (Add->getOperand(i) == SymbolicName)
2300 if (FoundIndex == e) {
2301 FoundIndex = i;
2302 break;
2303 }
2304
2305 if (FoundIndex != Add->getNumOperands()) {
2306 // Create an add with everything but the specified operand.
Dan Gohman161ea032009-07-07 17:06:11 +00002307 SmallVector<const SCEV *, 8> Ops;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002308 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2309 if (i != FoundIndex)
2310 Ops.push_back(Add->getOperand(i));
Dan Gohman161ea032009-07-07 17:06:11 +00002311 const SCEV *Accum = getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002312
2313 // This is not a valid addrec if the step amount is varying each
2314 // loop iteration, but is not itself an addrec in this loop.
2315 if (Accum->isLoopInvariant(L) ||
2316 (isa<SCEVAddRecExpr>(Accum) &&
2317 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
Dan Gohman9bc642f2009-06-24 04:48:43 +00002318 const SCEV *StartVal =
2319 getSCEV(PN->getIncomingValue(IncomingEdge));
2320 const SCEV *PHISCEV =
2321 getAddRecExpr(StartVal, Accum, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002322
2323 // Okay, for the entire analysis of this edge we assumed the PHI
2324 // to be symbolic. We now need to go back and update all of the
2325 // entries for the scalars that use the PHI (except for the PHI
2326 // itself) to use the new analyzed value instead of the "symbolic"
2327 // value.
2328 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
2329 return PHISCEV;
2330 }
2331 }
Dan Gohmanc76b5452009-05-04 22:02:23 +00002332 } else if (const SCEVAddRecExpr *AddRec =
2333 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002334 // Otherwise, this could be a loop like this:
2335 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2336 // In this case, j = {1,+,1} and BEValue is j.
2337 // Because the other in-value of i (0) fits the evolution of BEValue
2338 // i really is an addrec evolution.
2339 if (AddRec->getLoop() == L && AddRec->isAffine()) {
Dan Gohman161ea032009-07-07 17:06:11 +00002340 const SCEV *StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002341
2342 // If StartVal = j.start - j.stride, we can use StartVal as the
2343 // initial step of the addrec evolution.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002344 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman89f85052007-10-22 18:31:58 +00002345 AddRec->getOperand(1))) {
Dan Gohman161ea032009-07-07 17:06:11 +00002346 const SCEV *PHISCEV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002347 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002348
2349 // Okay, for the entire analysis of this edge we assumed the PHI
2350 // to be symbolic. We now need to go back and update all of the
2351 // entries for the scalars that use the PHI (except for the PHI
2352 // itself) to use the new analyzed value instead of the "symbolic"
2353 // value.
2354 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
2355 return PHISCEV;
2356 }
2357 }
2358 }
2359
2360 return SymbolicName;
2361 }
2362
2363 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002364 return getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002365}
2366
Dan Gohman509cf4d2009-05-08 20:26:55 +00002367/// createNodeForGEP - Expand GEP instructions into add and multiply
2368/// operations. This allows them to be analyzed by regular SCEV code.
2369///
Dan Gohman161ea032009-07-07 17:06:11 +00002370const SCEV *ScalarEvolution::createNodeForGEP(User *GEP) {
Dan Gohman509cf4d2009-05-08 20:26:55 +00002371
2372 const Type *IntPtrTy = TD->getIntPtrType();
Dan Gohmanc7034fa2009-05-08 20:36:47 +00002373 Value *Base = GEP->getOperand(0);
Dan Gohmand586a4f2009-05-09 00:14:52 +00002374 // Don't attempt to analyze GEPs over unsized objects.
2375 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2376 return getUnknown(GEP);
Dan Gohman161ea032009-07-07 17:06:11 +00002377 const SCEV *TotalOffset = getIntegerSCEV(0, IntPtrTy);
Dan Gohmanc7034fa2009-05-08 20:36:47 +00002378 gep_type_iterator GTI = gep_type_begin(GEP);
2379 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
2380 E = GEP->op_end();
Dan Gohman509cf4d2009-05-08 20:26:55 +00002381 I != E; ++I) {
2382 Value *Index = *I;
2383 // Compute the (potentially symbolic) offset in bytes for this index.
2384 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2385 // For a struct, add the member offset.
2386 const StructLayout &SL = *TD->getStructLayout(STy);
2387 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
2388 uint64_t Offset = SL.getElementOffset(FieldNo);
Nick Lewycky9425be92009-07-11 20:38:25 +00002389 TotalOffset = getAddExpr(TotalOffset,
2390 getIntegerSCEV(Offset, IntPtrTy));
Dan Gohman509cf4d2009-05-08 20:26:55 +00002391 } else {
2392 // For an array, add the element offset, explicitly scaled.
Dan Gohman161ea032009-07-07 17:06:11 +00002393 const SCEV *LocalOffset = getSCEV(Index);
Dan Gohman509cf4d2009-05-08 20:26:55 +00002394 if (!isa<PointerType>(LocalOffset->getType()))
2395 // Getelementptr indicies are signed.
Nick Lewycky9425be92009-07-11 20:38:25 +00002396 LocalOffset = getTruncateOrSignExtend(LocalOffset,
2397 IntPtrTy);
Dan Gohman509cf4d2009-05-08 20:26:55 +00002398 LocalOffset =
2399 getMulExpr(LocalOffset,
Nick Lewycky9425be92009-07-11 20:38:25 +00002400 getIntegerSCEV(TD->getTypeAllocSize(*GTI),
2401 IntPtrTy));
Dan Gohman509cf4d2009-05-08 20:26:55 +00002402 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
2403 }
2404 }
2405 return getAddExpr(getSCEV(Base), TotalOffset);
2406}
2407
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002408/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2409/// guaranteed to end in (at every loop iteration). It is, at the same time,
2410/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2411/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohman6e923a72009-06-19 23:29:04 +00002412uint32_t
Dan Gohman161ea032009-07-07 17:06:11 +00002413ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00002414 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner6ecce2a2007-11-23 22:36:49 +00002415 return C->getValue()->getValue().countTrailingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002416
Dan Gohmanc76b5452009-05-04 22:02:23 +00002417 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohman6e923a72009-06-19 23:29:04 +00002418 return std::min(GetMinTrailingZeros(T->getOperand()),
2419 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002420
Dan Gohmanc76b5452009-05-04 22:02:23 +00002421 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohman6e923a72009-06-19 23:29:04 +00002422 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2423 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2424 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002425 }
2426
Dan Gohmanc76b5452009-05-04 22:02:23 +00002427 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohman6e923a72009-06-19 23:29:04 +00002428 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2429 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2430 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002431 }
2432
Dan Gohmanc76b5452009-05-04 22:02:23 +00002433 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002434 // The result is the min of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002435 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002436 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002437 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002438 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002439 }
2440
Dan Gohmanc76b5452009-05-04 22:02:23 +00002441 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002442 // The result is the sum of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002443 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2444 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002445 for (unsigned i = 1, e = M->getNumOperands();
2446 SumOpRes != BitWidth && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002447 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002448 BitWidth);
2449 return SumOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002450 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002451
Dan Gohmanc76b5452009-05-04 22:02:23 +00002452 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002453 // The result is the min of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002454 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002455 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002456 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002457 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002458 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002459
Dan Gohmanc76b5452009-05-04 22:02:23 +00002460 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewycky711640a2007-11-25 22:41:31 +00002461 // The result is the min of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002462 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky711640a2007-11-25 22:41:31 +00002463 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002464 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky711640a2007-11-25 22:41:31 +00002465 return MinOpRes;
2466 }
2467
Dan Gohmanc76b5452009-05-04 22:02:23 +00002468 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002469 // The result is the min of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002470 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002471 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002472 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002473 return MinOpRes;
2474 }
2475
Dan Gohman6e923a72009-06-19 23:29:04 +00002476 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2477 // For a SCEVUnknown, ask ValueTracking.
2478 unsigned BitWidth = getTypeSizeInBits(U->getType());
2479 APInt Mask = APInt::getAllOnesValue(BitWidth);
2480 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2481 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2482 return Zeros.countTrailingOnes();
2483 }
2484
2485 // SCEVUDivExpr
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002486 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002487}
2488
Nick Lewycky9425be92009-07-11 20:38:25 +00002489uint32_t
2490ScalarEvolution::GetMinLeadingZeros(const SCEV *S) {
2491 // TODO: Handle other SCEV expression types here.
Dan Gohman6e923a72009-06-19 23:29:04 +00002492
2493 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Nick Lewycky9425be92009-07-11 20:38:25 +00002494 return C->getValue()->getValue().countLeadingZeros();
Dan Gohman6e923a72009-06-19 23:29:04 +00002495
Nick Lewycky9425be92009-07-11 20:38:25 +00002496 if (const SCEVZeroExtendExpr *C = dyn_cast<SCEVZeroExtendExpr>(S)) {
2497 // A zero-extension cast adds zero bits.
2498 return GetMinLeadingZeros(C->getOperand()) +
2499 (getTypeSizeInBits(C->getType()) -
2500 getTypeSizeInBits(C->getOperand()->getType()));
Dan Gohman6e923a72009-06-19 23:29:04 +00002501 }
2502
2503 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2504 // For a SCEVUnknown, ask ValueTracking.
2505 unsigned BitWidth = getTypeSizeInBits(U->getType());
2506 APInt Mask = APInt::getAllOnesValue(BitWidth);
2507 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2508 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
Nick Lewycky9425be92009-07-11 20:38:25 +00002509 return Zeros.countLeadingOnes();
Dan Gohman6e923a72009-06-19 23:29:04 +00002510 }
2511
Nick Lewycky9425be92009-07-11 20:38:25 +00002512 return 1;
Dan Gohman6e923a72009-06-19 23:29:04 +00002513}
2514
Nick Lewycky9425be92009-07-11 20:38:25 +00002515uint32_t
2516ScalarEvolution::GetMinSignBits(const SCEV *S) {
2517 // TODO: Handle other SCEV expression types here.
Dan Gohman6e923a72009-06-19 23:29:04 +00002518
Nick Lewycky9425be92009-07-11 20:38:25 +00002519 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
2520 const APInt &A = C->getValue()->getValue();
2521 return A.isNegative() ? A.countLeadingOnes() :
2522 A.countLeadingZeros();
Dan Gohman6e923a72009-06-19 23:29:04 +00002523 }
2524
Nick Lewycky9425be92009-07-11 20:38:25 +00002525 if (const SCEVSignExtendExpr *C = dyn_cast<SCEVSignExtendExpr>(S)) {
2526 // A sign-extension cast adds sign bits.
2527 return GetMinSignBits(C->getOperand()) +
2528 (getTypeSizeInBits(C->getType()) -
2529 getTypeSizeInBits(C->getOperand()->getType()));
Dan Gohman6e923a72009-06-19 23:29:04 +00002530 }
2531
Nick Lewycky9425be92009-07-11 20:38:25 +00002532 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
2533 unsigned BitWidth = getTypeSizeInBits(A->getType());
Dan Gohman61e0c4c2009-06-24 01:05:09 +00002534
Nick Lewycky9425be92009-07-11 20:38:25 +00002535 // Special case decrementing a value (ADD X, -1):
2536 if (const SCEVConstant *CRHS = dyn_cast<SCEVConstant>(A->getOperand(0)))
2537 if (CRHS->isAllOnesValue()) {
2538 SmallVector<const SCEV *, 4> OtherOps(A->op_begin() + 1, A->op_end());
2539 const SCEV *OtherOpsAdd = getAddExpr(OtherOps);
2540 unsigned LZ = GetMinLeadingZeros(OtherOpsAdd);
Dan Gohman61e0c4c2009-06-24 01:05:09 +00002541
Nick Lewycky9425be92009-07-11 20:38:25 +00002542 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2543 // sign bits set.
2544 if (LZ == BitWidth - 1)
2545 return BitWidth;
Dan Gohman61e0c4c2009-06-24 01:05:09 +00002546
Nick Lewycky9425be92009-07-11 20:38:25 +00002547 // If we are subtracting one from a positive number, there is no carry
2548 // out of the result.
2549 if (LZ > 0)
2550 return GetMinSignBits(OtherOpsAdd);
Dan Gohman61e0c4c2009-06-24 01:05:09 +00002551 }
Nick Lewycky9425be92009-07-11 20:38:25 +00002552
2553 // Add can have at most one carry bit. Thus we know that the output
2554 // is, at worst, one more bit than the inputs.
2555 unsigned Min = BitWidth;
2556 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
2557 unsigned N = GetMinSignBits(A->getOperand(i));
2558 Min = std::min(Min, N) - 1;
2559 if (Min == 0) return 1;
Dan Gohman61e0c4c2009-06-24 01:05:09 +00002560 }
Nick Lewycky9425be92009-07-11 20:38:25 +00002561 return 1;
Dan Gohman61e0c4c2009-06-24 01:05:09 +00002562 }
2563
Dan Gohman6e923a72009-06-19 23:29:04 +00002564 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2565 // For a SCEVUnknown, ask ValueTracking.
Nick Lewycky9425be92009-07-11 20:38:25 +00002566 return ComputeNumSignBits(U->getValue(), TD);
Dan Gohman6e923a72009-06-19 23:29:04 +00002567 }
2568
Nick Lewycky9425be92009-07-11 20:38:25 +00002569 return 1;
Dan Gohman6e923a72009-06-19 23:29:04 +00002570}
2571
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002572/// createSCEV - We know that there is no SCEV for the specified value.
2573/// Analyze the expression.
2574///
Dan Gohman161ea032009-07-07 17:06:11 +00002575const SCEV *ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002576 if (!isSCEVable(V->getType()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002577 return getUnknown(V);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002578
Dan Gohman3996f472008-06-22 19:56:46 +00002579 unsigned Opcode = Instruction::UserOp1;
2580 if (Instruction *I = dyn_cast<Instruction>(V))
2581 Opcode = I->getOpcode();
2582 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
2583 Opcode = CE->getOpcode();
Dan Gohman984c78a2009-06-24 00:54:57 +00002584 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2585 return getConstant(CI);
2586 else if (isa<ConstantPointerNull>(V))
2587 return getIntegerSCEV(0, V->getType());
2588 else if (isa<UndefValue>(V))
2589 return getIntegerSCEV(0, V->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002590 else
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002591 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002592
Dan Gohman3996f472008-06-22 19:56:46 +00002593 User *U = cast<User>(V);
2594 switch (Opcode) {
2595 case Instruction::Add:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002596 return getAddExpr(getSCEV(U->getOperand(0)),
2597 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002598 case Instruction::Mul:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002599 return getMulExpr(getSCEV(U->getOperand(0)),
2600 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002601 case Instruction::UDiv:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002602 return getUDivExpr(getSCEV(U->getOperand(0)),
2603 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002604 case Instruction::Sub:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002605 return getMinusSCEV(getSCEV(U->getOperand(0)),
2606 getSCEV(U->getOperand(1)));
Dan Gohman53bf64a2009-04-21 02:26:00 +00002607 case Instruction::And:
2608 // For an expression like x&255 that merely masks off the high bits,
2609 // use zext(trunc(x)) as the SCEV expression.
2610 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman91ae1e72009-04-25 17:05:40 +00002611 if (CI->isNullValue())
2612 return getSCEV(U->getOperand(1));
Dan Gohmanc7ebba12009-04-27 01:41:10 +00002613 if (CI->isAllOnesValue())
2614 return getSCEV(U->getOperand(0));
Dan Gohman53bf64a2009-04-21 02:26:00 +00002615 const APInt &A = CI->getValue();
Dan Gohmana7726c32009-06-16 19:52:01 +00002616
2617 // Instcombine's ShrinkDemandedConstant may strip bits out of
2618 // constants, obscuring what would otherwise be a low-bits mask.
2619 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
2620 // knew about to reconstruct a low-bits mask value.
2621 unsigned LZ = A.countLeadingZeros();
2622 unsigned BitWidth = A.getBitWidth();
2623 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
2624 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2625 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
2626
2627 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
2628
Dan Gohmanae1d7dd2009-06-17 23:54:37 +00002629 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
Dan Gohman53bf64a2009-04-21 02:26:00 +00002630 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002631 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
Dan Gohmana7726c32009-06-16 19:52:01 +00002632 IntegerType::get(BitWidth - LZ)),
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002633 U->getType());
Dan Gohman53bf64a2009-04-21 02:26:00 +00002634 }
2635 break;
Dan Gohmana7726c32009-06-16 19:52:01 +00002636
Dan Gohman3996f472008-06-22 19:56:46 +00002637 case Instruction::Or:
2638 // If the RHS of the Or is a constant, we may have something like:
2639 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
2640 // optimizations will transparently handle this case.
2641 //
2642 // In order for this transformation to be safe, the LHS must be of the
2643 // form X*(2^n) and the Or constant must be less than 2^n.
2644 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman161ea032009-07-07 17:06:11 +00002645 const SCEV *LHS = getSCEV(U->getOperand(0));
Dan Gohman3996f472008-06-22 19:56:46 +00002646 const APInt &CIVal = CI->getValue();
Dan Gohman6e923a72009-06-19 23:29:04 +00002647 if (GetMinTrailingZeros(LHS) >=
Dan Gohman3996f472008-06-22 19:56:46 +00002648 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002649 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002650 }
Dan Gohman3996f472008-06-22 19:56:46 +00002651 break;
2652 case Instruction::Xor:
Dan Gohman3996f472008-06-22 19:56:46 +00002653 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky7fd27892008-07-07 06:15:49 +00002654 // If the RHS of the xor is a signbit, then this is just an add.
2655 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman3996f472008-06-22 19:56:46 +00002656 if (CI->getValue().isSignBit())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002657 return getAddExpr(getSCEV(U->getOperand(0)),
2658 getSCEV(U->getOperand(1)));
Nick Lewycky7fd27892008-07-07 06:15:49 +00002659
2660 // If the RHS of xor is -1, then this is a not operation.
Dan Gohmanc897f752009-05-18 16:17:44 +00002661 if (CI->isAllOnesValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002662 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohmanfc78cff2009-05-18 16:29:04 +00002663
2664 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
2665 // This is a variant of the check for xor with -1, and it handles
2666 // the case where instcombine has trimmed non-demanded bits out
2667 // of an xor with -1.
2668 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
2669 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
2670 if (BO->getOpcode() == Instruction::And &&
2671 LCI->getValue() == CI->getValue())
2672 if (const SCEVZeroExtendExpr *Z =
Dan Gohmane49ae432009-06-17 01:22:39 +00002673 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
Dan Gohmaned1d8bb2009-06-18 00:00:20 +00002674 const Type *UTy = U->getType();
Dan Gohman161ea032009-07-07 17:06:11 +00002675 const SCEV *Z0 = Z->getOperand();
Dan Gohmaned1d8bb2009-06-18 00:00:20 +00002676 const Type *Z0Ty = Z0->getType();
2677 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
2678
2679 // If C is a low-bits mask, the zero extend is zerving to
2680 // mask off the high bits. Complement the operand and
2681 // re-apply the zext.
2682 if (APIntOps::isMask(Z0TySize, CI->getValue()))
2683 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
2684
2685 // If C is a single bit, it may be in the sign-bit position
2686 // before the zero-extend. In this case, represent the xor
2687 // using an add, which is equivalent, and re-apply the zext.
2688 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
2689 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
2690 Trunc.isSignBit())
2691 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
2692 UTy);
Dan Gohmane49ae432009-06-17 01:22:39 +00002693 }
Dan Gohman3996f472008-06-22 19:56:46 +00002694 }
2695 break;
2696
2697 case Instruction::Shl:
2698 // Turn shift left of a constant amount into a multiply.
2699 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2700 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2701 Constant *X = ConstantInt::get(
2702 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002703 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman3996f472008-06-22 19:56:46 +00002704 }
2705 break;
2706
Nick Lewycky7fd27892008-07-07 06:15:49 +00002707 case Instruction::LShr:
Nick Lewycky35b56022009-01-13 09:18:58 +00002708 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky7fd27892008-07-07 06:15:49 +00002709 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2710 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2711 Constant *X = ConstantInt::get(
2712 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002713 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky7fd27892008-07-07 06:15:49 +00002714 }
2715 break;
2716
Dan Gohman53bf64a2009-04-21 02:26:00 +00002717 case Instruction::AShr:
2718 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
2719 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
2720 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
2721 if (L->getOpcode() == Instruction::Shl &&
2722 L->getOperand(1) == U->getOperand(1)) {
Dan Gohman91ae1e72009-04-25 17:05:40 +00002723 unsigned BitWidth = getTypeSizeInBits(U->getType());
2724 uint64_t Amt = BitWidth - CI->getZExtValue();
2725 if (Amt == BitWidth)
2726 return getSCEV(L->getOperand(0)); // shift by zero --> noop
2727 if (Amt > BitWidth)
2728 return getIntegerSCEV(0, U->getType()); // value is undefined
Dan Gohman53bf64a2009-04-21 02:26:00 +00002729 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002730 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohman91ae1e72009-04-25 17:05:40 +00002731 IntegerType::get(Amt)),
Dan Gohman53bf64a2009-04-21 02:26:00 +00002732 U->getType());
2733 }
2734 break;
2735
Dan Gohman3996f472008-06-22 19:56:46 +00002736 case Instruction::Trunc:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002737 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002738
2739 case Instruction::ZExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002740 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002741
2742 case Instruction::SExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002743 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002744
2745 case Instruction::BitCast:
2746 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002747 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman3996f472008-06-22 19:56:46 +00002748 return getSCEV(U->getOperand(0));
2749 break;
2750
Dan Gohman01c2ee72009-04-16 03:18:22 +00002751 case Instruction::IntToPtr:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002752 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00002753 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002754 TD->getIntPtrType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00002755
2756 case Instruction::PtrToInt:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002757 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00002758 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
2759 U->getType());
2760
Dan Gohman509cf4d2009-05-08 20:26:55 +00002761 case Instruction::GetElementPtr:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002762 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohmanca5a39e2009-05-08 20:58:38 +00002763 return createNodeForGEP(U);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002764
Dan Gohman3996f472008-06-22 19:56:46 +00002765 case Instruction::PHI:
2766 return createNodeForPHI(cast<PHINode>(U));
2767
2768 case Instruction::Select:
2769 // This could be a smax or umax that was lowered earlier.
2770 // Try to recover it.
2771 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2772 Value *LHS = ICI->getOperand(0);
2773 Value *RHS = ICI->getOperand(1);
2774 switch (ICI->getPredicate()) {
2775 case ICmpInst::ICMP_SLT:
2776 case ICmpInst::ICMP_SLE:
2777 std::swap(LHS, RHS);
2778 // fall through
2779 case ICmpInst::ICMP_SGT:
2780 case ICmpInst::ICMP_SGE:
2781 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002782 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002783 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmand01fff82009-06-22 03:18:45 +00002784 return getSMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002785 break;
2786 case ICmpInst::ICMP_ULT:
2787 case ICmpInst::ICMP_ULE:
2788 std::swap(LHS, RHS);
2789 // fall through
2790 case ICmpInst::ICMP_UGT:
2791 case ICmpInst::ICMP_UGE:
2792 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002793 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002794 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmand01fff82009-06-22 03:18:45 +00002795 return getUMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002796 break;
Dan Gohmanf27dc692009-06-18 20:21:07 +00002797 case ICmpInst::ICMP_NE:
2798 // n != 0 ? n : 1 -> umax(n, 1)
2799 if (LHS == U->getOperand(1) &&
2800 isa<ConstantInt>(U->getOperand(2)) &&
2801 cast<ConstantInt>(U->getOperand(2))->isOne() &&
2802 isa<ConstantInt>(RHS) &&
2803 cast<ConstantInt>(RHS)->isZero())
2804 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(2)));
2805 break;
2806 case ICmpInst::ICMP_EQ:
2807 // n == 0 ? 1 : n -> umax(n, 1)
2808 if (LHS == U->getOperand(2) &&
2809 isa<ConstantInt>(U->getOperand(1)) &&
2810 cast<ConstantInt>(U->getOperand(1))->isOne() &&
2811 isa<ConstantInt>(RHS) &&
2812 cast<ConstantInt>(RHS)->isZero())
2813 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(1)));
2814 break;
Dan Gohman3996f472008-06-22 19:56:46 +00002815 default:
2816 break;
2817 }
2818 }
2819
2820 default: // We cannot analyze this expression.
2821 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002822 }
2823
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002824 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002825}
2826
2827
2828
2829//===----------------------------------------------------------------------===//
2830// Iteration Count Computation Code
2831//
2832
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002833/// getBackedgeTakenCount - If the specified loop has a predictable
2834/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
2835/// object. The backedge-taken count is the number of times the loop header
2836/// will be branched to from within the loop. This is one less than the
2837/// trip count of the loop, since it doesn't count the first iteration,
2838/// when the header is branched to from outside the loop.
2839///
2840/// Note that it is not valid to call this method on a loop without a
2841/// loop-invariant backedge-taken count (see
2842/// hasLoopInvariantBackedgeTakenCount).
2843///
Dan Gohman161ea032009-07-07 17:06:11 +00002844const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002845 return getBackedgeTakenInfo(L).Exact;
2846}
2847
2848/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
2849/// return the least SCEV value that is known never to be less than the
2850/// actual backedge taken count.
Dan Gohman161ea032009-07-07 17:06:11 +00002851const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002852 return getBackedgeTakenInfo(L).Max;
2853}
2854
Dan Gohmanb7d04aa2009-07-08 19:23:34 +00002855/// PushLoopPHIs - Push PHI nodes in the header of the given loop
2856/// onto the given Worklist.
2857static void
2858PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
2859 BasicBlock *Header = L->getHeader();
2860
2861 // Push all Loop-header PHIs onto the Worklist stack.
2862 for (BasicBlock::iterator I = Header->begin();
2863 PHINode *PN = dyn_cast<PHINode>(I); ++I)
2864 Worklist.push_back(PN);
2865}
2866
2867/// PushDefUseChildren - Push users of the given Instruction
2868/// onto the given Worklist.
2869static void
2870PushDefUseChildren(Instruction *I,
2871 SmallVectorImpl<Instruction *> &Worklist) {
2872 // Push the def-use children onto the Worklist stack.
2873 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2874 UI != UE; ++UI)
2875 Worklist.push_back(cast<Instruction>(UI));
2876}
2877
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002878const ScalarEvolution::BackedgeTakenInfo &
2879ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohmana9dba962009-04-27 20:16:15 +00002880 // Initially insert a CouldNotCompute for this loop. If the insertion
2881 // succeeds, procede to actually compute a backedge-taken count and
2882 // update the value. The temporary CouldNotCompute value tells SCEV
2883 // code elsewhere that it shouldn't attempt to request a new
2884 // backedge-taken count, which could result in infinite recursion.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002885 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohmana9dba962009-04-27 20:16:15 +00002886 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
2887 if (Pair.second) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002888 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00002889 if (ItCount.Exact != getCouldNotCompute()) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002890 assert(ItCount.Exact->isLoopInvariant(L) &&
2891 ItCount.Max->isLoopInvariant(L) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002892 "Computed trip count isn't loop invariant for loop!");
2893 ++NumTripCountsComputed;
Dan Gohmana9dba962009-04-27 20:16:15 +00002894
Dan Gohmana9dba962009-04-27 20:16:15 +00002895 // Update the value in the map.
2896 Pair.first->second = ItCount;
Dan Gohman8e8b5232009-06-22 00:31:57 +00002897 } else {
Dan Gohmanc6475cb2009-06-27 21:21:31 +00002898 if (ItCount.Max != getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00002899 // Update the value in the map.
2900 Pair.first->second = ItCount;
2901 if (isa<PHINode>(L->getHeader()->begin()))
2902 // Only count loops that have phi nodes as not being computable.
2903 ++NumTripCountsNotComputed;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002904 }
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002905
2906 // Now that we know more about the trip count for this loop, forget any
2907 // existing SCEV values for PHI nodes in this loop since they are only
Dan Gohmanb7d04aa2009-07-08 19:23:34 +00002908 // conservative estimates made without the benefit of trip count
2909 // information. This is similar to the code in
2910 // forgetLoopBackedgeTakenCount, except that it handles SCEVUnknown PHI
2911 // nodes specially.
2912 if (ItCount.hasAnyInfo()) {
2913 SmallVector<Instruction *, 16> Worklist;
2914 PushLoopPHIs(L, Worklist);
2915
2916 SmallPtrSet<Instruction *, 8> Visited;
2917 while (!Worklist.empty()) {
2918 Instruction *I = Worklist.pop_back_val();
2919 if (!Visited.insert(I)) continue;
2920
2921 std::map<SCEVCallbackVH, const SCEV*>::iterator It =
2922 Scalars.find(static_cast<Value *>(I));
2923 if (It != Scalars.end()) {
2924 // SCEVUnknown for a PHI either means that it has an unrecognized
2925 // structure, or it's a PHI that's in the progress of being computed
2926 // by createNodeForPHI. In the former case, additional loop trip count
2927 // information isn't going to change anything. In the later case,
2928 // createNodeForPHI will perform the necessary updates on its own when
2929 // it gets to that point.
2930 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(It->second))
2931 Scalars.erase(It);
2932 ValuesAtScopes.erase(I);
2933 if (PHINode *PN = dyn_cast<PHINode>(I))
2934 ConstantEvolutionLoopExitValue.erase(PN);
2935 }
2936
2937 PushDefUseChildren(I, Worklist);
2938 }
2939 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002940 }
Dan Gohmana9dba962009-04-27 20:16:15 +00002941 return Pair.first->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002942}
2943
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002944/// forgetLoopBackedgeTakenCount - This method should be called by the
Dan Gohmanf3a060a2009-02-17 20:49:49 +00002945/// client when it has changed a loop in a way that may effect
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002946/// ScalarEvolution's ability to compute a trip count, or if the loop
2947/// is deleted.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002948void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002949 BackedgeTakenCounts.erase(L);
Dan Gohman94623022009-05-02 17:43:35 +00002950
Dan Gohmanbff6b582009-05-04 22:30:44 +00002951 SmallVector<Instruction *, 16> Worklist;
Dan Gohmanb7d04aa2009-07-08 19:23:34 +00002952 PushLoopPHIs(L, Worklist);
Dan Gohmanbff6b582009-05-04 22:30:44 +00002953
Dan Gohmanb7d04aa2009-07-08 19:23:34 +00002954 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohmanbff6b582009-05-04 22:30:44 +00002955 while (!Worklist.empty()) {
2956 Instruction *I = Worklist.pop_back_val();
Dan Gohmanb7d04aa2009-07-08 19:23:34 +00002957 if (!Visited.insert(I)) continue;
2958
2959 std::map<SCEVCallbackVH, const SCEV*>::iterator It =
2960 Scalars.find(static_cast<Value *>(I));
2961 if (It != Scalars.end()) {
2962 Scalars.erase(It);
2963 ValuesAtScopes.erase(I);
2964 if (PHINode *PN = dyn_cast<PHINode>(I))
2965 ConstantEvolutionLoopExitValue.erase(PN);
2966 }
2967
2968 PushDefUseChildren(I, Worklist);
Dan Gohmanbff6b582009-05-04 22:30:44 +00002969 }
Dan Gohmanf3a060a2009-02-17 20:49:49 +00002970}
2971
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002972/// ComputeBackedgeTakenCount - Compute the number of times the backedge
2973/// of the specified loop will execute.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002974ScalarEvolution::BackedgeTakenInfo
2975ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohman8e8b5232009-06-22 00:31:57 +00002976 SmallVector<BasicBlock*, 8> ExitingBlocks;
2977 L->getExitingBlocks(ExitingBlocks);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002978
Dan Gohman8e8b5232009-06-22 00:31:57 +00002979 // Examine all exits and pick the most conservative values.
Dan Gohman161ea032009-07-07 17:06:11 +00002980 const SCEV *BECount = getCouldNotCompute();
2981 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohman8e8b5232009-06-22 00:31:57 +00002982 bool CouldNotComputeBECount = false;
Dan Gohman8e8b5232009-06-22 00:31:57 +00002983 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
2984 BackedgeTakenInfo NewBTI =
2985 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002986
Dan Gohmanc6475cb2009-06-27 21:21:31 +00002987 if (NewBTI.Exact == getCouldNotCompute()) {
Dan Gohman8e8b5232009-06-22 00:31:57 +00002988 // We couldn't compute an exact value for this exit, so
Dan Gohmanc6e8c832009-06-22 21:10:22 +00002989 // we won't be able to compute an exact value for the loop.
Dan Gohman8e8b5232009-06-22 00:31:57 +00002990 CouldNotComputeBECount = true;
Dan Gohmanc6475cb2009-06-27 21:21:31 +00002991 BECount = getCouldNotCompute();
Dan Gohman8e8b5232009-06-22 00:31:57 +00002992 } else if (!CouldNotComputeBECount) {
Dan Gohmanc6475cb2009-06-27 21:21:31 +00002993 if (BECount == getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00002994 BECount = NewBTI.Exact;
Dan Gohman8e8b5232009-06-22 00:31:57 +00002995 else
Dan Gohman423ed6c2009-06-24 01:18:18 +00002996 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
Dan Gohman8e8b5232009-06-22 00:31:57 +00002997 }
Dan Gohmanc6475cb2009-06-27 21:21:31 +00002998 if (MaxBECount == getCouldNotCompute())
Dan Gohman423ed6c2009-06-24 01:18:18 +00002999 MaxBECount = NewBTI.Max;
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003000 else if (NewBTI.Max != getCouldNotCompute())
Dan Gohman423ed6c2009-06-24 01:18:18 +00003001 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
Dan Gohman8e8b5232009-06-22 00:31:57 +00003002 }
3003
3004 return BackedgeTakenInfo(BECount, MaxBECount);
3005}
3006
3007/// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
3008/// of the specified loop will execute if it exits via the specified block.
3009ScalarEvolution::BackedgeTakenInfo
3010ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
3011 BasicBlock *ExitingBlock) {
3012
3013 // Okay, we've chosen an exiting block. See what condition causes us to
3014 // exit at this block.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003015 //
3016 // FIXME: we should be able to handle switch instructions (with a single exit)
3017 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003018 if (ExitBr == 0) return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003019 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Dan Gohman9bc642f2009-06-24 04:48:43 +00003020
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003021 // At this point, we know we have a conditional branch that determines whether
3022 // the loop is exited. However, we don't know if the branch is executed each
3023 // time through the loop. If not, then the execution count of the branch will
3024 // not be equal to the trip count of the loop.
3025 //
3026 // Currently we check for this by checking to see if the Exit branch goes to
3027 // the loop header. If so, we know it will always execute the same number of
3028 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohman8e8b5232009-06-22 00:31:57 +00003029 // loop header. This is common for un-rotated loops.
3030 //
3031 // If both of those tests fail, walk up the unique predecessor chain to the
3032 // header, stopping if there is an edge that doesn't exit the loop. If the
3033 // header is reached, the execution count of the branch will be equal to the
3034 // trip count of the loop.
3035 //
3036 // More extensive analysis could be done to handle more cases here.
3037 //
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003038 if (ExitBr->getSuccessor(0) != L->getHeader() &&
3039 ExitBr->getSuccessor(1) != L->getHeader() &&
Dan Gohman8e8b5232009-06-22 00:31:57 +00003040 ExitBr->getParent() != L->getHeader()) {
3041 // The simple checks failed, try climbing the unique predecessor chain
3042 // up to the header.
3043 bool Ok = false;
3044 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
3045 BasicBlock *Pred = BB->getUniquePredecessor();
3046 if (!Pred)
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003047 return getCouldNotCompute();
Dan Gohman8e8b5232009-06-22 00:31:57 +00003048 TerminatorInst *PredTerm = Pred->getTerminator();
3049 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
3050 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
3051 if (PredSucc == BB)
3052 continue;
3053 // If the predecessor has a successor that isn't BB and isn't
3054 // outside the loop, assume the worst.
3055 if (L->contains(PredSucc))
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003056 return getCouldNotCompute();
Dan Gohman8e8b5232009-06-22 00:31:57 +00003057 }
3058 if (Pred == L->getHeader()) {
3059 Ok = true;
3060 break;
3061 }
3062 BB = Pred;
3063 }
3064 if (!Ok)
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003065 return getCouldNotCompute();
Dan Gohman8e8b5232009-06-22 00:31:57 +00003066 }
3067
3068 // Procede to the next level to examine the exit condition expression.
3069 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
3070 ExitBr->getSuccessor(0),
3071 ExitBr->getSuccessor(1));
3072}
3073
3074/// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
3075/// backedge of the specified loop will execute if its exit condition
3076/// were a conditional branch of ExitCond, TBB, and FBB.
3077ScalarEvolution::BackedgeTakenInfo
3078ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
3079 Value *ExitCond,
3080 BasicBlock *TBB,
3081 BasicBlock *FBB) {
Dan Gohman423ed6c2009-06-24 01:18:18 +00003082 // Check if the controlling expression for this loop is an And or Or.
Dan Gohman8e8b5232009-06-22 00:31:57 +00003083 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
3084 if (BO->getOpcode() == Instruction::And) {
3085 // Recurse on the operands of the and.
3086 BackedgeTakenInfo BTI0 =
3087 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3088 BackedgeTakenInfo BTI1 =
3089 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman161ea032009-07-07 17:06:11 +00003090 const SCEV *BECount = getCouldNotCompute();
3091 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohman8e8b5232009-06-22 00:31:57 +00003092 if (L->contains(TBB)) {
3093 // Both conditions must be true for the loop to continue executing.
3094 // Choose the less conservative count.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003095 if (BTI0.Exact == getCouldNotCompute() ||
3096 BTI1.Exact == getCouldNotCompute())
3097 BECount = getCouldNotCompute();
Dan Gohmanac958b32009-06-22 15:09:28 +00003098 else
3099 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003100 if (BTI0.Max == getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003101 MaxBECount = BTI1.Max;
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003102 else if (BTI1.Max == getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003103 MaxBECount = BTI0.Max;
Dan Gohmanac958b32009-06-22 15:09:28 +00003104 else
3105 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohman8e8b5232009-06-22 00:31:57 +00003106 } else {
3107 // Both conditions must be true for the loop to exit.
3108 assert(L->contains(FBB) && "Loop block has no successor in loop!");
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003109 if (BTI0.Exact != getCouldNotCompute() &&
3110 BTI1.Exact != getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003111 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003112 if (BTI0.Max != getCouldNotCompute() &&
3113 BTI1.Max != getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003114 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3115 }
3116
3117 return BackedgeTakenInfo(BECount, MaxBECount);
3118 }
3119 if (BO->getOpcode() == Instruction::Or) {
3120 // Recurse on the operands of the or.
3121 BackedgeTakenInfo BTI0 =
3122 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3123 BackedgeTakenInfo BTI1 =
3124 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman161ea032009-07-07 17:06:11 +00003125 const SCEV *BECount = getCouldNotCompute();
3126 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohman8e8b5232009-06-22 00:31:57 +00003127 if (L->contains(FBB)) {
3128 // Both conditions must be false for the loop to continue executing.
3129 // Choose the less conservative count.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003130 if (BTI0.Exact == getCouldNotCompute() ||
3131 BTI1.Exact == getCouldNotCompute())
3132 BECount = getCouldNotCompute();
Dan Gohmanac958b32009-06-22 15:09:28 +00003133 else
3134 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003135 if (BTI0.Max == getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003136 MaxBECount = BTI1.Max;
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003137 else if (BTI1.Max == getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003138 MaxBECount = BTI0.Max;
Dan Gohmanac958b32009-06-22 15:09:28 +00003139 else
3140 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohman8e8b5232009-06-22 00:31:57 +00003141 } else {
3142 // Both conditions must be false for the loop to exit.
3143 assert(L->contains(TBB) && "Loop block has no successor in loop!");
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003144 if (BTI0.Exact != getCouldNotCompute() &&
3145 BTI1.Exact != getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003146 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003147 if (BTI0.Max != getCouldNotCompute() &&
3148 BTI1.Max != getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003149 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3150 }
3151
3152 return BackedgeTakenInfo(BECount, MaxBECount);
3153 }
3154 }
3155
3156 // With an icmp, it may be feasible to compute an exact backedge-taken count.
3157 // Procede to the next level to examine the icmp.
3158 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
3159 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003160
Eli Friedman459d7292009-05-09 12:32:42 +00003161 // If it's not an integer or pointer comparison then compute it the hard way.
Dan Gohman8e8b5232009-06-22 00:31:57 +00003162 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3163}
3164
3165/// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
3166/// backedge of the specified loop will execute if its exit condition
3167/// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
3168ScalarEvolution::BackedgeTakenInfo
3169ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
3170 ICmpInst *ExitCond,
3171 BasicBlock *TBB,
3172 BasicBlock *FBB) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003173
3174 // If the condition was exit on true, convert the condition to exit on false
3175 ICmpInst::Predicate Cond;
Dan Gohman8e8b5232009-06-22 00:31:57 +00003176 if (!L->contains(FBB))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003177 Cond = ExitCond->getPredicate();
3178 else
3179 Cond = ExitCond->getInversePredicate();
3180
3181 // Handle common loops like: for (X = "string"; *X; ++X)
3182 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
3183 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Dan Gohman161ea032009-07-07 17:06:11 +00003184 const SCEV *ItCnt =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003185 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohman8e8b5232009-06-22 00:31:57 +00003186 if (!isa<SCEVCouldNotCompute>(ItCnt)) {
3187 unsigned BitWidth = getTypeSizeInBits(ItCnt->getType());
3188 return BackedgeTakenInfo(ItCnt,
3189 isa<SCEVConstant>(ItCnt) ? ItCnt :
3190 getConstant(APInt::getMaxValue(BitWidth)-1));
3191 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003192 }
3193
Dan Gohman161ea032009-07-07 17:06:11 +00003194 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
3195 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003196
3197 // Try to evaluate any dependencies out of the loop.
Dan Gohmanaff14d62009-05-24 23:25:42 +00003198 LHS = getSCEVAtScope(LHS, L);
3199 RHS = getSCEVAtScope(RHS, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003200
Dan Gohman9bc642f2009-06-24 04:48:43 +00003201 // At this point, we would like to compute how many iterations of the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003202 // loop the predicate will return true for these inputs.
Dan Gohman2d96e352008-09-16 18:52:57 +00003203 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
3204 // If there is a loop-invariant, force it into the RHS.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003205 std::swap(LHS, RHS);
3206 Cond = ICmpInst::getSwappedPredicate(Cond);
3207 }
3208
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003209 // If we have a comparison of a chrec against a constant, try to use value
3210 // ranges to answer this query.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003211 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
3212 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003213 if (AddRec->getLoop() == L) {
Eli Friedman459d7292009-05-09 12:32:42 +00003214 // Form the constant range.
3215 ConstantRange CompRange(
3216 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003217
Dan Gohman161ea032009-07-07 17:06:11 +00003218 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedman459d7292009-05-09 12:32:42 +00003219 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003220 }
3221
3222 switch (Cond) {
3223 case ICmpInst::ICMP_NE: { // while (X != Y)
3224 // Convert to: while (X-Y != 0)
Dan Gohman161ea032009-07-07 17:06:11 +00003225 const SCEV *TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003226 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
3227 break;
3228 }
3229 case ICmpInst::ICMP_EQ: {
3230 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohman161ea032009-07-07 17:06:11 +00003231 const SCEV *TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003232 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
3233 break;
3234 }
3235 case ICmpInst::ICMP_SLT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003236 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
3237 if (BTI.hasAnyInfo()) return BTI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003238 break;
3239 }
3240 case ICmpInst::ICMP_SGT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003241 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3242 getNotSCEV(RHS), L, true);
3243 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyb7c28942007-08-06 19:21:00 +00003244 break;
3245 }
3246 case ICmpInst::ICMP_ULT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003247 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
3248 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyb7c28942007-08-06 19:21:00 +00003249 break;
3250 }
3251 case ICmpInst::ICMP_UGT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003252 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3253 getNotSCEV(RHS), L, false);
3254 if (BTI.hasAnyInfo()) return BTI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003255 break;
3256 }
3257 default:
3258#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00003259 errs() << "ComputeBackedgeTakenCount ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003260 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Dan Gohman13058cc2009-04-21 00:47:46 +00003261 errs() << "[unsigned] ";
3262 errs() << *LHS << " "
Dan Gohman9bc642f2009-06-24 04:48:43 +00003263 << Instruction::getOpcodeName(Instruction::ICmp)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003264 << " " << *RHS << "\n";
3265#endif
3266 break;
3267 }
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003268 return
Dan Gohman8e8b5232009-06-22 00:31:57 +00003269 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003270}
3271
3272static ConstantInt *
Dan Gohman89f85052007-10-22 18:31:58 +00003273EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
3274 ScalarEvolution &SE) {
Dan Gohman161ea032009-07-07 17:06:11 +00003275 const SCEV *InVal = SE.getConstant(C);
3276 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003277 assert(isa<SCEVConstant>(Val) &&
3278 "Evaluation of SCEV at constant didn't fold correctly?");
3279 return cast<SCEVConstant>(Val)->getValue();
3280}
3281
3282/// GetAddressedElementFromGlobal - Given a global variable with an initializer
3283/// and a GEP expression (missing the pointer index) indexing into it, return
3284/// the addressed element of the initializer or null if the index expression is
3285/// invalid.
3286static Constant *
3287GetAddressedElementFromGlobal(GlobalVariable *GV,
3288 const std::vector<ConstantInt*> &Indices) {
3289 Constant *Init = GV->getInitializer();
3290 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
3291 uint64_t Idx = Indices[i]->getZExtValue();
3292 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
3293 assert(Idx < CS->getNumOperands() && "Bad struct index!");
3294 Init = cast<Constant>(CS->getOperand(Idx));
3295 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
3296 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
3297 Init = cast<Constant>(CA->getOperand(Idx));
3298 } else if (isa<ConstantAggregateZero>(Init)) {
3299 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
3300 assert(Idx < STy->getNumElements() && "Bad struct index!");
3301 Init = Constant::getNullValue(STy->getElementType(Idx));
3302 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
3303 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
3304 Init = Constant::getNullValue(ATy->getElementType());
3305 } else {
Edwin Török675d5622009-07-11 20:10:48 +00003306 LLVM_UNREACHABLE("Unknown constant aggregate type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003307 }
3308 return 0;
3309 } else {
3310 return 0; // Unknown initializer type
3311 }
3312 }
3313 return Init;
3314}
3315
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003316/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
3317/// 'icmp op load X, cst', try to see if we can compute the backedge
3318/// execution count.
Dan Gohman9bc642f2009-06-24 04:48:43 +00003319const SCEV *
3320ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
3321 LoadInst *LI,
3322 Constant *RHS,
3323 const Loop *L,
3324 ICmpInst::Predicate predicate) {
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003325 if (LI->isVolatile()) return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003326
3327 // Check to see if the loaded pointer is a getelementptr of a global.
3328 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003329 if (!GEP) return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003330
3331 // Make sure that it is really a constant global we are gepping, with an
3332 // initializer, and make sure the first IDX is really 0.
3333 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
3334 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
3335 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
3336 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003337 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003338
3339 // Okay, we allow one non-constant index into the GEP instruction.
3340 Value *VarIdx = 0;
3341 std::vector<ConstantInt*> Indexes;
3342 unsigned VarIdxNum = 0;
3343 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
3344 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
3345 Indexes.push_back(CI);
3346 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003347 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003348 VarIdx = GEP->getOperand(i);
3349 VarIdxNum = i-2;
3350 Indexes.push_back(0);
3351 }
3352
3353 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
3354 // Check to see if X is a loop variant variable value now.
Dan Gohman161ea032009-07-07 17:06:11 +00003355 const SCEV *Idx = getSCEV(VarIdx);
Dan Gohmanaff14d62009-05-24 23:25:42 +00003356 Idx = getSCEVAtScope(Idx, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003357
3358 // We can only recognize very limited forms of loop index expressions, in
3359 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohmanbff6b582009-05-04 22:30:44 +00003360 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003361 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
3362 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
3363 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003364 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003365
3366 unsigned MaxSteps = MaxBruteForceIterations;
3367 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
3368 ConstantInt *ItCst =
Dan Gohman8fd520a2009-06-15 22:12:54 +00003369 ConstantInt::get(cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003370 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003371
3372 // Form the GEP offset.
3373 Indexes[VarIdxNum] = Val;
3374
3375 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
3376 if (Result == 0) break; // Cannot compute!
3377
3378 // Evaluate the condition for this iteration.
3379 Result = ConstantExpr::getICmp(predicate, Result, RHS);
3380 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
3381 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
3382#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00003383 errs() << "\n***\n*** Computed loop count " << *ItCst
3384 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
3385 << "***\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003386#endif
3387 ++NumArrayLenItCounts;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003388 return getConstant(ItCst); // Found terminating iteration!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003389 }
3390 }
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003391 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003392}
3393
3394
3395/// CanConstantFold - Return true if we can constant fold an instruction of the
3396/// specified type, assuming that all operands were constants.
3397static bool CanConstantFold(const Instruction *I) {
3398 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
3399 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
3400 return true;
3401
3402 if (const CallInst *CI = dyn_cast<CallInst>(I))
3403 if (const Function *F = CI->getCalledFunction())
Dan Gohmane6e001f2008-01-31 01:05:10 +00003404 return canConstantFoldCallTo(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003405 return false;
3406}
3407
3408/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
3409/// in the loop that V is derived from. We allow arbitrary operations along the
3410/// way, but the operands of an operation must either be constants or a value
3411/// derived from a constant PHI. If this expression does not fit with these
3412/// constraints, return null.
3413static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
3414 // If this is not an instruction, or if this is an instruction outside of the
3415 // loop, it can't be derived from a loop PHI.
3416 Instruction *I = dyn_cast<Instruction>(V);
3417 if (I == 0 || !L->contains(I->getParent())) return 0;
3418
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00003419 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003420 if (L->getHeader() == I->getParent())
3421 return PN;
3422 else
3423 // We don't currently keep track of the control flow needed to evaluate
3424 // PHIs, so we cannot handle PHIs inside of loops.
3425 return 0;
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00003426 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003427
3428 // If we won't be able to constant fold this expression even if the operands
3429 // are constants, return early.
3430 if (!CanConstantFold(I)) return 0;
3431
3432 // Otherwise, we can evaluate this instruction if all of its operands are
3433 // constant or derived from a PHI node themselves.
3434 PHINode *PHI = 0;
3435 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
3436 if (!(isa<Constant>(I->getOperand(Op)) ||
3437 isa<GlobalValue>(I->getOperand(Op)))) {
3438 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
3439 if (P == 0) return 0; // Not evolving from PHI
3440 if (PHI == 0)
3441 PHI = P;
3442 else if (PHI != P)
3443 return 0; // Evolving from multiple different PHIs.
3444 }
3445
3446 // This is a expression evolving from a constant PHI!
3447 return PHI;
3448}
3449
3450/// EvaluateExpression - Given an expression that passes the
3451/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
3452/// in the loop has the value PHIVal. If we can't fold this expression for some
3453/// reason, return null.
3454static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
3455 if (isa<PHINode>(V)) return PHIVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003456 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman01c2ee72009-04-16 03:18:22 +00003457 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003458 Instruction *I = cast<Instruction>(V);
Owen Anderson5349f052009-07-06 23:00:19 +00003459 LLVMContext *Context = I->getParent()->getContext();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003460
3461 std::vector<Constant*> Operands;
3462 Operands.resize(I->getNumOperands());
3463
3464 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3465 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
3466 if (Operands[i] == 0) return 0;
3467 }
3468
Chris Lattnerd6e56912007-12-10 22:53:04 +00003469 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3470 return ConstantFoldCompareInstOperands(CI->getPredicate(),
Owen Andersond4d90a02009-07-06 18:42:36 +00003471 &Operands[0], Operands.size(),
3472 Context);
Chris Lattnerd6e56912007-12-10 22:53:04 +00003473 else
3474 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Owen Andersond4d90a02009-07-06 18:42:36 +00003475 &Operands[0], Operands.size(),
3476 Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003477}
3478
3479/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
3480/// in the header of its containing loop, we know the loop executes a
3481/// constant number of times, and the PHI node is just a recurrence
3482/// involving constants, fold it.
Dan Gohman9bc642f2009-06-24 04:48:43 +00003483Constant *
3484ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
3485 const APInt& BEs,
3486 const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003487 std::map<PHINode*, Constant*>::iterator I =
3488 ConstantEvolutionLoopExitValue.find(PN);
3489 if (I != ConstantEvolutionLoopExitValue.end())
3490 return I->second;
3491
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003492 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003493 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
3494
3495 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
3496
3497 // Since the loop is canonicalized, the PHI node must have two entries. One
3498 // entry must be a constant (coming in from outside of the loop), and the
3499 // second must be derived from the same PHI.
3500 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3501 Constant *StartCST =
3502 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
3503 if (StartCST == 0)
3504 return RetVal = 0; // Must be a constant.
3505
3506 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3507 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
3508 if (PN2 != PN)
3509 return RetVal = 0; // Not derived from same PHI.
3510
3511 // Execute the loop symbolically to determine the exit value.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003512 if (BEs.getActiveBits() >= 32)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003513 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
3514
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003515 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003516 unsigned IterationNum = 0;
3517 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
3518 if (IterationNum == NumIterations)
3519 return RetVal = PHIVal; // Got exit value!
3520
3521 // Compute the value of the PHI node for the next iteration.
3522 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3523 if (NextPHI == PHIVal)
3524 return RetVal = NextPHI; // Stopped evolving!
3525 if (NextPHI == 0)
3526 return 0; // Couldn't evaluate!
3527 PHIVal = NextPHI;
3528 }
3529}
3530
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003531/// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003532/// constant number of times (the condition evolves only from constants),
3533/// try to evaluate a few iterations of the loop until we get the exit
3534/// condition gets a value of ExitWhen (true or false). If we cannot
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003535/// evaluate the trip count of the loop, return getCouldNotCompute().
Dan Gohman9bc642f2009-06-24 04:48:43 +00003536const SCEV *
3537ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
3538 Value *Cond,
3539 bool ExitWhen) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003540 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003541 if (PN == 0) return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003542
3543 // Since the loop is canonicalized, the PHI node must have two entries. One
3544 // entry must be a constant (coming in from outside of the loop), and the
3545 // second must be derived from the same PHI.
3546 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3547 Constant *StartCST =
3548 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003549 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003550
3551 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3552 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003553 if (PN2 != PN) return getCouldNotCompute(); // Not derived from same PHI.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003554
3555 // Okay, we find a PHI node that defines the trip count of this loop. Execute
3556 // the loop symbolically to determine when the condition gets a value of
3557 // "ExitWhen".
3558 unsigned IterationNum = 0;
3559 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
3560 for (Constant *PHIVal = StartCST;
3561 IterationNum != MaxIterations; ++IterationNum) {
3562 ConstantInt *CondVal =
3563 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
3564
3565 // Couldn't symbolically evaluate.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003566 if (!CondVal) return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003567
3568 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003569 ++NumBruteForceTripCountsComputed;
Dan Gohman8fd520a2009-06-15 22:12:54 +00003570 return getConstant(Type::Int32Ty, IterationNum);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003571 }
3572
3573 // Compute the value of the PHI node for the next iteration.
3574 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3575 if (NextPHI == 0 || NextPHI == PHIVal)
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003576 return getCouldNotCompute();// Couldn't evaluate or not making progress...
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003577 PHIVal = NextPHI;
3578 }
3579
3580 // Too many iterations were needed to evaluate.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003581 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003582}
3583
Dan Gohmandd40e9a2009-05-08 20:38:54 +00003584/// getSCEVAtScope - Return a SCEV expression handle for the specified value
3585/// at the specified scope in the program. The L value specifies a loop
3586/// nest to evaluate the expression at, where null is the top-level or a
3587/// specified loop is immediately inside of the loop.
3588///
3589/// This method can be used to compute the exit value for a variable defined
3590/// in a loop by querying what the value will hold in the parent loop.
3591///
Dan Gohmanaff14d62009-05-24 23:25:42 +00003592/// In the case that a relevant loop exit value cannot be computed, the
3593/// original value V is returned.
Dan Gohman161ea032009-07-07 17:06:11 +00003594const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003595 // FIXME: this should be turned into a virtual method on SCEV!
3596
3597 if (isa<SCEVConstant>(V)) return V;
3598
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00003599 // If this instruction is evolved from a constant-evolving PHI, compute the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003600 // exit value from the loop without using SCEVs.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003601 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003602 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003603 const Loop *LI = (*this->LI)[I->getParent()];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003604 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
3605 if (PHINode *PN = dyn_cast<PHINode>(I))
3606 if (PN->getParent() == LI->getHeader()) {
3607 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003608 // to see if the loop that contains it has a known backedge-taken
3609 // count. If so, we may be able to force computation of the exit
3610 // value.
Dan Gohman161ea032009-07-07 17:06:11 +00003611 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohmanc76b5452009-05-04 22:02:23 +00003612 if (const SCEVConstant *BTCC =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003613 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003614 // Okay, we know how many times the containing loop executes. If
3615 // this is a constant evolving PHI node, get the final value at
3616 // the specified iteration number.
3617 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003618 BTCC->getValue()->getValue(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003619 LI);
Dan Gohman652caf12009-06-29 21:31:18 +00003620 if (RV) return getSCEV(RV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003621 }
3622 }
3623
3624 // Okay, this is an expression that we cannot symbolically evaluate
3625 // into a SCEV. Check to see if it's possible to symbolically evaluate
3626 // the arguments into constants, and if so, try to constant propagate the
3627 // result. This is particularly useful for computing loop exit values.
3628 if (CanConstantFold(I)) {
Dan Gohmanda0071e2009-05-08 20:47:27 +00003629 // Check to see if we've folded this instruction at this loop before.
3630 std::map<const Loop *, Constant *> &Values = ValuesAtScopes[I];
3631 std::pair<std::map<const Loop *, Constant *>::iterator, bool> Pair =
3632 Values.insert(std::make_pair(L, static_cast<Constant *>(0)));
3633 if (!Pair.second)
Dan Gohman652caf12009-06-29 21:31:18 +00003634 return Pair.first->second ? &*getSCEV(Pair.first->second) : V;
Dan Gohmanda0071e2009-05-08 20:47:27 +00003635
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003636 std::vector<Constant*> Operands;
3637 Operands.reserve(I->getNumOperands());
3638 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3639 Value *Op = I->getOperand(i);
3640 if (Constant *C = dyn_cast<Constant>(Op)) {
3641 Operands.push_back(C);
3642 } else {
Chris Lattner3fff4642007-11-23 08:46:22 +00003643 // If any of the operands is non-constant and if they are
Dan Gohman01c2ee72009-04-16 03:18:22 +00003644 // non-integer and non-pointer, don't even try to analyze them
3645 // with scev techniques.
Dan Gohman5e4eb762009-04-30 16:40:30 +00003646 if (!isSCEVable(Op->getType()))
Chris Lattner3fff4642007-11-23 08:46:22 +00003647 return V;
Dan Gohman01c2ee72009-04-16 03:18:22 +00003648
Nick Lewycky9425be92009-07-11 20:38:25 +00003649 const SCEV *OpV = getSCEVAtScope(getSCEV(Op), L);
Dan Gohmanc76b5452009-05-04 22:02:23 +00003650 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
Dan Gohman5e4eb762009-04-30 16:40:30 +00003651 Constant *C = SC->getValue();
3652 if (C->getType() != Op->getType())
3653 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3654 Op->getType(),
3655 false),
3656 C, Op->getType());
3657 Operands.push_back(C);
Dan Gohmanc76b5452009-05-04 22:02:23 +00003658 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
Dan Gohman5e4eb762009-04-30 16:40:30 +00003659 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
3660 if (C->getType() != Op->getType())
3661 C =
3662 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3663 Op->getType(),
3664 false),
3665 C, Op->getType());
3666 Operands.push_back(C);
3667 } else
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003668 return V;
3669 } else {
3670 return V;
3671 }
3672 }
3673 }
Dan Gohman9bc642f2009-06-24 04:48:43 +00003674
Chris Lattnerd6e56912007-12-10 22:53:04 +00003675 Constant *C;
3676 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3677 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
Owen Andersond4d90a02009-07-06 18:42:36 +00003678 &Operands[0], Operands.size(),
3679 Context);
Chris Lattnerd6e56912007-12-10 22:53:04 +00003680 else
3681 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Owen Andersond4d90a02009-07-06 18:42:36 +00003682 &Operands[0], Operands.size(), Context);
Dan Gohmanda0071e2009-05-08 20:47:27 +00003683 Pair.first->second = C;
Dan Gohman652caf12009-06-29 21:31:18 +00003684 return getSCEV(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003685 }
3686 }
3687
3688 // This is some other type of SCEVUnknown, just return it.
3689 return V;
3690 }
3691
Dan Gohmanc76b5452009-05-04 22:02:23 +00003692 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003693 // Avoid performing the look-up in the common case where the specified
3694 // expression has no loop-variant portions.
3695 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Dan Gohman161ea032009-07-07 17:06:11 +00003696 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003697 if (OpAtScope != Comm->getOperand(i)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003698 // Okay, at least one of these operands is loop variant but might be
3699 // foldable. Build a new instance of the folded commutative expression.
Dan Gohman9bc642f2009-06-24 04:48:43 +00003700 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
3701 Comm->op_begin()+i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003702 NewOps.push_back(OpAtScope);
3703
3704 for (++i; i != e; ++i) {
3705 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003706 NewOps.push_back(OpAtScope);
3707 }
3708 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003709 return getAddExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00003710 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003711 return getMulExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00003712 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003713 return getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00003714 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003715 return getUMaxExpr(NewOps);
Edwin Török675d5622009-07-11 20:10:48 +00003716 LLVM_UNREACHABLE("Unknown commutative SCEV type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003717 }
3718 }
3719 // If we got here, all operands are loop invariant.
3720 return Comm;
3721 }
3722
Dan Gohmanc76b5452009-05-04 22:02:23 +00003723 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Dan Gohman161ea032009-07-07 17:06:11 +00003724 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
3725 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky35b56022009-01-13 09:18:58 +00003726 if (LHS == Div->getLHS() && RHS == Div->getRHS())
3727 return Div; // must be loop invariant
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003728 return getUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003729 }
3730
3731 // If this is a loop recurrence for a loop that does not contain L, then we
3732 // are dealing with the final value computed by the loop.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003733 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003734 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
3735 // To evaluate this recurrence, we need to know how many times the AddRec
3736 // loop iterates. Compute this now.
Dan Gohman161ea032009-07-07 17:06:11 +00003737 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003738 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003739
Eli Friedman7489ec92008-08-04 23:49:06 +00003740 // Then, evaluate the AddRec.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003741 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003742 }
Dan Gohmanaff14d62009-05-24 23:25:42 +00003743 return AddRec;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003744 }
3745
Dan Gohmanc76b5452009-05-04 22:02:23 +00003746 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohman161ea032009-07-07 17:06:11 +00003747 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman78d63c82009-04-29 22:29:01 +00003748 if (Op == Cast->getOperand())
3749 return Cast; // must be loop invariant
3750 return getZeroExtendExpr(Op, Cast->getType());
3751 }
3752
Dan Gohmanc76b5452009-05-04 22:02:23 +00003753 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohman161ea032009-07-07 17:06:11 +00003754 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman78d63c82009-04-29 22:29:01 +00003755 if (Op == Cast->getOperand())
3756 return Cast; // must be loop invariant
3757 return getSignExtendExpr(Op, Cast->getType());
3758 }
3759
Dan Gohmanc76b5452009-05-04 22:02:23 +00003760 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohman161ea032009-07-07 17:06:11 +00003761 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman78d63c82009-04-29 22:29:01 +00003762 if (Op == Cast->getOperand())
3763 return Cast; // must be loop invariant
3764 return getTruncateExpr(Op, Cast->getType());
3765 }
3766
Edwin Török675d5622009-07-11 20:10:48 +00003767 LLVM_UNREACHABLE("Unknown SCEV type!");
Daniel Dunbara95d96c2009-05-18 16:43:04 +00003768 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003769}
3770
Dan Gohmandd40e9a2009-05-08 20:38:54 +00003771/// getSCEVAtScope - This is a convenience function which does
3772/// getSCEVAtScope(getSCEV(V), L).
Dan Gohman161ea032009-07-07 17:06:11 +00003773const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003774 return getSCEVAtScope(getSCEV(V), L);
3775}
3776
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003777/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
3778/// following equation:
3779///
3780/// A * X = B (mod N)
3781///
3782/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
3783/// A and B isn't important.
3784///
3785/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Dan Gohman161ea032009-07-07 17:06:11 +00003786static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003787 ScalarEvolution &SE) {
3788 uint32_t BW = A.getBitWidth();
3789 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
3790 assert(A != 0 && "A must be non-zero.");
3791
3792 // 1. D = gcd(A, N)
3793 //
3794 // The gcd of A and N may have only one prime factor: 2. The number of
3795 // trailing zeros in A is its multiplicity
3796 uint32_t Mult2 = A.countTrailingZeros();
3797 // D = 2^Mult2
3798
3799 // 2. Check if B is divisible by D.
3800 //
3801 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
3802 // is not less than multiplicity of this prime factor for D.
3803 if (B.countTrailingZeros() < Mult2)
Dan Gohman0ad08b02009-04-18 17:58:19 +00003804 return SE.getCouldNotCompute();
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003805
3806 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
3807 // modulo (N / D).
3808 //
3809 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
3810 // bit width during computations.
3811 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
3812 APInt Mod(BW + 1, 0);
3813 Mod.set(BW - Mult2); // Mod = N / D
3814 APInt I = AD.multiplicativeInverse(Mod);
3815
3816 // 4. Compute the minimum unsigned root of the equation:
3817 // I * (B / D) mod (N / D)
3818 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
3819
3820 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
3821 // bits.
3822 return SE.getConstant(Result.trunc(BW));
3823}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003824
3825/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
3826/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
3827/// might be the same) or two SCEVCouldNotCompute objects.
3828///
Dan Gohman161ea032009-07-07 17:06:11 +00003829static std::pair<const SCEV *,const SCEV *>
Dan Gohman89f85052007-10-22 18:31:58 +00003830SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003831 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohmanbff6b582009-05-04 22:30:44 +00003832 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
3833 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
3834 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003835
3836 // We currently can only solve this if the coefficients are constants.
3837 if (!LC || !MC || !NC) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00003838 const SCEV *CNC = SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003839 return std::make_pair(CNC, CNC);
3840 }
3841
3842 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
3843 const APInt &L = LC->getValue()->getValue();
3844 const APInt &M = MC->getValue()->getValue();
3845 const APInt &N = NC->getValue()->getValue();
3846 APInt Two(BitWidth, 2);
3847 APInt Four(BitWidth, 4);
3848
Dan Gohman9bc642f2009-06-24 04:48:43 +00003849 {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003850 using namespace APIntOps;
3851 const APInt& C = L;
3852 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
3853 // The B coefficient is M-N/2
3854 APInt B(M);
3855 B -= sdiv(N,Two);
3856
3857 // The A coefficient is N/2
3858 APInt A(N.sdiv(Two));
3859
3860 // Compute the B^2-4ac term.
3861 APInt SqrtTerm(B);
3862 SqrtTerm *= B;
3863 SqrtTerm -= Four * (A * C);
3864
3865 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
3866 // integer value or else APInt::sqrt() will assert.
3867 APInt SqrtVal(SqrtTerm.sqrt());
3868
Dan Gohman9bc642f2009-06-24 04:48:43 +00003869 // Compute the two solutions for the quadratic formula.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003870 // The divisions must be performed as signed divisions.
3871 APInt NegB(-B);
3872 APInt TwoA( A << 1 );
Nick Lewycky35776692008-11-03 02:43:49 +00003873 if (TwoA.isMinValue()) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00003874 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky35776692008-11-03 02:43:49 +00003875 return std::make_pair(CNC, CNC);
3876 }
3877
Owen Andersone755b092009-07-06 22:37:39 +00003878 LLVMContext *Context = SE.getContext();
3879
3880 ConstantInt *Solution1 =
3881 Context->getConstantInt((NegB + SqrtVal).sdiv(TwoA));
3882 ConstantInt *Solution2 =
3883 Context->getConstantInt((NegB - SqrtVal).sdiv(TwoA));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003884
Dan Gohman9bc642f2009-06-24 04:48:43 +00003885 return std::make_pair(SE.getConstant(Solution1),
Dan Gohman89f85052007-10-22 18:31:58 +00003886 SE.getConstant(Solution2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003887 } // end APIntOps namespace
3888}
3889
3890/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman0c850912009-06-06 14:37:11 +00003891/// value to zero will execute. If not computable, return CouldNotCompute.
Dan Gohman161ea032009-07-07 17:06:11 +00003892const SCEV *ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003893 // If the value is a constant
Dan Gohmanc76b5452009-05-04 22:02:23 +00003894 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003895 // If the value is already zero, the branch will execute zero times.
3896 if (C->getValue()->isZero()) return C;
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003897 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003898 }
3899
Dan Gohmanbff6b582009-05-04 22:30:44 +00003900 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003901 if (!AddRec || AddRec->getLoop() != L)
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003902 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003903
3904 if (AddRec->isAffine()) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003905 // If this is an affine expression, the execution count of this branch is
3906 // the minimum unsigned root of the following equation:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003907 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003908 // Start + Step*N = 0 (mod 2^BW)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003909 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003910 // equivalent to:
3911 //
3912 // Step*N = -Start (mod 2^BW)
3913 //
3914 // where BW is the common bit width of Start and Step.
3915
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003916 // Get the initial value for the loop.
Dan Gohman9bc642f2009-06-24 04:48:43 +00003917 const SCEV *Start = getSCEVAtScope(AddRec->getStart(),
3918 L->getParentLoop());
3919 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1),
3920 L->getParentLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003921
Dan Gohmanc76b5452009-05-04 22:02:23 +00003922 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003923 // For now we handle only constant steps.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003924
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003925 // First, handle unitary steps.
3926 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003927 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003928 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
3929 return Start; // N = Start (as unsigned)
3930
3931 // Then, try to solve the above equation provided that Start is constant.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003932 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003933 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003934 -StartC->getValue()->getValue(),
3935 *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003936 }
3937 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
3938 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
3939 // the quadratic equation to solve it.
Dan Gohman161ea032009-07-07 17:06:11 +00003940 std::pair<const SCEV *,const SCEV *> Roots = SolveQuadraticEquation(AddRec,
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003941 *this);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003942 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3943 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003944 if (R1) {
3945#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00003946 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
3947 << " sol#2: " << *R2 << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003948#endif
3949 // Pick the smallest positive root value.
3950 if (ConstantInt *CB =
Owen Andersone755b092009-07-06 22:37:39 +00003951 dyn_cast<ConstantInt>(Context->getConstantExprICmp(ICmpInst::ICMP_ULT,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003952 R1->getValue(), R2->getValue()))) {
3953 if (CB->getZExtValue() == false)
3954 std::swap(R1, R2); // R1 is the minimum root now.
3955
3956 // We can only use this value if the chrec ends up with an exact zero
3957 // value at this index. When solving for "X*X != 5", for example, we
3958 // should not accept a root of 2.
Dan Gohman161ea032009-07-07 17:06:11 +00003959 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohman7b560c42008-06-18 16:23:07 +00003960 if (Val->isZero())
3961 return R1; // We found a quadratic root!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003962 }
3963 }
3964 }
3965
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003966 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003967}
3968
3969/// HowFarToNonZero - Return the number of times a backedge checking the
3970/// specified value for nonzero will execute. If not computable, return
Dan Gohman0c850912009-06-06 14:37:11 +00003971/// CouldNotCompute
Dan Gohman161ea032009-07-07 17:06:11 +00003972const SCEV *ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003973 // Loops that look like: while (X == 0) are very strange indeed. We don't
3974 // handle them yet except for the trivial case. This could be expanded in the
3975 // future as needed.
3976
3977 // If the value is a constant, check to see if it is known to be non-zero
3978 // already. If so, the backedge will execute zero times.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003979 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewyckyf6805182008-02-21 09:14:53 +00003980 if (!C->getValue()->isNullValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003981 return getIntegerSCEV(0, C->getType());
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003982 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003983 }
3984
3985 // We could implement others, but I really doubt anyone writes loops like
3986 // this, and if they did, they would already be constant folded.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003987 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003988}
3989
Dan Gohmanab157b22009-05-18 15:36:09 +00003990/// getLoopPredecessor - If the given loop's header has exactly one unique
3991/// predecessor outside the loop, return it. Otherwise return null.
3992///
3993BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) {
3994 BasicBlock *Header = L->getHeader();
3995 BasicBlock *Pred = 0;
3996 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header);
3997 PI != E; ++PI)
3998 if (!L->contains(*PI)) {
3999 if (Pred && Pred != *PI) return 0; // Multiple predecessors.
4000 Pred = *PI;
4001 }
4002 return Pred;
4003}
4004
Dan Gohman1cddf972008-09-15 22:18:04 +00004005/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
4006/// (which may not be an immediate predecessor) which has exactly one
4007/// successor from which BB is reachable, or null if no such block is
4008/// found.
4009///
4010BasicBlock *
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004011ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman1116ea72009-04-30 20:48:53 +00004012 // If the block has a unique predecessor, then there is no path from the
4013 // predecessor to the block that does not go through the direct edge
4014 // from the predecessor to the block.
Dan Gohman1cddf972008-09-15 22:18:04 +00004015 if (BasicBlock *Pred = BB->getSinglePredecessor())
4016 return Pred;
4017
4018 // A loop's header is defined to be a block that dominates the loop.
Dan Gohmanab157b22009-05-18 15:36:09 +00004019 // If the header has a unique predecessor outside the loop, it must be
4020 // a block that has exactly one successor that can reach the loop.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004021 if (Loop *L = LI->getLoopFor(BB))
Dan Gohmanab157b22009-05-18 15:36:09 +00004022 return getLoopPredecessor(L);
Dan Gohman1cddf972008-09-15 22:18:04 +00004023
4024 return 0;
4025}
4026
Dan Gohmanbc1e3472009-06-20 00:35:32 +00004027/// HasSameValue - SCEV structural equivalence is usually sufficient for
4028/// testing whether two expressions are equal, however for the purposes of
4029/// looking for a condition guarding a loop, it can be useful to be a little
4030/// more general, since a front-end may have replicated the controlling
4031/// expression.
4032///
Dan Gohman161ea032009-07-07 17:06:11 +00004033static bool HasSameValue(const SCEV *A, const SCEV *B) {
Dan Gohmanbc1e3472009-06-20 00:35:32 +00004034 // Quick check to see if they are the same SCEV.
4035 if (A == B) return true;
4036
4037 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
4038 // two different instructions with the same value. Check for this case.
4039 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
4040 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
4041 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
4042 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
4043 if (AI->isIdenticalTo(BI))
4044 return true;
4045
4046 // Otherwise assume they may have a different value.
4047 return false;
4048}
4049
Nick Lewycky9425be92009-07-11 20:38:25 +00004050/// isLoopGuardedByCond - Test whether entry to the loop is protected by
4051/// a conditional between LHS and RHS. This is used to help avoid max
4052/// expressions in loop trip counts.
4053bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
4054 ICmpInst::Predicate Pred,
4055 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman8b938182009-05-18 16:03:58 +00004056 // Interpret a null as meaning no loop, where there is obviously no guard
4057 // (interprocedural conditions notwithstanding).
4058 if (!L) return false;
4059
Dan Gohmanab157b22009-05-18 15:36:09 +00004060 BasicBlock *Predecessor = getLoopPredecessor(L);
4061 BasicBlock *PredecessorDest = L->getHeader();
Nick Lewycky1b020bf2008-07-12 07:41:32 +00004062
Dan Gohmanab157b22009-05-18 15:36:09 +00004063 // Starting at the loop predecessor, climb up the predecessor chain, as long
4064 // as there are predecessors that can be found that have unique successors
Dan Gohman1cddf972008-09-15 22:18:04 +00004065 // leading to the original header.
Dan Gohmanab157b22009-05-18 15:36:09 +00004066 for (; Predecessor;
4067 PredecessorDest = Predecessor,
4068 Predecessor = getPredecessorWithUniqueSuccessorForBB(Predecessor)) {
Dan Gohmanab678fb2008-08-12 20:17:31 +00004069
4070 BranchInst *LoopEntryPredicate =
Dan Gohmanab157b22009-05-18 15:36:09 +00004071 dyn_cast<BranchInst>(Predecessor->getTerminator());
Dan Gohmanab678fb2008-08-12 20:17:31 +00004072 if (!LoopEntryPredicate ||
4073 LoopEntryPredicate->isUnconditional())
4074 continue;
4075
Dan Gohman423ed6c2009-06-24 01:18:18 +00004076 if (isNecessaryCond(LoopEntryPredicate->getCondition(), Pred, LHS, RHS,
4077 LoopEntryPredicate->getSuccessor(0) != PredecessorDest))
Dan Gohmanab678fb2008-08-12 20:17:31 +00004078 return true;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00004079 }
4080
Dan Gohmanab678fb2008-08-12 20:17:31 +00004081 return false;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00004082}
4083
Nick Lewycky9425be92009-07-11 20:38:25 +00004084/// isNecessaryCond - Test whether the given CondValue value is a condition
4085/// which is at least as strict as the one described by Pred, LHS, and RHS.
Dan Gohman423ed6c2009-06-24 01:18:18 +00004086bool ScalarEvolution::isNecessaryCond(Value *CondValue,
4087 ICmpInst::Predicate Pred,
4088 const SCEV *LHS, const SCEV *RHS,
4089 bool Inverse) {
4090 // Recursivly handle And and Or conditions.
4091 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CondValue)) {
4092 if (BO->getOpcode() == Instruction::And) {
4093 if (!Inverse)
4094 return isNecessaryCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4095 isNecessaryCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
4096 } else if (BO->getOpcode() == Instruction::Or) {
4097 if (Inverse)
4098 return isNecessaryCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4099 isNecessaryCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
4100 }
4101 }
4102
4103 ICmpInst *ICI = dyn_cast<ICmpInst>(CondValue);
4104 if (!ICI) return false;
4105
4106 // Now that we found a conditional branch that dominates the loop, check to
4107 // see if it is the comparison we are looking for.
4108 Value *PreCondLHS = ICI->getOperand(0);
4109 Value *PreCondRHS = ICI->getOperand(1);
Nick Lewycky9425be92009-07-11 20:38:25 +00004110 ICmpInst::Predicate Cond;
Dan Gohman423ed6c2009-06-24 01:18:18 +00004111 if (Inverse)
Nick Lewycky9425be92009-07-11 20:38:25 +00004112 Cond = ICI->getInversePredicate();
Dan Gohman423ed6c2009-06-24 01:18:18 +00004113 else
Nick Lewycky9425be92009-07-11 20:38:25 +00004114 Cond = ICI->getPredicate();
Dan Gohman423ed6c2009-06-24 01:18:18 +00004115
Nick Lewycky9425be92009-07-11 20:38:25 +00004116 if (Cond == Pred)
Dan Gohman423ed6c2009-06-24 01:18:18 +00004117 ; // An exact match.
Nick Lewycky9425be92009-07-11 20:38:25 +00004118 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
4119 ; // The actual condition is beyond sufficient.
4120 else
Dan Gohman423ed6c2009-06-24 01:18:18 +00004121 // Check a few special cases.
Nick Lewycky9425be92009-07-11 20:38:25 +00004122 switch (Cond) {
Dan Gohman423ed6c2009-06-24 01:18:18 +00004123 case ICmpInst::ICMP_UGT:
4124 if (Pred == ICmpInst::ICMP_ULT) {
4125 std::swap(PreCondLHS, PreCondRHS);
Nick Lewycky9425be92009-07-11 20:38:25 +00004126 Cond = ICmpInst::ICMP_ULT;
Dan Gohman423ed6c2009-06-24 01:18:18 +00004127 break;
4128 }
4129 return false;
4130 case ICmpInst::ICMP_SGT:
4131 if (Pred == ICmpInst::ICMP_SLT) {
4132 std::swap(PreCondLHS, PreCondRHS);
Nick Lewycky9425be92009-07-11 20:38:25 +00004133 Cond = ICmpInst::ICMP_SLT;
Dan Gohman423ed6c2009-06-24 01:18:18 +00004134 break;
4135 }
4136 return false;
4137 case ICmpInst::ICMP_NE:
4138 // Expressions like (x >u 0) are often canonicalized to (x != 0),
4139 // so check for this case by checking if the NE is comparing against
4140 // a minimum or maximum constant.
4141 if (!ICmpInst::isTrueWhenEqual(Pred))
Nick Lewycky9425be92009-07-11 20:38:25 +00004142 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
4143 const APInt &A = CI->getValue();
Dan Gohman423ed6c2009-06-24 01:18:18 +00004144 switch (Pred) {
4145 case ICmpInst::ICMP_SLT:
4146 if (A.isMaxSignedValue()) break;
4147 return false;
4148 case ICmpInst::ICMP_SGT:
4149 if (A.isMinSignedValue()) break;
4150 return false;
4151 case ICmpInst::ICMP_ULT:
4152 if (A.isMaxValue()) break;
4153 return false;
4154 case ICmpInst::ICMP_UGT:
4155 if (A.isMinValue()) break;
4156 return false;
4157 default:
4158 return false;
4159 }
Nick Lewycky9425be92009-07-11 20:38:25 +00004160 Cond = ICmpInst::ICMP_NE;
Dan Gohman423ed6c2009-06-24 01:18:18 +00004161 // NE is symmetric but the original comparison may not be. Swap
4162 // the operands if necessary so that they match below.
4163 if (isa<SCEVConstant>(LHS))
4164 std::swap(PreCondLHS, PreCondRHS);
4165 break;
4166 }
4167 return false;
4168 default:
4169 // We weren't able to reconcile the condition.
4170 return false;
4171 }
4172
Nick Lewycky9425be92009-07-11 20:38:25 +00004173 if (!PreCondLHS->getType()->isInteger()) return false;
Dan Gohman423ed6c2009-06-24 01:18:18 +00004174
Nick Lewycky9425be92009-07-11 20:38:25 +00004175 const SCEV *PreCondLHSSCEV = getSCEV(PreCondLHS);
4176 const SCEV *PreCondRHSSCEV = getSCEV(PreCondRHS);
4177 return (HasSameValue(LHS, PreCondLHSSCEV) &&
4178 HasSameValue(RHS, PreCondRHSSCEV)) ||
4179 (HasSameValue(LHS, getNotSCEV(PreCondRHSSCEV)) &&
4180 HasSameValue(RHS, getNotSCEV(PreCondLHSSCEV)));
Dan Gohman423ed6c2009-06-24 01:18:18 +00004181}
4182
Dan Gohmand2b62c42009-06-21 23:46:38 +00004183/// getBECount - Subtract the end and start values and divide by the step,
4184/// rounding up, to get the number of times the backedge is executed. Return
4185/// CouldNotCompute if an intermediate computation overflows.
Dan Gohman161ea032009-07-07 17:06:11 +00004186const SCEV *ScalarEvolution::getBECount(const SCEV *Start,
4187 const SCEV *End,
4188 const SCEV *Step) {
Dan Gohmand2b62c42009-06-21 23:46:38 +00004189 const Type *Ty = Start->getType();
Dan Gohman161ea032009-07-07 17:06:11 +00004190 const SCEV *NegOne = getIntegerSCEV(-1, Ty);
4191 const SCEV *Diff = getMinusSCEV(End, Start);
4192 const SCEV *RoundUp = getAddExpr(Step, NegOne);
Dan Gohmand2b62c42009-06-21 23:46:38 +00004193
4194 // Add an adjustment to the difference between End and Start so that
4195 // the division will effectively round up.
Dan Gohman161ea032009-07-07 17:06:11 +00004196 const SCEV *Add = getAddExpr(Diff, RoundUp);
Dan Gohmand2b62c42009-06-21 23:46:38 +00004197
4198 // Check Add for unsigned overflow.
4199 // TODO: More sophisticated things could be done here.
Owen Andersone755b092009-07-06 22:37:39 +00004200 const Type *WideTy = Context->getIntegerType(getTypeSizeInBits(Ty) + 1);
Dan Gohman161ea032009-07-07 17:06:11 +00004201 const SCEV *OperandExtendedAdd =
Dan Gohmand2b62c42009-06-21 23:46:38 +00004202 getAddExpr(getZeroExtendExpr(Diff, WideTy),
4203 getZeroExtendExpr(RoundUp, WideTy));
4204 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004205 return getCouldNotCompute();
Dan Gohmand2b62c42009-06-21 23:46:38 +00004206
4207 return getUDivExpr(Add, Step);
4208}
4209
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004210/// HowManyLessThans - Return the number of times a backedge containing the
4211/// specified less-than comparison will execute. If not computable, return
Dan Gohman0c850912009-06-06 14:37:11 +00004212/// CouldNotCompute.
Dan Gohman9bc642f2009-06-24 04:48:43 +00004213ScalarEvolution::BackedgeTakenInfo
4214ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
4215 const Loop *L, bool isSigned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004216 // Only handle: "ADDREC < LoopInvariant".
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004217 if (!RHS->isLoopInvariant(L)) return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004218
Dan Gohmanbff6b582009-05-04 22:30:44 +00004219 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004220 if (!AddRec || AddRec->getLoop() != L)
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004221 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004222
4223 if (AddRec->isAffine()) {
Nick Lewycky35b56022009-01-13 09:18:58 +00004224 // FORNOW: We only support unit strides.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004225 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
Dan Gohman161ea032009-07-07 17:06:11 +00004226 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004227
4228 // TODO: handle non-constant strides.
4229 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
4230 if (!CStep || CStep->isZero())
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004231 return getCouldNotCompute();
Dan Gohmanf8bc8e82009-05-18 15:22:39 +00004232 if (CStep->isOne()) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004233 // With unit stride, the iteration never steps past the limit value.
4234 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
4235 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
4236 // Test whether a positive iteration iteration can step past the limit
4237 // value and past the maximum value for its type in a single step.
4238 if (isSigned) {
4239 APInt Max = APInt::getSignedMaxValue(BitWidth);
4240 if ((Max - CStep->getValue()->getValue())
4241 .slt(CLimit->getValue()->getValue()))
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004242 return getCouldNotCompute();
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004243 } else {
4244 APInt Max = APInt::getMaxValue(BitWidth);
4245 if ((Max - CStep->getValue()->getValue())
4246 .ult(CLimit->getValue()->getValue()))
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004247 return getCouldNotCompute();
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004248 }
4249 } else
4250 // TODO: handle non-constant limit values below.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004251 return getCouldNotCompute();
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004252 } else
4253 // TODO: handle negative strides below.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004254 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004255
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004256 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
4257 // m. So, we count the number of iterations in which {n,+,s} < m is true.
4258 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicz1377a542008-02-13 12:21:32 +00004259 // treat m-n as signed nor unsigned due to overflow possibility.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004260
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00004261 // First, we get the value of the LHS in the first iteration: n
Dan Gohman161ea032009-07-07 17:06:11 +00004262 const SCEV *Start = AddRec->getOperand(0);
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00004263
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004264 // Determine the minimum constant start value.
Nick Lewycky9425be92009-07-11 20:38:25 +00004265 const SCEV *MinStart = isa<SCEVConstant>(Start) ? Start :
4266 getConstant(isSigned ? APInt::getSignedMinValue(BitWidth) :
4267 APInt::getMinValue(BitWidth));
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00004268
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004269 // If we know that the condition is true in order to enter the loop,
4270 // then we know that it will run exactly (m-n)/s times. Otherwise, we
Dan Gohmanc8a29272009-05-24 23:45:28 +00004271 // only know that it will execute (max(m,n)-n)/s times. In both cases,
4272 // the division must round up.
Dan Gohman161ea032009-07-07 17:06:11 +00004273 const SCEV *End = RHS;
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004274 if (!isLoopGuardedByCond(L,
Nick Lewycky9425be92009-07-11 20:38:25 +00004275 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004276 getMinusSCEV(Start, Step), RHS))
4277 End = isSigned ? getSMaxExpr(RHS, Start)
4278 : getUMaxExpr(RHS, Start);
4279
4280 // Determine the maximum constant end value.
Nick Lewycky9425be92009-07-11 20:38:25 +00004281 const SCEV *MaxEnd =
4282 isa<SCEVConstant>(End) ? End :
4283 getConstant(isSigned ? APInt::getSignedMaxValue(BitWidth)
4284 .ashr(GetMinSignBits(End) - 1) :
4285 APInt::getMaxValue(BitWidth)
4286 .lshr(GetMinLeadingZeros(End)));
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004287
4288 // Finally, we subtract these two values and divide, rounding up, to get
4289 // the number of times the backedge is executed.
Dan Gohman161ea032009-07-07 17:06:11 +00004290 const SCEV *BECount = getBECount(Start, End, Step);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004291
4292 // The maximum backedge count is similar, except using the minimum start
4293 // value and the maximum end value.
Dan Gohman161ea032009-07-07 17:06:11 +00004294 const SCEV *MaxBECount = getBECount(MinStart, MaxEnd, Step);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004295
4296 return BackedgeTakenInfo(BECount, MaxBECount);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004297 }
4298
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004299 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004300}
4301
4302/// getNumIterationsInRange - Return the number of iterations of this loop that
4303/// produce values in the specified constant range. Another way of looking at
4304/// this is that it returns the first iteration number where the value is not in
4305/// the condition, thus computing the exit count. If the iteration count can't
4306/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman161ea032009-07-07 17:06:11 +00004307const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
Dan Gohman9bc642f2009-06-24 04:48:43 +00004308 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004309 if (Range.isFullSet()) // Infinite loop.
Dan Gohman0ad08b02009-04-18 17:58:19 +00004310 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004311
4312 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohmanc76b5452009-05-04 22:02:23 +00004313 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004314 if (!SC->getValue()->isZero()) {
Dan Gohman161ea032009-07-07 17:06:11 +00004315 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00004316 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
Dan Gohman161ea032009-07-07 17:06:11 +00004317 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohmanc76b5452009-05-04 22:02:23 +00004318 if (const SCEVAddRecExpr *ShiftedAddRec =
4319 dyn_cast<SCEVAddRecExpr>(Shifted))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004320 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman89f85052007-10-22 18:31:58 +00004321 Range.subtract(SC->getValue()->getValue()), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004322 // This is strange and shouldn't happen.
Dan Gohman0ad08b02009-04-18 17:58:19 +00004323 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004324 }
4325
4326 // The only time we can solve this is when we have all constant indices.
4327 // Otherwise, we cannot determine the overflow conditions.
4328 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
4329 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohman0ad08b02009-04-18 17:58:19 +00004330 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004331
4332
4333 // Okay at this point we know that all elements of the chrec are constants and
4334 // that the start element is zero.
4335
4336 // First check to see if the range contains zero. If not, the first
4337 // iteration exits.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00004338 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00004339 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman8fd520a2009-06-15 22:12:54 +00004340 return SE.getIntegerSCEV(0, getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004341
4342 if (isAffine()) {
4343 // If this is an affine expression then we have this situation:
4344 // Solve {0,+,A} in Range === Ax in Range
4345
4346 // We know that zero is in the range. If A is positive then we know that
4347 // the upper value of the range must be the first possible exit value.
4348 // If A is negative then the lower of the range is the last possible loop
4349 // value. Also note that we already checked for a full range.
Dan Gohman01c2ee72009-04-16 03:18:22 +00004350 APInt One(BitWidth,1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004351 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
4352 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
4353
4354 // The exit value should be (End+A)/A.
Nick Lewyckya0facae2007-09-27 14:12:54 +00004355 APInt ExitVal = (End + A).udiv(A);
Owen Andersone755b092009-07-06 22:37:39 +00004356 ConstantInt *ExitValue = SE.getContext()->getConstantInt(ExitVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004357
4358 // Evaluate at the exit value. If we really did fall out of the valid
4359 // range, then we computed our trip count, otherwise wrap around or other
4360 // things must have happened.
Dan Gohman89f85052007-10-22 18:31:58 +00004361 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004362 if (Range.contains(Val->getValue()))
Dan Gohman0ad08b02009-04-18 17:58:19 +00004363 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004364
4365 // Ensure that the previous value is in the range. This is a sanity check.
4366 assert(Range.contains(
Dan Gohman9bc642f2009-06-24 04:48:43 +00004367 EvaluateConstantChrecAtConstant(this,
Owen Andersone755b092009-07-06 22:37:39 +00004368 SE.getContext()->getConstantInt(ExitVal - One), SE)->getValue()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004369 "Linear scev computation is off in a bad way!");
Dan Gohman89f85052007-10-22 18:31:58 +00004370 return SE.getConstant(ExitValue);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004371 } else if (isQuadratic()) {
4372 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
4373 // quadratic equation to solve it. To do this, we must frame our problem in
4374 // terms of figuring out when zero is crossed, instead of when
4375 // Range.getUpper() is crossed.
Dan Gohman161ea032009-07-07 17:06:11 +00004376 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00004377 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Dan Gohman161ea032009-07-07 17:06:11 +00004378 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004379
4380 // Next, solve the constructed addrec
Dan Gohman161ea032009-07-07 17:06:11 +00004381 std::pair<const SCEV *,const SCEV *> Roots =
Dan Gohman89f85052007-10-22 18:31:58 +00004382 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohmanbff6b582009-05-04 22:30:44 +00004383 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4384 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004385 if (R1) {
4386 // Pick the smallest positive root value.
4387 if (ConstantInt *CB =
Owen Andersone755b092009-07-06 22:37:39 +00004388 dyn_cast<ConstantInt>(
4389 SE.getContext()->getConstantExprICmp(ICmpInst::ICMP_ULT,
4390 R1->getValue(), R2->getValue()))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004391 if (CB->getZExtValue() == false)
4392 std::swap(R1, R2); // R1 is the minimum root now.
4393
4394 // Make sure the root is not off by one. The returned iteration should
4395 // not be in the range, but the previous one should be. When solving
4396 // for "X*X < 5", for example, we should not return a root of 2.
4397 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00004398 R1->getValue(),
4399 SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004400 if (Range.contains(R1Val->getValue())) {
4401 // The next iteration must be out of the range...
Owen Andersone755b092009-07-06 22:37:39 +00004402 ConstantInt *NextVal =
4403 SE.getContext()->getConstantInt(R1->getValue()->getValue()+1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004404
Dan Gohman89f85052007-10-22 18:31:58 +00004405 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004406 if (!Range.contains(R1Val->getValue()))
Dan Gohman89f85052007-10-22 18:31:58 +00004407 return SE.getConstant(NextVal);
Dan Gohman0ad08b02009-04-18 17:58:19 +00004408 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004409 }
4410
4411 // If R1 was not in the range, then it is a good return value. Make
4412 // sure that R1-1 WAS in the range though, just in case.
Owen Andersone755b092009-07-06 22:37:39 +00004413 ConstantInt *NextVal =
4414 SE.getContext()->getConstantInt(R1->getValue()->getValue()-1);
Dan Gohman89f85052007-10-22 18:31:58 +00004415 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004416 if (Range.contains(R1Val->getValue()))
4417 return R1;
Dan Gohman0ad08b02009-04-18 17:58:19 +00004418 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004419 }
4420 }
4421 }
4422
Dan Gohman0ad08b02009-04-18 17:58:19 +00004423 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004424}
4425
4426
4427
4428//===----------------------------------------------------------------------===//
Dan Gohmanbff6b582009-05-04 22:30:44 +00004429// SCEVCallbackVH Class Implementation
4430//===----------------------------------------------------------------------===//
4431
Dan Gohman999d14e2009-05-19 19:22:47 +00004432void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmanbff6b582009-05-04 22:30:44 +00004433 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
4434 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
4435 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00004436 if (Instruction *I = dyn_cast<Instruction>(getValPtr()))
4437 SE->ValuesAtScopes.erase(I);
Dan Gohmanbff6b582009-05-04 22:30:44 +00004438 SE->Scalars.erase(getValPtr());
4439 // this now dangles!
4440}
4441
Dan Gohman999d14e2009-05-19 19:22:47 +00004442void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00004443 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
4444
4445 // Forget all the expressions associated with users of the old value,
4446 // so that future queries will recompute the expressions using the new
4447 // value.
4448 SmallVector<User *, 16> Worklist;
4449 Value *Old = getValPtr();
4450 bool DeleteOld = false;
4451 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
4452 UI != UE; ++UI)
4453 Worklist.push_back(*UI);
4454 while (!Worklist.empty()) {
4455 User *U = Worklist.pop_back_val();
4456 // Deleting the Old value will cause this to dangle. Postpone
4457 // that until everything else is done.
4458 if (U == Old) {
4459 DeleteOld = true;
4460 continue;
4461 }
4462 if (PHINode *PN = dyn_cast<PHINode>(U))
4463 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00004464 if (Instruction *I = dyn_cast<Instruction>(U))
4465 SE->ValuesAtScopes.erase(I);
Dan Gohmanbff6b582009-05-04 22:30:44 +00004466 if (SE->Scalars.erase(U))
4467 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
4468 UI != UE; ++UI)
4469 Worklist.push_back(*UI);
4470 }
4471 if (DeleteOld) {
4472 if (PHINode *PN = dyn_cast<PHINode>(Old))
4473 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00004474 if (Instruction *I = dyn_cast<Instruction>(Old))
4475 SE->ValuesAtScopes.erase(I);
Dan Gohmanbff6b582009-05-04 22:30:44 +00004476 SE->Scalars.erase(Old);
4477 // this now dangles!
4478 }
4479 // this may dangle!
4480}
4481
Dan Gohman999d14e2009-05-19 19:22:47 +00004482ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohmanbff6b582009-05-04 22:30:44 +00004483 : CallbackVH(V), SE(se) {}
4484
4485//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004486// ScalarEvolution Class Implementation
4487//===----------------------------------------------------------------------===//
4488
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004489ScalarEvolution::ScalarEvolution()
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004490 : FunctionPass(&ID) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004491}
4492
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004493bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004494 this->F = &F;
4495 LI = &getAnalysis<LoopInfo>();
4496 TD = getAnalysisIfAvailable<TargetData>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004497 return false;
4498}
4499
4500void ScalarEvolution::releaseMemory() {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004501 Scalars.clear();
4502 BackedgeTakenCounts.clear();
4503 ConstantEvolutionLoopExitValue.clear();
Dan Gohmanda0071e2009-05-08 20:47:27 +00004504 ValuesAtScopes.clear();
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004505 UniqueSCEVs.clear();
4506 SCEVAllocator.Reset();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004507}
4508
4509void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
4510 AU.setPreservesAll();
4511 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman01c2ee72009-04-16 03:18:22 +00004512}
4513
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004514bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00004515 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004516}
4517
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004518static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004519 const Loop *L) {
4520 // Print all inner loops first
4521 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
4522 PrintLoopInfo(OS, SE, *I);
4523
Nick Lewyckye5da1912008-01-02 02:49:20 +00004524 OS << "Loop " << L->getHeader()->getName() << ": ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004525
Devang Patel02451fa2007-08-21 00:31:24 +00004526 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004527 L->getExitBlocks(ExitBlocks);
4528 if (ExitBlocks.size() != 1)
Nick Lewyckye5da1912008-01-02 02:49:20 +00004529 OS << "<multiple exits> ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004530
Dan Gohman76d5a0d2009-02-24 18:55:53 +00004531 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
4532 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004533 } else {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00004534 OS << "Unpredictable backedge-taken count. ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004535 }
4536
Nick Lewyckye5da1912008-01-02 02:49:20 +00004537 OS << "\n";
Dan Gohmanb6b9e9e2009-06-24 00:33:16 +00004538 OS << "Loop " << L->getHeader()->getName() << ": ";
4539
4540 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
4541 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
4542 } else {
4543 OS << "Unpredictable max backedge-taken count. ";
4544 }
4545
4546 OS << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004547}
4548
Dan Gohman13058cc2009-04-21 00:47:46 +00004549void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004550 // ScalarEvolution's implementaiton of the print method is to print
4551 // out SCEV values of all instructions that are interesting. Doing
4552 // this potentially causes it to create new SCEV objects though,
4553 // which technically conflicts with the const qualifier. This isn't
Dan Gohmanac2a9d62009-07-10 20:25:29 +00004554 // observable from outside the class though, so casting away the
4555 // const isn't dangerous.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004556 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004557
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004558 OS << "Classifying expressions for: " << F->getName() << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004559 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohman43d37e92009-04-30 01:30:18 +00004560 if (isSCEVable(I->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004561 OS << *I;
Dan Gohmanabe991f2008-09-14 17:21:12 +00004562 OS << " --> ";
Dan Gohman161ea032009-07-07 17:06:11 +00004563 const SCEV *SV = SE.getSCEV(&*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004564 SV->print(OS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004565
Dan Gohman8db598a2009-06-19 17:49:54 +00004566 const Loop *L = LI->getLoopFor((*I).getParent());
4567
Dan Gohman161ea032009-07-07 17:06:11 +00004568 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohman8db598a2009-06-19 17:49:54 +00004569 if (AtUse != SV) {
4570 OS << " --> ";
4571 AtUse->print(OS);
4572 }
4573
4574 if (L) {
Dan Gohmane5b60842009-06-18 00:37:45 +00004575 OS << "\t\t" "Exits: ";
Dan Gohman161ea032009-07-07 17:06:11 +00004576 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohmanaff14d62009-05-24 23:25:42 +00004577 if (!ExitValue->isLoopInvariant(L)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004578 OS << "<<Unknown>>";
4579 } else {
4580 OS << *ExitValue;
4581 }
4582 }
4583
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004584 OS << "\n";
4585 }
4586
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004587 OS << "Determining loop execution counts for: " << F->getName() << "\n";
4588 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
4589 PrintLoopInfo(OS, &SE, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004590}
Dan Gohman13058cc2009-04-21 00:47:46 +00004591
4592void ScalarEvolution::print(std::ostream &o, const Module *M) const {
4593 raw_os_ostream OS(o);
4594 print(OS, M);
4595}