blob: 6a028c19faf152b62e82e3da1f22aa470cf6827c [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() :
Dan Gohmand43a8282009-07-13 20:50:19 +0000148 SCEV(FoldingSetNodeID(), scCouldNotCompute) {}
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000149
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000150bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
Edwin Török675d5622009-07-11 20:10:48 +0000151 LLVM_UNREACHABLE("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000152 return false;
153}
154
155const Type *SCEVCouldNotCompute::getType() const {
Edwin Török675d5622009-07-11 20:10:48 +0000156 LLVM_UNREACHABLE("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000157 return 0;
158}
159
160bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
Edwin Török675d5622009-07-11 20:10:48 +0000161 LLVM_UNREACHABLE("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000162 return false;
163}
164
Dan Gohman9bc642f2009-06-24 04:48:43 +0000165const SCEV *
166SCEVCouldNotCompute::replaceSymbolicValuesWithConcrete(
167 const SCEV *Sym,
168 const SCEV *Conc,
169 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000170 return this;
171}
172
Dan Gohman13058cc2009-04-21 00:47:46 +0000173void SCEVCouldNotCompute::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000174 OS << "***COULDNOTCOMPUTE***";
175}
176
177bool SCEVCouldNotCompute::classof(const SCEV *S) {
178 return S->getSCEVType() == scCouldNotCompute;
179}
180
Dan Gohman161ea032009-07-07 17:06:11 +0000181const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000182 FoldingSetNodeID ID;
183 ID.AddInteger(scConstant);
184 ID.AddPointer(V);
185 void *IP = 0;
186 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
187 SCEV *S = SCEVAllocator.Allocate<SCEVConstant>();
Dan Gohmand43a8282009-07-13 20:50:19 +0000188 new (S) SCEVConstant(ID, V);
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000189 UniqueSCEVs.InsertNode(S, IP);
190 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000191}
192
Dan Gohman161ea032009-07-07 17:06:11 +0000193const SCEV *ScalarEvolution::getConstant(const APInt& Val) {
Dan Gohman89f85052007-10-22 18:31:58 +0000194 return getConstant(ConstantInt::get(Val));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000195}
196
Dan Gohman161ea032009-07-07 17:06:11 +0000197const SCEV *
Dan Gohman8fd520a2009-06-15 22:12:54 +0000198ScalarEvolution::getConstant(const Type *Ty, uint64_t V, bool isSigned) {
199 return getConstant(ConstantInt::get(cast<IntegerType>(Ty), V, isSigned));
200}
201
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000202const Type *SCEVConstant::getType() const { return V->getType(); }
203
Dan Gohman13058cc2009-04-21 00:47:46 +0000204void SCEVConstant::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000205 WriteAsOperand(OS, V, false);
206}
207
Dan Gohmand43a8282009-07-13 20:50:19 +0000208SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeID &ID,
209 unsigned SCEVTy, const SCEV *op, const Type *ty)
210 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000211
Dan Gohman2a381532009-04-21 01:25:57 +0000212bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
213 return Op->dominates(BB, DT);
214}
215
Dan Gohmand43a8282009-07-13 20:50:19 +0000216SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeID &ID,
217 const SCEV *op, const Type *ty)
218 : SCEVCastExpr(ID, scTruncate, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000219 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
220 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000221 "Cannot truncate non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000222}
223
Dan Gohman13058cc2009-04-21 00:47:46 +0000224void SCEVTruncateExpr::print(raw_ostream &OS) const {
Dan Gohmanc9119222009-04-29 20:27:52 +0000225 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000226}
227
Dan Gohmand43a8282009-07-13 20:50:19 +0000228SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeID &ID,
229 const SCEV *op, const Type *ty)
230 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000231 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
232 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000233 "Cannot zero extend non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000234}
235
Dan Gohman13058cc2009-04-21 00:47:46 +0000236void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
Dan Gohmanc9119222009-04-29 20:27:52 +0000237 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000238}
239
Dan Gohmand43a8282009-07-13 20:50:19 +0000240SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeID &ID,
241 const SCEV *op, const Type *ty)
242 : SCEVCastExpr(ID, scSignExtend, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000243 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
244 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000245 "Cannot sign extend non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000246}
247
Dan Gohman13058cc2009-04-21 00:47:46 +0000248void SCEVSignExtendExpr::print(raw_ostream &OS) const {
Dan Gohmanc9119222009-04-29 20:27:52 +0000249 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000250}
251
Dan Gohman13058cc2009-04-21 00:47:46 +0000252void SCEVCommutativeExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000253 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
254 const char *OpStr = getOperationStr();
255 OS << "(" << *Operands[0];
256 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
257 OS << OpStr << *Operands[i];
258 OS << ")";
259}
260
Dan Gohman9bc642f2009-06-24 04:48:43 +0000261const SCEV *
262SCEVCommutativeExpr::replaceSymbolicValuesWithConcrete(
263 const SCEV *Sym,
264 const SCEV *Conc,
265 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000266 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman161ea032009-07-07 17:06:11 +0000267 const SCEV *H =
Dan Gohman89f85052007-10-22 18:31:58 +0000268 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000269 if (H != getOperand(i)) {
Dan Gohman161ea032009-07-07 17:06:11 +0000270 SmallVector<const SCEV *, 8> NewOps;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000271 NewOps.reserve(getNumOperands());
272 for (unsigned j = 0; j != i; ++j)
273 NewOps.push_back(getOperand(j));
274 NewOps.push_back(H);
275 for (++i; i != e; ++i)
276 NewOps.push_back(getOperand(i)->
Dan Gohman89f85052007-10-22 18:31:58 +0000277 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000278
279 if (isa<SCEVAddExpr>(this))
Dan Gohman89f85052007-10-22 18:31:58 +0000280 return SE.getAddExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000281 else if (isa<SCEVMulExpr>(this))
Dan Gohman89f85052007-10-22 18:31:58 +0000282 return SE.getMulExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +0000283 else if (isa<SCEVSMaxExpr>(this))
284 return SE.getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000285 else if (isa<SCEVUMaxExpr>(this))
286 return SE.getUMaxExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000287 else
Edwin Török675d5622009-07-11 20:10:48 +0000288 LLVM_UNREACHABLE("Unknown commutative expr!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000289 }
290 }
291 return this;
292}
293
Dan Gohman72a8a022009-05-07 14:00:19 +0000294bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
Evan Cheng98c073b2009-02-17 00:13:06 +0000295 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
296 if (!getOperand(i)->dominates(BB, DT))
297 return false;
298 }
299 return true;
300}
301
Evan Cheng98c073b2009-02-17 00:13:06 +0000302bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
303 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
304}
305
Dan Gohman13058cc2009-04-21 00:47:46 +0000306void SCEVUDivExpr::print(raw_ostream &OS) const {
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000307 OS << "(" << *LHS << " /u " << *RHS << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000308}
309
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000310const Type *SCEVUDivExpr::getType() const {
Dan Gohman140f08f2009-05-26 17:44:05 +0000311 // In most cases the types of LHS and RHS will be the same, but in some
312 // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
313 // depend on the type for correctness, but handling types carefully can
314 // avoid extra casts in the SCEVExpander. The LHS is more likely to be
315 // a pointer type than the RHS, so use the RHS' type here.
316 return RHS->getType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000317}
318
Dan Gohman9bc642f2009-06-24 04:48:43 +0000319const SCEV *
320SCEVAddRecExpr::replaceSymbolicValuesWithConcrete(const SCEV *Sym,
321 const SCEV *Conc,
322 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000323 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman161ea032009-07-07 17:06:11 +0000324 const SCEV *H =
Dan Gohman89f85052007-10-22 18:31:58 +0000325 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000326 if (H != getOperand(i)) {
Dan Gohman161ea032009-07-07 17:06:11 +0000327 SmallVector<const SCEV *, 8> NewOps;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000328 NewOps.reserve(getNumOperands());
329 for (unsigned j = 0; j != i; ++j)
330 NewOps.push_back(getOperand(j));
331 NewOps.push_back(H);
332 for (++i; i != e; ++i)
333 NewOps.push_back(getOperand(i)->
Dan Gohman89f85052007-10-22 18:31:58 +0000334 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000335
Dan Gohman89f85052007-10-22 18:31:58 +0000336 return SE.getAddRecExpr(NewOps, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000337 }
338 }
339 return this;
340}
341
342
343bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
Dan Gohmanae1eaae2009-05-20 01:01:24 +0000344 // Add recurrences are never invariant in the function-body (null loop).
Dan Gohman2d888d82009-06-26 22:17:21 +0000345 if (!QueryLoop)
346 return false;
347
348 // This recurrence is variant w.r.t. QueryLoop if QueryLoop contains L.
349 if (QueryLoop->contains(L->getHeader()))
350 return false;
351
352 // This recurrence is variant w.r.t. QueryLoop if any of its operands
353 // are variant.
354 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
355 if (!getOperand(i)->isLoopInvariant(QueryLoop))
356 return false;
357
358 // Otherwise it's loop-invariant.
359 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000360}
361
Dan Gohman13058cc2009-04-21 00:47:46 +0000362void SCEVAddRecExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000363 OS << "{" << *Operands[0];
364 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
365 OS << ",+," << *Operands[i];
366 OS << "}<" << L->getHeader()->getName() + ">";
367}
368
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000369bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
370 // All non-instruction values are loop invariant. All instructions are loop
371 // invariant if they are not contained in the specified loop.
Dan Gohmanae1eaae2009-05-20 01:01:24 +0000372 // Instructions are never considered invariant in the function body
373 // (null loop) because they are defined within the "loop".
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000374 if (Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmanae1eaae2009-05-20 01:01:24 +0000375 return L && !L->contains(I->getParent());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000376 return true;
377}
378
Evan Cheng98c073b2009-02-17 00:13:06 +0000379bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
380 if (Instruction *I = dyn_cast<Instruction>(getValue()))
381 return DT->dominates(I->getParent(), BB);
382 return true;
383}
384
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000385const Type *SCEVUnknown::getType() const {
386 return V->getType();
387}
388
Dan Gohman13058cc2009-04-21 00:47:46 +0000389void SCEVUnknown::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000390 WriteAsOperand(OS, V, false);
391}
392
393//===----------------------------------------------------------------------===//
394// SCEV Utilities
395//===----------------------------------------------------------------------===//
396
397namespace {
398 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
399 /// than the complexity of the RHS. This comparator is used to canonicalize
400 /// expressions.
Dan Gohman5d486452009-05-07 14:39:04 +0000401 class VISIBILITY_HIDDEN SCEVComplexityCompare {
402 LoopInfo *LI;
403 public:
404 explicit SCEVComplexityCompare(LoopInfo *li) : LI(li) {}
405
Dan Gohmanc0c69cf2008-04-14 18:23:56 +0000406 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman5d486452009-05-07 14:39:04 +0000407 // Primarily, sort the SCEVs by their getSCEVType().
408 if (LHS->getSCEVType() != RHS->getSCEVType())
409 return LHS->getSCEVType() < RHS->getSCEVType();
410
411 // Aside from the getSCEVType() ordering, the particular ordering
412 // isn't very important except that it's beneficial to be consistent,
413 // so that (a + b) and (b + a) don't end up as different expressions.
414
415 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
416 // not as complete as it could be.
417 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
418 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
419
Dan Gohmand0c01232009-05-19 02:15:55 +0000420 // Order pointer values after integer values. This helps SCEVExpander
421 // form GEPs.
422 if (isa<PointerType>(LU->getType()) && !isa<PointerType>(RU->getType()))
423 return false;
424 if (isa<PointerType>(RU->getType()) && !isa<PointerType>(LU->getType()))
425 return true;
426
Dan Gohman5d486452009-05-07 14:39:04 +0000427 // Compare getValueID values.
428 if (LU->getValue()->getValueID() != RU->getValue()->getValueID())
429 return LU->getValue()->getValueID() < RU->getValue()->getValueID();
430
431 // Sort arguments by their position.
432 if (const Argument *LA = dyn_cast<Argument>(LU->getValue())) {
433 const Argument *RA = cast<Argument>(RU->getValue());
434 return LA->getArgNo() < RA->getArgNo();
435 }
436
437 // For instructions, compare their loop depth, and their opcode.
438 // This is pretty loose.
439 if (Instruction *LV = dyn_cast<Instruction>(LU->getValue())) {
440 Instruction *RV = cast<Instruction>(RU->getValue());
441
442 // Compare loop depths.
443 if (LI->getLoopDepth(LV->getParent()) !=
444 LI->getLoopDepth(RV->getParent()))
445 return LI->getLoopDepth(LV->getParent()) <
446 LI->getLoopDepth(RV->getParent());
447
448 // Compare opcodes.
449 if (LV->getOpcode() != RV->getOpcode())
450 return LV->getOpcode() < RV->getOpcode();
451
452 // Compare the number of operands.
453 if (LV->getNumOperands() != RV->getNumOperands())
454 return LV->getNumOperands() < RV->getNumOperands();
455 }
456
457 return false;
458 }
459
Dan Gohman56fc8f12009-06-14 22:51:25 +0000460 // Compare constant values.
461 if (const SCEVConstant *LC = dyn_cast<SCEVConstant>(LHS)) {
462 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
Nick Lewycky9bb14052009-07-04 17:24:52 +0000463 if (LC->getValue()->getBitWidth() != RC->getValue()->getBitWidth())
464 return LC->getValue()->getBitWidth() < RC->getValue()->getBitWidth();
Dan Gohman56fc8f12009-06-14 22:51:25 +0000465 return LC->getValue()->getValue().ult(RC->getValue()->getValue());
466 }
467
468 // Compare addrec loop depths.
469 if (const SCEVAddRecExpr *LA = dyn_cast<SCEVAddRecExpr>(LHS)) {
470 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
471 if (LA->getLoop()->getLoopDepth() != RA->getLoop()->getLoopDepth())
472 return LA->getLoop()->getLoopDepth() < RA->getLoop()->getLoopDepth();
473 }
Dan Gohman5d486452009-05-07 14:39:04 +0000474
475 // Lexicographically compare n-ary expressions.
476 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
477 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
478 for (unsigned i = 0, e = LC->getNumOperands(); i != e; ++i) {
479 if (i >= RC->getNumOperands())
480 return false;
481 if (operator()(LC->getOperand(i), RC->getOperand(i)))
482 return true;
483 if (operator()(RC->getOperand(i), LC->getOperand(i)))
484 return false;
485 }
486 return LC->getNumOperands() < RC->getNumOperands();
487 }
488
Dan Gohman6e10db12009-05-07 19:23:21 +0000489 // Lexicographically compare udiv expressions.
490 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
491 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
492 if (operator()(LC->getLHS(), RC->getLHS()))
493 return true;
494 if (operator()(RC->getLHS(), LC->getLHS()))
495 return false;
496 if (operator()(LC->getRHS(), RC->getRHS()))
497 return true;
498 if (operator()(RC->getRHS(), LC->getRHS()))
499 return false;
500 return false;
501 }
502
Dan Gohman5d486452009-05-07 14:39:04 +0000503 // Compare cast expressions by operand.
504 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
505 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
506 return operator()(LC->getOperand(), RC->getOperand());
507 }
508
Edwin Török675d5622009-07-11 20:10:48 +0000509 LLVM_UNREACHABLE("Unknown SCEV kind!");
Dan Gohman5d486452009-05-07 14:39:04 +0000510 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000511 }
512 };
513}
514
515/// GroupByComplexity - Given a list of SCEV objects, order them by their
516/// complexity, and group objects of the same complexity together by value.
517/// When this routine is finished, we know that any duplicates in the vector are
518/// consecutive and that complexity is monotonically increasing.
519///
520/// Note that we go take special precautions to ensure that we get determinstic
521/// results from this routine. In other words, we don't want the results of
522/// this to depend on where the addresses of various SCEV objects happened to
523/// land in memory.
524///
Dan Gohman161ea032009-07-07 17:06:11 +0000525static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
Dan Gohman5d486452009-05-07 14:39:04 +0000526 LoopInfo *LI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000527 if (Ops.size() < 2) return; // Noop
528 if (Ops.size() == 2) {
529 // This is the common case, which also happens to be trivially simple.
530 // Special case it.
Dan Gohman5d486452009-05-07 14:39:04 +0000531 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000532 std::swap(Ops[0], Ops[1]);
533 return;
534 }
535
536 // Do the rough sort by complexity.
Dan Gohman5d486452009-05-07 14:39:04 +0000537 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000538
539 // Now that we are sorted by complexity, group elements of the same
540 // complexity. Note that this is, at worst, N^2, but the vector is likely to
541 // be extremely short in practice. Note that we take this approach because we
542 // do not want to depend on the addresses of the objects we are grouping.
543 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Dan Gohmanbff6b582009-05-04 22:30:44 +0000544 const SCEV *S = Ops[i];
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000545 unsigned Complexity = S->getSCEVType();
546
547 // If there are any objects of the same complexity and same value as this
548 // one, group them.
549 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
550 if (Ops[j] == S) { // Found a duplicate.
551 // Move it to immediately after i'th element.
552 std::swap(Ops[i+1], Ops[j]);
553 ++i; // no need to rescan it.
554 if (i == e-2) return; // Done!
555 }
556 }
557 }
558}
559
560
561
562//===----------------------------------------------------------------------===//
563// Simple SCEV method implementations
564//===----------------------------------------------------------------------===//
565
Eli Friedman7489ec92008-08-04 23:49:06 +0000566/// BinomialCoefficient - Compute BC(It, K). The result has width W.
Dan Gohmanc8a29272009-05-24 23:45:28 +0000567/// Assume, K > 0.
Dan Gohman161ea032009-07-07 17:06:11 +0000568static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
Eli Friedman7489ec92008-08-04 23:49:06 +0000569 ScalarEvolution &SE,
Dan Gohman01c2ee72009-04-16 03:18:22 +0000570 const Type* ResultTy) {
Eli Friedman7489ec92008-08-04 23:49:06 +0000571 // Handle the simplest case efficiently.
572 if (K == 1)
573 return SE.getTruncateOrZeroExtend(It, ResultTy);
574
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000575 // We are using the following formula for BC(It, K):
576 //
577 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
578 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000579 // Suppose, W is the bitwidth of the return value. We must be prepared for
580 // overflow. Hence, we must assure that the result of our computation is
581 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
582 // safe in modular arithmetic.
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000583 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000584 // However, this code doesn't use exactly that formula; the formula it uses
Dan Gohman9bc642f2009-06-24 04:48:43 +0000585 // is something like the following, where T is the number of factors of 2 in
Eli Friedman7489ec92008-08-04 23:49:06 +0000586 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
587 // exponentiation:
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000588 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000589 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000590 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000591 // This formula is trivially equivalent to the previous formula. However,
592 // this formula can be implemented much more efficiently. The trick is that
593 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
594 // arithmetic. To do exact division in modular arithmetic, all we have
595 // to do is multiply by the inverse. Therefore, this step can be done at
596 // width W.
Dan Gohman9bc642f2009-06-24 04:48:43 +0000597 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000598 // The next issue is how to safely do the division by 2^T. The way this
599 // is done is by doing the multiplication step at a width of at least W + T
600 // bits. This way, the bottom W+T bits of the product are accurate. Then,
601 // when we perform the division by 2^T (which is equivalent to a right shift
602 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
603 // truncated out after the division by 2^T.
604 //
605 // In comparison to just directly using the first formula, this technique
606 // is much more efficient; using the first formula requires W * K bits,
607 // but this formula less than W + K bits. Also, the first formula requires
608 // a division step, whereas this formula only requires multiplies and shifts.
609 //
610 // It doesn't matter whether the subtraction step is done in the calculation
611 // width or the input iteration count's width; if the subtraction overflows,
612 // the result must be zero anyway. We prefer here to do it in the width of
613 // the induction variable because it helps a lot for certain cases; CodeGen
614 // isn't smart enough to ignore the overflow, which leads to much less
615 // efficient code if the width of the subtraction is wider than the native
616 // register width.
617 //
618 // (It's possible to not widen at all by pulling out factors of 2 before
619 // the multiplication; for example, K=2 can be calculated as
620 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
621 // extra arithmetic, so it's not an obvious win, and it gets
622 // much more complicated for K > 3.)
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000623
Eli Friedman7489ec92008-08-04 23:49:06 +0000624 // Protection from insane SCEVs; this bound is conservative,
625 // but it probably doesn't matter.
626 if (K > 1000)
Dan Gohman0ad08b02009-04-18 17:58:19 +0000627 return SE.getCouldNotCompute();
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000628
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000629 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000630
Eli Friedman7489ec92008-08-04 23:49:06 +0000631 // Calculate K! / 2^T and T; we divide out the factors of two before
632 // multiplying for calculating K! / 2^T to avoid overflow.
633 // Other overflow doesn't matter because we only care about the bottom
634 // W bits of the result.
635 APInt OddFactorial(W, 1);
636 unsigned T = 1;
637 for (unsigned i = 3; i <= K; ++i) {
638 APInt Mult(W, i);
639 unsigned TwoFactors = Mult.countTrailingZeros();
640 T += TwoFactors;
641 Mult = Mult.lshr(TwoFactors);
642 OddFactorial *= Mult;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000643 }
Nick Lewyckydbaa60a2008-06-13 04:38:55 +0000644
Eli Friedman7489ec92008-08-04 23:49:06 +0000645 // We need at least W + T bits for the multiplication step
nicholas9e3e5fd2009-01-25 08:16:27 +0000646 unsigned CalculationBits = W + T;
Eli Friedman7489ec92008-08-04 23:49:06 +0000647
648 // Calcuate 2^T, at width T+W.
649 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
650
651 // Calculate the multiplicative inverse of K! / 2^T;
652 // this multiplication factor will perform the exact division by
653 // K! / 2^T.
654 APInt Mod = APInt::getSignedMinValue(W+1);
655 APInt MultiplyFactor = OddFactorial.zext(W+1);
656 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
657 MultiplyFactor = MultiplyFactor.trunc(W);
658
659 // Calculate the product, at width T+W
660 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
Dan Gohman161ea032009-07-07 17:06:11 +0000661 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
Eli Friedman7489ec92008-08-04 23:49:06 +0000662 for (unsigned i = 1; i != K; ++i) {
Dan Gohman161ea032009-07-07 17:06:11 +0000663 const SCEV *S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
Eli Friedman7489ec92008-08-04 23:49:06 +0000664 Dividend = SE.getMulExpr(Dividend,
665 SE.getTruncateOrZeroExtend(S, CalculationTy));
666 }
667
668 // Divide by 2^T
Dan Gohman161ea032009-07-07 17:06:11 +0000669 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
Eli Friedman7489ec92008-08-04 23:49:06 +0000670
671 // Truncate the result, and divide by K! / 2^T.
672
673 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
674 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000675}
676
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000677/// evaluateAtIteration - Return the value of this chain of recurrences at
678/// the specified iteration number. We can evaluate this recurrence by
679/// multiplying each element in the chain by the binomial coefficient
680/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
681///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000682/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000683///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000684/// where BC(It, k) stands for binomial coefficient.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000685///
Dan Gohman161ea032009-07-07 17:06:11 +0000686const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
Dan Gohman89f85052007-10-22 18:31:58 +0000687 ScalarEvolution &SE) const {
Dan Gohman161ea032009-07-07 17:06:11 +0000688 const SCEV *Result = getStart();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000689 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000690 // The computation is correct in the face of overflow provided that the
691 // multiplication is performed _after_ the evaluation of the binomial
692 // coefficient.
Dan Gohman161ea032009-07-07 17:06:11 +0000693 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckyb6218e02008-10-13 03:58:02 +0000694 if (isa<SCEVCouldNotCompute>(Coeff))
695 return Coeff;
696
697 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000698 }
699 return Result;
700}
701
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000702//===----------------------------------------------------------------------===//
703// SCEV Expression folder implementations
704//===----------------------------------------------------------------------===//
705
Dan Gohman161ea032009-07-07 17:06:11 +0000706const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
Dan Gohman9c8abcc2009-05-01 16:44:56 +0000707 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000708 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000709 "This is not a truncating conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000710 assert(isSCEVable(Ty) &&
711 "This is not a conversion to a SCEVable type!");
712 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000713
Dan Gohmand43a8282009-07-13 20:50:19 +0000714 FoldingSetNodeID ID;
715 ID.AddInteger(scTruncate);
716 ID.AddPointer(Op);
717 ID.AddPointer(Ty);
718 void *IP = 0;
719 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
720
Dan Gohmanc86c0df2009-06-30 20:13:32 +0000721 // Fold if the operand is constant.
Dan Gohmanc76b5452009-05-04 22:02:23 +0000722 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman55788cf2009-06-24 00:38:39 +0000723 return getConstant(
724 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000725
Dan Gohman1a5c4992009-04-22 16:20:48 +0000726 // trunc(trunc(x)) --> trunc(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000727 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000728 return getTruncateExpr(ST->getOperand(), Ty);
729
Nick Lewycky37d04642009-04-23 05:15:08 +0000730 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohmanc76b5452009-05-04 22:02:23 +0000731 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewycky37d04642009-04-23 05:15:08 +0000732 return getTruncateOrSignExtend(SS->getOperand(), Ty);
733
734 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohmanc76b5452009-05-04 22:02:23 +0000735 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewycky37d04642009-04-23 05:15:08 +0000736 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
737
Dan Gohman1c0aa2c2009-06-18 16:24:47 +0000738 // If the input value is a chrec scev, truncate the chrec's operands.
Dan Gohmanc76b5452009-05-04 22:02:23 +0000739 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohman161ea032009-07-07 17:06:11 +0000740 SmallVector<const SCEV *, 4> Operands;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000741 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman45b3b542009-05-08 21:03:19 +0000742 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
743 return getAddRecExpr(Operands, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000744 }
745
Dan Gohmand43a8282009-07-13 20:50:19 +0000746 // The cast wasn't folded; create an explicit cast node.
747 // Recompute the insert position, as it may have been invalidated.
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000748 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
749 SCEV *S = SCEVAllocator.Allocate<SCEVTruncateExpr>();
Dan Gohmand43a8282009-07-13 20:50:19 +0000750 new (S) SCEVTruncateExpr(ID, Op, Ty);
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000751 UniqueSCEVs.InsertNode(S, IP);
752 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000753}
754
Dan Gohman161ea032009-07-07 17:06:11 +0000755const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
Dan Gohman36d40922009-04-16 19:25:55 +0000756 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000757 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman36d40922009-04-16 19:25:55 +0000758 "This is not an extending conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000759 assert(isSCEVable(Ty) &&
760 "This is not a conversion to a SCEVable type!");
761 Ty = getEffectiveSCEVType(Ty);
Dan Gohman36d40922009-04-16 19:25:55 +0000762
Dan Gohmanc86c0df2009-06-30 20:13:32 +0000763 // Fold if the operand is constant.
Dan Gohmanc76b5452009-05-04 22:02:23 +0000764 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000765 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000766 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
767 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
Dan Gohman55788cf2009-06-24 00:38:39 +0000768 return getConstant(cast<ConstantInt>(C));
Dan Gohman01c2ee72009-04-16 03:18:22 +0000769 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000770
Dan Gohman1a5c4992009-04-22 16:20:48 +0000771 // zext(zext(x)) --> zext(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000772 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000773 return getZeroExtendExpr(SZ->getOperand(), Ty);
774
Dan Gohmandb888422009-07-13 20:55:53 +0000775 // Before doing any expensive analysis, check to see if we've already
776 // computed a SCEV for this Op and Ty.
777 FoldingSetNodeID ID;
778 ID.AddInteger(scZeroExtend);
779 ID.AddPointer(Op);
780 ID.AddPointer(Ty);
781 void *IP = 0;
782 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
783
Dan Gohmana9dba962009-04-27 20:16:15 +0000784 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000785 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohmana9dba962009-04-27 20:16:15 +0000786 // operands (often constants). This allows analysis of something like
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000787 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmanc76b5452009-05-04 22:02:23 +0000788 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohmana9dba962009-04-27 20:16:15 +0000789 if (AR->isAffine()) {
790 // Check whether the backedge-taken count is SCEVCouldNotCompute.
791 // Note that this serves two purposes: It filters out loops that are
792 // simply not analyzable, and it covers the case where this code is
793 // being called from within backedge-taken count analysis, such that
794 // attempting to ask for the backedge-taken count would likely result
795 // in infinite recursion. In the later case, the analysis code will
796 // cope with a conservative value, and it will take care to purge
797 // that value once it has finished.
Nick Lewycky9425be92009-07-11 20:38:25 +0000798 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000799 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman4ada77f2009-04-29 01:54:20 +0000800 // Manually compute the final value for AR, checking for
Dan Gohman3ded5b22009-04-29 22:28:28 +0000801 // overflow.
Nick Lewycky9425be92009-07-11 20:38:25 +0000802 const SCEV *Start = AR->getStart();
803 const SCEV *Step = AR->getStepRecurrence(*this);
Dan Gohmana9dba962009-04-27 20:16:15 +0000804
805 // Check whether the backedge-taken count can be losslessly casted to
806 // the addrec's type. The count is always unsigned.
Dan Gohman161ea032009-07-07 17:06:11 +0000807 const SCEV *CastedMaxBECount =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000808 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman161ea032009-07-07 17:06:11 +0000809 const SCEV *RecastedMaxBECount =
Dan Gohman3bb37f52009-05-18 15:58:39 +0000810 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
811 if (MaxBECount == RecastedMaxBECount) {
Nick Lewycky9425be92009-07-11 20:38:25 +0000812 const Type *WideTy =
813 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000814 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohman161ea032009-07-07 17:06:11 +0000815 const SCEV *ZMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000816 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000817 getTruncateOrZeroExtend(Step, Start->getType()));
Dan Gohman161ea032009-07-07 17:06:11 +0000818 const SCEV *Add = getAddExpr(Start, ZMul);
819 const SCEV *OperandExtendedAdd =
Dan Gohman3bb37f52009-05-18 15:58:39 +0000820 getAddExpr(getZeroExtendExpr(Start, WideTy),
821 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
822 getZeroExtendExpr(Step, WideTy)));
823 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman3ded5b22009-04-29 22:28:28 +0000824 // Return the expression with the addrec on the outside.
825 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
826 getZeroExtendExpr(Step, Ty),
Nick Lewycky9425be92009-07-11 20:38:25 +0000827 AR->getLoop());
Dan Gohmana9dba962009-04-27 20:16:15 +0000828
829 // Similar to above, only this time treat the step value as signed.
830 // This covers loops that count down.
Dan Gohman161ea032009-07-07 17:06:11 +0000831 const SCEV *SMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000832 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000833 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohman3ded5b22009-04-29 22:28:28 +0000834 Add = getAddExpr(Start, SMul);
Dan Gohman3bb37f52009-05-18 15:58:39 +0000835 OperandExtendedAdd =
836 getAddExpr(getZeroExtendExpr(Start, WideTy),
837 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
838 getSignExtendExpr(Step, WideTy)));
839 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman3ded5b22009-04-29 22:28:28 +0000840 // Return the expression with the addrec on the outside.
841 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
842 getSignExtendExpr(Step, Ty),
Nick Lewycky9425be92009-07-11 20:38:25 +0000843 AR->getLoop());
Dan Gohmana9dba962009-04-27 20:16:15 +0000844 }
845 }
846 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000847
Dan Gohmandb888422009-07-13 20:55:53 +0000848 // The cast wasn't folded; create an explicit cast node.
849 // Recompute the insert position, as it may have been invalidated.
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000850 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
851 SCEV *S = SCEVAllocator.Allocate<SCEVZeroExtendExpr>();
Dan Gohmand43a8282009-07-13 20:50:19 +0000852 new (S) SCEVZeroExtendExpr(ID, Op, Ty);
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000853 UniqueSCEVs.InsertNode(S, IP);
854 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000855}
856
Dan Gohman161ea032009-07-07 17:06:11 +0000857const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
Dan Gohmana9dba962009-04-27 20:16:15 +0000858 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000859 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000860 "This is not an extending conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000861 assert(isSCEVable(Ty) &&
862 "This is not a conversion to a SCEVable type!");
863 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000864
Dan Gohmanc86c0df2009-06-30 20:13:32 +0000865 // Fold if the operand is constant.
Dan Gohmanc76b5452009-05-04 22:02:23 +0000866 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000867 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000868 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
869 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
Dan Gohman55788cf2009-06-24 00:38:39 +0000870 return getConstant(cast<ConstantInt>(C));
Dan Gohman01c2ee72009-04-16 03:18:22 +0000871 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000872
Dan Gohman1a5c4992009-04-22 16:20:48 +0000873 // sext(sext(x)) --> sext(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000874 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000875 return getSignExtendExpr(SS->getOperand(), Ty);
876
Dan Gohmandb888422009-07-13 20:55:53 +0000877 // Before doing any expensive analysis, check to see if we've already
878 // computed a SCEV for this Op and Ty.
879 FoldingSetNodeID ID;
880 ID.AddInteger(scSignExtend);
881 ID.AddPointer(Op);
882 ID.AddPointer(Ty);
883 void *IP = 0;
884 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
885
Dan Gohmana9dba962009-04-27 20:16:15 +0000886 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000887 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohmana9dba962009-04-27 20:16:15 +0000888 // operands (often constants). This allows analysis of something like
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000889 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmanc76b5452009-05-04 22:02:23 +0000890 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohmana9dba962009-04-27 20:16:15 +0000891 if (AR->isAffine()) {
892 // Check whether the backedge-taken count is SCEVCouldNotCompute.
893 // Note that this serves two purposes: It filters out loops that are
894 // simply not analyzable, and it covers the case where this code is
895 // being called from within backedge-taken count analysis, such that
896 // attempting to ask for the backedge-taken count would likely result
897 // in infinite recursion. In the later case, the analysis code will
898 // cope with a conservative value, and it will take care to purge
899 // that value once it has finished.
Nick Lewycky9425be92009-07-11 20:38:25 +0000900 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000901 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman4ada77f2009-04-29 01:54:20 +0000902 // Manually compute the final value for AR, checking for
Dan Gohman3ded5b22009-04-29 22:28:28 +0000903 // overflow.
Nick Lewycky9425be92009-07-11 20:38:25 +0000904 const SCEV *Start = AR->getStart();
905 const SCEV *Step = AR->getStepRecurrence(*this);
Dan Gohmana9dba962009-04-27 20:16:15 +0000906
907 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohman3ded5b22009-04-29 22:28:28 +0000908 // the addrec's type. The count is always unsigned.
Dan Gohman161ea032009-07-07 17:06:11 +0000909 const SCEV *CastedMaxBECount =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000910 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman161ea032009-07-07 17:06:11 +0000911 const SCEV *RecastedMaxBECount =
Dan Gohman3bb37f52009-05-18 15:58:39 +0000912 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
913 if (MaxBECount == RecastedMaxBECount) {
Nick Lewycky9425be92009-07-11 20:38:25 +0000914 const Type *WideTy =
915 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000916 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman161ea032009-07-07 17:06:11 +0000917 const SCEV *SMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000918 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000919 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohman161ea032009-07-07 17:06:11 +0000920 const SCEV *Add = getAddExpr(Start, SMul);
921 const SCEV *OperandExtendedAdd =
Dan Gohman3bb37f52009-05-18 15:58:39 +0000922 getAddExpr(getSignExtendExpr(Start, WideTy),
923 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
924 getSignExtendExpr(Step, WideTy)));
925 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman3ded5b22009-04-29 22:28:28 +0000926 // Return the expression with the addrec on the outside.
927 return getAddRecExpr(getSignExtendExpr(Start, Ty),
928 getSignExtendExpr(Step, Ty),
Nick Lewycky9425be92009-07-11 20:38:25 +0000929 AR->getLoop());
Dan Gohmana9dba962009-04-27 20:16:15 +0000930 }
931 }
932 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000933
Dan Gohmandb888422009-07-13 20:55:53 +0000934 // The cast wasn't folded; create an explicit cast node.
935 // Recompute the insert position, as it may have been invalidated.
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000936 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
937 SCEV *S = SCEVAllocator.Allocate<SCEVSignExtendExpr>();
Dan Gohmand43a8282009-07-13 20:50:19 +0000938 new (S) SCEVSignExtendExpr(ID, Op, Ty);
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000939 UniqueSCEVs.InsertNode(S, IP);
940 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000941}
942
Dan Gohmane1ca7e82009-06-13 15:56:47 +0000943/// getAnyExtendExpr - Return a SCEV for the given operand extended with
944/// unspecified bits out to the given type.
945///
Dan Gohman161ea032009-07-07 17:06:11 +0000946const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
Dan Gohmane1ca7e82009-06-13 15:56:47 +0000947 const Type *Ty) {
948 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
949 "This is not an extending conversion!");
950 assert(isSCEVable(Ty) &&
951 "This is not a conversion to a SCEVable type!");
952 Ty = getEffectiveSCEVType(Ty);
953
954 // Sign-extend negative constants.
955 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
956 if (SC->getValue()->getValue().isNegative())
957 return getSignExtendExpr(Op, Ty);
958
959 // Peel off a truncate cast.
960 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
Dan Gohman161ea032009-07-07 17:06:11 +0000961 const SCEV *NewOp = T->getOperand();
Dan Gohmane1ca7e82009-06-13 15:56:47 +0000962 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
963 return getAnyExtendExpr(NewOp, Ty);
964 return getTruncateOrNoop(NewOp, Ty);
965 }
966
967 // Next try a zext cast. If the cast is folded, use it.
Dan Gohman161ea032009-07-07 17:06:11 +0000968 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
Dan Gohmane1ca7e82009-06-13 15:56:47 +0000969 if (!isa<SCEVZeroExtendExpr>(ZExt))
970 return ZExt;
971
972 // Next try a sext cast. If the cast is folded, use it.
Dan Gohman161ea032009-07-07 17:06:11 +0000973 const SCEV *SExt = getSignExtendExpr(Op, Ty);
Dan Gohmane1ca7e82009-06-13 15:56:47 +0000974 if (!isa<SCEVSignExtendExpr>(SExt))
975 return SExt;
976
977 // If the expression is obviously signed, use the sext cast value.
978 if (isa<SCEVSMaxExpr>(Op))
979 return SExt;
980
981 // Absent any other information, use the zext cast value.
982 return ZExt;
983}
984
Dan Gohman27bd4cb2009-06-14 22:58:51 +0000985/// CollectAddOperandsWithScales - Process the given Ops list, which is
986/// a list of operands to be added under the given scale, update the given
987/// map. This is a helper function for getAddRecExpr. As an example of
988/// what it does, given a sequence of operands that would form an add
989/// expression like this:
990///
991/// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
992///
993/// where A and B are constants, update the map with these values:
994///
995/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
996///
997/// and add 13 + A*B*29 to AccumulatedConstant.
998/// This will allow getAddRecExpr to produce this:
999///
1000/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1001///
1002/// This form often exposes folding opportunities that are hidden in
1003/// the original operand list.
1004///
1005/// Return true iff it appears that any interesting folding opportunities
1006/// may be exposed. This helps getAddRecExpr short-circuit extra work in
1007/// the common case where no interesting opportunities are present, and
1008/// is also used as a check to avoid infinite recursion.
1009///
1010static bool
Dan Gohman161ea032009-07-07 17:06:11 +00001011CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1012 SmallVector<const SCEV *, 8> &NewOps,
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001013 APInt &AccumulatedConstant,
Dan Gohman161ea032009-07-07 17:06:11 +00001014 const SmallVectorImpl<const SCEV *> &Ops,
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001015 const APInt &Scale,
1016 ScalarEvolution &SE) {
1017 bool Interesting = false;
1018
1019 // Iterate over the add operands.
1020 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1021 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1022 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1023 APInt NewScale =
1024 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1025 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1026 // A multiplication of a constant with another add; recurse.
1027 Interesting |=
1028 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1029 cast<SCEVAddExpr>(Mul->getOperand(1))
1030 ->getOperands(),
1031 NewScale, SE);
1032 } else {
1033 // A multiplication of a constant with some other value. Update
1034 // the map.
Dan Gohman161ea032009-07-07 17:06:11 +00001035 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1036 const SCEV *Key = SE.getMulExpr(MulOps);
1037 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman3bf01f02009-06-29 18:25:52 +00001038 M.insert(std::make_pair(Key, NewScale));
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001039 if (Pair.second) {
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001040 NewOps.push_back(Pair.first->first);
1041 } else {
1042 Pair.first->second += NewScale;
1043 // The map already had an entry for this value, which may indicate
1044 // a folding opportunity.
1045 Interesting = true;
1046 }
1047 }
1048 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1049 // Pull a buried constant out to the outside.
1050 if (Scale != 1 || AccumulatedConstant != 0 || C->isZero())
1051 Interesting = true;
1052 AccumulatedConstant += Scale * C->getValue()->getValue();
1053 } else {
1054 // An ordinary operand. Update the map.
Dan Gohman161ea032009-07-07 17:06:11 +00001055 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman3bf01f02009-06-29 18:25:52 +00001056 M.insert(std::make_pair(Ops[i], Scale));
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001057 if (Pair.second) {
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001058 NewOps.push_back(Pair.first->first);
1059 } else {
1060 Pair.first->second += Scale;
1061 // The map already had an entry for this value, which may indicate
1062 // a folding opportunity.
1063 Interesting = true;
1064 }
1065 }
1066 }
1067
1068 return Interesting;
1069}
1070
1071namespace {
1072 struct APIntCompare {
1073 bool operator()(const APInt &LHS, const APInt &RHS) const {
1074 return LHS.ult(RHS);
1075 }
1076 };
1077}
1078
Dan Gohmanc8a29272009-05-24 23:45:28 +00001079/// getAddExpr - Get a canonical add expression, or something simpler if
1080/// possible.
Dan Gohman161ea032009-07-07 17:06:11 +00001081const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001082 assert(!Ops.empty() && "Cannot get empty add!");
1083 if (Ops.size() == 1) return Ops[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001084#ifndef NDEBUG
1085 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1086 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1087 getEffectiveSCEVType(Ops[0]->getType()) &&
1088 "SCEVAddExpr operand types don't match!");
1089#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001090
1091 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001092 GroupByComplexity(Ops, LI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001093
1094 // If there are any constants, fold them together.
1095 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001096 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001097 ++Idx;
1098 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001099 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001100 // We found two constants, fold them together!
Dan Gohman02ff9392009-06-14 22:47:23 +00001101 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1102 RHSC->getValue()->getValue());
Dan Gohman68f23e82009-06-14 22:53:57 +00001103 if (Ops.size() == 2) return Ops[0];
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001104 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001105 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001106 }
1107
1108 // If we are left with a constant zero being added, strip it off.
1109 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1110 Ops.erase(Ops.begin());
1111 --Idx;
1112 }
1113 }
1114
1115 if (Ops.size() == 1) return Ops[0];
1116
1117 // Okay, check to see if the same value occurs in the operand list twice. If
1118 // so, merge them together into an multiply expression. Since we sorted the
1119 // list, these values are required to be adjacent.
1120 const Type *Ty = Ops[0]->getType();
1121 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1122 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1123 // Found a match, merge the two values into a multiply, and add any
1124 // remaining values to the result.
Dan Gohman161ea032009-07-07 17:06:11 +00001125 const SCEV *Two = getIntegerSCEV(2, Ty);
1126 const SCEV *Mul = getMulExpr(Ops[i], Two);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001127 if (Ops.size() == 2)
1128 return Mul;
1129 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
1130 Ops.push_back(Mul);
Dan Gohman89f85052007-10-22 18:31:58 +00001131 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001132 }
1133
Dan Gohman45b3b542009-05-08 21:03:19 +00001134 // Check for truncates. If all the operands are truncated from the same
1135 // type, see if factoring out the truncate would permit the result to be
1136 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1137 // if the contents of the resulting outer trunc fold to something simple.
1138 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1139 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1140 const Type *DstType = Trunc->getType();
1141 const Type *SrcType = Trunc->getOperand()->getType();
Dan Gohman161ea032009-07-07 17:06:11 +00001142 SmallVector<const SCEV *, 8> LargeOps;
Dan Gohman45b3b542009-05-08 21:03:19 +00001143 bool Ok = true;
1144 // Check all the operands to see if they can be represented in the
1145 // source type of the truncate.
1146 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1147 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1148 if (T->getOperand()->getType() != SrcType) {
1149 Ok = false;
1150 break;
1151 }
1152 LargeOps.push_back(T->getOperand());
1153 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1154 // This could be either sign or zero extension, but sign extension
1155 // is much more likely to be foldable here.
1156 LargeOps.push_back(getSignExtendExpr(C, SrcType));
1157 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Dan Gohman161ea032009-07-07 17:06:11 +00001158 SmallVector<const SCEV *, 8> LargeMulOps;
Dan Gohman45b3b542009-05-08 21:03:19 +00001159 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1160 if (const SCEVTruncateExpr *T =
1161 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1162 if (T->getOperand()->getType() != SrcType) {
1163 Ok = false;
1164 break;
1165 }
1166 LargeMulOps.push_back(T->getOperand());
1167 } else if (const SCEVConstant *C =
1168 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1169 // This could be either sign or zero extension, but sign extension
1170 // is much more likely to be foldable here.
1171 LargeMulOps.push_back(getSignExtendExpr(C, SrcType));
1172 } else {
1173 Ok = false;
1174 break;
1175 }
1176 }
1177 if (Ok)
1178 LargeOps.push_back(getMulExpr(LargeMulOps));
1179 } else {
1180 Ok = false;
1181 break;
1182 }
1183 }
1184 if (Ok) {
1185 // Evaluate the expression in the larger type.
Dan Gohman161ea032009-07-07 17:06:11 +00001186 const SCEV *Fold = getAddExpr(LargeOps);
Dan Gohman45b3b542009-05-08 21:03:19 +00001187 // If it folds to something simple, use it. Otherwise, don't.
1188 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1189 return getTruncateExpr(Fold, DstType);
1190 }
1191 }
1192
1193 // Skip past any other cast SCEVs.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001194 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1195 ++Idx;
1196
1197 // If there are add operands they would be next.
1198 if (Idx < Ops.size()) {
1199 bool DeletedAdd = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001200 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001201 // If we have an add, expand the add operands onto the end of the operands
1202 // list.
1203 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
1204 Ops.erase(Ops.begin()+Idx);
1205 DeletedAdd = true;
1206 }
1207
1208 // If we deleted at least one add, we added operands to the end of the list,
1209 // and they are not necessarily sorted. Recurse to resort and resimplify
1210 // any operands we just aquired.
1211 if (DeletedAdd)
Dan Gohman89f85052007-10-22 18:31:58 +00001212 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001213 }
1214
1215 // Skip over the add expression until we get to a multiply.
1216 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1217 ++Idx;
1218
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001219 // Check to see if there are any folding opportunities present with
1220 // operands multiplied by constant values.
1221 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1222 uint64_t BitWidth = getTypeSizeInBits(Ty);
Dan Gohman161ea032009-07-07 17:06:11 +00001223 DenseMap<const SCEV *, APInt> M;
1224 SmallVector<const SCEV *, 8> NewOps;
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001225 APInt AccumulatedConstant(BitWidth, 0);
1226 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1227 Ops, APInt(BitWidth, 1), *this)) {
1228 // Some interesting folding opportunity is present, so its worthwhile to
1229 // re-generate the operands list. Group the operands by constant scale,
1230 // to avoid multiplying by the same constant scale multiple times.
Dan Gohman161ea032009-07-07 17:06:11 +00001231 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
1232 for (SmallVector<const SCEV *, 8>::iterator I = NewOps.begin(),
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001233 E = NewOps.end(); I != E; ++I)
1234 MulOpLists[M.find(*I)->second].push_back(*I);
1235 // Re-generate the operands list.
1236 Ops.clear();
1237 if (AccumulatedConstant != 0)
1238 Ops.push_back(getConstant(AccumulatedConstant));
Dan Gohman9bc642f2009-06-24 04:48:43 +00001239 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1240 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001241 if (I->first != 0)
Dan Gohman9bc642f2009-06-24 04:48:43 +00001242 Ops.push_back(getMulExpr(getConstant(I->first),
1243 getAddExpr(I->second)));
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001244 if (Ops.empty())
1245 return getIntegerSCEV(0, Ty);
1246 if (Ops.size() == 1)
1247 return Ops[0];
1248 return getAddExpr(Ops);
1249 }
1250 }
1251
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001252 // If we are adding something to a multiply expression, make sure the
1253 // something is not already an operand of the multiply. If so, merge it into
1254 // the multiply.
1255 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001256 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001257 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001258 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001259 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohman02ff9392009-06-14 22:47:23 +00001260 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(Ops[AddOp])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001261 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Dan Gohman161ea032009-07-07 17:06:11 +00001262 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001263 if (Mul->getNumOperands() != 2) {
1264 // If the multiply has more than two operands, we must get the
1265 // Y*Z term.
Dan Gohman161ea032009-07-07 17:06:11 +00001266 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), Mul->op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001267 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001268 InnerMul = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001269 }
Dan Gohman161ea032009-07-07 17:06:11 +00001270 const SCEV *One = getIntegerSCEV(1, Ty);
1271 const SCEV *AddOne = getAddExpr(InnerMul, One);
1272 const SCEV *OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001273 if (Ops.size() == 2) return OuterMul;
1274 if (AddOp < Idx) {
1275 Ops.erase(Ops.begin()+AddOp);
1276 Ops.erase(Ops.begin()+Idx-1);
1277 } else {
1278 Ops.erase(Ops.begin()+Idx);
1279 Ops.erase(Ops.begin()+AddOp-1);
1280 }
1281 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +00001282 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001283 }
1284
1285 // Check this multiply against other multiplies being added together.
1286 for (unsigned OtherMulIdx = Idx+1;
1287 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1288 ++OtherMulIdx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001289 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001290 // If MulOp occurs in OtherMul, we can fold the two multiplies
1291 // together.
1292 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1293 OMulOp != e; ++OMulOp)
1294 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1295 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Dan Gohman161ea032009-07-07 17:06:11 +00001296 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001297 if (Mul->getNumOperands() != 2) {
Dan Gohman9bc642f2009-06-24 04:48:43 +00001298 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1299 Mul->op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001300 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001301 InnerMul1 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001302 }
Dan Gohman161ea032009-07-07 17:06:11 +00001303 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001304 if (OtherMul->getNumOperands() != 2) {
Dan Gohman9bc642f2009-06-24 04:48:43 +00001305 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
1306 OtherMul->op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001307 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001308 InnerMul2 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001309 }
Dan Gohman161ea032009-07-07 17:06:11 +00001310 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1311 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001312 if (Ops.size() == 2) return OuterMul;
1313 Ops.erase(Ops.begin()+Idx);
1314 Ops.erase(Ops.begin()+OtherMulIdx-1);
1315 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +00001316 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001317 }
1318 }
1319 }
1320 }
1321
1322 // If there are any add recurrences in the operands list, see if any other
1323 // added values are loop invariant. If so, we can fold them into the
1324 // recurrence.
1325 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1326 ++Idx;
1327
1328 // Scan over all recurrences, trying to fold loop invariants into them.
1329 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1330 // Scan all of the other operands to this add and add them to the vector if
1331 // they are loop invariant w.r.t. the recurrence.
Dan Gohman161ea032009-07-07 17:06:11 +00001332 SmallVector<const SCEV *, 8> LIOps;
Dan Gohmanbff6b582009-05-04 22:30:44 +00001333 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001334 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1335 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1336 LIOps.push_back(Ops[i]);
1337 Ops.erase(Ops.begin()+i);
1338 --i; --e;
1339 }
1340
1341 // If we found some loop invariants, fold them into the recurrence.
1342 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001343 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001344 LIOps.push_back(AddRec->getStart());
1345
Dan Gohman161ea032009-07-07 17:06:11 +00001346 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
Dan Gohman02ff9392009-06-14 22:47:23 +00001347 AddRec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001348 AddRecOps[0] = getAddExpr(LIOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001349
Dan Gohman161ea032009-07-07 17:06:11 +00001350 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001351 // If all of the other operands were loop invariant, we are done.
1352 if (Ops.size() == 1) return NewRec;
1353
1354 // Otherwise, add the folded AddRec by the non-liv parts.
1355 for (unsigned i = 0;; ++i)
1356 if (Ops[i] == AddRec) {
1357 Ops[i] = NewRec;
1358 break;
1359 }
Dan Gohman89f85052007-10-22 18:31:58 +00001360 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001361 }
1362
1363 // Okay, if there weren't any loop invariants to be folded, check to see if
1364 // there are multiple AddRec's with the same loop induction variable being
1365 // added together. If so, we can fold them.
1366 for (unsigned OtherIdx = Idx+1;
1367 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1368 if (OtherIdx != Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001369 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001370 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1371 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
Dan Gohman9bc642f2009-06-24 04:48:43 +00001372 SmallVector<const SCEV *, 4> NewOps(AddRec->op_begin(),
1373 AddRec->op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001374 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1375 if (i >= NewOps.size()) {
1376 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1377 OtherAddRec->op_end());
1378 break;
1379 }
Dan Gohman89f85052007-10-22 18:31:58 +00001380 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001381 }
Dan Gohman161ea032009-07-07 17:06:11 +00001382 const SCEV *NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001383
1384 if (Ops.size() == 2) return NewAddRec;
1385
1386 Ops.erase(Ops.begin()+Idx);
1387 Ops.erase(Ops.begin()+OtherIdx-1);
1388 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001389 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001390 }
1391 }
1392
1393 // Otherwise couldn't fold anything into this recurrence. Move onto the
1394 // next one.
1395 }
1396
1397 // Okay, it looks like we really DO need an add expr. Check to see if we
1398 // already have one, otherwise create a new one.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001399 FoldingSetNodeID ID;
1400 ID.AddInteger(scAddExpr);
1401 ID.AddInteger(Ops.size());
1402 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1403 ID.AddPointer(Ops[i]);
1404 void *IP = 0;
1405 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1406 SCEV *S = SCEVAllocator.Allocate<SCEVAddExpr>();
Dan Gohmand43a8282009-07-13 20:50:19 +00001407 new (S) SCEVAddExpr(ID, Ops);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001408 UniqueSCEVs.InsertNode(S, IP);
1409 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001410}
1411
1412
Dan Gohmanc8a29272009-05-24 23:45:28 +00001413/// getMulExpr - Get a canonical multiply expression, or something simpler if
1414/// possible.
Dan Gohman161ea032009-07-07 17:06:11 +00001415const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001416 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohmana77b3d42009-05-18 15:44:58 +00001417#ifndef NDEBUG
1418 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1419 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1420 getEffectiveSCEVType(Ops[0]->getType()) &&
1421 "SCEVMulExpr operand types don't match!");
1422#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001423
1424 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001425 GroupByComplexity(Ops, LI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001426
1427 // If there are any constants, fold them together.
1428 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001429 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001430
1431 // C1*(C2+V) -> C1*C2 + C1*V
1432 if (Ops.size() == 2)
Dan Gohmanc76b5452009-05-04 22:02:23 +00001433 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001434 if (Add->getNumOperands() == 2 &&
1435 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman89f85052007-10-22 18:31:58 +00001436 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1437 getMulExpr(LHSC, Add->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001438
1439
1440 ++Idx;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001441 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001442 // We found two constants, fold them together!
Dan Gohman9bc642f2009-06-24 04:48:43 +00001443 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001444 RHSC->getValue()->getValue());
1445 Ops[0] = getConstant(Fold);
1446 Ops.erase(Ops.begin()+1); // Erase the folded element
1447 if (Ops.size() == 1) return Ops[0];
1448 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001449 }
1450
1451 // If we are left with a constant one being multiplied, strip it off.
1452 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1453 Ops.erase(Ops.begin());
1454 --Idx;
1455 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1456 // If we have a multiply of zero, it will always be zero.
1457 return Ops[0];
1458 }
1459 }
1460
1461 // Skip over the add expression until we get to a multiply.
1462 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1463 ++Idx;
1464
1465 if (Ops.size() == 1)
1466 return Ops[0];
1467
1468 // If there are mul operands inline them all into this expression.
1469 if (Idx < Ops.size()) {
1470 bool DeletedMul = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001471 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001472 // If we have an mul, expand the mul operands onto the end of the operands
1473 // list.
1474 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1475 Ops.erase(Ops.begin()+Idx);
1476 DeletedMul = true;
1477 }
1478
1479 // If we deleted at least one mul, we added operands to the end of the list,
1480 // and they are not necessarily sorted. Recurse to resort and resimplify
1481 // any operands we just aquired.
1482 if (DeletedMul)
Dan Gohman89f85052007-10-22 18:31:58 +00001483 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001484 }
1485
1486 // If there are any add recurrences in the operands list, see if any other
1487 // added values are loop invariant. If so, we can fold them into the
1488 // recurrence.
1489 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1490 ++Idx;
1491
1492 // Scan over all recurrences, trying to fold loop invariants into them.
1493 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1494 // Scan all of the other operands to this mul and add them to the vector if
1495 // they are loop invariant w.r.t. the recurrence.
Dan Gohman161ea032009-07-07 17:06:11 +00001496 SmallVector<const SCEV *, 8> LIOps;
Dan Gohmanbff6b582009-05-04 22:30:44 +00001497 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001498 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1499 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1500 LIOps.push_back(Ops[i]);
1501 Ops.erase(Ops.begin()+i);
1502 --i; --e;
1503 }
1504
1505 // If we found some loop invariants, fold them into the recurrence.
1506 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001507 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohman161ea032009-07-07 17:06:11 +00001508 SmallVector<const SCEV *, 4> NewOps;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001509 NewOps.reserve(AddRec->getNumOperands());
1510 if (LIOps.size() == 1) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001511 const SCEV *Scale = LIOps[0];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001512 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman89f85052007-10-22 18:31:58 +00001513 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001514 } else {
1515 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
Dan Gohman161ea032009-07-07 17:06:11 +00001516 SmallVector<const SCEV *, 4> MulOps(LIOps.begin(), LIOps.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001517 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman89f85052007-10-22 18:31:58 +00001518 NewOps.push_back(getMulExpr(MulOps));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001519 }
1520 }
1521
Dan Gohman161ea032009-07-07 17:06:11 +00001522 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001523
1524 // If all of the other operands were loop invariant, we are done.
1525 if (Ops.size() == 1) return NewRec;
1526
1527 // Otherwise, multiply the folded AddRec by the non-liv parts.
1528 for (unsigned i = 0;; ++i)
1529 if (Ops[i] == AddRec) {
1530 Ops[i] = NewRec;
1531 break;
1532 }
Dan Gohman89f85052007-10-22 18:31:58 +00001533 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001534 }
1535
1536 // Okay, if there weren't any loop invariants to be folded, check to see if
1537 // there are multiple AddRec's with the same loop induction variable being
1538 // multiplied together. If so, we can fold them.
1539 for (unsigned OtherIdx = Idx+1;
1540 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1541 if (OtherIdx != Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001542 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001543 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1544 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
Dan Gohmanbff6b582009-05-04 22:30:44 +00001545 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman161ea032009-07-07 17:06:11 +00001546 const SCEV *NewStart = getMulExpr(F->getStart(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001547 G->getStart());
Dan Gohman161ea032009-07-07 17:06:11 +00001548 const SCEV *B = F->getStepRecurrence(*this);
1549 const SCEV *D = G->getStepRecurrence(*this);
1550 const SCEV *NewStep = getAddExpr(getMulExpr(F, D),
Dan Gohman89f85052007-10-22 18:31:58 +00001551 getMulExpr(G, B),
1552 getMulExpr(B, D));
Dan Gohman161ea032009-07-07 17:06:11 +00001553 const SCEV *NewAddRec = getAddRecExpr(NewStart, NewStep,
Dan Gohman89f85052007-10-22 18:31:58 +00001554 F->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001555 if (Ops.size() == 2) return NewAddRec;
1556
1557 Ops.erase(Ops.begin()+Idx);
1558 Ops.erase(Ops.begin()+OtherIdx-1);
1559 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001560 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001561 }
1562 }
1563
1564 // Otherwise couldn't fold anything into this recurrence. Move onto the
1565 // next one.
1566 }
1567
1568 // Okay, it looks like we really DO need an mul expr. Check to see if we
1569 // already have one, otherwise create a new one.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001570 FoldingSetNodeID ID;
1571 ID.AddInteger(scMulExpr);
1572 ID.AddInteger(Ops.size());
1573 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1574 ID.AddPointer(Ops[i]);
1575 void *IP = 0;
1576 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1577 SCEV *S = SCEVAllocator.Allocate<SCEVMulExpr>();
Dan Gohmand43a8282009-07-13 20:50:19 +00001578 new (S) SCEVMulExpr(ID, Ops);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001579 UniqueSCEVs.InsertNode(S, IP);
1580 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001581}
1582
Dan Gohmanc8a29272009-05-24 23:45:28 +00001583/// getUDivExpr - Get a canonical multiply expression, or something simpler if
1584/// possible.
Dan Gohman8c4f20b2009-06-24 14:49:00 +00001585const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
1586 const SCEV *RHS) {
Dan Gohmana77b3d42009-05-18 15:44:58 +00001587 assert(getEffectiveSCEVType(LHS->getType()) ==
1588 getEffectiveSCEVType(RHS->getType()) &&
1589 "SCEVUDivExpr operand types don't match!");
1590
Dan Gohmanc76b5452009-05-04 22:02:23 +00001591 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001592 if (RHSC->getValue()->equalsInt(1))
Nick Lewycky35b56022009-01-13 09:18:58 +00001593 return LHS; // X udiv 1 --> x
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001594 if (RHSC->isZero())
1595 return getIntegerSCEV(0, LHS->getType()); // value is undefined
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001596
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001597 // Determine if the division can be folded into the operands of
1598 // its operands.
1599 // TODO: Generalize this to non-constants by using known-bits information.
1600 const Type *Ty = LHS->getType();
1601 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1602 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1603 // For non-power-of-two values, effectively round the value up to the
1604 // nearest power of two.
1605 if (!RHSC->getValue()->getValue().isPowerOf2())
1606 ++MaxShiftAmt;
1607 const IntegerType *ExtTy =
1608 IntegerType::get(getTypeSizeInBits(Ty) + MaxShiftAmt);
1609 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1610 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1611 if (const SCEVConstant *Step =
1612 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1613 if (!Step->getValue()->getValue()
1614 .urem(RHSC->getValue()->getValue()) &&
Dan Gohman14374d32009-05-08 23:11:16 +00001615 getZeroExtendExpr(AR, ExtTy) ==
1616 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1617 getZeroExtendExpr(Step, ExtTy),
1618 AR->getLoop())) {
Dan Gohman161ea032009-07-07 17:06:11 +00001619 SmallVector<const SCEV *, 4> Operands;
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001620 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1621 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1622 return getAddRecExpr(Operands, AR->getLoop());
1623 }
1624 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
Dan Gohman14374d32009-05-08 23:11:16 +00001625 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
Dan Gohman161ea032009-07-07 17:06:11 +00001626 SmallVector<const SCEV *, 4> Operands;
Dan Gohman14374d32009-05-08 23:11:16 +00001627 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1628 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1629 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001630 // Find an operand that's safely divisible.
1631 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
Dan Gohman161ea032009-07-07 17:06:11 +00001632 const SCEV *Op = M->getOperand(i);
1633 const SCEV *Div = getUDivExpr(Op, RHSC);
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001634 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
Dan Gohman161ea032009-07-07 17:06:11 +00001635 const SmallVectorImpl<const SCEV *> &MOperands = M->getOperands();
1636 Operands = SmallVector<const SCEV *, 4>(MOperands.begin(),
Dan Gohman02ff9392009-06-14 22:47:23 +00001637 MOperands.end());
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001638 Operands[i] = Div;
1639 return getMulExpr(Operands);
1640 }
1641 }
Dan Gohman14374d32009-05-08 23:11:16 +00001642 }
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001643 // (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 +00001644 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
Dan Gohman161ea032009-07-07 17:06:11 +00001645 SmallVector<const SCEV *, 4> Operands;
Dan Gohman14374d32009-05-08 23:11:16 +00001646 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1647 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1648 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1649 Operands.clear();
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001650 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
Dan Gohman161ea032009-07-07 17:06:11 +00001651 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001652 if (isa<SCEVUDivExpr>(Op) || getMulExpr(Op, RHS) != A->getOperand(i))
1653 break;
1654 Operands.push_back(Op);
1655 }
1656 if (Operands.size() == A->getNumOperands())
1657 return getAddExpr(Operands);
1658 }
Dan Gohman14374d32009-05-08 23:11:16 +00001659 }
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001660
1661 // Fold if both operands are constant.
Dan Gohmanc76b5452009-05-04 22:02:23 +00001662 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001663 Constant *LHSCV = LHSC->getValue();
1664 Constant *RHSCV = RHSC->getValue();
Dan Gohman55788cf2009-06-24 00:38:39 +00001665 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
1666 RHSCV)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001667 }
1668 }
1669
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001670 FoldingSetNodeID ID;
1671 ID.AddInteger(scUDivExpr);
1672 ID.AddPointer(LHS);
1673 ID.AddPointer(RHS);
1674 void *IP = 0;
1675 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1676 SCEV *S = SCEVAllocator.Allocate<SCEVUDivExpr>();
Dan Gohmand43a8282009-07-13 20:50:19 +00001677 new (S) SCEVUDivExpr(ID, LHS, RHS);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001678 UniqueSCEVs.InsertNode(S, IP);
1679 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001680}
1681
1682
Dan Gohmanc8a29272009-05-24 23:45:28 +00001683/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1684/// Simplify the expression as much as possible.
Dan Gohman161ea032009-07-07 17:06:11 +00001685const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start,
1686 const SCEV *Step, const Loop *L) {
1687 SmallVector<const SCEV *, 4> Operands;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001688 Operands.push_back(Start);
Dan Gohmanc76b5452009-05-04 22:02:23 +00001689 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001690 if (StepChrec->getLoop() == L) {
1691 Operands.insert(Operands.end(), StepChrec->op_begin(),
1692 StepChrec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001693 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001694 }
1695
1696 Operands.push_back(Step);
Dan Gohman89f85052007-10-22 18:31:58 +00001697 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001698}
1699
Dan Gohmanc8a29272009-05-24 23:45:28 +00001700/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1701/// Simplify the expression as much as possible.
Dan Gohman9bc642f2009-06-24 04:48:43 +00001702const SCEV *
Dan Gohman161ea032009-07-07 17:06:11 +00001703ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
Dan Gohman9bc642f2009-06-24 04:48:43 +00001704 const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001705 if (Operands.size() == 1) return Operands[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001706#ifndef NDEBUG
1707 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1708 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
1709 getEffectiveSCEVType(Operands[0]->getType()) &&
1710 "SCEVAddRecExpr operand types don't match!");
1711#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001712
Dan Gohman7b560c42008-06-18 16:23:07 +00001713 if (Operands.back()->isZero()) {
1714 Operands.pop_back();
Dan Gohmanabe991f2008-09-14 17:21:12 +00001715 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohman7b560c42008-06-18 16:23:07 +00001716 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001717
Dan Gohman42936882008-08-08 18:33:12 +00001718 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohmanc76b5452009-05-04 22:02:23 +00001719 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohman42936882008-08-08 18:33:12 +00001720 const Loop* NestedLoop = NestedAR->getLoop();
1721 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
Dan Gohman161ea032009-07-07 17:06:11 +00001722 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohman02ff9392009-06-14 22:47:23 +00001723 NestedAR->op_end());
Dan Gohman42936882008-08-08 18:33:12 +00001724 Operands[0] = NestedAR->getStart();
Dan Gohman08c4c072009-06-26 22:36:20 +00001725 // AddRecs require their operands be loop-invariant with respect to their
1726 // loops. Don't perform this transformation if it would break this
1727 // requirement.
1728 bool AllInvariant = true;
1729 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1730 if (!Operands[i]->isLoopInvariant(L)) {
1731 AllInvariant = false;
1732 break;
1733 }
1734 if (AllInvariant) {
1735 NestedOperands[0] = getAddRecExpr(Operands, L);
1736 AllInvariant = true;
1737 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
1738 if (!NestedOperands[i]->isLoopInvariant(NestedLoop)) {
1739 AllInvariant = false;
1740 break;
1741 }
1742 if (AllInvariant)
1743 // Ok, both add recurrences are valid after the transformation.
1744 return getAddRecExpr(NestedOperands, NestedLoop);
1745 }
1746 // Reset Operands to its original state.
1747 Operands[0] = NestedAR;
Dan Gohman42936882008-08-08 18:33:12 +00001748 }
1749 }
1750
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001751 FoldingSetNodeID ID;
1752 ID.AddInteger(scAddRecExpr);
1753 ID.AddInteger(Operands.size());
1754 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1755 ID.AddPointer(Operands[i]);
1756 ID.AddPointer(L);
1757 void *IP = 0;
1758 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1759 SCEV *S = SCEVAllocator.Allocate<SCEVAddRecExpr>();
Dan Gohmand43a8282009-07-13 20:50:19 +00001760 new (S) SCEVAddRecExpr(ID, Operands, L);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001761 UniqueSCEVs.InsertNode(S, IP);
1762 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001763}
1764
Dan Gohman8c4f20b2009-06-24 14:49:00 +00001765const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
1766 const SCEV *RHS) {
Dan Gohman161ea032009-07-07 17:06:11 +00001767 SmallVector<const SCEV *, 2> Ops;
Nick Lewycky711640a2007-11-25 22:41:31 +00001768 Ops.push_back(LHS);
1769 Ops.push_back(RHS);
1770 return getSMaxExpr(Ops);
1771}
1772
Dan Gohman161ea032009-07-07 17:06:11 +00001773const SCEV *
1774ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001775 assert(!Ops.empty() && "Cannot get empty smax!");
1776 if (Ops.size() == 1) return Ops[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001777#ifndef NDEBUG
1778 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1779 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1780 getEffectiveSCEVType(Ops[0]->getType()) &&
1781 "SCEVSMaxExpr operand types don't match!");
1782#endif
Nick Lewycky711640a2007-11-25 22:41:31 +00001783
1784 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001785 GroupByComplexity(Ops, LI);
Nick Lewycky711640a2007-11-25 22:41:31 +00001786
1787 // If there are any constants, fold them together.
1788 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001789 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001790 ++Idx;
1791 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001792 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001793 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001794 ConstantInt *Fold = ConstantInt::get(
Nick Lewycky711640a2007-11-25 22:41:31 +00001795 APIntOps::smax(LHSC->getValue()->getValue(),
1796 RHSC->getValue()->getValue()));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001797 Ops[0] = getConstant(Fold);
1798 Ops.erase(Ops.begin()+1); // Erase the folded element
1799 if (Ops.size() == 1) return Ops[0];
1800 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewycky711640a2007-11-25 22:41:31 +00001801 }
1802
Dan Gohmand156c092009-06-24 14:46:22 +00001803 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky711640a2007-11-25 22:41:31 +00001804 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1805 Ops.erase(Ops.begin());
1806 --Idx;
Dan Gohmand156c092009-06-24 14:46:22 +00001807 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
1808 // If we have an smax with a constant maximum-int, it will always be
1809 // maximum-int.
1810 return Ops[0];
Nick Lewycky711640a2007-11-25 22:41:31 +00001811 }
1812 }
1813
1814 if (Ops.size() == 1) return Ops[0];
1815
1816 // Find the first SMax
1817 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1818 ++Idx;
1819
1820 // Check to see if one of the operands is an SMax. If so, expand its operands
1821 // onto our operand list, and recurse to simplify.
1822 if (Idx < Ops.size()) {
1823 bool DeletedSMax = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001824 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001825 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1826 Ops.erase(Ops.begin()+Idx);
1827 DeletedSMax = true;
1828 }
1829
1830 if (DeletedSMax)
1831 return getSMaxExpr(Ops);
1832 }
1833
1834 // Okay, check to see if the same value occurs in the operand list twice. If
1835 // so, delete one. Since we sorted the list, these values are required to
1836 // be adjacent.
1837 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1838 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1839 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1840 --i; --e;
1841 }
1842
1843 if (Ops.size() == 1) return Ops[0];
1844
1845 assert(!Ops.empty() && "Reduced smax down to nothing!");
1846
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001847 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewycky711640a2007-11-25 22:41:31 +00001848 // already have one, otherwise create a new one.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001849 FoldingSetNodeID ID;
1850 ID.AddInteger(scSMaxExpr);
1851 ID.AddInteger(Ops.size());
1852 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1853 ID.AddPointer(Ops[i]);
1854 void *IP = 0;
1855 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1856 SCEV *S = SCEVAllocator.Allocate<SCEVSMaxExpr>();
Dan Gohmand43a8282009-07-13 20:50:19 +00001857 new (S) SCEVSMaxExpr(ID, Ops);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001858 UniqueSCEVs.InsertNode(S, IP);
1859 return S;
Nick Lewycky711640a2007-11-25 22:41:31 +00001860}
1861
Dan Gohman8c4f20b2009-06-24 14:49:00 +00001862const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
1863 const SCEV *RHS) {
Dan Gohman161ea032009-07-07 17:06:11 +00001864 SmallVector<const SCEV *, 2> Ops;
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001865 Ops.push_back(LHS);
1866 Ops.push_back(RHS);
1867 return getUMaxExpr(Ops);
1868}
1869
Dan Gohman161ea032009-07-07 17:06:11 +00001870const SCEV *
1871ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001872 assert(!Ops.empty() && "Cannot get empty umax!");
1873 if (Ops.size() == 1) return Ops[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001874#ifndef NDEBUG
1875 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1876 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1877 getEffectiveSCEVType(Ops[0]->getType()) &&
1878 "SCEVUMaxExpr operand types don't match!");
1879#endif
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001880
1881 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001882 GroupByComplexity(Ops, LI);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001883
1884 // If there are any constants, fold them together.
1885 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001886 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001887 ++Idx;
1888 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001889 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001890 // We found two constants, fold them together!
1891 ConstantInt *Fold = ConstantInt::get(
1892 APIntOps::umax(LHSC->getValue()->getValue(),
1893 RHSC->getValue()->getValue()));
1894 Ops[0] = getConstant(Fold);
1895 Ops.erase(Ops.begin()+1); // Erase the folded element
1896 if (Ops.size() == 1) return Ops[0];
1897 LHSC = cast<SCEVConstant>(Ops[0]);
1898 }
1899
Dan Gohmand156c092009-06-24 14:46:22 +00001900 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001901 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1902 Ops.erase(Ops.begin());
1903 --Idx;
Dan Gohmand156c092009-06-24 14:46:22 +00001904 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
1905 // If we have an umax with a constant maximum-int, it will always be
1906 // maximum-int.
1907 return Ops[0];
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001908 }
1909 }
1910
1911 if (Ops.size() == 1) return Ops[0];
1912
1913 // Find the first UMax
1914 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1915 ++Idx;
1916
1917 // Check to see if one of the operands is a UMax. If so, expand its operands
1918 // onto our operand list, and recurse to simplify.
1919 if (Idx < Ops.size()) {
1920 bool DeletedUMax = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001921 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001922 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1923 Ops.erase(Ops.begin()+Idx);
1924 DeletedUMax = true;
1925 }
1926
1927 if (DeletedUMax)
1928 return getUMaxExpr(Ops);
1929 }
1930
1931 // Okay, check to see if the same value occurs in the operand list twice. If
1932 // so, delete one. Since we sorted the list, these values are required to
1933 // be adjacent.
1934 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1935 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1936 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1937 --i; --e;
1938 }
1939
1940 if (Ops.size() == 1) return Ops[0];
1941
1942 assert(!Ops.empty() && "Reduced umax down to nothing!");
1943
1944 // Okay, it looks like we really DO need a umax expr. Check to see if we
1945 // already have one, otherwise create a new one.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001946 FoldingSetNodeID ID;
1947 ID.AddInteger(scUMaxExpr);
1948 ID.AddInteger(Ops.size());
1949 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1950 ID.AddPointer(Ops[i]);
1951 void *IP = 0;
1952 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1953 SCEV *S = SCEVAllocator.Allocate<SCEVUMaxExpr>();
Dan Gohmand43a8282009-07-13 20:50:19 +00001954 new (S) SCEVUMaxExpr(ID, Ops);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001955 UniqueSCEVs.InsertNode(S, IP);
1956 return S;
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001957}
1958
Dan Gohman8c4f20b2009-06-24 14:49:00 +00001959const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
1960 const SCEV *RHS) {
Dan Gohmand01fff82009-06-22 03:18:45 +00001961 // ~smax(~x, ~y) == smin(x, y).
1962 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
1963}
1964
Dan Gohman8c4f20b2009-06-24 14:49:00 +00001965const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
1966 const SCEV *RHS) {
Dan Gohmand01fff82009-06-22 03:18:45 +00001967 // ~umax(~x, ~y) == umin(x, y)
1968 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
1969}
1970
Dan Gohman161ea032009-07-07 17:06:11 +00001971const SCEV *ScalarEvolution::getUnknown(Value *V) {
Dan Gohman984c78a2009-06-24 00:54:57 +00001972 // Don't attempt to do anything other than create a SCEVUnknown object
1973 // here. createSCEV only calls getUnknown after checking for all other
1974 // interesting possibilities, and any other code that calls getUnknown
1975 // is doing so in order to hide a value from SCEV canonicalization.
1976
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001977 FoldingSetNodeID ID;
1978 ID.AddInteger(scUnknown);
1979 ID.AddPointer(V);
1980 void *IP = 0;
1981 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1982 SCEV *S = SCEVAllocator.Allocate<SCEVUnknown>();
Dan Gohmand43a8282009-07-13 20:50:19 +00001983 new (S) SCEVUnknown(ID, V);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001984 UniqueSCEVs.InsertNode(S, IP);
1985 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001986}
1987
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001988//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001989// Basic SCEV Analysis and PHI Idiom Recognition Code
1990//
1991
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001992/// isSCEVable - Test if values of the given type are analyzable within
1993/// the SCEV framework. This primarily includes integer types, and it
1994/// can optionally include pointer types if the ScalarEvolution class
1995/// has access to target-specific information.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001996bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001997 // Integers are always SCEVable.
1998 if (Ty->isInteger())
1999 return true;
2000
2001 // Pointers are SCEVable if TargetData information is available
2002 // to provide pointer size information.
2003 if (isa<PointerType>(Ty))
2004 return TD != NULL;
2005
2006 // Otherwise it's not SCEVable.
2007 return false;
2008}
2009
2010/// getTypeSizeInBits - Return the size in bits of the specified type,
2011/// for which isSCEVable must return true.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002012uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002013 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2014
2015 // If we have a TargetData, use it!
2016 if (TD)
2017 return TD->getTypeSizeInBits(Ty);
2018
2019 // Otherwise, we support only integer types.
2020 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
2021 return Ty->getPrimitiveSizeInBits();
2022}
2023
2024/// getEffectiveSCEVType - Return a type with the same bitwidth as
2025/// the given type and which represents how SCEV will treat the given
2026/// type, for which isSCEVable must return true. For pointer types,
2027/// this is the pointer-sized integer type.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002028const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002029 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2030
2031 if (Ty->isInteger())
2032 return Ty;
2033
2034 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
2035 return TD->getIntPtrType();
Dan Gohman01c2ee72009-04-16 03:18:22 +00002036}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002037
Dan Gohman161ea032009-07-07 17:06:11 +00002038const SCEV *ScalarEvolution::getCouldNotCompute() {
Dan Gohmanc6475cb2009-06-27 21:21:31 +00002039 return &CouldNotCompute;
Dan Gohman0ad08b02009-04-18 17:58:19 +00002040}
2041
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002042/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2043/// expression and create a new one.
Dan Gohman161ea032009-07-07 17:06:11 +00002044const SCEV *ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002045 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002046
Dan Gohman161ea032009-07-07 17:06:11 +00002047 std::map<SCEVCallbackVH, const SCEV *>::iterator I = Scalars.find(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002048 if (I != Scalars.end()) return I->second;
Dan Gohman161ea032009-07-07 17:06:11 +00002049 const SCEV *S = createSCEV(V);
Dan Gohmanbff6b582009-05-04 22:30:44 +00002050 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002051 return S;
2052}
2053
Dan Gohman984c78a2009-06-24 00:54:57 +00002054/// getIntegerSCEV - Given a SCEVable type, create a constant for the
Dan Gohman01c2ee72009-04-16 03:18:22 +00002055/// specified signed integer value and return a SCEV for the constant.
Dan Gohman161ea032009-07-07 17:06:11 +00002056const SCEV *ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
Dan Gohman984c78a2009-06-24 00:54:57 +00002057 const IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
2058 return getConstant(ConstantInt::get(ITy, Val));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002059}
2060
2061/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2062///
Dan Gohman161ea032009-07-07 17:06:11 +00002063const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00002064 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson15b39322009-07-13 04:09:18 +00002065 return getConstant(
2066 cast<ConstantInt>(Context->getConstantExprNeg(VC->getValue())));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002067
2068 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002069 Ty = getEffectiveSCEVType(Ty);
2070 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(Ty)));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002071}
2072
2073/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohman161ea032009-07-07 17:06:11 +00002074const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00002075 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohman55788cf2009-06-24 00:38:39 +00002076 return getConstant(cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002077
2078 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002079 Ty = getEffectiveSCEVType(Ty);
Dan Gohman161ea032009-07-07 17:06:11 +00002080 const SCEV *AllOnes = getConstant(ConstantInt::getAllOnesValue(Ty));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002081 return getMinusSCEV(AllOnes, V);
2082}
2083
2084/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2085///
Dan Gohman8c4f20b2009-06-24 14:49:00 +00002086const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS,
2087 const SCEV *RHS) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00002088 // X - Y --> X + -Y
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002089 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002090}
2091
2092/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2093/// input value to the specified type. If the type must be extended, it is zero
2094/// extended.
Dan Gohman161ea032009-07-07 17:06:11 +00002095const SCEV *
2096ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V,
Nick Lewycky37d04642009-04-23 05:15:08 +00002097 const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00002098 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002099 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2100 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00002101 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002102 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00002103 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002104 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002105 return getTruncateExpr(V, Ty);
2106 return getZeroExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002107}
2108
2109/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2110/// input value to the specified type. If the type must be extended, it is sign
2111/// extended.
Dan Gohman161ea032009-07-07 17:06:11 +00002112const SCEV *
2113ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
Nick Lewycky37d04642009-04-23 05:15:08 +00002114 const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00002115 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002116 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2117 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00002118 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002119 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00002120 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002121 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002122 return getTruncateExpr(V, Ty);
2123 return getSignExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002124}
2125
Dan Gohmanac959332009-05-13 03:46:30 +00002126/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2127/// input value to the specified type. If the type must be extended, it is zero
2128/// extended. The conversion must not be narrowing.
Dan Gohman161ea032009-07-07 17:06:11 +00002129const SCEV *
2130ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, const Type *Ty) {
Dan Gohmanac959332009-05-13 03:46:30 +00002131 const Type *SrcTy = V->getType();
2132 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2133 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2134 "Cannot noop or zero extend with non-integer arguments!");
2135 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2136 "getNoopOrZeroExtend cannot truncate!");
2137 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2138 return V; // No conversion
2139 return getZeroExtendExpr(V, Ty);
2140}
2141
2142/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2143/// input value to the specified type. If the type must be extended, it is sign
2144/// extended. The conversion must not be narrowing.
Dan Gohman161ea032009-07-07 17:06:11 +00002145const SCEV *
2146ScalarEvolution::getNoopOrSignExtend(const SCEV *V, const Type *Ty) {
Dan Gohmanac959332009-05-13 03:46:30 +00002147 const Type *SrcTy = V->getType();
2148 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2149 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2150 "Cannot noop or sign extend with non-integer arguments!");
2151 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2152 "getNoopOrSignExtend cannot truncate!");
2153 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2154 return V; // No conversion
2155 return getSignExtendExpr(V, Ty);
2156}
2157
Dan Gohmane1ca7e82009-06-13 15:56:47 +00002158/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2159/// the input value to the specified type. If the type must be extended,
2160/// it is extended with unspecified bits. The conversion must not be
2161/// narrowing.
Dan Gohman161ea032009-07-07 17:06:11 +00002162const SCEV *
2163ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, const Type *Ty) {
Dan Gohmane1ca7e82009-06-13 15:56:47 +00002164 const Type *SrcTy = V->getType();
2165 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2166 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2167 "Cannot noop or any extend with non-integer arguments!");
2168 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2169 "getNoopOrAnyExtend cannot truncate!");
2170 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2171 return V; // No conversion
2172 return getAnyExtendExpr(V, Ty);
2173}
2174
Dan Gohmanac959332009-05-13 03:46:30 +00002175/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2176/// input value to the specified type. The conversion must not be widening.
Dan Gohman161ea032009-07-07 17:06:11 +00002177const SCEV *
2178ScalarEvolution::getTruncateOrNoop(const SCEV *V, const Type *Ty) {
Dan Gohmanac959332009-05-13 03:46:30 +00002179 const Type *SrcTy = V->getType();
2180 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2181 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2182 "Cannot truncate or noop with non-integer arguments!");
2183 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2184 "getTruncateOrNoop cannot extend!");
2185 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2186 return V; // No conversion
2187 return getTruncateExpr(V, Ty);
2188}
2189
Dan Gohman8e8b5232009-06-22 00:31:57 +00002190/// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2191/// the types using zero-extension, and then perform a umax operation
2192/// with them.
Dan Gohman8c4f20b2009-06-24 14:49:00 +00002193const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2194 const SCEV *RHS) {
Dan Gohman161ea032009-07-07 17:06:11 +00002195 const SCEV *PromotedLHS = LHS;
2196 const SCEV *PromotedRHS = RHS;
Dan Gohman8e8b5232009-06-22 00:31:57 +00002197
2198 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2199 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2200 else
2201 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2202
2203 return getUMaxExpr(PromotedLHS, PromotedRHS);
2204}
2205
Dan Gohman9e62bb02009-06-22 15:03:27 +00002206/// getUMinFromMismatchedTypes - Promote the operands to the wider of
2207/// the types using zero-extension, and then perform a umin operation
2208/// with them.
Dan Gohman8c4f20b2009-06-24 14:49:00 +00002209const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2210 const SCEV *RHS) {
Dan Gohman161ea032009-07-07 17:06:11 +00002211 const SCEV *PromotedLHS = LHS;
2212 const SCEV *PromotedRHS = RHS;
Dan Gohman9e62bb02009-06-22 15:03:27 +00002213
2214 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2215 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2216 else
2217 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2218
2219 return getUMinExpr(PromotedLHS, PromotedRHS);
2220}
2221
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002222/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
2223/// the specified instruction and replaces any references to the symbolic value
2224/// SymName with the specified value. This is used during PHI resolution.
Dan Gohman9bc642f2009-06-24 04:48:43 +00002225void
2226ScalarEvolution::ReplaceSymbolicValueWithConcrete(Instruction *I,
2227 const SCEV *SymName,
2228 const SCEV *NewVal) {
Dan Gohman161ea032009-07-07 17:06:11 +00002229 std::map<SCEVCallbackVH, const SCEV *>::iterator SI =
Dan Gohmanbff6b582009-05-04 22:30:44 +00002230 Scalars.find(SCEVCallbackVH(I, this));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002231 if (SI == Scalars.end()) return;
2232
Dan Gohman161ea032009-07-07 17:06:11 +00002233 const SCEV *NV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002234 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002235 if (NV == SI->second) return; // No change.
2236
2237 SI->second = NV; // Update the scalars map!
2238
2239 // Any instruction values that use this instruction might also need to be
2240 // updated!
2241 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
2242 UI != E; ++UI)
2243 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
2244}
2245
2246/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2247/// a loop header, making it a potential recurrence, or it doesn't.
2248///
Dan Gohman161ea032009-07-07 17:06:11 +00002249const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002250 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002251 if (const Loop *L = LI->getLoopFor(PN->getParent()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002252 if (L->getHeader() == PN->getParent()) {
2253 // If it lives in the loop header, it has two incoming values, one
2254 // from outside the loop, and one from inside.
2255 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
2256 unsigned BackEdge = IncomingEdge^1;
2257
2258 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohman161ea032009-07-07 17:06:11 +00002259 const SCEV *SymbolicName = getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002260 assert(Scalars.find(PN) == Scalars.end() &&
2261 "PHI node already processed?");
Dan Gohmanbff6b582009-05-04 22:30:44 +00002262 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002263
2264 // Using this symbolic name for the PHI, analyze the value coming around
2265 // the back-edge.
Dan Gohman161ea032009-07-07 17:06:11 +00002266 const SCEV *BEValue = getSCEV(PN->getIncomingValue(BackEdge));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002267
2268 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2269 // has a special value for the first iteration of the loop.
2270
2271 // If the value coming around the backedge is an add with the symbolic
2272 // value we just inserted, then we found a simple induction variable!
Dan Gohmanc76b5452009-05-04 22:02:23 +00002273 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002274 // If there is a single occurrence of the symbolic value, replace it
2275 // with a recurrence.
2276 unsigned FoundIndex = Add->getNumOperands();
2277 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2278 if (Add->getOperand(i) == SymbolicName)
2279 if (FoundIndex == e) {
2280 FoundIndex = i;
2281 break;
2282 }
2283
2284 if (FoundIndex != Add->getNumOperands()) {
2285 // Create an add with everything but the specified operand.
Dan Gohman161ea032009-07-07 17:06:11 +00002286 SmallVector<const SCEV *, 8> Ops;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002287 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2288 if (i != FoundIndex)
2289 Ops.push_back(Add->getOperand(i));
Dan Gohman161ea032009-07-07 17:06:11 +00002290 const SCEV *Accum = getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002291
2292 // This is not a valid addrec if the step amount is varying each
2293 // loop iteration, but is not itself an addrec in this loop.
2294 if (Accum->isLoopInvariant(L) ||
2295 (isa<SCEVAddRecExpr>(Accum) &&
2296 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
Dan Gohman9bc642f2009-06-24 04:48:43 +00002297 const SCEV *StartVal =
2298 getSCEV(PN->getIncomingValue(IncomingEdge));
2299 const SCEV *PHISCEV =
2300 getAddRecExpr(StartVal, Accum, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002301
2302 // Okay, for the entire analysis of this edge we assumed the PHI
2303 // to be symbolic. We now need to go back and update all of the
2304 // entries for the scalars that use the PHI (except for the PHI
2305 // itself) to use the new analyzed value instead of the "symbolic"
2306 // value.
2307 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
2308 return PHISCEV;
2309 }
2310 }
Dan Gohmanc76b5452009-05-04 22:02:23 +00002311 } else if (const SCEVAddRecExpr *AddRec =
2312 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002313 // Otherwise, this could be a loop like this:
2314 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2315 // In this case, j = {1,+,1} and BEValue is j.
2316 // Because the other in-value of i (0) fits the evolution of BEValue
2317 // i really is an addrec evolution.
2318 if (AddRec->getLoop() == L && AddRec->isAffine()) {
Dan Gohman161ea032009-07-07 17:06:11 +00002319 const SCEV *StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002320
2321 // If StartVal = j.start - j.stride, we can use StartVal as the
2322 // initial step of the addrec evolution.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002323 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman89f85052007-10-22 18:31:58 +00002324 AddRec->getOperand(1))) {
Dan Gohman161ea032009-07-07 17:06:11 +00002325 const SCEV *PHISCEV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002326 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002327
2328 // Okay, for the entire analysis of this edge we assumed the PHI
2329 // to be symbolic. We now need to go back and update all of the
2330 // entries for the scalars that use the PHI (except for the PHI
2331 // itself) to use the new analyzed value instead of the "symbolic"
2332 // value.
2333 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
2334 return PHISCEV;
2335 }
2336 }
2337 }
2338
2339 return SymbolicName;
2340 }
2341
2342 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002343 return getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002344}
2345
Dan Gohman509cf4d2009-05-08 20:26:55 +00002346/// createNodeForGEP - Expand GEP instructions into add and multiply
2347/// operations. This allows them to be analyzed by regular SCEV code.
2348///
Dan Gohman161ea032009-07-07 17:06:11 +00002349const SCEV *ScalarEvolution::createNodeForGEP(User *GEP) {
Dan Gohman509cf4d2009-05-08 20:26:55 +00002350
2351 const Type *IntPtrTy = TD->getIntPtrType();
Dan Gohmanc7034fa2009-05-08 20:36:47 +00002352 Value *Base = GEP->getOperand(0);
Dan Gohmand586a4f2009-05-09 00:14:52 +00002353 // Don't attempt to analyze GEPs over unsized objects.
2354 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2355 return getUnknown(GEP);
Dan Gohman161ea032009-07-07 17:06:11 +00002356 const SCEV *TotalOffset = getIntegerSCEV(0, IntPtrTy);
Dan Gohmanc7034fa2009-05-08 20:36:47 +00002357 gep_type_iterator GTI = gep_type_begin(GEP);
2358 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
2359 E = GEP->op_end();
Dan Gohman509cf4d2009-05-08 20:26:55 +00002360 I != E; ++I) {
2361 Value *Index = *I;
2362 // Compute the (potentially symbolic) offset in bytes for this index.
2363 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2364 // For a struct, add the member offset.
2365 const StructLayout &SL = *TD->getStructLayout(STy);
2366 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
2367 uint64_t Offset = SL.getElementOffset(FieldNo);
Nick Lewycky9425be92009-07-11 20:38:25 +00002368 TotalOffset = getAddExpr(TotalOffset,
2369 getIntegerSCEV(Offset, IntPtrTy));
Dan Gohman509cf4d2009-05-08 20:26:55 +00002370 } else {
2371 // For an array, add the element offset, explicitly scaled.
Dan Gohman161ea032009-07-07 17:06:11 +00002372 const SCEV *LocalOffset = getSCEV(Index);
Dan Gohman509cf4d2009-05-08 20:26:55 +00002373 if (!isa<PointerType>(LocalOffset->getType()))
2374 // Getelementptr indicies are signed.
Nick Lewycky9425be92009-07-11 20:38:25 +00002375 LocalOffset = getTruncateOrSignExtend(LocalOffset,
2376 IntPtrTy);
Dan Gohman509cf4d2009-05-08 20:26:55 +00002377 LocalOffset =
2378 getMulExpr(LocalOffset,
Nick Lewycky9425be92009-07-11 20:38:25 +00002379 getIntegerSCEV(TD->getTypeAllocSize(*GTI),
2380 IntPtrTy));
Dan Gohman509cf4d2009-05-08 20:26:55 +00002381 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
2382 }
2383 }
2384 return getAddExpr(getSCEV(Base), TotalOffset);
2385}
2386
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002387/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2388/// guaranteed to end in (at every loop iteration). It is, at the same time,
2389/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2390/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohman6e923a72009-06-19 23:29:04 +00002391uint32_t
Dan Gohman161ea032009-07-07 17:06:11 +00002392ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00002393 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner6ecce2a2007-11-23 22:36:49 +00002394 return C->getValue()->getValue().countTrailingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002395
Dan Gohmanc76b5452009-05-04 22:02:23 +00002396 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohman6e923a72009-06-19 23:29:04 +00002397 return std::min(GetMinTrailingZeros(T->getOperand()),
2398 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002399
Dan Gohmanc76b5452009-05-04 22:02:23 +00002400 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohman6e923a72009-06-19 23:29:04 +00002401 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2402 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2403 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002404 }
2405
Dan Gohmanc76b5452009-05-04 22:02:23 +00002406 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohman6e923a72009-06-19 23:29:04 +00002407 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2408 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2409 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002410 }
2411
Dan Gohmanc76b5452009-05-04 22:02:23 +00002412 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002413 // The result is the min of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002414 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002415 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002416 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002417 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002418 }
2419
Dan Gohmanc76b5452009-05-04 22:02:23 +00002420 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002421 // The result is the sum of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002422 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2423 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002424 for (unsigned i = 1, e = M->getNumOperands();
2425 SumOpRes != BitWidth && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002426 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002427 BitWidth);
2428 return SumOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002429 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002430
Dan Gohmanc76b5452009-05-04 22:02:23 +00002431 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002432 // The result is the min of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002433 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002434 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002435 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002436 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002437 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002438
Dan Gohmanc76b5452009-05-04 22:02:23 +00002439 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewycky711640a2007-11-25 22:41:31 +00002440 // The result is the min of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002441 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky711640a2007-11-25 22:41:31 +00002442 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002443 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky711640a2007-11-25 22:41:31 +00002444 return MinOpRes;
2445 }
2446
Dan Gohmanc76b5452009-05-04 22:02:23 +00002447 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002448 // The result is the min of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002449 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002450 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002451 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002452 return MinOpRes;
2453 }
2454
Dan Gohman6e923a72009-06-19 23:29:04 +00002455 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2456 // For a SCEVUnknown, ask ValueTracking.
2457 unsigned BitWidth = getTypeSizeInBits(U->getType());
2458 APInt Mask = APInt::getAllOnesValue(BitWidth);
2459 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2460 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2461 return Zeros.countTrailingOnes();
2462 }
2463
2464 // SCEVUDivExpr
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002465 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002466}
2467
Nick Lewycky9425be92009-07-11 20:38:25 +00002468uint32_t
2469ScalarEvolution::GetMinLeadingZeros(const SCEV *S) {
2470 // TODO: Handle other SCEV expression types here.
Dan Gohman6e923a72009-06-19 23:29:04 +00002471
2472 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Nick Lewycky9425be92009-07-11 20:38:25 +00002473 return C->getValue()->getValue().countLeadingZeros();
Dan Gohman6e923a72009-06-19 23:29:04 +00002474
Nick Lewycky9425be92009-07-11 20:38:25 +00002475 if (const SCEVZeroExtendExpr *C = dyn_cast<SCEVZeroExtendExpr>(S)) {
2476 // A zero-extension cast adds zero bits.
2477 return GetMinLeadingZeros(C->getOperand()) +
2478 (getTypeSizeInBits(C->getType()) -
2479 getTypeSizeInBits(C->getOperand()->getType()));
Dan Gohman6e923a72009-06-19 23:29:04 +00002480 }
2481
2482 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2483 // For a SCEVUnknown, ask ValueTracking.
2484 unsigned BitWidth = getTypeSizeInBits(U->getType());
2485 APInt Mask = APInt::getAllOnesValue(BitWidth);
2486 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2487 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
Nick Lewycky9425be92009-07-11 20:38:25 +00002488 return Zeros.countLeadingOnes();
Dan Gohman6e923a72009-06-19 23:29:04 +00002489 }
2490
Nick Lewycky9425be92009-07-11 20:38:25 +00002491 return 1;
Dan Gohman6e923a72009-06-19 23:29:04 +00002492}
2493
Nick Lewycky9425be92009-07-11 20:38:25 +00002494uint32_t
2495ScalarEvolution::GetMinSignBits(const SCEV *S) {
2496 // TODO: Handle other SCEV expression types here.
Dan Gohman6e923a72009-06-19 23:29:04 +00002497
Nick Lewycky9425be92009-07-11 20:38:25 +00002498 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
2499 const APInt &A = C->getValue()->getValue();
2500 return A.isNegative() ? A.countLeadingOnes() :
2501 A.countLeadingZeros();
Dan Gohman6e923a72009-06-19 23:29:04 +00002502 }
2503
Nick Lewycky9425be92009-07-11 20:38:25 +00002504 if (const SCEVSignExtendExpr *C = dyn_cast<SCEVSignExtendExpr>(S)) {
2505 // A sign-extension cast adds sign bits.
2506 return GetMinSignBits(C->getOperand()) +
2507 (getTypeSizeInBits(C->getType()) -
2508 getTypeSizeInBits(C->getOperand()->getType()));
Dan Gohman6e923a72009-06-19 23:29:04 +00002509 }
2510
Nick Lewycky9425be92009-07-11 20:38:25 +00002511 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
2512 unsigned BitWidth = getTypeSizeInBits(A->getType());
Dan Gohman61e0c4c2009-06-24 01:05:09 +00002513
Nick Lewycky9425be92009-07-11 20:38:25 +00002514 // Special case decrementing a value (ADD X, -1):
2515 if (const SCEVConstant *CRHS = dyn_cast<SCEVConstant>(A->getOperand(0)))
2516 if (CRHS->isAllOnesValue()) {
2517 SmallVector<const SCEV *, 4> OtherOps(A->op_begin() + 1, A->op_end());
2518 const SCEV *OtherOpsAdd = getAddExpr(OtherOps);
2519 unsigned LZ = GetMinLeadingZeros(OtherOpsAdd);
Dan Gohman61e0c4c2009-06-24 01:05:09 +00002520
Nick Lewycky9425be92009-07-11 20:38:25 +00002521 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2522 // sign bits set.
2523 if (LZ == BitWidth - 1)
2524 return BitWidth;
Dan Gohman61e0c4c2009-06-24 01:05:09 +00002525
Nick Lewycky9425be92009-07-11 20:38:25 +00002526 // If we are subtracting one from a positive number, there is no carry
2527 // out of the result.
2528 if (LZ > 0)
2529 return GetMinSignBits(OtherOpsAdd);
Dan Gohman61e0c4c2009-06-24 01:05:09 +00002530 }
Nick Lewycky9425be92009-07-11 20:38:25 +00002531
2532 // Add can have at most one carry bit. Thus we know that the output
2533 // is, at worst, one more bit than the inputs.
2534 unsigned Min = BitWidth;
2535 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
2536 unsigned N = GetMinSignBits(A->getOperand(i));
2537 Min = std::min(Min, N) - 1;
2538 if (Min == 0) return 1;
Dan Gohman61e0c4c2009-06-24 01:05:09 +00002539 }
Nick Lewycky9425be92009-07-11 20:38:25 +00002540 return 1;
Dan Gohman61e0c4c2009-06-24 01:05:09 +00002541 }
2542
Dan Gohman6e923a72009-06-19 23:29:04 +00002543 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2544 // For a SCEVUnknown, ask ValueTracking.
Nick Lewycky9425be92009-07-11 20:38:25 +00002545 return ComputeNumSignBits(U->getValue(), TD);
Dan Gohman6e923a72009-06-19 23:29:04 +00002546 }
2547
Nick Lewycky9425be92009-07-11 20:38:25 +00002548 return 1;
Dan Gohman6e923a72009-06-19 23:29:04 +00002549}
2550
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002551/// createSCEV - We know that there is no SCEV for the specified value.
2552/// Analyze the expression.
2553///
Dan Gohman161ea032009-07-07 17:06:11 +00002554const SCEV *ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002555 if (!isSCEVable(V->getType()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002556 return getUnknown(V);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002557
Dan Gohman3996f472008-06-22 19:56:46 +00002558 unsigned Opcode = Instruction::UserOp1;
2559 if (Instruction *I = dyn_cast<Instruction>(V))
2560 Opcode = I->getOpcode();
2561 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
2562 Opcode = CE->getOpcode();
Dan Gohman984c78a2009-06-24 00:54:57 +00002563 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2564 return getConstant(CI);
2565 else if (isa<ConstantPointerNull>(V))
2566 return getIntegerSCEV(0, V->getType());
2567 else if (isa<UndefValue>(V))
2568 return getIntegerSCEV(0, V->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002569 else
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002570 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002571
Dan Gohman3996f472008-06-22 19:56:46 +00002572 User *U = cast<User>(V);
2573 switch (Opcode) {
2574 case Instruction::Add:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002575 return getAddExpr(getSCEV(U->getOperand(0)),
2576 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002577 case Instruction::Mul:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002578 return getMulExpr(getSCEV(U->getOperand(0)),
2579 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002580 case Instruction::UDiv:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002581 return getUDivExpr(getSCEV(U->getOperand(0)),
2582 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002583 case Instruction::Sub:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002584 return getMinusSCEV(getSCEV(U->getOperand(0)),
2585 getSCEV(U->getOperand(1)));
Dan Gohman53bf64a2009-04-21 02:26:00 +00002586 case Instruction::And:
2587 // For an expression like x&255 that merely masks off the high bits,
2588 // use zext(trunc(x)) as the SCEV expression.
2589 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman91ae1e72009-04-25 17:05:40 +00002590 if (CI->isNullValue())
2591 return getSCEV(U->getOperand(1));
Dan Gohmanc7ebba12009-04-27 01:41:10 +00002592 if (CI->isAllOnesValue())
2593 return getSCEV(U->getOperand(0));
Dan Gohman53bf64a2009-04-21 02:26:00 +00002594 const APInt &A = CI->getValue();
Dan Gohmana7726c32009-06-16 19:52:01 +00002595
2596 // Instcombine's ShrinkDemandedConstant may strip bits out of
2597 // constants, obscuring what would otherwise be a low-bits mask.
2598 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
2599 // knew about to reconstruct a low-bits mask value.
2600 unsigned LZ = A.countLeadingZeros();
2601 unsigned BitWidth = A.getBitWidth();
2602 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
2603 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2604 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
2605
2606 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
2607
Dan Gohmanae1d7dd2009-06-17 23:54:37 +00002608 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
Dan Gohman53bf64a2009-04-21 02:26:00 +00002609 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002610 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
Dan Gohmana7726c32009-06-16 19:52:01 +00002611 IntegerType::get(BitWidth - LZ)),
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002612 U->getType());
Dan Gohman53bf64a2009-04-21 02:26:00 +00002613 }
2614 break;
Dan Gohmana7726c32009-06-16 19:52:01 +00002615
Dan Gohman3996f472008-06-22 19:56:46 +00002616 case Instruction::Or:
2617 // If the RHS of the Or is a constant, we may have something like:
2618 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
2619 // optimizations will transparently handle this case.
2620 //
2621 // In order for this transformation to be safe, the LHS must be of the
2622 // form X*(2^n) and the Or constant must be less than 2^n.
2623 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman161ea032009-07-07 17:06:11 +00002624 const SCEV *LHS = getSCEV(U->getOperand(0));
Dan Gohman3996f472008-06-22 19:56:46 +00002625 const APInt &CIVal = CI->getValue();
Dan Gohman6e923a72009-06-19 23:29:04 +00002626 if (GetMinTrailingZeros(LHS) >=
Dan Gohman3996f472008-06-22 19:56:46 +00002627 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002628 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002629 }
Dan Gohman3996f472008-06-22 19:56:46 +00002630 break;
2631 case Instruction::Xor:
Dan Gohman3996f472008-06-22 19:56:46 +00002632 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky7fd27892008-07-07 06:15:49 +00002633 // If the RHS of the xor is a signbit, then this is just an add.
2634 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman3996f472008-06-22 19:56:46 +00002635 if (CI->getValue().isSignBit())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002636 return getAddExpr(getSCEV(U->getOperand(0)),
2637 getSCEV(U->getOperand(1)));
Nick Lewycky7fd27892008-07-07 06:15:49 +00002638
2639 // If the RHS of xor is -1, then this is a not operation.
Dan Gohmanc897f752009-05-18 16:17:44 +00002640 if (CI->isAllOnesValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002641 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohmanfc78cff2009-05-18 16:29:04 +00002642
2643 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
2644 // This is a variant of the check for xor with -1, and it handles
2645 // the case where instcombine has trimmed non-demanded bits out
2646 // of an xor with -1.
2647 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
2648 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
2649 if (BO->getOpcode() == Instruction::And &&
2650 LCI->getValue() == CI->getValue())
2651 if (const SCEVZeroExtendExpr *Z =
Dan Gohmane49ae432009-06-17 01:22:39 +00002652 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
Dan Gohmaned1d8bb2009-06-18 00:00:20 +00002653 const Type *UTy = U->getType();
Dan Gohman161ea032009-07-07 17:06:11 +00002654 const SCEV *Z0 = Z->getOperand();
Dan Gohmaned1d8bb2009-06-18 00:00:20 +00002655 const Type *Z0Ty = Z0->getType();
2656 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
2657
2658 // If C is a low-bits mask, the zero extend is zerving to
2659 // mask off the high bits. Complement the operand and
2660 // re-apply the zext.
2661 if (APIntOps::isMask(Z0TySize, CI->getValue()))
2662 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
2663
2664 // If C is a single bit, it may be in the sign-bit position
2665 // before the zero-extend. In this case, represent the xor
2666 // using an add, which is equivalent, and re-apply the zext.
2667 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
2668 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
2669 Trunc.isSignBit())
2670 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
2671 UTy);
Dan Gohmane49ae432009-06-17 01:22:39 +00002672 }
Dan Gohman3996f472008-06-22 19:56:46 +00002673 }
2674 break;
2675
2676 case Instruction::Shl:
2677 // Turn shift left of a constant amount into a multiply.
2678 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2679 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2680 Constant *X = ConstantInt::get(
2681 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002682 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman3996f472008-06-22 19:56:46 +00002683 }
2684 break;
2685
Nick Lewycky7fd27892008-07-07 06:15:49 +00002686 case Instruction::LShr:
Nick Lewycky35b56022009-01-13 09:18:58 +00002687 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky7fd27892008-07-07 06:15:49 +00002688 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2689 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2690 Constant *X = ConstantInt::get(
2691 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002692 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky7fd27892008-07-07 06:15:49 +00002693 }
2694 break;
2695
Dan Gohman53bf64a2009-04-21 02:26:00 +00002696 case Instruction::AShr:
2697 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
2698 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
2699 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
2700 if (L->getOpcode() == Instruction::Shl &&
2701 L->getOperand(1) == U->getOperand(1)) {
Dan Gohman91ae1e72009-04-25 17:05:40 +00002702 unsigned BitWidth = getTypeSizeInBits(U->getType());
2703 uint64_t Amt = BitWidth - CI->getZExtValue();
2704 if (Amt == BitWidth)
2705 return getSCEV(L->getOperand(0)); // shift by zero --> noop
2706 if (Amt > BitWidth)
2707 return getIntegerSCEV(0, U->getType()); // value is undefined
Dan Gohman53bf64a2009-04-21 02:26:00 +00002708 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002709 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohman91ae1e72009-04-25 17:05:40 +00002710 IntegerType::get(Amt)),
Dan Gohman53bf64a2009-04-21 02:26:00 +00002711 U->getType());
2712 }
2713 break;
2714
Dan Gohman3996f472008-06-22 19:56:46 +00002715 case Instruction::Trunc:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002716 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002717
2718 case Instruction::ZExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002719 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002720
2721 case Instruction::SExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002722 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002723
2724 case Instruction::BitCast:
2725 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002726 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman3996f472008-06-22 19:56:46 +00002727 return getSCEV(U->getOperand(0));
2728 break;
2729
Dan Gohman01c2ee72009-04-16 03:18:22 +00002730 case Instruction::IntToPtr:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002731 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00002732 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002733 TD->getIntPtrType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00002734
2735 case Instruction::PtrToInt:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002736 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00002737 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
2738 U->getType());
2739
Dan Gohman509cf4d2009-05-08 20:26:55 +00002740 case Instruction::GetElementPtr:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002741 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohmanca5a39e2009-05-08 20:58:38 +00002742 return createNodeForGEP(U);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002743
Dan Gohman3996f472008-06-22 19:56:46 +00002744 case Instruction::PHI:
2745 return createNodeForPHI(cast<PHINode>(U));
2746
2747 case Instruction::Select:
2748 // This could be a smax or umax that was lowered earlier.
2749 // Try to recover it.
2750 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2751 Value *LHS = ICI->getOperand(0);
2752 Value *RHS = ICI->getOperand(1);
2753 switch (ICI->getPredicate()) {
2754 case ICmpInst::ICMP_SLT:
2755 case ICmpInst::ICMP_SLE:
2756 std::swap(LHS, RHS);
2757 // fall through
2758 case ICmpInst::ICMP_SGT:
2759 case ICmpInst::ICMP_SGE:
2760 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002761 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002762 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmand01fff82009-06-22 03:18:45 +00002763 return getSMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002764 break;
2765 case ICmpInst::ICMP_ULT:
2766 case ICmpInst::ICMP_ULE:
2767 std::swap(LHS, RHS);
2768 // fall through
2769 case ICmpInst::ICMP_UGT:
2770 case ICmpInst::ICMP_UGE:
2771 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002772 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002773 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmand01fff82009-06-22 03:18:45 +00002774 return getUMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002775 break;
Dan Gohmanf27dc692009-06-18 20:21:07 +00002776 case ICmpInst::ICMP_NE:
2777 // n != 0 ? n : 1 -> umax(n, 1)
2778 if (LHS == U->getOperand(1) &&
2779 isa<ConstantInt>(U->getOperand(2)) &&
2780 cast<ConstantInt>(U->getOperand(2))->isOne() &&
2781 isa<ConstantInt>(RHS) &&
2782 cast<ConstantInt>(RHS)->isZero())
2783 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(2)));
2784 break;
2785 case ICmpInst::ICMP_EQ:
2786 // n == 0 ? 1 : n -> umax(n, 1)
2787 if (LHS == U->getOperand(2) &&
2788 isa<ConstantInt>(U->getOperand(1)) &&
2789 cast<ConstantInt>(U->getOperand(1))->isOne() &&
2790 isa<ConstantInt>(RHS) &&
2791 cast<ConstantInt>(RHS)->isZero())
2792 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(1)));
2793 break;
Dan Gohman3996f472008-06-22 19:56:46 +00002794 default:
2795 break;
2796 }
2797 }
2798
2799 default: // We cannot analyze this expression.
2800 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002801 }
2802
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002803 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002804}
2805
2806
2807
2808//===----------------------------------------------------------------------===//
2809// Iteration Count Computation Code
2810//
2811
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002812/// getBackedgeTakenCount - If the specified loop has a predictable
2813/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
2814/// object. The backedge-taken count is the number of times the loop header
2815/// will be branched to from within the loop. This is one less than the
2816/// trip count of the loop, since it doesn't count the first iteration,
2817/// when the header is branched to from outside the loop.
2818///
2819/// Note that it is not valid to call this method on a loop without a
2820/// loop-invariant backedge-taken count (see
2821/// hasLoopInvariantBackedgeTakenCount).
2822///
Dan Gohman161ea032009-07-07 17:06:11 +00002823const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002824 return getBackedgeTakenInfo(L).Exact;
2825}
2826
2827/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
2828/// return the least SCEV value that is known never to be less than the
2829/// actual backedge taken count.
Dan Gohman161ea032009-07-07 17:06:11 +00002830const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002831 return getBackedgeTakenInfo(L).Max;
2832}
2833
Dan Gohmanb7d04aa2009-07-08 19:23:34 +00002834/// PushLoopPHIs - Push PHI nodes in the header of the given loop
2835/// onto the given Worklist.
2836static void
2837PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
2838 BasicBlock *Header = L->getHeader();
2839
2840 // Push all Loop-header PHIs onto the Worklist stack.
2841 for (BasicBlock::iterator I = Header->begin();
2842 PHINode *PN = dyn_cast<PHINode>(I); ++I)
2843 Worklist.push_back(PN);
2844}
2845
2846/// PushDefUseChildren - Push users of the given Instruction
2847/// onto the given Worklist.
2848static void
2849PushDefUseChildren(Instruction *I,
2850 SmallVectorImpl<Instruction *> &Worklist) {
2851 // Push the def-use children onto the Worklist stack.
2852 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2853 UI != UE; ++UI)
2854 Worklist.push_back(cast<Instruction>(UI));
2855}
2856
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002857const ScalarEvolution::BackedgeTakenInfo &
2858ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohmana9dba962009-04-27 20:16:15 +00002859 // Initially insert a CouldNotCompute for this loop. If the insertion
2860 // succeeds, procede to actually compute a backedge-taken count and
2861 // update the value. The temporary CouldNotCompute value tells SCEV
2862 // code elsewhere that it shouldn't attempt to request a new
2863 // backedge-taken count, which could result in infinite recursion.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002864 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohmana9dba962009-04-27 20:16:15 +00002865 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
2866 if (Pair.second) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002867 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00002868 if (ItCount.Exact != getCouldNotCompute()) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002869 assert(ItCount.Exact->isLoopInvariant(L) &&
2870 ItCount.Max->isLoopInvariant(L) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002871 "Computed trip count isn't loop invariant for loop!");
2872 ++NumTripCountsComputed;
Dan Gohmana9dba962009-04-27 20:16:15 +00002873
Dan Gohmana9dba962009-04-27 20:16:15 +00002874 // Update the value in the map.
2875 Pair.first->second = ItCount;
Dan Gohman8e8b5232009-06-22 00:31:57 +00002876 } else {
Dan Gohmanc6475cb2009-06-27 21:21:31 +00002877 if (ItCount.Max != getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00002878 // Update the value in the map.
2879 Pair.first->second = ItCount;
2880 if (isa<PHINode>(L->getHeader()->begin()))
2881 // Only count loops that have phi nodes as not being computable.
2882 ++NumTripCountsNotComputed;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002883 }
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002884
2885 // Now that we know more about the trip count for this loop, forget any
2886 // existing SCEV values for PHI nodes in this loop since they are only
Dan Gohmanb7d04aa2009-07-08 19:23:34 +00002887 // conservative estimates made without the benefit of trip count
2888 // information. This is similar to the code in
2889 // forgetLoopBackedgeTakenCount, except that it handles SCEVUnknown PHI
2890 // nodes specially.
2891 if (ItCount.hasAnyInfo()) {
2892 SmallVector<Instruction *, 16> Worklist;
2893 PushLoopPHIs(L, Worklist);
2894
2895 SmallPtrSet<Instruction *, 8> Visited;
2896 while (!Worklist.empty()) {
2897 Instruction *I = Worklist.pop_back_val();
2898 if (!Visited.insert(I)) continue;
2899
2900 std::map<SCEVCallbackVH, const SCEV*>::iterator It =
2901 Scalars.find(static_cast<Value *>(I));
2902 if (It != Scalars.end()) {
2903 // SCEVUnknown for a PHI either means that it has an unrecognized
2904 // structure, or it's a PHI that's in the progress of being computed
2905 // by createNodeForPHI. In the former case, additional loop trip count
2906 // information isn't going to change anything. In the later case,
2907 // createNodeForPHI will perform the necessary updates on its own when
2908 // it gets to that point.
2909 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(It->second))
2910 Scalars.erase(It);
2911 ValuesAtScopes.erase(I);
2912 if (PHINode *PN = dyn_cast<PHINode>(I))
2913 ConstantEvolutionLoopExitValue.erase(PN);
2914 }
2915
2916 PushDefUseChildren(I, Worklist);
2917 }
2918 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002919 }
Dan Gohmana9dba962009-04-27 20:16:15 +00002920 return Pair.first->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002921}
2922
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002923/// forgetLoopBackedgeTakenCount - This method should be called by the
Dan Gohmanf3a060a2009-02-17 20:49:49 +00002924/// client when it has changed a loop in a way that may effect
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002925/// ScalarEvolution's ability to compute a trip count, or if the loop
2926/// is deleted.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002927void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002928 BackedgeTakenCounts.erase(L);
Dan Gohman94623022009-05-02 17:43:35 +00002929
Dan Gohmanbff6b582009-05-04 22:30:44 +00002930 SmallVector<Instruction *, 16> Worklist;
Dan Gohmanb7d04aa2009-07-08 19:23:34 +00002931 PushLoopPHIs(L, Worklist);
Dan Gohmanbff6b582009-05-04 22:30:44 +00002932
Dan Gohmanb7d04aa2009-07-08 19:23:34 +00002933 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohmanbff6b582009-05-04 22:30:44 +00002934 while (!Worklist.empty()) {
2935 Instruction *I = Worklist.pop_back_val();
Dan Gohmanb7d04aa2009-07-08 19:23:34 +00002936 if (!Visited.insert(I)) continue;
2937
2938 std::map<SCEVCallbackVH, const SCEV*>::iterator It =
2939 Scalars.find(static_cast<Value *>(I));
2940 if (It != Scalars.end()) {
2941 Scalars.erase(It);
2942 ValuesAtScopes.erase(I);
2943 if (PHINode *PN = dyn_cast<PHINode>(I))
2944 ConstantEvolutionLoopExitValue.erase(PN);
2945 }
2946
2947 PushDefUseChildren(I, Worklist);
Dan Gohmanbff6b582009-05-04 22:30:44 +00002948 }
Dan Gohmanf3a060a2009-02-17 20:49:49 +00002949}
2950
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002951/// ComputeBackedgeTakenCount - Compute the number of times the backedge
2952/// of the specified loop will execute.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002953ScalarEvolution::BackedgeTakenInfo
2954ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohman8e8b5232009-06-22 00:31:57 +00002955 SmallVector<BasicBlock*, 8> ExitingBlocks;
2956 L->getExitingBlocks(ExitingBlocks);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002957
Dan Gohman8e8b5232009-06-22 00:31:57 +00002958 // Examine all exits and pick the most conservative values.
Dan Gohman161ea032009-07-07 17:06:11 +00002959 const SCEV *BECount = getCouldNotCompute();
2960 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohman8e8b5232009-06-22 00:31:57 +00002961 bool CouldNotComputeBECount = false;
Dan Gohman8e8b5232009-06-22 00:31:57 +00002962 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
2963 BackedgeTakenInfo NewBTI =
2964 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002965
Dan Gohmanc6475cb2009-06-27 21:21:31 +00002966 if (NewBTI.Exact == getCouldNotCompute()) {
Dan Gohman8e8b5232009-06-22 00:31:57 +00002967 // We couldn't compute an exact value for this exit, so
Dan Gohmanc6e8c832009-06-22 21:10:22 +00002968 // we won't be able to compute an exact value for the loop.
Dan Gohman8e8b5232009-06-22 00:31:57 +00002969 CouldNotComputeBECount = true;
Dan Gohmanc6475cb2009-06-27 21:21:31 +00002970 BECount = getCouldNotCompute();
Dan Gohman8e8b5232009-06-22 00:31:57 +00002971 } else if (!CouldNotComputeBECount) {
Dan Gohmanc6475cb2009-06-27 21:21:31 +00002972 if (BECount == getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00002973 BECount = NewBTI.Exact;
Dan Gohman8e8b5232009-06-22 00:31:57 +00002974 else
Dan Gohman423ed6c2009-06-24 01:18:18 +00002975 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
Dan Gohman8e8b5232009-06-22 00:31:57 +00002976 }
Dan Gohmanc6475cb2009-06-27 21:21:31 +00002977 if (MaxBECount == getCouldNotCompute())
Dan Gohman423ed6c2009-06-24 01:18:18 +00002978 MaxBECount = NewBTI.Max;
Dan Gohmanc6475cb2009-06-27 21:21:31 +00002979 else if (NewBTI.Max != getCouldNotCompute())
Dan Gohman423ed6c2009-06-24 01:18:18 +00002980 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
Dan Gohman8e8b5232009-06-22 00:31:57 +00002981 }
2982
2983 return BackedgeTakenInfo(BECount, MaxBECount);
2984}
2985
2986/// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
2987/// of the specified loop will execute if it exits via the specified block.
2988ScalarEvolution::BackedgeTakenInfo
2989ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
2990 BasicBlock *ExitingBlock) {
2991
2992 // Okay, we've chosen an exiting block. See what condition causes us to
2993 // exit at this block.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002994 //
2995 // FIXME: we should be able to handle switch instructions (with a single exit)
2996 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Dan Gohmanc6475cb2009-06-27 21:21:31 +00002997 if (ExitBr == 0) return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002998 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Dan Gohman9bc642f2009-06-24 04:48:43 +00002999
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003000 // At this point, we know we have a conditional branch that determines whether
3001 // the loop is exited. However, we don't know if the branch is executed each
3002 // time through the loop. If not, then the execution count of the branch will
3003 // not be equal to the trip count of the loop.
3004 //
3005 // Currently we check for this by checking to see if the Exit branch goes to
3006 // the loop header. If so, we know it will always execute the same number of
3007 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohman8e8b5232009-06-22 00:31:57 +00003008 // loop header. This is common for un-rotated loops.
3009 //
3010 // If both of those tests fail, walk up the unique predecessor chain to the
3011 // header, stopping if there is an edge that doesn't exit the loop. If the
3012 // header is reached, the execution count of the branch will be equal to the
3013 // trip count of the loop.
3014 //
3015 // More extensive analysis could be done to handle more cases here.
3016 //
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003017 if (ExitBr->getSuccessor(0) != L->getHeader() &&
3018 ExitBr->getSuccessor(1) != L->getHeader() &&
Dan Gohman8e8b5232009-06-22 00:31:57 +00003019 ExitBr->getParent() != L->getHeader()) {
3020 // The simple checks failed, try climbing the unique predecessor chain
3021 // up to the header.
3022 bool Ok = false;
3023 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
3024 BasicBlock *Pred = BB->getUniquePredecessor();
3025 if (!Pred)
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003026 return getCouldNotCompute();
Dan Gohman8e8b5232009-06-22 00:31:57 +00003027 TerminatorInst *PredTerm = Pred->getTerminator();
3028 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
3029 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
3030 if (PredSucc == BB)
3031 continue;
3032 // If the predecessor has a successor that isn't BB and isn't
3033 // outside the loop, assume the worst.
3034 if (L->contains(PredSucc))
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003035 return getCouldNotCompute();
Dan Gohman8e8b5232009-06-22 00:31:57 +00003036 }
3037 if (Pred == L->getHeader()) {
3038 Ok = true;
3039 break;
3040 }
3041 BB = Pred;
3042 }
3043 if (!Ok)
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003044 return getCouldNotCompute();
Dan Gohman8e8b5232009-06-22 00:31:57 +00003045 }
3046
3047 // Procede to the next level to examine the exit condition expression.
3048 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
3049 ExitBr->getSuccessor(0),
3050 ExitBr->getSuccessor(1));
3051}
3052
3053/// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
3054/// backedge of the specified loop will execute if its exit condition
3055/// were a conditional branch of ExitCond, TBB, and FBB.
3056ScalarEvolution::BackedgeTakenInfo
3057ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
3058 Value *ExitCond,
3059 BasicBlock *TBB,
3060 BasicBlock *FBB) {
Dan Gohman423ed6c2009-06-24 01:18:18 +00003061 // Check if the controlling expression for this loop is an And or Or.
Dan Gohman8e8b5232009-06-22 00:31:57 +00003062 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
3063 if (BO->getOpcode() == Instruction::And) {
3064 // Recurse on the operands of the and.
3065 BackedgeTakenInfo BTI0 =
3066 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3067 BackedgeTakenInfo BTI1 =
3068 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman161ea032009-07-07 17:06:11 +00003069 const SCEV *BECount = getCouldNotCompute();
3070 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohman8e8b5232009-06-22 00:31:57 +00003071 if (L->contains(TBB)) {
3072 // Both conditions must be true for the loop to continue executing.
3073 // Choose the less conservative count.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003074 if (BTI0.Exact == getCouldNotCompute() ||
3075 BTI1.Exact == getCouldNotCompute())
3076 BECount = getCouldNotCompute();
Dan Gohmanac958b32009-06-22 15:09:28 +00003077 else
3078 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003079 if (BTI0.Max == getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003080 MaxBECount = BTI1.Max;
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003081 else if (BTI1.Max == getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003082 MaxBECount = BTI0.Max;
Dan Gohmanac958b32009-06-22 15:09:28 +00003083 else
3084 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohman8e8b5232009-06-22 00:31:57 +00003085 } else {
3086 // Both conditions must be true for the loop to exit.
3087 assert(L->contains(FBB) && "Loop block has no successor in loop!");
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003088 if (BTI0.Exact != getCouldNotCompute() &&
3089 BTI1.Exact != getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003090 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003091 if (BTI0.Max != getCouldNotCompute() &&
3092 BTI1.Max != getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003093 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3094 }
3095
3096 return BackedgeTakenInfo(BECount, MaxBECount);
3097 }
3098 if (BO->getOpcode() == Instruction::Or) {
3099 // Recurse on the operands of the or.
3100 BackedgeTakenInfo BTI0 =
3101 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3102 BackedgeTakenInfo BTI1 =
3103 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman161ea032009-07-07 17:06:11 +00003104 const SCEV *BECount = getCouldNotCompute();
3105 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohman8e8b5232009-06-22 00:31:57 +00003106 if (L->contains(FBB)) {
3107 // Both conditions must be false for the loop to continue executing.
3108 // Choose the less conservative count.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003109 if (BTI0.Exact == getCouldNotCompute() ||
3110 BTI1.Exact == getCouldNotCompute())
3111 BECount = getCouldNotCompute();
Dan Gohmanac958b32009-06-22 15:09:28 +00003112 else
3113 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003114 if (BTI0.Max == getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003115 MaxBECount = BTI1.Max;
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003116 else if (BTI1.Max == getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003117 MaxBECount = BTI0.Max;
Dan Gohmanac958b32009-06-22 15:09:28 +00003118 else
3119 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohman8e8b5232009-06-22 00:31:57 +00003120 } else {
3121 // Both conditions must be false for the loop to exit.
3122 assert(L->contains(TBB) && "Loop block has no successor in loop!");
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003123 if (BTI0.Exact != getCouldNotCompute() &&
3124 BTI1.Exact != getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003125 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003126 if (BTI0.Max != getCouldNotCompute() &&
3127 BTI1.Max != getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003128 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3129 }
3130
3131 return BackedgeTakenInfo(BECount, MaxBECount);
3132 }
3133 }
3134
3135 // With an icmp, it may be feasible to compute an exact backedge-taken count.
3136 // Procede to the next level to examine the icmp.
3137 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
3138 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003139
Eli Friedman459d7292009-05-09 12:32:42 +00003140 // If it's not an integer or pointer comparison then compute it the hard way.
Dan Gohman8e8b5232009-06-22 00:31:57 +00003141 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3142}
3143
3144/// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
3145/// backedge of the specified loop will execute if its exit condition
3146/// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
3147ScalarEvolution::BackedgeTakenInfo
3148ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
3149 ICmpInst *ExitCond,
3150 BasicBlock *TBB,
3151 BasicBlock *FBB) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003152
3153 // If the condition was exit on true, convert the condition to exit on false
3154 ICmpInst::Predicate Cond;
Dan Gohman8e8b5232009-06-22 00:31:57 +00003155 if (!L->contains(FBB))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003156 Cond = ExitCond->getPredicate();
3157 else
3158 Cond = ExitCond->getInversePredicate();
3159
3160 // Handle common loops like: for (X = "string"; *X; ++X)
3161 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
3162 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Dan Gohman161ea032009-07-07 17:06:11 +00003163 const SCEV *ItCnt =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003164 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohman8e8b5232009-06-22 00:31:57 +00003165 if (!isa<SCEVCouldNotCompute>(ItCnt)) {
3166 unsigned BitWidth = getTypeSizeInBits(ItCnt->getType());
3167 return BackedgeTakenInfo(ItCnt,
3168 isa<SCEVConstant>(ItCnt) ? ItCnt :
3169 getConstant(APInt::getMaxValue(BitWidth)-1));
3170 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003171 }
3172
Dan Gohman161ea032009-07-07 17:06:11 +00003173 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
3174 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003175
3176 // Try to evaluate any dependencies out of the loop.
Dan Gohmanaff14d62009-05-24 23:25:42 +00003177 LHS = getSCEVAtScope(LHS, L);
3178 RHS = getSCEVAtScope(RHS, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003179
Dan Gohman9bc642f2009-06-24 04:48:43 +00003180 // At this point, we would like to compute how many iterations of the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003181 // loop the predicate will return true for these inputs.
Dan Gohman2d96e352008-09-16 18:52:57 +00003182 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
3183 // If there is a loop-invariant, force it into the RHS.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003184 std::swap(LHS, RHS);
3185 Cond = ICmpInst::getSwappedPredicate(Cond);
3186 }
3187
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003188 // If we have a comparison of a chrec against a constant, try to use value
3189 // ranges to answer this query.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003190 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
3191 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003192 if (AddRec->getLoop() == L) {
Eli Friedman459d7292009-05-09 12:32:42 +00003193 // Form the constant range.
3194 ConstantRange CompRange(
3195 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003196
Dan Gohman161ea032009-07-07 17:06:11 +00003197 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedman459d7292009-05-09 12:32:42 +00003198 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003199 }
3200
3201 switch (Cond) {
3202 case ICmpInst::ICMP_NE: { // while (X != Y)
3203 // Convert to: while (X-Y != 0)
Dan Gohman161ea032009-07-07 17:06:11 +00003204 const SCEV *TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003205 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
3206 break;
3207 }
3208 case ICmpInst::ICMP_EQ: {
3209 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohman161ea032009-07-07 17:06:11 +00003210 const SCEV *TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003211 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
3212 break;
3213 }
3214 case ICmpInst::ICMP_SLT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003215 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
3216 if (BTI.hasAnyInfo()) return BTI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003217 break;
3218 }
3219 case ICmpInst::ICMP_SGT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003220 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3221 getNotSCEV(RHS), L, true);
3222 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyb7c28942007-08-06 19:21:00 +00003223 break;
3224 }
3225 case ICmpInst::ICMP_ULT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003226 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
3227 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyb7c28942007-08-06 19:21:00 +00003228 break;
3229 }
3230 case ICmpInst::ICMP_UGT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003231 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3232 getNotSCEV(RHS), L, false);
3233 if (BTI.hasAnyInfo()) return BTI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003234 break;
3235 }
3236 default:
3237#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00003238 errs() << "ComputeBackedgeTakenCount ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003239 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Dan Gohman13058cc2009-04-21 00:47:46 +00003240 errs() << "[unsigned] ";
3241 errs() << *LHS << " "
Dan Gohman9bc642f2009-06-24 04:48:43 +00003242 << Instruction::getOpcodeName(Instruction::ICmp)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003243 << " " << *RHS << "\n";
3244#endif
3245 break;
3246 }
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003247 return
Dan Gohman8e8b5232009-06-22 00:31:57 +00003248 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003249}
3250
3251static ConstantInt *
Dan Gohman89f85052007-10-22 18:31:58 +00003252EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
3253 ScalarEvolution &SE) {
Dan Gohman161ea032009-07-07 17:06:11 +00003254 const SCEV *InVal = SE.getConstant(C);
3255 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003256 assert(isa<SCEVConstant>(Val) &&
3257 "Evaluation of SCEV at constant didn't fold correctly?");
3258 return cast<SCEVConstant>(Val)->getValue();
3259}
3260
3261/// GetAddressedElementFromGlobal - Given a global variable with an initializer
3262/// and a GEP expression (missing the pointer index) indexing into it, return
3263/// the addressed element of the initializer or null if the index expression is
3264/// invalid.
3265static Constant *
Owen Anderson15b39322009-07-13 04:09:18 +00003266GetAddressedElementFromGlobal(LLVMContext *Context, GlobalVariable *GV,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003267 const std::vector<ConstantInt*> &Indices) {
3268 Constant *Init = GV->getInitializer();
3269 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
3270 uint64_t Idx = Indices[i]->getZExtValue();
3271 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
3272 assert(Idx < CS->getNumOperands() && "Bad struct index!");
3273 Init = cast<Constant>(CS->getOperand(Idx));
3274 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
3275 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
3276 Init = cast<Constant>(CA->getOperand(Idx));
3277 } else if (isa<ConstantAggregateZero>(Init)) {
3278 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
3279 assert(Idx < STy->getNumElements() && "Bad struct index!");
Owen Anderson15b39322009-07-13 04:09:18 +00003280 Init = Context->getNullValue(STy->getElementType(Idx));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003281 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
3282 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
Owen Anderson15b39322009-07-13 04:09:18 +00003283 Init = Context->getNullValue(ATy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003284 } else {
Edwin Török675d5622009-07-11 20:10:48 +00003285 LLVM_UNREACHABLE("Unknown constant aggregate type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003286 }
3287 return 0;
3288 } else {
3289 return 0; // Unknown initializer type
3290 }
3291 }
3292 return Init;
3293}
3294
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003295/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
3296/// 'icmp op load X, cst', try to see if we can compute the backedge
3297/// execution count.
Dan Gohman9bc642f2009-06-24 04:48:43 +00003298const SCEV *
3299ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
3300 LoadInst *LI,
3301 Constant *RHS,
3302 const Loop *L,
3303 ICmpInst::Predicate predicate) {
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003304 if (LI->isVolatile()) return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003305
3306 // Check to see if the loaded pointer is a getelementptr of a global.
3307 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003308 if (!GEP) return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003309
3310 // Make sure that it is really a constant global we are gepping, with an
3311 // initializer, and make sure the first IDX is really 0.
3312 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
3313 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
3314 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
3315 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003316 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003317
3318 // Okay, we allow one non-constant index into the GEP instruction.
3319 Value *VarIdx = 0;
3320 std::vector<ConstantInt*> Indexes;
3321 unsigned VarIdxNum = 0;
3322 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
3323 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
3324 Indexes.push_back(CI);
3325 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003326 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003327 VarIdx = GEP->getOperand(i);
3328 VarIdxNum = i-2;
3329 Indexes.push_back(0);
3330 }
3331
3332 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
3333 // Check to see if X is a loop variant variable value now.
Dan Gohman161ea032009-07-07 17:06:11 +00003334 const SCEV *Idx = getSCEV(VarIdx);
Dan Gohmanaff14d62009-05-24 23:25:42 +00003335 Idx = getSCEVAtScope(Idx, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003336
3337 // We can only recognize very limited forms of loop index expressions, in
3338 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohmanbff6b582009-05-04 22:30:44 +00003339 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003340 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
3341 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
3342 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003343 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003344
3345 unsigned MaxSteps = MaxBruteForceIterations;
3346 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
3347 ConstantInt *ItCst =
Dan Gohman8fd520a2009-06-15 22:12:54 +00003348 ConstantInt::get(cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003349 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003350
3351 // Form the GEP offset.
3352 Indexes[VarIdxNum] = Val;
3353
Owen Anderson15b39322009-07-13 04:09:18 +00003354 Constant *Result = GetAddressedElementFromGlobal(Context, GV, Indexes);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003355 if (Result == 0) break; // Cannot compute!
3356
3357 // Evaluate the condition for this iteration.
3358 Result = ConstantExpr::getICmp(predicate, Result, RHS);
3359 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
3360 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
3361#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00003362 errs() << "\n***\n*** Computed loop count " << *ItCst
3363 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
3364 << "***\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003365#endif
3366 ++NumArrayLenItCounts;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003367 return getConstant(ItCst); // Found terminating iteration!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003368 }
3369 }
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003370 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003371}
3372
3373
3374/// CanConstantFold - Return true if we can constant fold an instruction of the
3375/// specified type, assuming that all operands were constants.
3376static bool CanConstantFold(const Instruction *I) {
3377 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
3378 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
3379 return true;
3380
3381 if (const CallInst *CI = dyn_cast<CallInst>(I))
3382 if (const Function *F = CI->getCalledFunction())
Dan Gohmane6e001f2008-01-31 01:05:10 +00003383 return canConstantFoldCallTo(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003384 return false;
3385}
3386
3387/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
3388/// in the loop that V is derived from. We allow arbitrary operations along the
3389/// way, but the operands of an operation must either be constants or a value
3390/// derived from a constant PHI. If this expression does not fit with these
3391/// constraints, return null.
3392static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
3393 // If this is not an instruction, or if this is an instruction outside of the
3394 // loop, it can't be derived from a loop PHI.
3395 Instruction *I = dyn_cast<Instruction>(V);
3396 if (I == 0 || !L->contains(I->getParent())) return 0;
3397
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00003398 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003399 if (L->getHeader() == I->getParent())
3400 return PN;
3401 else
3402 // We don't currently keep track of the control flow needed to evaluate
3403 // PHIs, so we cannot handle PHIs inside of loops.
3404 return 0;
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00003405 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003406
3407 // If we won't be able to constant fold this expression even if the operands
3408 // are constants, return early.
3409 if (!CanConstantFold(I)) return 0;
3410
3411 // Otherwise, we can evaluate this instruction if all of its operands are
3412 // constant or derived from a PHI node themselves.
3413 PHINode *PHI = 0;
3414 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
3415 if (!(isa<Constant>(I->getOperand(Op)) ||
3416 isa<GlobalValue>(I->getOperand(Op)))) {
3417 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
3418 if (P == 0) return 0; // Not evolving from PHI
3419 if (PHI == 0)
3420 PHI = P;
3421 else if (PHI != P)
3422 return 0; // Evolving from multiple different PHIs.
3423 }
3424
3425 // This is a expression evolving from a constant PHI!
3426 return PHI;
3427}
3428
3429/// EvaluateExpression - Given an expression that passes the
3430/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
3431/// in the loop has the value PHIVal. If we can't fold this expression for some
3432/// reason, return null.
3433static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
3434 if (isa<PHINode>(V)) return PHIVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003435 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman01c2ee72009-04-16 03:18:22 +00003436 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003437 Instruction *I = cast<Instruction>(V);
Owen Anderson5349f052009-07-06 23:00:19 +00003438 LLVMContext *Context = I->getParent()->getContext();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003439
3440 std::vector<Constant*> Operands;
3441 Operands.resize(I->getNumOperands());
3442
3443 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3444 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
3445 if (Operands[i] == 0) return 0;
3446 }
3447
Chris Lattnerd6e56912007-12-10 22:53:04 +00003448 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3449 return ConstantFoldCompareInstOperands(CI->getPredicate(),
Owen Andersond4d90a02009-07-06 18:42:36 +00003450 &Operands[0], Operands.size(),
3451 Context);
Chris Lattnerd6e56912007-12-10 22:53:04 +00003452 else
3453 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Owen Andersond4d90a02009-07-06 18:42:36 +00003454 &Operands[0], Operands.size(),
3455 Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003456}
3457
3458/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
3459/// in the header of its containing loop, we know the loop executes a
3460/// constant number of times, and the PHI node is just a recurrence
3461/// involving constants, fold it.
Dan Gohman9bc642f2009-06-24 04:48:43 +00003462Constant *
3463ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
3464 const APInt& BEs,
3465 const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003466 std::map<PHINode*, Constant*>::iterator I =
3467 ConstantEvolutionLoopExitValue.find(PN);
3468 if (I != ConstantEvolutionLoopExitValue.end())
3469 return I->second;
3470
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003471 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003472 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
3473
3474 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
3475
3476 // Since the loop is canonicalized, the PHI node must have two entries. One
3477 // entry must be a constant (coming in from outside of the loop), and the
3478 // second must be derived from the same PHI.
3479 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3480 Constant *StartCST =
3481 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
3482 if (StartCST == 0)
3483 return RetVal = 0; // Must be a constant.
3484
3485 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3486 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
3487 if (PN2 != PN)
3488 return RetVal = 0; // Not derived from same PHI.
3489
3490 // Execute the loop symbolically to determine the exit value.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003491 if (BEs.getActiveBits() >= 32)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003492 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
3493
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003494 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003495 unsigned IterationNum = 0;
3496 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
3497 if (IterationNum == NumIterations)
3498 return RetVal = PHIVal; // Got exit value!
3499
3500 // Compute the value of the PHI node for the next iteration.
3501 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3502 if (NextPHI == PHIVal)
3503 return RetVal = NextPHI; // Stopped evolving!
3504 if (NextPHI == 0)
3505 return 0; // Couldn't evaluate!
3506 PHIVal = NextPHI;
3507 }
3508}
3509
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003510/// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003511/// constant number of times (the condition evolves only from constants),
3512/// try to evaluate a few iterations of the loop until we get the exit
3513/// condition gets a value of ExitWhen (true or false). If we cannot
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003514/// evaluate the trip count of the loop, return getCouldNotCompute().
Dan Gohman9bc642f2009-06-24 04:48:43 +00003515const SCEV *
3516ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
3517 Value *Cond,
3518 bool ExitWhen) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003519 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003520 if (PN == 0) return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003521
3522 // Since the loop is canonicalized, the PHI node must have two entries. One
3523 // entry must be a constant (coming in from outside of the loop), and the
3524 // second must be derived from the same PHI.
3525 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3526 Constant *StartCST =
3527 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003528 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003529
3530 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3531 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003532 if (PN2 != PN) return getCouldNotCompute(); // Not derived from same PHI.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003533
3534 // Okay, we find a PHI node that defines the trip count of this loop. Execute
3535 // the loop symbolically to determine when the condition gets a value of
3536 // "ExitWhen".
3537 unsigned IterationNum = 0;
3538 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
3539 for (Constant *PHIVal = StartCST;
3540 IterationNum != MaxIterations; ++IterationNum) {
3541 ConstantInt *CondVal =
3542 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
3543
3544 // Couldn't symbolically evaluate.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003545 if (!CondVal) return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003546
3547 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003548 ++NumBruteForceTripCountsComputed;
Dan Gohman8fd520a2009-06-15 22:12:54 +00003549 return getConstant(Type::Int32Ty, IterationNum);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003550 }
3551
3552 // Compute the value of the PHI node for the next iteration.
3553 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3554 if (NextPHI == 0 || NextPHI == PHIVal)
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003555 return getCouldNotCompute();// Couldn't evaluate or not making progress...
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003556 PHIVal = NextPHI;
3557 }
3558
3559 // Too many iterations were needed to evaluate.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003560 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003561}
3562
Dan Gohmandd40e9a2009-05-08 20:38:54 +00003563/// getSCEVAtScope - Return a SCEV expression handle for the specified value
3564/// at the specified scope in the program. The L value specifies a loop
3565/// nest to evaluate the expression at, where null is the top-level or a
3566/// specified loop is immediately inside of the loop.
3567///
3568/// This method can be used to compute the exit value for a variable defined
3569/// in a loop by querying what the value will hold in the parent loop.
3570///
Dan Gohmanaff14d62009-05-24 23:25:42 +00003571/// In the case that a relevant loop exit value cannot be computed, the
3572/// original value V is returned.
Dan Gohman161ea032009-07-07 17:06:11 +00003573const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003574 // FIXME: this should be turned into a virtual method on SCEV!
3575
3576 if (isa<SCEVConstant>(V)) return V;
3577
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00003578 // If this instruction is evolved from a constant-evolving PHI, compute the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003579 // exit value from the loop without using SCEVs.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003580 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003581 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003582 const Loop *LI = (*this->LI)[I->getParent()];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003583 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
3584 if (PHINode *PN = dyn_cast<PHINode>(I))
3585 if (PN->getParent() == LI->getHeader()) {
3586 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003587 // to see if the loop that contains it has a known backedge-taken
3588 // count. If so, we may be able to force computation of the exit
3589 // value.
Dan Gohman161ea032009-07-07 17:06:11 +00003590 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohmanc76b5452009-05-04 22:02:23 +00003591 if (const SCEVConstant *BTCC =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003592 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003593 // Okay, we know how many times the containing loop executes. If
3594 // this is a constant evolving PHI node, get the final value at
3595 // the specified iteration number.
3596 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003597 BTCC->getValue()->getValue(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003598 LI);
Dan Gohman652caf12009-06-29 21:31:18 +00003599 if (RV) return getSCEV(RV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003600 }
3601 }
3602
3603 // Okay, this is an expression that we cannot symbolically evaluate
3604 // into a SCEV. Check to see if it's possible to symbolically evaluate
3605 // the arguments into constants, and if so, try to constant propagate the
3606 // result. This is particularly useful for computing loop exit values.
3607 if (CanConstantFold(I)) {
Dan Gohmanda0071e2009-05-08 20:47:27 +00003608 // Check to see if we've folded this instruction at this loop before.
3609 std::map<const Loop *, Constant *> &Values = ValuesAtScopes[I];
3610 std::pair<std::map<const Loop *, Constant *>::iterator, bool> Pair =
3611 Values.insert(std::make_pair(L, static_cast<Constant *>(0)));
3612 if (!Pair.second)
Dan Gohman652caf12009-06-29 21:31:18 +00003613 return Pair.first->second ? &*getSCEV(Pair.first->second) : V;
Dan Gohmanda0071e2009-05-08 20:47:27 +00003614
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003615 std::vector<Constant*> Operands;
3616 Operands.reserve(I->getNumOperands());
3617 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3618 Value *Op = I->getOperand(i);
3619 if (Constant *C = dyn_cast<Constant>(Op)) {
3620 Operands.push_back(C);
3621 } else {
Chris Lattner3fff4642007-11-23 08:46:22 +00003622 // If any of the operands is non-constant and if they are
Dan Gohman01c2ee72009-04-16 03:18:22 +00003623 // non-integer and non-pointer, don't even try to analyze them
3624 // with scev techniques.
Dan Gohman5e4eb762009-04-30 16:40:30 +00003625 if (!isSCEVable(Op->getType()))
Chris Lattner3fff4642007-11-23 08:46:22 +00003626 return V;
Dan Gohman01c2ee72009-04-16 03:18:22 +00003627
Nick Lewycky9425be92009-07-11 20:38:25 +00003628 const SCEV *OpV = getSCEVAtScope(getSCEV(Op), L);
Dan Gohmanc76b5452009-05-04 22:02:23 +00003629 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
Dan Gohman5e4eb762009-04-30 16:40:30 +00003630 Constant *C = SC->getValue();
3631 if (C->getType() != Op->getType())
3632 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3633 Op->getType(),
3634 false),
3635 C, Op->getType());
3636 Operands.push_back(C);
Dan Gohmanc76b5452009-05-04 22:02:23 +00003637 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
Dan Gohman5e4eb762009-04-30 16:40:30 +00003638 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
3639 if (C->getType() != Op->getType())
3640 C =
3641 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3642 Op->getType(),
3643 false),
3644 C, Op->getType());
3645 Operands.push_back(C);
3646 } else
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003647 return V;
3648 } else {
3649 return V;
3650 }
3651 }
3652 }
Dan Gohman9bc642f2009-06-24 04:48:43 +00003653
Chris Lattnerd6e56912007-12-10 22:53:04 +00003654 Constant *C;
3655 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3656 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
Owen Andersond4d90a02009-07-06 18:42:36 +00003657 &Operands[0], Operands.size(),
3658 Context);
Chris Lattnerd6e56912007-12-10 22:53:04 +00003659 else
3660 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Owen Andersond4d90a02009-07-06 18:42:36 +00003661 &Operands[0], Operands.size(), Context);
Dan Gohmanda0071e2009-05-08 20:47:27 +00003662 Pair.first->second = C;
Dan Gohman652caf12009-06-29 21:31:18 +00003663 return getSCEV(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003664 }
3665 }
3666
3667 // This is some other type of SCEVUnknown, just return it.
3668 return V;
3669 }
3670
Dan Gohmanc76b5452009-05-04 22:02:23 +00003671 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003672 // Avoid performing the look-up in the common case where the specified
3673 // expression has no loop-variant portions.
3674 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Dan Gohman161ea032009-07-07 17:06:11 +00003675 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003676 if (OpAtScope != Comm->getOperand(i)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003677 // Okay, at least one of these operands is loop variant but might be
3678 // foldable. Build a new instance of the folded commutative expression.
Dan Gohman9bc642f2009-06-24 04:48:43 +00003679 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
3680 Comm->op_begin()+i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003681 NewOps.push_back(OpAtScope);
3682
3683 for (++i; i != e; ++i) {
3684 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003685 NewOps.push_back(OpAtScope);
3686 }
3687 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003688 return getAddExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00003689 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003690 return getMulExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00003691 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003692 return getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00003693 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003694 return getUMaxExpr(NewOps);
Edwin Török675d5622009-07-11 20:10:48 +00003695 LLVM_UNREACHABLE("Unknown commutative SCEV type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003696 }
3697 }
3698 // If we got here, all operands are loop invariant.
3699 return Comm;
3700 }
3701
Dan Gohmanc76b5452009-05-04 22:02:23 +00003702 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Dan Gohman161ea032009-07-07 17:06:11 +00003703 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
3704 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky35b56022009-01-13 09:18:58 +00003705 if (LHS == Div->getLHS() && RHS == Div->getRHS())
3706 return Div; // must be loop invariant
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003707 return getUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003708 }
3709
3710 // If this is a loop recurrence for a loop that does not contain L, then we
3711 // are dealing with the final value computed by the loop.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003712 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003713 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
3714 // To evaluate this recurrence, we need to know how many times the AddRec
3715 // loop iterates. Compute this now.
Dan Gohman161ea032009-07-07 17:06:11 +00003716 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003717 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003718
Eli Friedman7489ec92008-08-04 23:49:06 +00003719 // Then, evaluate the AddRec.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003720 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003721 }
Dan Gohmanaff14d62009-05-24 23:25:42 +00003722 return AddRec;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003723 }
3724
Dan Gohmanc76b5452009-05-04 22:02:23 +00003725 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohman161ea032009-07-07 17:06:11 +00003726 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman78d63c82009-04-29 22:29:01 +00003727 if (Op == Cast->getOperand())
3728 return Cast; // must be loop invariant
3729 return getZeroExtendExpr(Op, Cast->getType());
3730 }
3731
Dan Gohmanc76b5452009-05-04 22:02:23 +00003732 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohman161ea032009-07-07 17:06:11 +00003733 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman78d63c82009-04-29 22:29:01 +00003734 if (Op == Cast->getOperand())
3735 return Cast; // must be loop invariant
3736 return getSignExtendExpr(Op, Cast->getType());
3737 }
3738
Dan Gohmanc76b5452009-05-04 22:02:23 +00003739 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohman161ea032009-07-07 17:06:11 +00003740 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman78d63c82009-04-29 22:29:01 +00003741 if (Op == Cast->getOperand())
3742 return Cast; // must be loop invariant
3743 return getTruncateExpr(Op, Cast->getType());
3744 }
3745
Edwin Török675d5622009-07-11 20:10:48 +00003746 LLVM_UNREACHABLE("Unknown SCEV type!");
Daniel Dunbara95d96c2009-05-18 16:43:04 +00003747 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003748}
3749
Dan Gohmandd40e9a2009-05-08 20:38:54 +00003750/// getSCEVAtScope - This is a convenience function which does
3751/// getSCEVAtScope(getSCEV(V), L).
Dan Gohman161ea032009-07-07 17:06:11 +00003752const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003753 return getSCEVAtScope(getSCEV(V), L);
3754}
3755
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003756/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
3757/// following equation:
3758///
3759/// A * X = B (mod N)
3760///
3761/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
3762/// A and B isn't important.
3763///
3764/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Dan Gohman161ea032009-07-07 17:06:11 +00003765static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003766 ScalarEvolution &SE) {
3767 uint32_t BW = A.getBitWidth();
3768 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
3769 assert(A != 0 && "A must be non-zero.");
3770
3771 // 1. D = gcd(A, N)
3772 //
3773 // The gcd of A and N may have only one prime factor: 2. The number of
3774 // trailing zeros in A is its multiplicity
3775 uint32_t Mult2 = A.countTrailingZeros();
3776 // D = 2^Mult2
3777
3778 // 2. Check if B is divisible by D.
3779 //
3780 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
3781 // is not less than multiplicity of this prime factor for D.
3782 if (B.countTrailingZeros() < Mult2)
Dan Gohman0ad08b02009-04-18 17:58:19 +00003783 return SE.getCouldNotCompute();
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003784
3785 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
3786 // modulo (N / D).
3787 //
3788 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
3789 // bit width during computations.
3790 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
3791 APInt Mod(BW + 1, 0);
3792 Mod.set(BW - Mult2); // Mod = N / D
3793 APInt I = AD.multiplicativeInverse(Mod);
3794
3795 // 4. Compute the minimum unsigned root of the equation:
3796 // I * (B / D) mod (N / D)
3797 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
3798
3799 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
3800 // bits.
3801 return SE.getConstant(Result.trunc(BW));
3802}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003803
3804/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
3805/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
3806/// might be the same) or two SCEVCouldNotCompute objects.
3807///
Dan Gohman161ea032009-07-07 17:06:11 +00003808static std::pair<const SCEV *,const SCEV *>
Dan Gohman89f85052007-10-22 18:31:58 +00003809SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003810 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohmanbff6b582009-05-04 22:30:44 +00003811 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
3812 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
3813 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003814
3815 // We currently can only solve this if the coefficients are constants.
3816 if (!LC || !MC || !NC) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00003817 const SCEV *CNC = SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003818 return std::make_pair(CNC, CNC);
3819 }
3820
3821 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
3822 const APInt &L = LC->getValue()->getValue();
3823 const APInt &M = MC->getValue()->getValue();
3824 const APInt &N = NC->getValue()->getValue();
3825 APInt Two(BitWidth, 2);
3826 APInt Four(BitWidth, 4);
3827
Dan Gohman9bc642f2009-06-24 04:48:43 +00003828 {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003829 using namespace APIntOps;
3830 const APInt& C = L;
3831 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
3832 // The B coefficient is M-N/2
3833 APInt B(M);
3834 B -= sdiv(N,Two);
3835
3836 // The A coefficient is N/2
3837 APInt A(N.sdiv(Two));
3838
3839 // Compute the B^2-4ac term.
3840 APInt SqrtTerm(B);
3841 SqrtTerm *= B;
3842 SqrtTerm -= Four * (A * C);
3843
3844 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
3845 // integer value or else APInt::sqrt() will assert.
3846 APInt SqrtVal(SqrtTerm.sqrt());
3847
Dan Gohman9bc642f2009-06-24 04:48:43 +00003848 // Compute the two solutions for the quadratic formula.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003849 // The divisions must be performed as signed divisions.
3850 APInt NegB(-B);
3851 APInt TwoA( A << 1 );
Nick Lewycky35776692008-11-03 02:43:49 +00003852 if (TwoA.isMinValue()) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00003853 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky35776692008-11-03 02:43:49 +00003854 return std::make_pair(CNC, CNC);
3855 }
3856
Owen Andersone755b092009-07-06 22:37:39 +00003857 LLVMContext *Context = SE.getContext();
3858
3859 ConstantInt *Solution1 =
3860 Context->getConstantInt((NegB + SqrtVal).sdiv(TwoA));
3861 ConstantInt *Solution2 =
3862 Context->getConstantInt((NegB - SqrtVal).sdiv(TwoA));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003863
Dan Gohman9bc642f2009-06-24 04:48:43 +00003864 return std::make_pair(SE.getConstant(Solution1),
Dan Gohman89f85052007-10-22 18:31:58 +00003865 SE.getConstant(Solution2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003866 } // end APIntOps namespace
3867}
3868
3869/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman0c850912009-06-06 14:37:11 +00003870/// value to zero will execute. If not computable, return CouldNotCompute.
Dan Gohman161ea032009-07-07 17:06:11 +00003871const SCEV *ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003872 // If the value is a constant
Dan Gohmanc76b5452009-05-04 22:02:23 +00003873 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003874 // If the value is already zero, the branch will execute zero times.
3875 if (C->getValue()->isZero()) return C;
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003876 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003877 }
3878
Dan Gohmanbff6b582009-05-04 22:30:44 +00003879 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003880 if (!AddRec || AddRec->getLoop() != L)
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003881 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003882
3883 if (AddRec->isAffine()) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003884 // If this is an affine expression, the execution count of this branch is
3885 // the minimum unsigned root of the following equation:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003886 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003887 // Start + Step*N = 0 (mod 2^BW)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003888 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003889 // equivalent to:
3890 //
3891 // Step*N = -Start (mod 2^BW)
3892 //
3893 // where BW is the common bit width of Start and Step.
3894
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003895 // Get the initial value for the loop.
Dan Gohman9bc642f2009-06-24 04:48:43 +00003896 const SCEV *Start = getSCEVAtScope(AddRec->getStart(),
3897 L->getParentLoop());
3898 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1),
3899 L->getParentLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003900
Dan Gohmanc76b5452009-05-04 22:02:23 +00003901 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003902 // For now we handle only constant steps.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003903
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003904 // First, handle unitary steps.
3905 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003906 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003907 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
3908 return Start; // N = Start (as unsigned)
3909
3910 // Then, try to solve the above equation provided that Start is constant.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003911 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003912 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003913 -StartC->getValue()->getValue(),
3914 *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003915 }
3916 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
3917 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
3918 // the quadratic equation to solve it.
Dan Gohman161ea032009-07-07 17:06:11 +00003919 std::pair<const SCEV *,const SCEV *> Roots = SolveQuadraticEquation(AddRec,
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003920 *this);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003921 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3922 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003923 if (R1) {
3924#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00003925 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
3926 << " sol#2: " << *R2 << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003927#endif
3928 // Pick the smallest positive root value.
3929 if (ConstantInt *CB =
Owen Andersone755b092009-07-06 22:37:39 +00003930 dyn_cast<ConstantInt>(Context->getConstantExprICmp(ICmpInst::ICMP_ULT,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003931 R1->getValue(), R2->getValue()))) {
3932 if (CB->getZExtValue() == false)
3933 std::swap(R1, R2); // R1 is the minimum root now.
3934
3935 // We can only use this value if the chrec ends up with an exact zero
3936 // value at this index. When solving for "X*X != 5", for example, we
3937 // should not accept a root of 2.
Dan Gohman161ea032009-07-07 17:06:11 +00003938 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohman7b560c42008-06-18 16:23:07 +00003939 if (Val->isZero())
3940 return R1; // We found a quadratic root!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003941 }
3942 }
3943 }
3944
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003945 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003946}
3947
3948/// HowFarToNonZero - Return the number of times a backedge checking the
3949/// specified value for nonzero will execute. If not computable, return
Dan Gohman0c850912009-06-06 14:37:11 +00003950/// CouldNotCompute
Dan Gohman161ea032009-07-07 17:06:11 +00003951const SCEV *ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003952 // Loops that look like: while (X == 0) are very strange indeed. We don't
3953 // handle them yet except for the trivial case. This could be expanded in the
3954 // future as needed.
3955
3956 // If the value is a constant, check to see if it is known to be non-zero
3957 // already. If so, the backedge will execute zero times.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003958 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewyckyf6805182008-02-21 09:14:53 +00003959 if (!C->getValue()->isNullValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003960 return getIntegerSCEV(0, C->getType());
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003961 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003962 }
3963
3964 // We could implement others, but I really doubt anyone writes loops like
3965 // this, and if they did, they would already be constant folded.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003966 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003967}
3968
Dan Gohmanab157b22009-05-18 15:36:09 +00003969/// getLoopPredecessor - If the given loop's header has exactly one unique
3970/// predecessor outside the loop, return it. Otherwise return null.
3971///
3972BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) {
3973 BasicBlock *Header = L->getHeader();
3974 BasicBlock *Pred = 0;
3975 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header);
3976 PI != E; ++PI)
3977 if (!L->contains(*PI)) {
3978 if (Pred && Pred != *PI) return 0; // Multiple predecessors.
3979 Pred = *PI;
3980 }
3981 return Pred;
3982}
3983
Dan Gohman1cddf972008-09-15 22:18:04 +00003984/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
3985/// (which may not be an immediate predecessor) which has exactly one
3986/// successor from which BB is reachable, or null if no such block is
3987/// found.
3988///
3989BasicBlock *
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003990ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman1116ea72009-04-30 20:48:53 +00003991 // If the block has a unique predecessor, then there is no path from the
3992 // predecessor to the block that does not go through the direct edge
3993 // from the predecessor to the block.
Dan Gohman1cddf972008-09-15 22:18:04 +00003994 if (BasicBlock *Pred = BB->getSinglePredecessor())
3995 return Pred;
3996
3997 // A loop's header is defined to be a block that dominates the loop.
Dan Gohmanab157b22009-05-18 15:36:09 +00003998 // If the header has a unique predecessor outside the loop, it must be
3999 // a block that has exactly one successor that can reach the loop.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004000 if (Loop *L = LI->getLoopFor(BB))
Dan Gohmanab157b22009-05-18 15:36:09 +00004001 return getLoopPredecessor(L);
Dan Gohman1cddf972008-09-15 22:18:04 +00004002
4003 return 0;
4004}
4005
Dan Gohmanbc1e3472009-06-20 00:35:32 +00004006/// HasSameValue - SCEV structural equivalence is usually sufficient for
4007/// testing whether two expressions are equal, however for the purposes of
4008/// looking for a condition guarding a loop, it can be useful to be a little
4009/// more general, since a front-end may have replicated the controlling
4010/// expression.
4011///
Dan Gohman161ea032009-07-07 17:06:11 +00004012static bool HasSameValue(const SCEV *A, const SCEV *B) {
Dan Gohmanbc1e3472009-06-20 00:35:32 +00004013 // Quick check to see if they are the same SCEV.
4014 if (A == B) return true;
4015
4016 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
4017 // two different instructions with the same value. Check for this case.
4018 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
4019 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
4020 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
4021 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
4022 if (AI->isIdenticalTo(BI))
4023 return true;
4024
4025 // Otherwise assume they may have a different value.
4026 return false;
4027}
4028
Nick Lewycky9425be92009-07-11 20:38:25 +00004029/// isLoopGuardedByCond - Test whether entry to the loop is protected by
4030/// a conditional between LHS and RHS. This is used to help avoid max
4031/// expressions in loop trip counts.
4032bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
4033 ICmpInst::Predicate Pred,
4034 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman8b938182009-05-18 16:03:58 +00004035 // Interpret a null as meaning no loop, where there is obviously no guard
4036 // (interprocedural conditions notwithstanding).
4037 if (!L) return false;
4038
Dan Gohmanab157b22009-05-18 15:36:09 +00004039 BasicBlock *Predecessor = getLoopPredecessor(L);
4040 BasicBlock *PredecessorDest = L->getHeader();
Nick Lewycky1b020bf2008-07-12 07:41:32 +00004041
Dan Gohmanab157b22009-05-18 15:36:09 +00004042 // Starting at the loop predecessor, climb up the predecessor chain, as long
4043 // as there are predecessors that can be found that have unique successors
Dan Gohman1cddf972008-09-15 22:18:04 +00004044 // leading to the original header.
Dan Gohmanab157b22009-05-18 15:36:09 +00004045 for (; Predecessor;
4046 PredecessorDest = Predecessor,
4047 Predecessor = getPredecessorWithUniqueSuccessorForBB(Predecessor)) {
Dan Gohmanab678fb2008-08-12 20:17:31 +00004048
4049 BranchInst *LoopEntryPredicate =
Dan Gohmanab157b22009-05-18 15:36:09 +00004050 dyn_cast<BranchInst>(Predecessor->getTerminator());
Dan Gohmanab678fb2008-08-12 20:17:31 +00004051 if (!LoopEntryPredicate ||
4052 LoopEntryPredicate->isUnconditional())
4053 continue;
4054
Dan Gohman423ed6c2009-06-24 01:18:18 +00004055 if (isNecessaryCond(LoopEntryPredicate->getCondition(), Pred, LHS, RHS,
4056 LoopEntryPredicate->getSuccessor(0) != PredecessorDest))
Dan Gohmanab678fb2008-08-12 20:17:31 +00004057 return true;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00004058 }
4059
Dan Gohmanab678fb2008-08-12 20:17:31 +00004060 return false;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00004061}
4062
Nick Lewycky9425be92009-07-11 20:38:25 +00004063/// isNecessaryCond - Test whether the given CondValue value is a condition
4064/// which is at least as strict as the one described by Pred, LHS, and RHS.
Dan Gohman423ed6c2009-06-24 01:18:18 +00004065bool ScalarEvolution::isNecessaryCond(Value *CondValue,
4066 ICmpInst::Predicate Pred,
4067 const SCEV *LHS, const SCEV *RHS,
4068 bool Inverse) {
4069 // Recursivly handle And and Or conditions.
4070 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CondValue)) {
4071 if (BO->getOpcode() == Instruction::And) {
4072 if (!Inverse)
4073 return isNecessaryCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4074 isNecessaryCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
4075 } else if (BO->getOpcode() == Instruction::Or) {
4076 if (Inverse)
4077 return isNecessaryCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4078 isNecessaryCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
4079 }
4080 }
4081
4082 ICmpInst *ICI = dyn_cast<ICmpInst>(CondValue);
4083 if (!ICI) return false;
4084
4085 // Now that we found a conditional branch that dominates the loop, check to
4086 // see if it is the comparison we are looking for.
4087 Value *PreCondLHS = ICI->getOperand(0);
4088 Value *PreCondRHS = ICI->getOperand(1);
Nick Lewycky9425be92009-07-11 20:38:25 +00004089 ICmpInst::Predicate Cond;
Dan Gohman423ed6c2009-06-24 01:18:18 +00004090 if (Inverse)
Nick Lewycky9425be92009-07-11 20:38:25 +00004091 Cond = ICI->getInversePredicate();
Dan Gohman423ed6c2009-06-24 01:18:18 +00004092 else
Nick Lewycky9425be92009-07-11 20:38:25 +00004093 Cond = ICI->getPredicate();
Dan Gohman423ed6c2009-06-24 01:18:18 +00004094
Nick Lewycky9425be92009-07-11 20:38:25 +00004095 if (Cond == Pred)
Dan Gohman423ed6c2009-06-24 01:18:18 +00004096 ; // An exact match.
Nick Lewycky9425be92009-07-11 20:38:25 +00004097 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
4098 ; // The actual condition is beyond sufficient.
4099 else
Dan Gohman423ed6c2009-06-24 01:18:18 +00004100 // Check a few special cases.
Nick Lewycky9425be92009-07-11 20:38:25 +00004101 switch (Cond) {
Dan Gohman423ed6c2009-06-24 01:18:18 +00004102 case ICmpInst::ICMP_UGT:
4103 if (Pred == ICmpInst::ICMP_ULT) {
4104 std::swap(PreCondLHS, PreCondRHS);
Nick Lewycky9425be92009-07-11 20:38:25 +00004105 Cond = ICmpInst::ICMP_ULT;
Dan Gohman423ed6c2009-06-24 01:18:18 +00004106 break;
4107 }
4108 return false;
4109 case ICmpInst::ICMP_SGT:
4110 if (Pred == ICmpInst::ICMP_SLT) {
4111 std::swap(PreCondLHS, PreCondRHS);
Nick Lewycky9425be92009-07-11 20:38:25 +00004112 Cond = ICmpInst::ICMP_SLT;
Dan Gohman423ed6c2009-06-24 01:18:18 +00004113 break;
4114 }
4115 return false;
4116 case ICmpInst::ICMP_NE:
4117 // Expressions like (x >u 0) are often canonicalized to (x != 0),
4118 // so check for this case by checking if the NE is comparing against
4119 // a minimum or maximum constant.
4120 if (!ICmpInst::isTrueWhenEqual(Pred))
Nick Lewycky9425be92009-07-11 20:38:25 +00004121 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
4122 const APInt &A = CI->getValue();
Dan Gohman423ed6c2009-06-24 01:18:18 +00004123 switch (Pred) {
4124 case ICmpInst::ICMP_SLT:
4125 if (A.isMaxSignedValue()) break;
4126 return false;
4127 case ICmpInst::ICMP_SGT:
4128 if (A.isMinSignedValue()) break;
4129 return false;
4130 case ICmpInst::ICMP_ULT:
4131 if (A.isMaxValue()) break;
4132 return false;
4133 case ICmpInst::ICMP_UGT:
4134 if (A.isMinValue()) break;
4135 return false;
4136 default:
4137 return false;
4138 }
Nick Lewycky9425be92009-07-11 20:38:25 +00004139 Cond = ICmpInst::ICMP_NE;
Dan Gohman423ed6c2009-06-24 01:18:18 +00004140 // NE is symmetric but the original comparison may not be. Swap
4141 // the operands if necessary so that they match below.
4142 if (isa<SCEVConstant>(LHS))
4143 std::swap(PreCondLHS, PreCondRHS);
4144 break;
4145 }
4146 return false;
4147 default:
4148 // We weren't able to reconcile the condition.
4149 return false;
4150 }
4151
Nick Lewycky9425be92009-07-11 20:38:25 +00004152 if (!PreCondLHS->getType()->isInteger()) return false;
Dan Gohman423ed6c2009-06-24 01:18:18 +00004153
Nick Lewycky9425be92009-07-11 20:38:25 +00004154 const SCEV *PreCondLHSSCEV = getSCEV(PreCondLHS);
4155 const SCEV *PreCondRHSSCEV = getSCEV(PreCondRHS);
4156 return (HasSameValue(LHS, PreCondLHSSCEV) &&
4157 HasSameValue(RHS, PreCondRHSSCEV)) ||
4158 (HasSameValue(LHS, getNotSCEV(PreCondRHSSCEV)) &&
4159 HasSameValue(RHS, getNotSCEV(PreCondLHSSCEV)));
Dan Gohman423ed6c2009-06-24 01:18:18 +00004160}
4161
Dan Gohmand2b62c42009-06-21 23:46:38 +00004162/// getBECount - Subtract the end and start values and divide by the step,
4163/// rounding up, to get the number of times the backedge is executed. Return
4164/// CouldNotCompute if an intermediate computation overflows.
Dan Gohman161ea032009-07-07 17:06:11 +00004165const SCEV *ScalarEvolution::getBECount(const SCEV *Start,
4166 const SCEV *End,
4167 const SCEV *Step) {
Dan Gohmand2b62c42009-06-21 23:46:38 +00004168 const Type *Ty = Start->getType();
Dan Gohman161ea032009-07-07 17:06:11 +00004169 const SCEV *NegOne = getIntegerSCEV(-1, Ty);
4170 const SCEV *Diff = getMinusSCEV(End, Start);
4171 const SCEV *RoundUp = getAddExpr(Step, NegOne);
Dan Gohmand2b62c42009-06-21 23:46:38 +00004172
4173 // Add an adjustment to the difference between End and Start so that
4174 // the division will effectively round up.
Dan Gohman161ea032009-07-07 17:06:11 +00004175 const SCEV *Add = getAddExpr(Diff, RoundUp);
Dan Gohmand2b62c42009-06-21 23:46:38 +00004176
4177 // Check Add for unsigned overflow.
4178 // TODO: More sophisticated things could be done here.
Owen Andersone755b092009-07-06 22:37:39 +00004179 const Type *WideTy = Context->getIntegerType(getTypeSizeInBits(Ty) + 1);
Dan Gohman161ea032009-07-07 17:06:11 +00004180 const SCEV *OperandExtendedAdd =
Dan Gohmand2b62c42009-06-21 23:46:38 +00004181 getAddExpr(getZeroExtendExpr(Diff, WideTy),
4182 getZeroExtendExpr(RoundUp, WideTy));
4183 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004184 return getCouldNotCompute();
Dan Gohmand2b62c42009-06-21 23:46:38 +00004185
4186 return getUDivExpr(Add, Step);
4187}
4188
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004189/// HowManyLessThans - Return the number of times a backedge containing the
4190/// specified less-than comparison will execute. If not computable, return
Dan Gohman0c850912009-06-06 14:37:11 +00004191/// CouldNotCompute.
Dan Gohman9bc642f2009-06-24 04:48:43 +00004192ScalarEvolution::BackedgeTakenInfo
4193ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
4194 const Loop *L, bool isSigned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004195 // Only handle: "ADDREC < LoopInvariant".
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004196 if (!RHS->isLoopInvariant(L)) return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004197
Dan Gohmanbff6b582009-05-04 22:30:44 +00004198 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004199 if (!AddRec || AddRec->getLoop() != L)
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004200 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004201
4202 if (AddRec->isAffine()) {
Nick Lewycky35b56022009-01-13 09:18:58 +00004203 // FORNOW: We only support unit strides.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004204 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
Dan Gohman161ea032009-07-07 17:06:11 +00004205 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004206
4207 // TODO: handle non-constant strides.
4208 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
4209 if (!CStep || CStep->isZero())
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004210 return getCouldNotCompute();
Dan Gohmanf8bc8e82009-05-18 15:22:39 +00004211 if (CStep->isOne()) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004212 // With unit stride, the iteration never steps past the limit value.
4213 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
4214 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
4215 // Test whether a positive iteration iteration can step past the limit
4216 // value and past the maximum value for its type in a single step.
4217 if (isSigned) {
4218 APInt Max = APInt::getSignedMaxValue(BitWidth);
4219 if ((Max - CStep->getValue()->getValue())
4220 .slt(CLimit->getValue()->getValue()))
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004221 return getCouldNotCompute();
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004222 } else {
4223 APInt Max = APInt::getMaxValue(BitWidth);
4224 if ((Max - CStep->getValue()->getValue())
4225 .ult(CLimit->getValue()->getValue()))
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004226 return getCouldNotCompute();
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004227 }
4228 } else
4229 // TODO: handle non-constant limit values below.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004230 return getCouldNotCompute();
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004231 } else
4232 // TODO: handle negative strides below.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004233 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004234
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004235 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
4236 // m. So, we count the number of iterations in which {n,+,s} < m is true.
4237 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicz1377a542008-02-13 12:21:32 +00004238 // treat m-n as signed nor unsigned due to overflow possibility.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004239
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00004240 // First, we get the value of the LHS in the first iteration: n
Dan Gohman161ea032009-07-07 17:06:11 +00004241 const SCEV *Start = AddRec->getOperand(0);
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00004242
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004243 // Determine the minimum constant start value.
Nick Lewycky9425be92009-07-11 20:38:25 +00004244 const SCEV *MinStart = isa<SCEVConstant>(Start) ? Start :
4245 getConstant(isSigned ? APInt::getSignedMinValue(BitWidth) :
4246 APInt::getMinValue(BitWidth));
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00004247
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004248 // If we know that the condition is true in order to enter the loop,
4249 // then we know that it will run exactly (m-n)/s times. Otherwise, we
Dan Gohmanc8a29272009-05-24 23:45:28 +00004250 // only know that it will execute (max(m,n)-n)/s times. In both cases,
4251 // the division must round up.
Dan Gohman161ea032009-07-07 17:06:11 +00004252 const SCEV *End = RHS;
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004253 if (!isLoopGuardedByCond(L,
Nick Lewycky9425be92009-07-11 20:38:25 +00004254 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004255 getMinusSCEV(Start, Step), RHS))
4256 End = isSigned ? getSMaxExpr(RHS, Start)
4257 : getUMaxExpr(RHS, Start);
4258
4259 // Determine the maximum constant end value.
Nick Lewycky9425be92009-07-11 20:38:25 +00004260 const SCEV *MaxEnd =
4261 isa<SCEVConstant>(End) ? End :
4262 getConstant(isSigned ? APInt::getSignedMaxValue(BitWidth)
4263 .ashr(GetMinSignBits(End) - 1) :
4264 APInt::getMaxValue(BitWidth)
4265 .lshr(GetMinLeadingZeros(End)));
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004266
4267 // Finally, we subtract these two values and divide, rounding up, to get
4268 // the number of times the backedge is executed.
Dan Gohman161ea032009-07-07 17:06:11 +00004269 const SCEV *BECount = getBECount(Start, End, Step);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004270
4271 // The maximum backedge count is similar, except using the minimum start
4272 // value and the maximum end value.
Dan Gohman161ea032009-07-07 17:06:11 +00004273 const SCEV *MaxBECount = getBECount(MinStart, MaxEnd, Step);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004274
4275 return BackedgeTakenInfo(BECount, MaxBECount);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004276 }
4277
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004278 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004279}
4280
4281/// getNumIterationsInRange - Return the number of iterations of this loop that
4282/// produce values in the specified constant range. Another way of looking at
4283/// this is that it returns the first iteration number where the value is not in
4284/// the condition, thus computing the exit count. If the iteration count can't
4285/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman161ea032009-07-07 17:06:11 +00004286const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
Dan Gohman9bc642f2009-06-24 04:48:43 +00004287 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004288 if (Range.isFullSet()) // Infinite loop.
Dan Gohman0ad08b02009-04-18 17:58:19 +00004289 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004290
4291 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohmanc76b5452009-05-04 22:02:23 +00004292 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004293 if (!SC->getValue()->isZero()) {
Dan Gohman161ea032009-07-07 17:06:11 +00004294 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00004295 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
Dan Gohman161ea032009-07-07 17:06:11 +00004296 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohmanc76b5452009-05-04 22:02:23 +00004297 if (const SCEVAddRecExpr *ShiftedAddRec =
4298 dyn_cast<SCEVAddRecExpr>(Shifted))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004299 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman89f85052007-10-22 18:31:58 +00004300 Range.subtract(SC->getValue()->getValue()), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004301 // This is strange and shouldn't happen.
Dan Gohman0ad08b02009-04-18 17:58:19 +00004302 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004303 }
4304
4305 // The only time we can solve this is when we have all constant indices.
4306 // Otherwise, we cannot determine the overflow conditions.
4307 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
4308 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohman0ad08b02009-04-18 17:58:19 +00004309 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004310
4311
4312 // Okay at this point we know that all elements of the chrec are constants and
4313 // that the start element is zero.
4314
4315 // First check to see if the range contains zero. If not, the first
4316 // iteration exits.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00004317 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00004318 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman8fd520a2009-06-15 22:12:54 +00004319 return SE.getIntegerSCEV(0, getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004320
4321 if (isAffine()) {
4322 // If this is an affine expression then we have this situation:
4323 // Solve {0,+,A} in Range === Ax in Range
4324
4325 // We know that zero is in the range. If A is positive then we know that
4326 // the upper value of the range must be the first possible exit value.
4327 // If A is negative then the lower of the range is the last possible loop
4328 // value. Also note that we already checked for a full range.
Dan Gohman01c2ee72009-04-16 03:18:22 +00004329 APInt One(BitWidth,1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004330 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
4331 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
4332
4333 // The exit value should be (End+A)/A.
Nick Lewyckya0facae2007-09-27 14:12:54 +00004334 APInt ExitVal = (End + A).udiv(A);
Owen Andersone755b092009-07-06 22:37:39 +00004335 ConstantInt *ExitValue = SE.getContext()->getConstantInt(ExitVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004336
4337 // Evaluate at the exit value. If we really did fall out of the valid
4338 // range, then we computed our trip count, otherwise wrap around or other
4339 // things must have happened.
Dan Gohman89f85052007-10-22 18:31:58 +00004340 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004341 if (Range.contains(Val->getValue()))
Dan Gohman0ad08b02009-04-18 17:58:19 +00004342 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004343
4344 // Ensure that the previous value is in the range. This is a sanity check.
4345 assert(Range.contains(
Dan Gohman9bc642f2009-06-24 04:48:43 +00004346 EvaluateConstantChrecAtConstant(this,
Owen Andersone755b092009-07-06 22:37:39 +00004347 SE.getContext()->getConstantInt(ExitVal - One), SE)->getValue()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004348 "Linear scev computation is off in a bad way!");
Dan Gohman89f85052007-10-22 18:31:58 +00004349 return SE.getConstant(ExitValue);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004350 } else if (isQuadratic()) {
4351 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
4352 // quadratic equation to solve it. To do this, we must frame our problem in
4353 // terms of figuring out when zero is crossed, instead of when
4354 // Range.getUpper() is crossed.
Dan Gohman161ea032009-07-07 17:06:11 +00004355 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00004356 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Dan Gohman161ea032009-07-07 17:06:11 +00004357 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004358
4359 // Next, solve the constructed addrec
Dan Gohman161ea032009-07-07 17:06:11 +00004360 std::pair<const SCEV *,const SCEV *> Roots =
Dan Gohman89f85052007-10-22 18:31:58 +00004361 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohmanbff6b582009-05-04 22:30:44 +00004362 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4363 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004364 if (R1) {
4365 // Pick the smallest positive root value.
4366 if (ConstantInt *CB =
Owen Andersone755b092009-07-06 22:37:39 +00004367 dyn_cast<ConstantInt>(
4368 SE.getContext()->getConstantExprICmp(ICmpInst::ICMP_ULT,
4369 R1->getValue(), R2->getValue()))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004370 if (CB->getZExtValue() == false)
4371 std::swap(R1, R2); // R1 is the minimum root now.
4372
4373 // Make sure the root is not off by one. The returned iteration should
4374 // not be in the range, but the previous one should be. When solving
4375 // for "X*X < 5", for example, we should not return a root of 2.
4376 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00004377 R1->getValue(),
4378 SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004379 if (Range.contains(R1Val->getValue())) {
4380 // The next iteration must be out of the range...
Owen Andersone755b092009-07-06 22:37:39 +00004381 ConstantInt *NextVal =
4382 SE.getContext()->getConstantInt(R1->getValue()->getValue()+1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004383
Dan Gohman89f85052007-10-22 18:31:58 +00004384 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004385 if (!Range.contains(R1Val->getValue()))
Dan Gohman89f85052007-10-22 18:31:58 +00004386 return SE.getConstant(NextVal);
Dan Gohman0ad08b02009-04-18 17:58:19 +00004387 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004388 }
4389
4390 // If R1 was not in the range, then it is a good return value. Make
4391 // sure that R1-1 WAS in the range though, just in case.
Owen Andersone755b092009-07-06 22:37:39 +00004392 ConstantInt *NextVal =
4393 SE.getContext()->getConstantInt(R1->getValue()->getValue()-1);
Dan Gohman89f85052007-10-22 18:31:58 +00004394 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004395 if (Range.contains(R1Val->getValue()))
4396 return R1;
Dan Gohman0ad08b02009-04-18 17:58:19 +00004397 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004398 }
4399 }
4400 }
4401
Dan Gohman0ad08b02009-04-18 17:58:19 +00004402 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004403}
4404
4405
4406
4407//===----------------------------------------------------------------------===//
Dan Gohmanbff6b582009-05-04 22:30:44 +00004408// SCEVCallbackVH Class Implementation
4409//===----------------------------------------------------------------------===//
4410
Dan Gohman999d14e2009-05-19 19:22:47 +00004411void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmanbff6b582009-05-04 22:30:44 +00004412 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
4413 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
4414 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00004415 if (Instruction *I = dyn_cast<Instruction>(getValPtr()))
4416 SE->ValuesAtScopes.erase(I);
Dan Gohmanbff6b582009-05-04 22:30:44 +00004417 SE->Scalars.erase(getValPtr());
4418 // this now dangles!
4419}
4420
Dan Gohman999d14e2009-05-19 19:22:47 +00004421void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00004422 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
4423
4424 // Forget all the expressions associated with users of the old value,
4425 // so that future queries will recompute the expressions using the new
4426 // value.
4427 SmallVector<User *, 16> Worklist;
4428 Value *Old = getValPtr();
4429 bool DeleteOld = false;
4430 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
4431 UI != UE; ++UI)
4432 Worklist.push_back(*UI);
4433 while (!Worklist.empty()) {
4434 User *U = Worklist.pop_back_val();
4435 // Deleting the Old value will cause this to dangle. Postpone
4436 // that until everything else is done.
4437 if (U == Old) {
4438 DeleteOld = true;
4439 continue;
4440 }
4441 if (PHINode *PN = dyn_cast<PHINode>(U))
4442 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00004443 if (Instruction *I = dyn_cast<Instruction>(U))
4444 SE->ValuesAtScopes.erase(I);
Dan Gohmanbff6b582009-05-04 22:30:44 +00004445 if (SE->Scalars.erase(U))
4446 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
4447 UI != UE; ++UI)
4448 Worklist.push_back(*UI);
4449 }
4450 if (DeleteOld) {
4451 if (PHINode *PN = dyn_cast<PHINode>(Old))
4452 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00004453 if (Instruction *I = dyn_cast<Instruction>(Old))
4454 SE->ValuesAtScopes.erase(I);
Dan Gohmanbff6b582009-05-04 22:30:44 +00004455 SE->Scalars.erase(Old);
4456 // this now dangles!
4457 }
4458 // this may dangle!
4459}
4460
Dan Gohman999d14e2009-05-19 19:22:47 +00004461ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohmanbff6b582009-05-04 22:30:44 +00004462 : CallbackVH(V), SE(se) {}
4463
4464//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004465// ScalarEvolution Class Implementation
4466//===----------------------------------------------------------------------===//
4467
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004468ScalarEvolution::ScalarEvolution()
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004469 : FunctionPass(&ID) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004470}
4471
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004472bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004473 this->F = &F;
4474 LI = &getAnalysis<LoopInfo>();
4475 TD = getAnalysisIfAvailable<TargetData>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004476 return false;
4477}
4478
4479void ScalarEvolution::releaseMemory() {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004480 Scalars.clear();
4481 BackedgeTakenCounts.clear();
4482 ConstantEvolutionLoopExitValue.clear();
Dan Gohmanda0071e2009-05-08 20:47:27 +00004483 ValuesAtScopes.clear();
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004484 UniqueSCEVs.clear();
4485 SCEVAllocator.Reset();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004486}
4487
4488void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
4489 AU.setPreservesAll();
4490 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman01c2ee72009-04-16 03:18:22 +00004491}
4492
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004493bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00004494 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004495}
4496
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004497static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004498 const Loop *L) {
4499 // Print all inner loops first
4500 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
4501 PrintLoopInfo(OS, SE, *I);
4502
Nick Lewyckye5da1912008-01-02 02:49:20 +00004503 OS << "Loop " << L->getHeader()->getName() << ": ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004504
Devang Patel02451fa2007-08-21 00:31:24 +00004505 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004506 L->getExitBlocks(ExitBlocks);
4507 if (ExitBlocks.size() != 1)
Nick Lewyckye5da1912008-01-02 02:49:20 +00004508 OS << "<multiple exits> ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004509
Dan Gohman76d5a0d2009-02-24 18:55:53 +00004510 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
4511 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004512 } else {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00004513 OS << "Unpredictable backedge-taken count. ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004514 }
4515
Nick Lewyckye5da1912008-01-02 02:49:20 +00004516 OS << "\n";
Dan Gohmanb6b9e9e2009-06-24 00:33:16 +00004517 OS << "Loop " << L->getHeader()->getName() << ": ";
4518
4519 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
4520 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
4521 } else {
4522 OS << "Unpredictable max backedge-taken count. ";
4523 }
4524
4525 OS << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004526}
4527
Dan Gohman13058cc2009-04-21 00:47:46 +00004528void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004529 // ScalarEvolution's implementaiton of the print method is to print
4530 // out SCEV values of all instructions that are interesting. Doing
4531 // this potentially causes it to create new SCEV objects though,
4532 // which technically conflicts with the const qualifier. This isn't
Dan Gohmanac2a9d62009-07-10 20:25:29 +00004533 // observable from outside the class though, so casting away the
4534 // const isn't dangerous.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004535 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004536
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004537 OS << "Classifying expressions for: " << F->getName() << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004538 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohman43d37e92009-04-30 01:30:18 +00004539 if (isSCEVable(I->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004540 OS << *I;
Dan Gohmanabe991f2008-09-14 17:21:12 +00004541 OS << " --> ";
Dan Gohman161ea032009-07-07 17:06:11 +00004542 const SCEV *SV = SE.getSCEV(&*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004543 SV->print(OS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004544
Dan Gohman8db598a2009-06-19 17:49:54 +00004545 const Loop *L = LI->getLoopFor((*I).getParent());
4546
Dan Gohman161ea032009-07-07 17:06:11 +00004547 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohman8db598a2009-06-19 17:49:54 +00004548 if (AtUse != SV) {
4549 OS << " --> ";
4550 AtUse->print(OS);
4551 }
4552
4553 if (L) {
Dan Gohmane5b60842009-06-18 00:37:45 +00004554 OS << "\t\t" "Exits: ";
Dan Gohman161ea032009-07-07 17:06:11 +00004555 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohmanaff14d62009-05-24 23:25:42 +00004556 if (!ExitValue->isLoopInvariant(L)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004557 OS << "<<Unknown>>";
4558 } else {
4559 OS << *ExitValue;
4560 }
4561 }
4562
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004563 OS << "\n";
4564 }
4565
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004566 OS << "Determining loop execution counts for: " << F->getName() << "\n";
4567 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
4568 PrintLoopInfo(OS, &SE, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004569}
Dan Gohman13058cc2009-04-21 00:47:46 +00004570
4571void ScalarEvolution::print(std::ostream &o, const Module *M) const {
4572 raw_os_ostream OS(o);
4573 print(OS, M);
4574}