blob: 6592e0d0778b15bc4813704961fd3462546076bd [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 Gohman9545fb02009-07-17 20:47:02 +000069#include "llvm/Operator.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000070#include "llvm/Analysis/ConstantFolding.h"
Evan Cheng98c073b2009-02-17 00:13:06 +000071#include "llvm/Analysis/Dominators.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000072#include "llvm/Analysis/LoopInfo.h"
Dan Gohmana7726c32009-06-16 19:52:01 +000073#include "llvm/Analysis/ValueTracking.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000074#include "llvm/Assembly/Writer.h"
Dan Gohman01c2ee72009-04-16 03:18:22 +000075#include "llvm/Target/TargetData.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000076#include "llvm/Support/CommandLine.h"
77#include "llvm/Support/Compiler.h"
78#include "llvm/Support/ConstantRange.h"
Edwin Török675d5622009-07-11 20:10:48 +000079#include "llvm/Support/ErrorHandling.h"
Dan Gohman01c2ee72009-04-16 03:18:22 +000080#include "llvm/Support/GetElementPtrTypeIterator.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000081#include "llvm/Support/InstIterator.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000082#include "llvm/Support/MathExtras.h"
Dan Gohman13058cc2009-04-21 00:47:46 +000083#include "llvm/Support/raw_ostream.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000084#include "llvm/ADT/Statistic.h"
Dan Gohman01c2ee72009-04-16 03:18:22 +000085#include "llvm/ADT/STLExtras.h"
Dan Gohmanb7d04aa2009-07-08 19:23:34 +000086#include "llvm/ADT/SmallPtrSet.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000087#include <algorithm>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000088using namespace llvm;
89
Dan Gohmanf17a25c2007-07-18 16:29:46 +000090STATISTIC(NumArrayLenItCounts,
91 "Number of trip counts computed with array length");
92STATISTIC(NumTripCountsComputed,
93 "Number of loops with predictable loop counts");
94STATISTIC(NumTripCountsNotComputed,
95 "Number of loops without predictable loop counts");
96STATISTIC(NumBruteForceTripCountsComputed,
97 "Number of loops with trip counts computed by force");
98
Dan Gohman089efff2008-05-13 00:00:25 +000099static cl::opt<unsigned>
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000100MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
101 cl::desc("Maximum number of iterations SCEV will "
Dan Gohman9bc642f2009-06-24 04:48:43 +0000102 "symbolically execute a constant "
103 "derived loop"),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000104 cl::init(100));
105
Dan Gohman089efff2008-05-13 00:00:25 +0000106static RegisterPass<ScalarEvolution>
107R("scalar-evolution", "Scalar Evolution Analysis", false, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000108char ScalarEvolution::ID = 0;
109
110//===----------------------------------------------------------------------===//
111// SCEV class definitions
112//===----------------------------------------------------------------------===//
113
114//===----------------------------------------------------------------------===//
115// Implementation of the SCEV class.
116//
Dan Gohmanc86c0df2009-06-30 20:13:32 +0000117
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000118SCEV::~SCEV() {}
Dan Gohmanc86c0df2009-06-30 20:13:32 +0000119
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000120void SCEV::dump() const {
Dan Gohman13058cc2009-04-21 00:47:46 +0000121 print(errs());
122 errs() << '\n';
123}
124
125void SCEV::print(std::ostream &o) const {
126 raw_os_ostream OS(o);
127 print(OS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000128}
129
Dan Gohman7b560c42008-06-18 16:23:07 +0000130bool SCEV::isZero() const {
131 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
132 return SC->getValue()->isZero();
133 return false;
134}
135
Dan Gohmanf8bc8e82009-05-18 15:22:39 +0000136bool SCEV::isOne() const {
137 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
138 return SC->getValue()->isOne();
139 return false;
140}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000141
Dan Gohmanf05118e2009-06-24 00:30:26 +0000142bool SCEV::isAllOnesValue() const {
143 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
144 return SC->getValue()->isAllOnesValue();
145 return false;
146}
147
Owen Andersonb70139d2009-06-22 21:57:23 +0000148SCEVCouldNotCompute::SCEVCouldNotCompute() :
Dan Gohmand43a8282009-07-13 20:50:19 +0000149 SCEV(FoldingSetNodeID(), scCouldNotCompute) {}
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000150
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000151bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
Edwin Törökbd448e32009-07-14 16:55:14 +0000152 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000153 return false;
154}
155
156const Type *SCEVCouldNotCompute::getType() const {
Edwin Törökbd448e32009-07-14 16:55:14 +0000157 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000158 return 0;
159}
160
161bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
Edwin Törökbd448e32009-07-14 16:55:14 +0000162 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000163 return false;
164}
165
Dan Gohman2aa3f042009-07-25 01:13:03 +0000166bool SCEVCouldNotCompute::hasOperand(const SCEV *) const {
167 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
168 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000169}
170
Dan Gohman13058cc2009-04-21 00:47:46 +0000171void SCEVCouldNotCompute::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000172 OS << "***COULDNOTCOMPUTE***";
173}
174
175bool SCEVCouldNotCompute::classof(const SCEV *S) {
176 return S->getSCEVType() == scCouldNotCompute;
177}
178
Dan Gohman161ea032009-07-07 17:06:11 +0000179const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000180 FoldingSetNodeID ID;
181 ID.AddInteger(scConstant);
182 ID.AddPointer(V);
183 void *IP = 0;
184 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
185 SCEV *S = SCEVAllocator.Allocate<SCEVConstant>();
Dan Gohmand43a8282009-07-13 20:50:19 +0000186 new (S) SCEVConstant(ID, V);
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000187 UniqueSCEVs.InsertNode(S, IP);
188 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000189}
190
Dan Gohman161ea032009-07-07 17:06:11 +0000191const SCEV *ScalarEvolution::getConstant(const APInt& Val) {
Owen Andersoneacb44d2009-07-24 23:12:02 +0000192 return getConstant(ConstantInt::get(getContext(), Val));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000193}
194
Dan Gohman161ea032009-07-07 17:06:11 +0000195const SCEV *
Dan Gohman8fd520a2009-06-15 22:12:54 +0000196ScalarEvolution::getConstant(const Type *Ty, uint64_t V, bool isSigned) {
Owen Anderson9f5b2aa2009-07-14 23:09:55 +0000197 return getConstant(
Owen Andersoneacb44d2009-07-24 23:12:02 +0000198 ConstantInt::get(cast<IntegerType>(Ty), V, isSigned));
Dan Gohman8fd520a2009-06-15 22:12:54 +0000199}
200
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000201const Type *SCEVConstant::getType() const { return V->getType(); }
202
Dan Gohman13058cc2009-04-21 00:47:46 +0000203void SCEVConstant::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000204 WriteAsOperand(OS, V, false);
205}
206
Dan Gohmand43a8282009-07-13 20:50:19 +0000207SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeID &ID,
208 unsigned SCEVTy, const SCEV *op, const Type *ty)
209 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000210
Dan Gohman2a381532009-04-21 01:25:57 +0000211bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
212 return Op->dominates(BB, DT);
213}
214
Dan Gohmand43a8282009-07-13 20:50:19 +0000215SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeID &ID,
216 const SCEV *op, const Type *ty)
217 : SCEVCastExpr(ID, scTruncate, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000218 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
219 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000220 "Cannot truncate non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000221}
222
Dan Gohman13058cc2009-04-21 00:47:46 +0000223void SCEVTruncateExpr::print(raw_ostream &OS) const {
Dan Gohmanc9119222009-04-29 20:27:52 +0000224 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000225}
226
Dan Gohmand43a8282009-07-13 20:50:19 +0000227SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeID &ID,
228 const SCEV *op, const Type *ty)
229 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000230 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
231 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000232 "Cannot zero extend non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000233}
234
Dan Gohman13058cc2009-04-21 00:47:46 +0000235void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
Dan Gohmanc9119222009-04-29 20:27:52 +0000236 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000237}
238
Dan Gohmand43a8282009-07-13 20:50:19 +0000239SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeID &ID,
240 const SCEV *op, const Type *ty)
241 : SCEVCastExpr(ID, scSignExtend, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000242 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
243 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000244 "Cannot sign extend non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000245}
246
Dan Gohman13058cc2009-04-21 00:47:46 +0000247void SCEVSignExtendExpr::print(raw_ostream &OS) const {
Dan Gohmanc9119222009-04-29 20:27:52 +0000248 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000249}
250
Dan Gohman13058cc2009-04-21 00:47:46 +0000251void SCEVCommutativeExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000252 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
253 const char *OpStr = getOperationStr();
254 OS << "(" << *Operands[0];
255 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
256 OS << OpStr << *Operands[i];
257 OS << ")";
258}
259
Dan Gohman72a8a022009-05-07 14:00:19 +0000260bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
Evan Cheng98c073b2009-02-17 00:13:06 +0000261 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
262 if (!getOperand(i)->dominates(BB, DT))
263 return false;
264 }
265 return true;
266}
267
Evan Cheng98c073b2009-02-17 00:13:06 +0000268bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
269 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
270}
271
Dan Gohman13058cc2009-04-21 00:47:46 +0000272void SCEVUDivExpr::print(raw_ostream &OS) const {
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000273 OS << "(" << *LHS << " /u " << *RHS << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000274}
275
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000276const Type *SCEVUDivExpr::getType() const {
Dan Gohman140f08f2009-05-26 17:44:05 +0000277 // In most cases the types of LHS and RHS will be the same, but in some
278 // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
279 // depend on the type for correctness, but handling types carefully can
280 // avoid extra casts in the SCEVExpander. The LHS is more likely to be
281 // a pointer type than the RHS, so use the RHS' type here.
282 return RHS->getType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000283}
284
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000285bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
Dan Gohmanae1eaae2009-05-20 01:01:24 +0000286 // Add recurrences are never invariant in the function-body (null loop).
Dan Gohman2d888d82009-06-26 22:17:21 +0000287 if (!QueryLoop)
288 return false;
289
290 // This recurrence is variant w.r.t. QueryLoop if QueryLoop contains L.
291 if (QueryLoop->contains(L->getHeader()))
292 return false;
293
294 // This recurrence is variant w.r.t. QueryLoop if any of its operands
295 // are variant.
296 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
297 if (!getOperand(i)->isLoopInvariant(QueryLoop))
298 return false;
299
300 // Otherwise it's loop-invariant.
301 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000302}
303
Dan Gohman13058cc2009-04-21 00:47:46 +0000304void SCEVAddRecExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000305 OS << "{" << *Operands[0];
306 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
307 OS << ",+," << *Operands[i];
308 OS << "}<" << L->getHeader()->getName() + ">";
309}
310
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000311bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
312 // All non-instruction values are loop invariant. All instructions are loop
313 // invariant if they are not contained in the specified loop.
Dan Gohmanae1eaae2009-05-20 01:01:24 +0000314 // Instructions are never considered invariant in the function body
315 // (null loop) because they are defined within the "loop".
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000316 if (Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmanae1eaae2009-05-20 01:01:24 +0000317 return L && !L->contains(I->getParent());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000318 return true;
319}
320
Evan Cheng98c073b2009-02-17 00:13:06 +0000321bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
322 if (Instruction *I = dyn_cast<Instruction>(getValue()))
323 return DT->dominates(I->getParent(), BB);
324 return true;
325}
326
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000327const Type *SCEVUnknown::getType() const {
328 return V->getType();
329}
330
Dan Gohman13058cc2009-04-21 00:47:46 +0000331void SCEVUnknown::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000332 WriteAsOperand(OS, V, false);
333}
334
335//===----------------------------------------------------------------------===//
336// SCEV Utilities
337//===----------------------------------------------------------------------===//
338
339namespace {
340 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
341 /// than the complexity of the RHS. This comparator is used to canonicalize
342 /// expressions.
Dan Gohman5d486452009-05-07 14:39:04 +0000343 class VISIBILITY_HIDDEN SCEVComplexityCompare {
344 LoopInfo *LI;
345 public:
346 explicit SCEVComplexityCompare(LoopInfo *li) : LI(li) {}
347
Dan Gohmanc0c69cf2008-04-14 18:23:56 +0000348 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman5d486452009-05-07 14:39:04 +0000349 // Primarily, sort the SCEVs by their getSCEVType().
350 if (LHS->getSCEVType() != RHS->getSCEVType())
351 return LHS->getSCEVType() < RHS->getSCEVType();
352
353 // Aside from the getSCEVType() ordering, the particular ordering
354 // isn't very important except that it's beneficial to be consistent,
355 // so that (a + b) and (b + a) don't end up as different expressions.
356
357 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
358 // not as complete as it could be.
359 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
360 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
361
Dan Gohmand0c01232009-05-19 02:15:55 +0000362 // Order pointer values after integer values. This helps SCEVExpander
363 // form GEPs.
364 if (isa<PointerType>(LU->getType()) && !isa<PointerType>(RU->getType()))
365 return false;
366 if (isa<PointerType>(RU->getType()) && !isa<PointerType>(LU->getType()))
367 return true;
368
Dan Gohman5d486452009-05-07 14:39:04 +0000369 // Compare getValueID values.
370 if (LU->getValue()->getValueID() != RU->getValue()->getValueID())
371 return LU->getValue()->getValueID() < RU->getValue()->getValueID();
372
373 // Sort arguments by their position.
374 if (const Argument *LA = dyn_cast<Argument>(LU->getValue())) {
375 const Argument *RA = cast<Argument>(RU->getValue());
376 return LA->getArgNo() < RA->getArgNo();
377 }
378
379 // For instructions, compare their loop depth, and their opcode.
380 // This is pretty loose.
381 if (Instruction *LV = dyn_cast<Instruction>(LU->getValue())) {
382 Instruction *RV = cast<Instruction>(RU->getValue());
383
384 // Compare loop depths.
385 if (LI->getLoopDepth(LV->getParent()) !=
386 LI->getLoopDepth(RV->getParent()))
387 return LI->getLoopDepth(LV->getParent()) <
388 LI->getLoopDepth(RV->getParent());
389
390 // Compare opcodes.
391 if (LV->getOpcode() != RV->getOpcode())
392 return LV->getOpcode() < RV->getOpcode();
393
394 // Compare the number of operands.
395 if (LV->getNumOperands() != RV->getNumOperands())
396 return LV->getNumOperands() < RV->getNumOperands();
397 }
398
399 return false;
400 }
401
Dan Gohman56fc8f12009-06-14 22:51:25 +0000402 // Compare constant values.
403 if (const SCEVConstant *LC = dyn_cast<SCEVConstant>(LHS)) {
404 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
Nick Lewycky9bb14052009-07-04 17:24:52 +0000405 if (LC->getValue()->getBitWidth() != RC->getValue()->getBitWidth())
406 return LC->getValue()->getBitWidth() < RC->getValue()->getBitWidth();
Dan Gohman56fc8f12009-06-14 22:51:25 +0000407 return LC->getValue()->getValue().ult(RC->getValue()->getValue());
408 }
409
410 // Compare addrec loop depths.
411 if (const SCEVAddRecExpr *LA = dyn_cast<SCEVAddRecExpr>(LHS)) {
412 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
413 if (LA->getLoop()->getLoopDepth() != RA->getLoop()->getLoopDepth())
414 return LA->getLoop()->getLoopDepth() < RA->getLoop()->getLoopDepth();
415 }
Dan Gohman5d486452009-05-07 14:39:04 +0000416
417 // Lexicographically compare n-ary expressions.
418 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
419 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
420 for (unsigned i = 0, e = LC->getNumOperands(); i != e; ++i) {
421 if (i >= RC->getNumOperands())
422 return false;
423 if (operator()(LC->getOperand(i), RC->getOperand(i)))
424 return true;
425 if (operator()(RC->getOperand(i), LC->getOperand(i)))
426 return false;
427 }
428 return LC->getNumOperands() < RC->getNumOperands();
429 }
430
Dan Gohman6e10db12009-05-07 19:23:21 +0000431 // Lexicographically compare udiv expressions.
432 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
433 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
434 if (operator()(LC->getLHS(), RC->getLHS()))
435 return true;
436 if (operator()(RC->getLHS(), LC->getLHS()))
437 return false;
438 if (operator()(LC->getRHS(), RC->getRHS()))
439 return true;
440 if (operator()(RC->getRHS(), LC->getRHS()))
441 return false;
442 return false;
443 }
444
Dan Gohman5d486452009-05-07 14:39:04 +0000445 // Compare cast expressions by operand.
446 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
447 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
448 return operator()(LC->getOperand(), RC->getOperand());
449 }
450
Edwin Törökbd448e32009-07-14 16:55:14 +0000451 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman5d486452009-05-07 14:39:04 +0000452 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000453 }
454 };
455}
456
457/// GroupByComplexity - Given a list of SCEV objects, order them by their
458/// complexity, and group objects of the same complexity together by value.
459/// When this routine is finished, we know that any duplicates in the vector are
460/// consecutive and that complexity is monotonically increasing.
461///
462/// Note that we go take special precautions to ensure that we get determinstic
463/// results from this routine. In other words, we don't want the results of
464/// this to depend on where the addresses of various SCEV objects happened to
465/// land in memory.
466///
Dan Gohman161ea032009-07-07 17:06:11 +0000467static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
Dan Gohman5d486452009-05-07 14:39:04 +0000468 LoopInfo *LI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000469 if (Ops.size() < 2) return; // Noop
470 if (Ops.size() == 2) {
471 // This is the common case, which also happens to be trivially simple.
472 // Special case it.
Dan Gohman5d486452009-05-07 14:39:04 +0000473 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000474 std::swap(Ops[0], Ops[1]);
475 return;
476 }
477
478 // Do the rough sort by complexity.
Dan Gohman5d486452009-05-07 14:39:04 +0000479 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000480
481 // Now that we are sorted by complexity, group elements of the same
482 // complexity. Note that this is, at worst, N^2, but the vector is likely to
483 // be extremely short in practice. Note that we take this approach because we
484 // do not want to depend on the addresses of the objects we are grouping.
485 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Dan Gohmanbff6b582009-05-04 22:30:44 +0000486 const SCEV *S = Ops[i];
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000487 unsigned Complexity = S->getSCEVType();
488
489 // If there are any objects of the same complexity and same value as this
490 // one, group them.
491 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
492 if (Ops[j] == S) { // Found a duplicate.
493 // Move it to immediately after i'th element.
494 std::swap(Ops[i+1], Ops[j]);
495 ++i; // no need to rescan it.
496 if (i == e-2) return; // Done!
497 }
498 }
499 }
500}
501
502
503
504//===----------------------------------------------------------------------===//
505// Simple SCEV method implementations
506//===----------------------------------------------------------------------===//
507
Eli Friedman7489ec92008-08-04 23:49:06 +0000508/// BinomialCoefficient - Compute BC(It, K). The result has width W.
Dan Gohmanc8a29272009-05-24 23:45:28 +0000509/// Assume, K > 0.
Dan Gohman161ea032009-07-07 17:06:11 +0000510static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
Dan Gohmanf5606fd2009-07-21 00:38:55 +0000511 ScalarEvolution &SE,
512 const Type* ResultTy) {
Eli Friedman7489ec92008-08-04 23:49:06 +0000513 // Handle the simplest case efficiently.
514 if (K == 1)
515 return SE.getTruncateOrZeroExtend(It, ResultTy);
516
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000517 // We are using the following formula for BC(It, K):
518 //
519 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
520 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000521 // Suppose, W is the bitwidth of the return value. We must be prepared for
522 // overflow. Hence, we must assure that the result of our computation is
523 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
524 // safe in modular arithmetic.
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000525 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000526 // However, this code doesn't use exactly that formula; the formula it uses
Dan Gohman9bc642f2009-06-24 04:48:43 +0000527 // is something like the following, where T is the number of factors of 2 in
Eli Friedman7489ec92008-08-04 23:49:06 +0000528 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
529 // exponentiation:
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000530 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000531 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000532 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000533 // This formula is trivially equivalent to the previous formula. However,
534 // this formula can be implemented much more efficiently. The trick is that
535 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
536 // arithmetic. To do exact division in modular arithmetic, all we have
537 // to do is multiply by the inverse. Therefore, this step can be done at
538 // width W.
Dan Gohman9bc642f2009-06-24 04:48:43 +0000539 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000540 // The next issue is how to safely do the division by 2^T. The way this
541 // is done is by doing the multiplication step at a width of at least W + T
542 // bits. This way, the bottom W+T bits of the product are accurate. Then,
543 // when we perform the division by 2^T (which is equivalent to a right shift
544 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
545 // truncated out after the division by 2^T.
546 //
547 // In comparison to just directly using the first formula, this technique
548 // is much more efficient; using the first formula requires W * K bits,
549 // but this formula less than W + K bits. Also, the first formula requires
550 // a division step, whereas this formula only requires multiplies and shifts.
551 //
552 // It doesn't matter whether the subtraction step is done in the calculation
553 // width or the input iteration count's width; if the subtraction overflows,
554 // the result must be zero anyway. We prefer here to do it in the width of
555 // the induction variable because it helps a lot for certain cases; CodeGen
556 // isn't smart enough to ignore the overflow, which leads to much less
557 // efficient code if the width of the subtraction is wider than the native
558 // register width.
559 //
560 // (It's possible to not widen at all by pulling out factors of 2 before
561 // the multiplication; for example, K=2 can be calculated as
562 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
563 // extra arithmetic, so it's not an obvious win, and it gets
564 // much more complicated for K > 3.)
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000565
Eli Friedman7489ec92008-08-04 23:49:06 +0000566 // Protection from insane SCEVs; this bound is conservative,
567 // but it probably doesn't matter.
568 if (K > 1000)
Dan Gohman0ad08b02009-04-18 17:58:19 +0000569 return SE.getCouldNotCompute();
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000570
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000571 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000572
Eli Friedman7489ec92008-08-04 23:49:06 +0000573 // Calculate K! / 2^T and T; we divide out the factors of two before
574 // multiplying for calculating K! / 2^T to avoid overflow.
575 // Other overflow doesn't matter because we only care about the bottom
576 // W bits of the result.
577 APInt OddFactorial(W, 1);
578 unsigned T = 1;
579 for (unsigned i = 3; i <= K; ++i) {
580 APInt Mult(W, i);
581 unsigned TwoFactors = Mult.countTrailingZeros();
582 T += TwoFactors;
583 Mult = Mult.lshr(TwoFactors);
584 OddFactorial *= Mult;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000585 }
Nick Lewyckydbaa60a2008-06-13 04:38:55 +0000586
Eli Friedman7489ec92008-08-04 23:49:06 +0000587 // We need at least W + T bits for the multiplication step
nicholas9e3e5fd2009-01-25 08:16:27 +0000588 unsigned CalculationBits = W + T;
Eli Friedman7489ec92008-08-04 23:49:06 +0000589
590 // Calcuate 2^T, at width T+W.
591 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
592
593 // Calculate the multiplicative inverse of K! / 2^T;
594 // this multiplication factor will perform the exact division by
595 // K! / 2^T.
596 APInt Mod = APInt::getSignedMinValue(W+1);
597 APInt MultiplyFactor = OddFactorial.zext(W+1);
598 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
599 MultiplyFactor = MultiplyFactor.trunc(W);
600
601 // Calculate the product, at width T+W
602 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
Dan Gohman161ea032009-07-07 17:06:11 +0000603 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
Eli Friedman7489ec92008-08-04 23:49:06 +0000604 for (unsigned i = 1; i != K; ++i) {
Dan Gohman161ea032009-07-07 17:06:11 +0000605 const SCEV *S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
Eli Friedman7489ec92008-08-04 23:49:06 +0000606 Dividend = SE.getMulExpr(Dividend,
607 SE.getTruncateOrZeroExtend(S, CalculationTy));
608 }
609
610 // Divide by 2^T
Dan Gohman161ea032009-07-07 17:06:11 +0000611 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
Eli Friedman7489ec92008-08-04 23:49:06 +0000612
613 // Truncate the result, and divide by K! / 2^T.
614
615 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
616 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000617}
618
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000619/// evaluateAtIteration - Return the value of this chain of recurrences at
620/// the specified iteration number. We can evaluate this recurrence by
621/// multiplying each element in the chain by the binomial coefficient
622/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
623///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000624/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000625///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000626/// where BC(It, k) stands for binomial coefficient.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000627///
Dan Gohman161ea032009-07-07 17:06:11 +0000628const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
Dan Gohmanf5606fd2009-07-21 00:38:55 +0000629 ScalarEvolution &SE) const {
Dan Gohman161ea032009-07-07 17:06:11 +0000630 const SCEV *Result = getStart();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000631 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000632 // The computation is correct in the face of overflow provided that the
633 // multiplication is performed _after_ the evaluation of the binomial
634 // coefficient.
Dan Gohman161ea032009-07-07 17:06:11 +0000635 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckyb6218e02008-10-13 03:58:02 +0000636 if (isa<SCEVCouldNotCompute>(Coeff))
637 return Coeff;
638
639 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000640 }
641 return Result;
642}
643
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000644//===----------------------------------------------------------------------===//
645// SCEV Expression folder implementations
646//===----------------------------------------------------------------------===//
647
Dan Gohman161ea032009-07-07 17:06:11 +0000648const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
Dan Gohman69eacc72009-07-13 22:05:32 +0000649 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000650 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000651 "This is not a truncating conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000652 assert(isSCEVable(Ty) &&
653 "This is not a conversion to a SCEVable type!");
654 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000655
Dan Gohmand43a8282009-07-13 20:50:19 +0000656 FoldingSetNodeID ID;
657 ID.AddInteger(scTruncate);
658 ID.AddPointer(Op);
659 ID.AddPointer(Ty);
660 void *IP = 0;
661 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
662
Dan Gohmanc86c0df2009-06-30 20:13:32 +0000663 // Fold if the operand is constant.
Dan Gohmanc76b5452009-05-04 22:02:23 +0000664 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman55788cf2009-06-24 00:38:39 +0000665 return getConstant(
666 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000667
Dan Gohman1a5c4992009-04-22 16:20:48 +0000668 // trunc(trunc(x)) --> trunc(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000669 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000670 return getTruncateExpr(ST->getOperand(), Ty);
671
Nick Lewycky37d04642009-04-23 05:15:08 +0000672 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohmanc76b5452009-05-04 22:02:23 +0000673 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewycky37d04642009-04-23 05:15:08 +0000674 return getTruncateOrSignExtend(SS->getOperand(), Ty);
675
676 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohmanc76b5452009-05-04 22:02:23 +0000677 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewycky37d04642009-04-23 05:15:08 +0000678 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
679
Dan Gohman1c0aa2c2009-06-18 16:24:47 +0000680 // If the input value is a chrec scev, truncate the chrec's operands.
Dan Gohmanc76b5452009-05-04 22:02:23 +0000681 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohman161ea032009-07-07 17:06:11 +0000682 SmallVector<const SCEV *, 4> Operands;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000683 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman45b3b542009-05-08 21:03:19 +0000684 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
685 return getAddRecExpr(Operands, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000686 }
687
Dan Gohmand43a8282009-07-13 20:50:19 +0000688 // The cast wasn't folded; create an explicit cast node.
689 // Recompute the insert position, as it may have been invalidated.
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000690 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
691 SCEV *S = SCEVAllocator.Allocate<SCEVTruncateExpr>();
Dan Gohmand43a8282009-07-13 20:50:19 +0000692 new (S) SCEVTruncateExpr(ID, Op, Ty);
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000693 UniqueSCEVs.InsertNode(S, IP);
694 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000695}
696
Dan Gohman161ea032009-07-07 17:06:11 +0000697const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
Dan Gohman69eacc72009-07-13 22:05:32 +0000698 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000699 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman36d40922009-04-16 19:25:55 +0000700 "This is not an extending conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000701 assert(isSCEVable(Ty) &&
702 "This is not a conversion to a SCEVable type!");
703 Ty = getEffectiveSCEVType(Ty);
Dan Gohman36d40922009-04-16 19:25:55 +0000704
Dan Gohmanc86c0df2009-06-30 20:13:32 +0000705 // Fold if the operand is constant.
Dan Gohmanc76b5452009-05-04 22:02:23 +0000706 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000707 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000708 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
709 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
Dan Gohman55788cf2009-06-24 00:38:39 +0000710 return getConstant(cast<ConstantInt>(C));
Dan Gohman01c2ee72009-04-16 03:18:22 +0000711 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000712
Dan Gohman1a5c4992009-04-22 16:20:48 +0000713 // zext(zext(x)) --> zext(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000714 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000715 return getZeroExtendExpr(SZ->getOperand(), Ty);
716
Dan Gohmandb888422009-07-13 20:55:53 +0000717 // Before doing any expensive analysis, check to see if we've already
718 // computed a SCEV for this Op and Ty.
719 FoldingSetNodeID ID;
720 ID.AddInteger(scZeroExtend);
721 ID.AddPointer(Op);
722 ID.AddPointer(Ty);
723 void *IP = 0;
724 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
725
Dan Gohmana9dba962009-04-27 20:16:15 +0000726 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000727 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohmana9dba962009-04-27 20:16:15 +0000728 // operands (often constants). This allows analysis of something like
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000729 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmanc76b5452009-05-04 22:02:23 +0000730 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohmana9dba962009-04-27 20:16:15 +0000731 if (AR->isAffine()) {
Dan Gohman55e2d7e2009-07-13 21:35:55 +0000732 const SCEV *Start = AR->getStart();
733 const SCEV *Step = AR->getStepRecurrence(*this);
734 unsigned BitWidth = getTypeSizeInBits(AR->getType());
735 const Loop *L = AR->getLoop();
736
Dan Gohman1bc53162009-07-25 01:22:26 +0000737 // If we have special knowledge that this addrec won't overflow,
738 // we don't need to do any further analysis.
739 if (AR->hasNoUnsignedOverflow())
740 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
741 getZeroExtendExpr(Step, Ty),
742 L);
743
Dan Gohmana9dba962009-04-27 20:16:15 +0000744 // Check whether the backedge-taken count is SCEVCouldNotCompute.
745 // Note that this serves two purposes: It filters out loops that are
746 // simply not analyzable, and it covers the case where this code is
747 // being called from within backedge-taken count analysis, such that
748 // attempting to ask for the backedge-taken count would likely result
749 // in infinite recursion. In the later case, the analysis code will
750 // cope with a conservative value, and it will take care to purge
751 // that value once it has finished.
Dan Gohman55e2d7e2009-07-13 21:35:55 +0000752 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000753 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman4ada77f2009-04-29 01:54:20 +0000754 // Manually compute the final value for AR, checking for
Dan Gohman3ded5b22009-04-29 22:28:28 +0000755 // overflow.
Dan Gohmana9dba962009-04-27 20:16:15 +0000756
757 // Check whether the backedge-taken count can be losslessly casted to
758 // the addrec's type. The count is always unsigned.
Dan Gohman161ea032009-07-07 17:06:11 +0000759 const SCEV *CastedMaxBECount =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000760 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman161ea032009-07-07 17:06:11 +0000761 const SCEV *RecastedMaxBECount =
Dan Gohman3bb37f52009-05-18 15:58:39 +0000762 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
763 if (MaxBECount == RecastedMaxBECount) {
Dan Gohman55e2d7e2009-07-13 21:35:55 +0000764 const Type *WideTy = IntegerType::get(BitWidth * 2);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000765 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohman161ea032009-07-07 17:06:11 +0000766 const SCEV *ZMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000767 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000768 getTruncateOrZeroExtend(Step, Start->getType()));
Dan Gohman161ea032009-07-07 17:06:11 +0000769 const SCEV *Add = getAddExpr(Start, ZMul);
770 const SCEV *OperandExtendedAdd =
Dan Gohman3bb37f52009-05-18 15:58:39 +0000771 getAddExpr(getZeroExtendExpr(Start, WideTy),
772 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
773 getZeroExtendExpr(Step, WideTy)));
774 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman3ded5b22009-04-29 22:28:28 +0000775 // Return the expression with the addrec on the outside.
776 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
777 getZeroExtendExpr(Step, Ty),
Dan Gohman55e2d7e2009-07-13 21:35:55 +0000778 L);
Dan Gohmana9dba962009-04-27 20:16:15 +0000779
780 // Similar to above, only this time treat the step value as signed.
781 // This covers loops that count down.
Dan Gohman161ea032009-07-07 17:06:11 +0000782 const SCEV *SMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000783 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000784 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohman3ded5b22009-04-29 22:28:28 +0000785 Add = getAddExpr(Start, SMul);
Dan Gohman3bb37f52009-05-18 15:58:39 +0000786 OperandExtendedAdd =
787 getAddExpr(getZeroExtendExpr(Start, WideTy),
788 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
789 getSignExtendExpr(Step, WideTy)));
790 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman3ded5b22009-04-29 22:28:28 +0000791 // Return the expression with the addrec on the outside.
792 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
793 getSignExtendExpr(Step, Ty),
Dan Gohman55e2d7e2009-07-13 21:35:55 +0000794 L);
795 }
796
797 // If the backedge is guarded by a comparison with the pre-inc value
798 // the addrec is safe. Also, if the entry is guarded by a comparison
799 // with the start value and the backedge is guarded by a comparison
800 // with the post-inc value, the addrec is safe.
801 if (isKnownPositive(Step)) {
802 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
803 getUnsignedRange(Step).getUnsignedMax());
804 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
805 (isLoopGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
806 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
807 AR->getPostIncExpr(*this), N)))
808 // Return the expression with the addrec on the outside.
809 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
810 getZeroExtendExpr(Step, Ty),
811 L);
812 } else if (isKnownNegative(Step)) {
813 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
814 getSignedRange(Step).getSignedMin());
815 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) &&
816 (isLoopGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) ||
817 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
818 AR->getPostIncExpr(*this), N)))
819 // Return the expression with the addrec on the outside.
820 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
821 getSignExtendExpr(Step, Ty),
822 L);
Dan Gohmana9dba962009-04-27 20:16:15 +0000823 }
824 }
825 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000826
Dan Gohmandb888422009-07-13 20:55:53 +0000827 // The cast wasn't folded; create an explicit cast node.
828 // Recompute the insert position, as it may have been invalidated.
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000829 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
830 SCEV *S = SCEVAllocator.Allocate<SCEVZeroExtendExpr>();
Dan Gohmand43a8282009-07-13 20:50:19 +0000831 new (S) SCEVZeroExtendExpr(ID, Op, Ty);
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000832 UniqueSCEVs.InsertNode(S, IP);
833 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000834}
835
Dan Gohman161ea032009-07-07 17:06:11 +0000836const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
Dan Gohman69eacc72009-07-13 22:05:32 +0000837 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000838 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000839 "This is not an extending conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000840 assert(isSCEVable(Ty) &&
841 "This is not a conversion to a SCEVable type!");
842 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000843
Dan Gohmanc86c0df2009-06-30 20:13:32 +0000844 // Fold if the operand is constant.
Dan Gohmanc76b5452009-05-04 22:02:23 +0000845 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000846 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000847 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
848 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
Dan Gohman55788cf2009-06-24 00:38:39 +0000849 return getConstant(cast<ConstantInt>(C));
Dan Gohman01c2ee72009-04-16 03:18:22 +0000850 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000851
Dan Gohman1a5c4992009-04-22 16:20:48 +0000852 // sext(sext(x)) --> sext(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000853 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000854 return getSignExtendExpr(SS->getOperand(), Ty);
855
Dan Gohmandb888422009-07-13 20:55:53 +0000856 // Before doing any expensive analysis, check to see if we've already
857 // computed a SCEV for this Op and Ty.
858 FoldingSetNodeID ID;
859 ID.AddInteger(scSignExtend);
860 ID.AddPointer(Op);
861 ID.AddPointer(Ty);
862 void *IP = 0;
863 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
864
Dan Gohmana9dba962009-04-27 20:16:15 +0000865 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000866 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohmana9dba962009-04-27 20:16:15 +0000867 // operands (often constants). This allows analysis of something like
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000868 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmanc76b5452009-05-04 22:02:23 +0000869 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohmana9dba962009-04-27 20:16:15 +0000870 if (AR->isAffine()) {
Dan Gohman55e2d7e2009-07-13 21:35:55 +0000871 const SCEV *Start = AR->getStart();
872 const SCEV *Step = AR->getStepRecurrence(*this);
873 unsigned BitWidth = getTypeSizeInBits(AR->getType());
874 const Loop *L = AR->getLoop();
875
Dan Gohman1bc53162009-07-25 01:22:26 +0000876 // If we have special knowledge that this addrec won't overflow,
877 // we don't need to do any further analysis.
878 if (AR->hasNoSignedOverflow())
879 return getAddRecExpr(getSignExtendExpr(Start, Ty),
880 getSignExtendExpr(Step, Ty),
881 L);
882
Dan Gohmana9dba962009-04-27 20:16:15 +0000883 // Check whether the backedge-taken count is SCEVCouldNotCompute.
884 // Note that this serves two purposes: It filters out loops that are
885 // simply not analyzable, and it covers the case where this code is
886 // being called from within backedge-taken count analysis, such that
887 // attempting to ask for the backedge-taken count would likely result
888 // in infinite recursion. In the later case, the analysis code will
889 // cope with a conservative value, and it will take care to purge
890 // that value once it has finished.
Dan Gohman55e2d7e2009-07-13 21:35:55 +0000891 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000892 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman4ada77f2009-04-29 01:54:20 +0000893 // Manually compute the final value for AR, checking for
Dan Gohman3ded5b22009-04-29 22:28:28 +0000894 // overflow.
Dan Gohmana9dba962009-04-27 20:16:15 +0000895
896 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohman3ded5b22009-04-29 22:28:28 +0000897 // the addrec's type. The count is always unsigned.
Dan Gohman161ea032009-07-07 17:06:11 +0000898 const SCEV *CastedMaxBECount =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000899 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman161ea032009-07-07 17:06:11 +0000900 const SCEV *RecastedMaxBECount =
Dan Gohman3bb37f52009-05-18 15:58:39 +0000901 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
902 if (MaxBECount == RecastedMaxBECount) {
Dan Gohman55e2d7e2009-07-13 21:35:55 +0000903 const Type *WideTy = IntegerType::get(BitWidth * 2);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000904 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman161ea032009-07-07 17:06:11 +0000905 const SCEV *SMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000906 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000907 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohman161ea032009-07-07 17:06:11 +0000908 const SCEV *Add = getAddExpr(Start, SMul);
909 const SCEV *OperandExtendedAdd =
Dan Gohman3bb37f52009-05-18 15:58:39 +0000910 getAddExpr(getSignExtendExpr(Start, WideTy),
911 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
912 getSignExtendExpr(Step, WideTy)));
913 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman3ded5b22009-04-29 22:28:28 +0000914 // Return the expression with the addrec on the outside.
915 return getAddRecExpr(getSignExtendExpr(Start, Ty),
916 getSignExtendExpr(Step, Ty),
Dan Gohman55e2d7e2009-07-13 21:35:55 +0000917 L);
Dan Gohman2d4f5b12009-07-16 17:34:36 +0000918
919 // Similar to above, only this time treat the step value as unsigned.
920 // This covers loops that count up with an unsigned step.
921 const SCEV *UMul =
922 getMulExpr(CastedMaxBECount,
923 getTruncateOrZeroExtend(Step, Start->getType()));
924 Add = getAddExpr(Start, UMul);
925 OperandExtendedAdd =
Dan Gohman0658f612009-07-25 16:03:30 +0000926 getAddExpr(getSignExtendExpr(Start, WideTy),
Dan Gohman2d4f5b12009-07-16 17:34:36 +0000927 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
928 getZeroExtendExpr(Step, WideTy)));
Dan Gohman0658f612009-07-25 16:03:30 +0000929 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman2d4f5b12009-07-16 17:34:36 +0000930 // Return the expression with the addrec on the outside.
931 return getAddRecExpr(getSignExtendExpr(Start, Ty),
932 getZeroExtendExpr(Step, Ty),
933 L);
Dan Gohman55e2d7e2009-07-13 21:35:55 +0000934 }
935
936 // If the backedge is guarded by a comparison with the pre-inc value
937 // the addrec is safe. Also, if the entry is guarded by a comparison
938 // with the start value and the backedge is guarded by a comparison
939 // with the post-inc value, the addrec is safe.
940 if (isKnownPositive(Step)) {
941 const SCEV *N = getConstant(APInt::getSignedMinValue(BitWidth) -
942 getSignedRange(Step).getSignedMax());
943 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT, AR, N) ||
944 (isLoopGuardedByCond(L, ICmpInst::ICMP_SLT, Start, N) &&
945 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT,
946 AR->getPostIncExpr(*this), N)))
947 // Return the expression with the addrec on the outside.
948 return getAddRecExpr(getSignExtendExpr(Start, Ty),
949 getSignExtendExpr(Step, Ty),
950 L);
951 } else if (isKnownNegative(Step)) {
952 const SCEV *N = getConstant(APInt::getSignedMaxValue(BitWidth) -
953 getSignedRange(Step).getSignedMin());
954 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT, AR, N) ||
955 (isLoopGuardedByCond(L, ICmpInst::ICMP_SGT, Start, N) &&
956 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT,
957 AR->getPostIncExpr(*this), N)))
958 // Return the expression with the addrec on the outside.
959 return getAddRecExpr(getSignExtendExpr(Start, Ty),
960 getSignExtendExpr(Step, Ty),
961 L);
Dan Gohmana9dba962009-04-27 20:16:15 +0000962 }
963 }
964 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000965
Dan Gohmandb888422009-07-13 20:55:53 +0000966 // The cast wasn't folded; create an explicit cast node.
967 // Recompute the insert position, as it may have been invalidated.
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000968 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
969 SCEV *S = SCEVAllocator.Allocate<SCEVSignExtendExpr>();
Dan Gohmand43a8282009-07-13 20:50:19 +0000970 new (S) SCEVSignExtendExpr(ID, Op, Ty);
Dan Gohmanc6475cb2009-06-27 21:21:31 +0000971 UniqueSCEVs.InsertNode(S, IP);
972 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000973}
974
Dan Gohmane1ca7e82009-06-13 15:56:47 +0000975/// getAnyExtendExpr - Return a SCEV for the given operand extended with
976/// unspecified bits out to the given type.
977///
Dan Gohman161ea032009-07-07 17:06:11 +0000978const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
Dan Gohmane1ca7e82009-06-13 15:56:47 +0000979 const Type *Ty) {
980 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
981 "This is not an extending conversion!");
982 assert(isSCEVable(Ty) &&
983 "This is not a conversion to a SCEVable type!");
984 Ty = getEffectiveSCEVType(Ty);
985
986 // Sign-extend negative constants.
987 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
988 if (SC->getValue()->getValue().isNegative())
989 return getSignExtendExpr(Op, Ty);
990
991 // Peel off a truncate cast.
992 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
Dan Gohman161ea032009-07-07 17:06:11 +0000993 const SCEV *NewOp = T->getOperand();
Dan Gohmane1ca7e82009-06-13 15:56:47 +0000994 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
995 return getAnyExtendExpr(NewOp, Ty);
996 return getTruncateOrNoop(NewOp, Ty);
997 }
998
999 // Next try a zext cast. If the cast is folded, use it.
Dan Gohman161ea032009-07-07 17:06:11 +00001000 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
Dan Gohmane1ca7e82009-06-13 15:56:47 +00001001 if (!isa<SCEVZeroExtendExpr>(ZExt))
1002 return ZExt;
1003
1004 // Next try a sext cast. If the cast is folded, use it.
Dan Gohman161ea032009-07-07 17:06:11 +00001005 const SCEV *SExt = getSignExtendExpr(Op, Ty);
Dan Gohmane1ca7e82009-06-13 15:56:47 +00001006 if (!isa<SCEVSignExtendExpr>(SExt))
1007 return SExt;
1008
1009 // If the expression is obviously signed, use the sext cast value.
1010 if (isa<SCEVSMaxExpr>(Op))
1011 return SExt;
1012
1013 // Absent any other information, use the zext cast value.
1014 return ZExt;
1015}
1016
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001017/// CollectAddOperandsWithScales - Process the given Ops list, which is
1018/// a list of operands to be added under the given scale, update the given
1019/// map. This is a helper function for getAddRecExpr. As an example of
1020/// what it does, given a sequence of operands that would form an add
1021/// expression like this:
1022///
1023/// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1024///
1025/// where A and B are constants, update the map with these values:
1026///
1027/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1028///
1029/// and add 13 + A*B*29 to AccumulatedConstant.
1030/// This will allow getAddRecExpr to produce this:
1031///
1032/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1033///
1034/// This form often exposes folding opportunities that are hidden in
1035/// the original operand list.
1036///
1037/// Return true iff it appears that any interesting folding opportunities
1038/// may be exposed. This helps getAddRecExpr short-circuit extra work in
1039/// the common case where no interesting opportunities are present, and
1040/// is also used as a check to avoid infinite recursion.
1041///
1042static bool
Dan Gohman161ea032009-07-07 17:06:11 +00001043CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1044 SmallVector<const SCEV *, 8> &NewOps,
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001045 APInt &AccumulatedConstant,
Dan Gohman161ea032009-07-07 17:06:11 +00001046 const SmallVectorImpl<const SCEV *> &Ops,
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001047 const APInt &Scale,
1048 ScalarEvolution &SE) {
1049 bool Interesting = false;
1050
1051 // Iterate over the add operands.
1052 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1053 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1054 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1055 APInt NewScale =
1056 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1057 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1058 // A multiplication of a constant with another add; recurse.
1059 Interesting |=
1060 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1061 cast<SCEVAddExpr>(Mul->getOperand(1))
1062 ->getOperands(),
1063 NewScale, SE);
1064 } else {
1065 // A multiplication of a constant with some other value. Update
1066 // the map.
Dan Gohman161ea032009-07-07 17:06:11 +00001067 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1068 const SCEV *Key = SE.getMulExpr(MulOps);
1069 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman3bf01f02009-06-29 18:25:52 +00001070 M.insert(std::make_pair(Key, NewScale));
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001071 if (Pair.second) {
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001072 NewOps.push_back(Pair.first->first);
1073 } else {
1074 Pair.first->second += NewScale;
1075 // The map already had an entry for this value, which may indicate
1076 // a folding opportunity.
1077 Interesting = true;
1078 }
1079 }
1080 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1081 // Pull a buried constant out to the outside.
1082 if (Scale != 1 || AccumulatedConstant != 0 || C->isZero())
1083 Interesting = true;
1084 AccumulatedConstant += Scale * C->getValue()->getValue();
1085 } else {
1086 // An ordinary operand. Update the map.
Dan Gohman161ea032009-07-07 17:06:11 +00001087 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman3bf01f02009-06-29 18:25:52 +00001088 M.insert(std::make_pair(Ops[i], Scale));
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001089 if (Pair.second) {
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001090 NewOps.push_back(Pair.first->first);
1091 } else {
1092 Pair.first->second += Scale;
1093 // The map already had an entry for this value, which may indicate
1094 // a folding opportunity.
1095 Interesting = true;
1096 }
1097 }
1098 }
1099
1100 return Interesting;
1101}
1102
1103namespace {
1104 struct APIntCompare {
1105 bool operator()(const APInt &LHS, const APInt &RHS) const {
1106 return LHS.ult(RHS);
1107 }
1108 };
1109}
1110
Dan Gohmanc8a29272009-05-24 23:45:28 +00001111/// getAddExpr - Get a canonical add expression, or something simpler if
1112/// possible.
Dan Gohman161ea032009-07-07 17:06:11 +00001113const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001114 assert(!Ops.empty() && "Cannot get empty add!");
1115 if (Ops.size() == 1) return Ops[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001116#ifndef NDEBUG
1117 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1118 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1119 getEffectiveSCEVType(Ops[0]->getType()) &&
1120 "SCEVAddExpr operand types don't match!");
1121#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001122
1123 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001124 GroupByComplexity(Ops, LI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001125
1126 // If there are any constants, fold them together.
1127 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001128 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001129 ++Idx;
1130 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001131 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001132 // We found two constants, fold them together!
Dan Gohman02ff9392009-06-14 22:47:23 +00001133 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1134 RHSC->getValue()->getValue());
Dan Gohman68f23e82009-06-14 22:53:57 +00001135 if (Ops.size() == 2) return Ops[0];
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001136 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001137 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001138 }
1139
1140 // If we are left with a constant zero being added, strip it off.
1141 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1142 Ops.erase(Ops.begin());
1143 --Idx;
1144 }
1145 }
1146
1147 if (Ops.size() == 1) return Ops[0];
1148
1149 // Okay, check to see if the same value occurs in the operand list twice. If
1150 // so, merge them together into an multiply expression. Since we sorted the
1151 // list, these values are required to be adjacent.
1152 const Type *Ty = Ops[0]->getType();
1153 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1154 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1155 // Found a match, merge the two values into a multiply, and add any
1156 // remaining values to the result.
Dan Gohman161ea032009-07-07 17:06:11 +00001157 const SCEV *Two = getIntegerSCEV(2, Ty);
1158 const SCEV *Mul = getMulExpr(Ops[i], Two);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001159 if (Ops.size() == 2)
1160 return Mul;
1161 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
1162 Ops.push_back(Mul);
Dan Gohman89f85052007-10-22 18:31:58 +00001163 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001164 }
1165
Dan Gohman45b3b542009-05-08 21:03:19 +00001166 // Check for truncates. If all the operands are truncated from the same
1167 // type, see if factoring out the truncate would permit the result to be
1168 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1169 // if the contents of the resulting outer trunc fold to something simple.
1170 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1171 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1172 const Type *DstType = Trunc->getType();
1173 const Type *SrcType = Trunc->getOperand()->getType();
Dan Gohman161ea032009-07-07 17:06:11 +00001174 SmallVector<const SCEV *, 8> LargeOps;
Dan Gohman45b3b542009-05-08 21:03:19 +00001175 bool Ok = true;
1176 // Check all the operands to see if they can be represented in the
1177 // source type of the truncate.
1178 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1179 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1180 if (T->getOperand()->getType() != SrcType) {
1181 Ok = false;
1182 break;
1183 }
1184 LargeOps.push_back(T->getOperand());
1185 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1186 // This could be either sign or zero extension, but sign extension
1187 // is much more likely to be foldable here.
1188 LargeOps.push_back(getSignExtendExpr(C, SrcType));
1189 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Dan Gohman161ea032009-07-07 17:06:11 +00001190 SmallVector<const SCEV *, 8> LargeMulOps;
Dan Gohman45b3b542009-05-08 21:03:19 +00001191 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1192 if (const SCEVTruncateExpr *T =
1193 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1194 if (T->getOperand()->getType() != SrcType) {
1195 Ok = false;
1196 break;
1197 }
1198 LargeMulOps.push_back(T->getOperand());
1199 } else if (const SCEVConstant *C =
1200 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1201 // This could be either sign or zero extension, but sign extension
1202 // is much more likely to be foldable here.
1203 LargeMulOps.push_back(getSignExtendExpr(C, SrcType));
1204 } else {
1205 Ok = false;
1206 break;
1207 }
1208 }
1209 if (Ok)
1210 LargeOps.push_back(getMulExpr(LargeMulOps));
1211 } else {
1212 Ok = false;
1213 break;
1214 }
1215 }
1216 if (Ok) {
1217 // Evaluate the expression in the larger type.
Dan Gohman161ea032009-07-07 17:06:11 +00001218 const SCEV *Fold = getAddExpr(LargeOps);
Dan Gohman45b3b542009-05-08 21:03:19 +00001219 // If it folds to something simple, use it. Otherwise, don't.
1220 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1221 return getTruncateExpr(Fold, DstType);
1222 }
1223 }
1224
1225 // Skip past any other cast SCEVs.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001226 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1227 ++Idx;
1228
1229 // If there are add operands they would be next.
1230 if (Idx < Ops.size()) {
1231 bool DeletedAdd = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001232 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001233 // If we have an add, expand the add operands onto the end of the operands
1234 // list.
1235 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
1236 Ops.erase(Ops.begin()+Idx);
1237 DeletedAdd = true;
1238 }
1239
1240 // If we deleted at least one add, we added operands to the end of the list,
1241 // and they are not necessarily sorted. Recurse to resort and resimplify
1242 // any operands we just aquired.
1243 if (DeletedAdd)
Dan Gohman89f85052007-10-22 18:31:58 +00001244 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001245 }
1246
1247 // Skip over the add expression until we get to a multiply.
1248 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1249 ++Idx;
1250
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001251 // Check to see if there are any folding opportunities present with
1252 // operands multiplied by constant values.
1253 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1254 uint64_t BitWidth = getTypeSizeInBits(Ty);
Dan Gohman161ea032009-07-07 17:06:11 +00001255 DenseMap<const SCEV *, APInt> M;
1256 SmallVector<const SCEV *, 8> NewOps;
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001257 APInt AccumulatedConstant(BitWidth, 0);
1258 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1259 Ops, APInt(BitWidth, 1), *this)) {
1260 // Some interesting folding opportunity is present, so its worthwhile to
1261 // re-generate the operands list. Group the operands by constant scale,
1262 // to avoid multiplying by the same constant scale multiple times.
Dan Gohman161ea032009-07-07 17:06:11 +00001263 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
1264 for (SmallVector<const SCEV *, 8>::iterator I = NewOps.begin(),
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001265 E = NewOps.end(); I != E; ++I)
1266 MulOpLists[M.find(*I)->second].push_back(*I);
1267 // Re-generate the operands list.
1268 Ops.clear();
1269 if (AccumulatedConstant != 0)
1270 Ops.push_back(getConstant(AccumulatedConstant));
Dan Gohman9bc642f2009-06-24 04:48:43 +00001271 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1272 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001273 if (I->first != 0)
Dan Gohman9bc642f2009-06-24 04:48:43 +00001274 Ops.push_back(getMulExpr(getConstant(I->first),
1275 getAddExpr(I->second)));
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001276 if (Ops.empty())
1277 return getIntegerSCEV(0, Ty);
1278 if (Ops.size() == 1)
1279 return Ops[0];
1280 return getAddExpr(Ops);
1281 }
1282 }
1283
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001284 // If we are adding something to a multiply expression, make sure the
1285 // something is not already an operand of the multiply. If so, merge it into
1286 // the multiply.
1287 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001288 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001289 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001290 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001291 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohman02ff9392009-06-14 22:47:23 +00001292 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(Ops[AddOp])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001293 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Dan Gohman161ea032009-07-07 17:06:11 +00001294 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001295 if (Mul->getNumOperands() != 2) {
1296 // If the multiply has more than two operands, we must get the
1297 // Y*Z term.
Dan Gohman161ea032009-07-07 17:06:11 +00001298 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), Mul->op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001299 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001300 InnerMul = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001301 }
Dan Gohman161ea032009-07-07 17:06:11 +00001302 const SCEV *One = getIntegerSCEV(1, Ty);
1303 const SCEV *AddOne = getAddExpr(InnerMul, One);
1304 const SCEV *OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001305 if (Ops.size() == 2) return OuterMul;
1306 if (AddOp < Idx) {
1307 Ops.erase(Ops.begin()+AddOp);
1308 Ops.erase(Ops.begin()+Idx-1);
1309 } else {
1310 Ops.erase(Ops.begin()+Idx);
1311 Ops.erase(Ops.begin()+AddOp-1);
1312 }
1313 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +00001314 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001315 }
1316
1317 // Check this multiply against other multiplies being added together.
1318 for (unsigned OtherMulIdx = Idx+1;
1319 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1320 ++OtherMulIdx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001321 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001322 // If MulOp occurs in OtherMul, we can fold the two multiplies
1323 // together.
1324 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1325 OMulOp != e; ++OMulOp)
1326 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1327 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Dan Gohman161ea032009-07-07 17:06:11 +00001328 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001329 if (Mul->getNumOperands() != 2) {
Dan Gohman9bc642f2009-06-24 04:48:43 +00001330 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1331 Mul->op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001332 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001333 InnerMul1 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001334 }
Dan Gohman161ea032009-07-07 17:06:11 +00001335 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001336 if (OtherMul->getNumOperands() != 2) {
Dan Gohman9bc642f2009-06-24 04:48:43 +00001337 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
1338 OtherMul->op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001339 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001340 InnerMul2 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001341 }
Dan Gohman161ea032009-07-07 17:06:11 +00001342 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1343 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001344 if (Ops.size() == 2) return OuterMul;
1345 Ops.erase(Ops.begin()+Idx);
1346 Ops.erase(Ops.begin()+OtherMulIdx-1);
1347 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +00001348 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001349 }
1350 }
1351 }
1352 }
1353
1354 // If there are any add recurrences in the operands list, see if any other
1355 // added values are loop invariant. If so, we can fold them into the
1356 // recurrence.
1357 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1358 ++Idx;
1359
1360 // Scan over all recurrences, trying to fold loop invariants into them.
1361 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1362 // Scan all of the other operands to this add and add them to the vector if
1363 // they are loop invariant w.r.t. the recurrence.
Dan Gohman161ea032009-07-07 17:06:11 +00001364 SmallVector<const SCEV *, 8> LIOps;
Dan Gohmanbff6b582009-05-04 22:30:44 +00001365 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001366 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1367 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1368 LIOps.push_back(Ops[i]);
1369 Ops.erase(Ops.begin()+i);
1370 --i; --e;
1371 }
1372
1373 // If we found some loop invariants, fold them into the recurrence.
1374 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001375 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001376 LIOps.push_back(AddRec->getStart());
1377
Dan Gohman161ea032009-07-07 17:06:11 +00001378 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
Dan Gohman02ff9392009-06-14 22:47:23 +00001379 AddRec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001380 AddRecOps[0] = getAddExpr(LIOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001381
Dan Gohman161ea032009-07-07 17:06:11 +00001382 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001383 // If all of the other operands were loop invariant, we are done.
1384 if (Ops.size() == 1) return NewRec;
1385
1386 // Otherwise, add the folded AddRec by the non-liv parts.
1387 for (unsigned i = 0;; ++i)
1388 if (Ops[i] == AddRec) {
1389 Ops[i] = NewRec;
1390 break;
1391 }
Dan Gohman89f85052007-10-22 18:31:58 +00001392 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001393 }
1394
1395 // Okay, if there weren't any loop invariants to be folded, check to see if
1396 // there are multiple AddRec's with the same loop induction variable being
1397 // added together. If so, we can fold them.
1398 for (unsigned OtherIdx = Idx+1;
1399 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1400 if (OtherIdx != Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001401 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001402 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1403 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
Dan Gohman9bc642f2009-06-24 04:48:43 +00001404 SmallVector<const SCEV *, 4> NewOps(AddRec->op_begin(),
1405 AddRec->op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001406 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1407 if (i >= NewOps.size()) {
1408 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1409 OtherAddRec->op_end());
1410 break;
1411 }
Dan Gohman89f85052007-10-22 18:31:58 +00001412 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001413 }
Dan Gohman161ea032009-07-07 17:06:11 +00001414 const SCEV *NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001415
1416 if (Ops.size() == 2) return NewAddRec;
1417
1418 Ops.erase(Ops.begin()+Idx);
1419 Ops.erase(Ops.begin()+OtherIdx-1);
1420 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001421 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001422 }
1423 }
1424
1425 // Otherwise couldn't fold anything into this recurrence. Move onto the
1426 // next one.
1427 }
1428
1429 // Okay, it looks like we really DO need an add expr. Check to see if we
1430 // already have one, otherwise create a new one.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001431 FoldingSetNodeID ID;
1432 ID.AddInteger(scAddExpr);
1433 ID.AddInteger(Ops.size());
1434 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1435 ID.AddPointer(Ops[i]);
1436 void *IP = 0;
1437 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1438 SCEV *S = SCEVAllocator.Allocate<SCEVAddExpr>();
Dan Gohmand43a8282009-07-13 20:50:19 +00001439 new (S) SCEVAddExpr(ID, Ops);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001440 UniqueSCEVs.InsertNode(S, IP);
1441 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001442}
1443
1444
Dan Gohmanc8a29272009-05-24 23:45:28 +00001445/// getMulExpr - Get a canonical multiply expression, or something simpler if
1446/// possible.
Dan Gohman161ea032009-07-07 17:06:11 +00001447const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001448 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohmana77b3d42009-05-18 15:44:58 +00001449#ifndef NDEBUG
1450 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1451 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1452 getEffectiveSCEVType(Ops[0]->getType()) &&
1453 "SCEVMulExpr operand types don't match!");
1454#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001455
1456 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001457 GroupByComplexity(Ops, LI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001458
1459 // If there are any constants, fold them together.
1460 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001461 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001462
1463 // C1*(C2+V) -> C1*C2 + C1*V
1464 if (Ops.size() == 2)
Dan Gohmanc76b5452009-05-04 22:02:23 +00001465 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001466 if (Add->getNumOperands() == 2 &&
1467 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman89f85052007-10-22 18:31:58 +00001468 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1469 getMulExpr(LHSC, Add->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001470
1471
1472 ++Idx;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001473 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001474 // We found two constants, fold them together!
Owen Andersoneacb44d2009-07-24 23:12:02 +00001475 ConstantInt *Fold = ConstantInt::get(getContext(),
1476 LHSC->getValue()->getValue() *
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001477 RHSC->getValue()->getValue());
1478 Ops[0] = getConstant(Fold);
1479 Ops.erase(Ops.begin()+1); // Erase the folded element
1480 if (Ops.size() == 1) return Ops[0];
1481 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001482 }
1483
1484 // If we are left with a constant one being multiplied, strip it off.
1485 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1486 Ops.erase(Ops.begin());
1487 --Idx;
1488 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1489 // If we have a multiply of zero, it will always be zero.
1490 return Ops[0];
1491 }
1492 }
1493
1494 // Skip over the add expression until we get to a multiply.
1495 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1496 ++Idx;
1497
1498 if (Ops.size() == 1)
1499 return Ops[0];
1500
1501 // If there are mul operands inline them all into this expression.
1502 if (Idx < Ops.size()) {
1503 bool DeletedMul = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001504 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001505 // If we have an mul, expand the mul operands onto the end of the operands
1506 // list.
1507 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1508 Ops.erase(Ops.begin()+Idx);
1509 DeletedMul = true;
1510 }
1511
1512 // If we deleted at least one mul, we added operands to the end of the list,
1513 // and they are not necessarily sorted. Recurse to resort and resimplify
1514 // any operands we just aquired.
1515 if (DeletedMul)
Dan Gohman89f85052007-10-22 18:31:58 +00001516 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001517 }
1518
1519 // If there are any add recurrences in the operands list, see if any other
1520 // added values are loop invariant. If so, we can fold them into the
1521 // recurrence.
1522 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1523 ++Idx;
1524
1525 // Scan over all recurrences, trying to fold loop invariants into them.
1526 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1527 // Scan all of the other operands to this mul and add them to the vector if
1528 // they are loop invariant w.r.t. the recurrence.
Dan Gohman161ea032009-07-07 17:06:11 +00001529 SmallVector<const SCEV *, 8> LIOps;
Dan Gohmanbff6b582009-05-04 22:30:44 +00001530 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001531 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1532 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1533 LIOps.push_back(Ops[i]);
1534 Ops.erase(Ops.begin()+i);
1535 --i; --e;
1536 }
1537
1538 // If we found some loop invariants, fold them into the recurrence.
1539 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001540 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohman161ea032009-07-07 17:06:11 +00001541 SmallVector<const SCEV *, 4> NewOps;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001542 NewOps.reserve(AddRec->getNumOperands());
1543 if (LIOps.size() == 1) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001544 const SCEV *Scale = LIOps[0];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001545 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman89f85052007-10-22 18:31:58 +00001546 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001547 } else {
1548 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
Dan Gohman161ea032009-07-07 17:06:11 +00001549 SmallVector<const SCEV *, 4> MulOps(LIOps.begin(), LIOps.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001550 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman89f85052007-10-22 18:31:58 +00001551 NewOps.push_back(getMulExpr(MulOps));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001552 }
1553 }
1554
Dan Gohman161ea032009-07-07 17:06:11 +00001555 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001556
1557 // If all of the other operands were loop invariant, we are done.
1558 if (Ops.size() == 1) return NewRec;
1559
1560 // Otherwise, multiply the folded AddRec by the non-liv parts.
1561 for (unsigned i = 0;; ++i)
1562 if (Ops[i] == AddRec) {
1563 Ops[i] = NewRec;
1564 break;
1565 }
Dan Gohman89f85052007-10-22 18:31:58 +00001566 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001567 }
1568
1569 // Okay, if there weren't any loop invariants to be folded, check to see if
1570 // there are multiple AddRec's with the same loop induction variable being
1571 // multiplied together. If so, we can fold them.
1572 for (unsigned OtherIdx = Idx+1;
1573 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1574 if (OtherIdx != Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001575 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001576 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1577 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
Dan Gohmanbff6b582009-05-04 22:30:44 +00001578 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman161ea032009-07-07 17:06:11 +00001579 const SCEV *NewStart = getMulExpr(F->getStart(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001580 G->getStart());
Dan Gohman161ea032009-07-07 17:06:11 +00001581 const SCEV *B = F->getStepRecurrence(*this);
1582 const SCEV *D = G->getStepRecurrence(*this);
1583 const SCEV *NewStep = getAddExpr(getMulExpr(F, D),
Dan Gohman89f85052007-10-22 18:31:58 +00001584 getMulExpr(G, B),
1585 getMulExpr(B, D));
Dan Gohman161ea032009-07-07 17:06:11 +00001586 const SCEV *NewAddRec = getAddRecExpr(NewStart, NewStep,
Dan Gohman89f85052007-10-22 18:31:58 +00001587 F->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001588 if (Ops.size() == 2) return NewAddRec;
1589
1590 Ops.erase(Ops.begin()+Idx);
1591 Ops.erase(Ops.begin()+OtherIdx-1);
1592 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001593 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001594 }
1595 }
1596
1597 // Otherwise couldn't fold anything into this recurrence. Move onto the
1598 // next one.
1599 }
1600
1601 // Okay, it looks like we really DO need an mul expr. Check to see if we
1602 // already have one, otherwise create a new one.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001603 FoldingSetNodeID ID;
1604 ID.AddInteger(scMulExpr);
1605 ID.AddInteger(Ops.size());
1606 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1607 ID.AddPointer(Ops[i]);
1608 void *IP = 0;
1609 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1610 SCEV *S = SCEVAllocator.Allocate<SCEVMulExpr>();
Dan Gohmand43a8282009-07-13 20:50:19 +00001611 new (S) SCEVMulExpr(ID, Ops);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001612 UniqueSCEVs.InsertNode(S, IP);
1613 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001614}
1615
Dan Gohmanc8a29272009-05-24 23:45:28 +00001616/// getUDivExpr - Get a canonical multiply expression, or something simpler if
1617/// possible.
Dan Gohman8c4f20b2009-06-24 14:49:00 +00001618const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
1619 const SCEV *RHS) {
Dan Gohmana77b3d42009-05-18 15:44:58 +00001620 assert(getEffectiveSCEVType(LHS->getType()) ==
1621 getEffectiveSCEVType(RHS->getType()) &&
1622 "SCEVUDivExpr operand types don't match!");
1623
Dan Gohmanc76b5452009-05-04 22:02:23 +00001624 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001625 if (RHSC->getValue()->equalsInt(1))
Nick Lewycky35b56022009-01-13 09:18:58 +00001626 return LHS; // X udiv 1 --> x
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001627 if (RHSC->isZero())
1628 return getIntegerSCEV(0, LHS->getType()); // value is undefined
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001629
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001630 // Determine if the division can be folded into the operands of
1631 // its operands.
1632 // TODO: Generalize this to non-constants by using known-bits information.
1633 const Type *Ty = LHS->getType();
1634 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1635 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1636 // For non-power-of-two values, effectively round the value up to the
1637 // nearest power of two.
1638 if (!RHSC->getValue()->getValue().isPowerOf2())
1639 ++MaxShiftAmt;
1640 const IntegerType *ExtTy =
1641 IntegerType::get(getTypeSizeInBits(Ty) + MaxShiftAmt);
1642 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1643 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1644 if (const SCEVConstant *Step =
1645 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1646 if (!Step->getValue()->getValue()
1647 .urem(RHSC->getValue()->getValue()) &&
Dan Gohman14374d32009-05-08 23:11:16 +00001648 getZeroExtendExpr(AR, ExtTy) ==
1649 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1650 getZeroExtendExpr(Step, ExtTy),
1651 AR->getLoop())) {
Dan Gohman161ea032009-07-07 17:06:11 +00001652 SmallVector<const SCEV *, 4> Operands;
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001653 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1654 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1655 return getAddRecExpr(Operands, AR->getLoop());
1656 }
1657 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
Dan Gohman14374d32009-05-08 23:11:16 +00001658 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
Dan Gohman161ea032009-07-07 17:06:11 +00001659 SmallVector<const SCEV *, 4> Operands;
Dan Gohman14374d32009-05-08 23:11:16 +00001660 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1661 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1662 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001663 // Find an operand that's safely divisible.
1664 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
Dan Gohman161ea032009-07-07 17:06:11 +00001665 const SCEV *Op = M->getOperand(i);
1666 const SCEV *Div = getUDivExpr(Op, RHSC);
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001667 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
Dan Gohman161ea032009-07-07 17:06:11 +00001668 const SmallVectorImpl<const SCEV *> &MOperands = M->getOperands();
1669 Operands = SmallVector<const SCEV *, 4>(MOperands.begin(),
Dan Gohman02ff9392009-06-14 22:47:23 +00001670 MOperands.end());
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001671 Operands[i] = Div;
1672 return getMulExpr(Operands);
1673 }
1674 }
Dan Gohman14374d32009-05-08 23:11:16 +00001675 }
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001676 // (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 +00001677 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
Dan Gohman161ea032009-07-07 17:06:11 +00001678 SmallVector<const SCEV *, 4> Operands;
Dan Gohman14374d32009-05-08 23:11:16 +00001679 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1680 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1681 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1682 Operands.clear();
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001683 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
Dan Gohman161ea032009-07-07 17:06:11 +00001684 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001685 if (isa<SCEVUDivExpr>(Op) || getMulExpr(Op, RHS) != A->getOperand(i))
1686 break;
1687 Operands.push_back(Op);
1688 }
1689 if (Operands.size() == A->getNumOperands())
1690 return getAddExpr(Operands);
1691 }
Dan Gohman14374d32009-05-08 23:11:16 +00001692 }
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001693
1694 // Fold if both operands are constant.
Dan Gohmanc76b5452009-05-04 22:02:23 +00001695 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001696 Constant *LHSCV = LHSC->getValue();
1697 Constant *RHSCV = RHSC->getValue();
Owen Anderson175b6542009-07-22 00:24:57 +00001698 return getConstant(cast<ConstantInt>(getContext().getConstantExprUDiv(LHSCV,
Dan Gohman55788cf2009-06-24 00:38:39 +00001699 RHSCV)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001700 }
1701 }
1702
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001703 FoldingSetNodeID ID;
1704 ID.AddInteger(scUDivExpr);
1705 ID.AddPointer(LHS);
1706 ID.AddPointer(RHS);
1707 void *IP = 0;
1708 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1709 SCEV *S = SCEVAllocator.Allocate<SCEVUDivExpr>();
Dan Gohmand43a8282009-07-13 20:50:19 +00001710 new (S) SCEVUDivExpr(ID, LHS, RHS);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001711 UniqueSCEVs.InsertNode(S, IP);
1712 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001713}
1714
1715
Dan Gohmanc8a29272009-05-24 23:45:28 +00001716/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1717/// Simplify the expression as much as possible.
Dan Gohman161ea032009-07-07 17:06:11 +00001718const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start,
Dan Gohman1c4054f2009-07-24 01:03:59 +00001719 const SCEV *Step, const Loop *L) {
Dan Gohman161ea032009-07-07 17:06:11 +00001720 SmallVector<const SCEV *, 4> Operands;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001721 Operands.push_back(Start);
Dan Gohmanc76b5452009-05-04 22:02:23 +00001722 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001723 if (StepChrec->getLoop() == L) {
1724 Operands.insert(Operands.end(), StepChrec->op_begin(),
1725 StepChrec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001726 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001727 }
1728
1729 Operands.push_back(Step);
Dan Gohman89f85052007-10-22 18:31:58 +00001730 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001731}
1732
Dan Gohmanc8a29272009-05-24 23:45:28 +00001733/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1734/// Simplify the expression as much as possible.
Dan Gohman9bc642f2009-06-24 04:48:43 +00001735const SCEV *
Dan Gohman161ea032009-07-07 17:06:11 +00001736ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
Dan Gohman9bc642f2009-06-24 04:48:43 +00001737 const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001738 if (Operands.size() == 1) return Operands[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001739#ifndef NDEBUG
1740 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1741 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
1742 getEffectiveSCEVType(Operands[0]->getType()) &&
1743 "SCEVAddRecExpr operand types don't match!");
1744#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001745
Dan Gohman7b560c42008-06-18 16:23:07 +00001746 if (Operands.back()->isZero()) {
1747 Operands.pop_back();
Dan Gohmanabe991f2008-09-14 17:21:12 +00001748 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohman7b560c42008-06-18 16:23:07 +00001749 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001750
Dan Gohman42936882008-08-08 18:33:12 +00001751 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohmanc76b5452009-05-04 22:02:23 +00001752 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohman42936882008-08-08 18:33:12 +00001753 const Loop* NestedLoop = NestedAR->getLoop();
1754 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
Dan Gohman161ea032009-07-07 17:06:11 +00001755 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohman02ff9392009-06-14 22:47:23 +00001756 NestedAR->op_end());
Dan Gohman42936882008-08-08 18:33:12 +00001757 Operands[0] = NestedAR->getStart();
Dan Gohman08c4c072009-06-26 22:36:20 +00001758 // AddRecs require their operands be loop-invariant with respect to their
1759 // loops. Don't perform this transformation if it would break this
1760 // requirement.
1761 bool AllInvariant = true;
1762 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1763 if (!Operands[i]->isLoopInvariant(L)) {
1764 AllInvariant = false;
1765 break;
1766 }
1767 if (AllInvariant) {
1768 NestedOperands[0] = getAddRecExpr(Operands, L);
1769 AllInvariant = true;
1770 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
1771 if (!NestedOperands[i]->isLoopInvariant(NestedLoop)) {
1772 AllInvariant = false;
1773 break;
1774 }
1775 if (AllInvariant)
1776 // Ok, both add recurrences are valid after the transformation.
1777 return getAddRecExpr(NestedOperands, NestedLoop);
1778 }
1779 // Reset Operands to its original state.
1780 Operands[0] = NestedAR;
Dan Gohman42936882008-08-08 18:33:12 +00001781 }
1782 }
1783
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001784 FoldingSetNodeID ID;
1785 ID.AddInteger(scAddRecExpr);
1786 ID.AddInteger(Operands.size());
1787 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1788 ID.AddPointer(Operands[i]);
1789 ID.AddPointer(L);
1790 void *IP = 0;
1791 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1792 SCEV *S = SCEVAllocator.Allocate<SCEVAddRecExpr>();
Dan Gohmand43a8282009-07-13 20:50:19 +00001793 new (S) SCEVAddRecExpr(ID, Operands, L);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001794 UniqueSCEVs.InsertNode(S, IP);
1795 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001796}
1797
Dan Gohman8c4f20b2009-06-24 14:49:00 +00001798const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
1799 const SCEV *RHS) {
Dan Gohman161ea032009-07-07 17:06:11 +00001800 SmallVector<const SCEV *, 2> Ops;
Nick Lewycky711640a2007-11-25 22:41:31 +00001801 Ops.push_back(LHS);
1802 Ops.push_back(RHS);
1803 return getSMaxExpr(Ops);
1804}
1805
Dan Gohman161ea032009-07-07 17:06:11 +00001806const SCEV *
1807ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001808 assert(!Ops.empty() && "Cannot get empty smax!");
1809 if (Ops.size() == 1) return Ops[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001810#ifndef NDEBUG
1811 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1812 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1813 getEffectiveSCEVType(Ops[0]->getType()) &&
1814 "SCEVSMaxExpr operand types don't match!");
1815#endif
Nick Lewycky711640a2007-11-25 22:41:31 +00001816
1817 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001818 GroupByComplexity(Ops, LI);
Nick Lewycky711640a2007-11-25 22:41:31 +00001819
1820 // If there are any constants, fold them together.
1821 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001822 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001823 ++Idx;
1824 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001825 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001826 // We found two constants, fold them together!
Owen Andersoneacb44d2009-07-24 23:12:02 +00001827 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewycky711640a2007-11-25 22:41:31 +00001828 APIntOps::smax(LHSC->getValue()->getValue(),
1829 RHSC->getValue()->getValue()));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001830 Ops[0] = getConstant(Fold);
1831 Ops.erase(Ops.begin()+1); // Erase the folded element
1832 if (Ops.size() == 1) return Ops[0];
1833 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewycky711640a2007-11-25 22:41:31 +00001834 }
1835
Dan Gohmand156c092009-06-24 14:46:22 +00001836 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky711640a2007-11-25 22:41:31 +00001837 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1838 Ops.erase(Ops.begin());
1839 --Idx;
Dan Gohmand156c092009-06-24 14:46:22 +00001840 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
1841 // If we have an smax with a constant maximum-int, it will always be
1842 // maximum-int.
1843 return Ops[0];
Nick Lewycky711640a2007-11-25 22:41:31 +00001844 }
1845 }
1846
1847 if (Ops.size() == 1) return Ops[0];
1848
1849 // Find the first SMax
1850 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1851 ++Idx;
1852
1853 // Check to see if one of the operands is an SMax. If so, expand its operands
1854 // onto our operand list, and recurse to simplify.
1855 if (Idx < Ops.size()) {
1856 bool DeletedSMax = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001857 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001858 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1859 Ops.erase(Ops.begin()+Idx);
1860 DeletedSMax = true;
1861 }
1862
1863 if (DeletedSMax)
1864 return getSMaxExpr(Ops);
1865 }
1866
1867 // Okay, check to see if the same value occurs in the operand list twice. If
1868 // so, delete one. Since we sorted the list, these values are required to
1869 // be adjacent.
1870 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1871 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1872 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1873 --i; --e;
1874 }
1875
1876 if (Ops.size() == 1) return Ops[0];
1877
1878 assert(!Ops.empty() && "Reduced smax down to nothing!");
1879
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001880 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewycky711640a2007-11-25 22:41:31 +00001881 // already have one, otherwise create a new one.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001882 FoldingSetNodeID ID;
1883 ID.AddInteger(scSMaxExpr);
1884 ID.AddInteger(Ops.size());
1885 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1886 ID.AddPointer(Ops[i]);
1887 void *IP = 0;
1888 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1889 SCEV *S = SCEVAllocator.Allocate<SCEVSMaxExpr>();
Dan Gohmand43a8282009-07-13 20:50:19 +00001890 new (S) SCEVSMaxExpr(ID, Ops);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001891 UniqueSCEVs.InsertNode(S, IP);
1892 return S;
Nick Lewycky711640a2007-11-25 22:41:31 +00001893}
1894
Dan Gohman8c4f20b2009-06-24 14:49:00 +00001895const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
1896 const SCEV *RHS) {
Dan Gohman161ea032009-07-07 17:06:11 +00001897 SmallVector<const SCEV *, 2> Ops;
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001898 Ops.push_back(LHS);
1899 Ops.push_back(RHS);
1900 return getUMaxExpr(Ops);
1901}
1902
Dan Gohman161ea032009-07-07 17:06:11 +00001903const SCEV *
1904ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001905 assert(!Ops.empty() && "Cannot get empty umax!");
1906 if (Ops.size() == 1) return Ops[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001907#ifndef NDEBUG
1908 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1909 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1910 getEffectiveSCEVType(Ops[0]->getType()) &&
1911 "SCEVUMaxExpr operand types don't match!");
1912#endif
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001913
1914 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001915 GroupByComplexity(Ops, LI);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001916
1917 // If there are any constants, fold them together.
1918 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001919 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001920 ++Idx;
1921 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001922 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001923 // We found two constants, fold them together!
Owen Andersoneacb44d2009-07-24 23:12:02 +00001924 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001925 APIntOps::umax(LHSC->getValue()->getValue(),
1926 RHSC->getValue()->getValue()));
1927 Ops[0] = getConstant(Fold);
1928 Ops.erase(Ops.begin()+1); // Erase the folded element
1929 if (Ops.size() == 1) return Ops[0];
1930 LHSC = cast<SCEVConstant>(Ops[0]);
1931 }
1932
Dan Gohmand156c092009-06-24 14:46:22 +00001933 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001934 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1935 Ops.erase(Ops.begin());
1936 --Idx;
Dan Gohmand156c092009-06-24 14:46:22 +00001937 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
1938 // If we have an umax with a constant maximum-int, it will always be
1939 // maximum-int.
1940 return Ops[0];
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001941 }
1942 }
1943
1944 if (Ops.size() == 1) return Ops[0];
1945
1946 // Find the first UMax
1947 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1948 ++Idx;
1949
1950 // Check to see if one of the operands is a UMax. If so, expand its operands
1951 // onto our operand list, and recurse to simplify.
1952 if (Idx < Ops.size()) {
1953 bool DeletedUMax = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001954 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001955 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1956 Ops.erase(Ops.begin()+Idx);
1957 DeletedUMax = true;
1958 }
1959
1960 if (DeletedUMax)
1961 return getUMaxExpr(Ops);
1962 }
1963
1964 // Okay, check to see if the same value occurs in the operand list twice. If
1965 // so, delete one. Since we sorted the list, these values are required to
1966 // be adjacent.
1967 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1968 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1969 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1970 --i; --e;
1971 }
1972
1973 if (Ops.size() == 1) return Ops[0];
1974
1975 assert(!Ops.empty() && "Reduced umax down to nothing!");
1976
1977 // Okay, it looks like we really DO need a umax expr. Check to see if we
1978 // already have one, otherwise create a new one.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001979 FoldingSetNodeID ID;
1980 ID.AddInteger(scUMaxExpr);
1981 ID.AddInteger(Ops.size());
1982 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1983 ID.AddPointer(Ops[i]);
1984 void *IP = 0;
1985 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1986 SCEV *S = SCEVAllocator.Allocate<SCEVUMaxExpr>();
Dan Gohmand43a8282009-07-13 20:50:19 +00001987 new (S) SCEVUMaxExpr(ID, Ops);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00001988 UniqueSCEVs.InsertNode(S, IP);
1989 return S;
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001990}
1991
Dan Gohman8c4f20b2009-06-24 14:49:00 +00001992const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
1993 const SCEV *RHS) {
Dan Gohmand01fff82009-06-22 03:18:45 +00001994 // ~smax(~x, ~y) == smin(x, y).
1995 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
1996}
1997
Dan Gohman8c4f20b2009-06-24 14:49:00 +00001998const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
1999 const SCEV *RHS) {
Dan Gohmand01fff82009-06-22 03:18:45 +00002000 // ~umax(~x, ~y) == umin(x, y)
2001 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2002}
2003
Dan Gohman161ea032009-07-07 17:06:11 +00002004const SCEV *ScalarEvolution::getUnknown(Value *V) {
Dan Gohman984c78a2009-06-24 00:54:57 +00002005 // Don't attempt to do anything other than create a SCEVUnknown object
2006 // here. createSCEV only calls getUnknown after checking for all other
2007 // interesting possibilities, and any other code that calls getUnknown
2008 // is doing so in order to hide a value from SCEV canonicalization.
2009
Dan Gohmanc6475cb2009-06-27 21:21:31 +00002010 FoldingSetNodeID ID;
2011 ID.AddInteger(scUnknown);
2012 ID.AddPointer(V);
2013 void *IP = 0;
2014 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2015 SCEV *S = SCEVAllocator.Allocate<SCEVUnknown>();
Dan Gohmand43a8282009-07-13 20:50:19 +00002016 new (S) SCEVUnknown(ID, V);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00002017 UniqueSCEVs.InsertNode(S, IP);
2018 return S;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002019}
2020
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002021//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002022// Basic SCEV Analysis and PHI Idiom Recognition Code
2023//
2024
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002025/// isSCEVable - Test if values of the given type are analyzable within
2026/// the SCEV framework. This primarily includes integer types, and it
2027/// can optionally include pointer types if the ScalarEvolution class
2028/// has access to target-specific information.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002029bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002030 // Integers are always SCEVable.
2031 if (Ty->isInteger())
2032 return true;
2033
2034 // Pointers are SCEVable if TargetData information is available
2035 // to provide pointer size information.
2036 if (isa<PointerType>(Ty))
2037 return TD != NULL;
2038
2039 // Otherwise it's not SCEVable.
2040 return false;
2041}
2042
2043/// getTypeSizeInBits - Return the size in bits of the specified type,
2044/// for which isSCEVable must return true.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002045uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002046 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2047
2048 // If we have a TargetData, use it!
2049 if (TD)
2050 return TD->getTypeSizeInBits(Ty);
2051
2052 // Otherwise, we support only integer types.
2053 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
2054 return Ty->getPrimitiveSizeInBits();
2055}
2056
2057/// getEffectiveSCEVType - Return a type with the same bitwidth as
2058/// the given type and which represents how SCEV will treat the given
2059/// type, for which isSCEVable must return true. For pointer types,
2060/// this is the pointer-sized integer type.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002061const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002062 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2063
2064 if (Ty->isInteger())
2065 return Ty;
2066
2067 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
2068 return TD->getIntPtrType();
Dan Gohman01c2ee72009-04-16 03:18:22 +00002069}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002070
Dan Gohman161ea032009-07-07 17:06:11 +00002071const SCEV *ScalarEvolution::getCouldNotCompute() {
Dan Gohmanc6475cb2009-06-27 21:21:31 +00002072 return &CouldNotCompute;
Dan Gohman0ad08b02009-04-18 17:58:19 +00002073}
2074
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002075/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2076/// expression and create a new one.
Dan Gohman161ea032009-07-07 17:06:11 +00002077const SCEV *ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002078 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002079
Dan Gohman161ea032009-07-07 17:06:11 +00002080 std::map<SCEVCallbackVH, const SCEV *>::iterator I = Scalars.find(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002081 if (I != Scalars.end()) return I->second;
Dan Gohman161ea032009-07-07 17:06:11 +00002082 const SCEV *S = createSCEV(V);
Dan Gohmanbff6b582009-05-04 22:30:44 +00002083 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002084 return S;
2085}
2086
Dan Gohman984c78a2009-06-24 00:54:57 +00002087/// getIntegerSCEV - Given a SCEVable type, create a constant for the
Dan Gohman01c2ee72009-04-16 03:18:22 +00002088/// specified signed integer value and return a SCEV for the constant.
Dan Gohman161ea032009-07-07 17:06:11 +00002089const SCEV *ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
Dan Gohman984c78a2009-06-24 00:54:57 +00002090 const IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
Owen Andersoneacb44d2009-07-24 23:12:02 +00002091 return getConstant(ConstantInt::get(ITy, Val));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002092}
2093
2094/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2095///
Dan Gohman161ea032009-07-07 17:06:11 +00002096const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00002097 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson15b39322009-07-13 04:09:18 +00002098 return getConstant(
Owen Anderson175b6542009-07-22 00:24:57 +00002099 cast<ConstantInt>(getContext().getConstantExprNeg(VC->getValue())));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002100
2101 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002102 Ty = getEffectiveSCEVType(Ty);
Owen Anderson035d41d2009-07-13 20:58:05 +00002103 return getMulExpr(V,
Owen Anderson175b6542009-07-22 00:24:57 +00002104 getConstant(cast<ConstantInt>(getContext().getAllOnesValue(Ty))));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002105}
2106
2107/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohman161ea032009-07-07 17:06:11 +00002108const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00002109 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson035d41d2009-07-13 20:58:05 +00002110 return getConstant(
Owen Anderson175b6542009-07-22 00:24:57 +00002111 cast<ConstantInt>(getContext().getConstantExprNot(VC->getValue())));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002112
2113 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002114 Ty = getEffectiveSCEVType(Ty);
Owen Anderson035d41d2009-07-13 20:58:05 +00002115 const SCEV *AllOnes =
Owen Anderson175b6542009-07-22 00:24:57 +00002116 getConstant(cast<ConstantInt>(getContext().getAllOnesValue(Ty)));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002117 return getMinusSCEV(AllOnes, V);
2118}
2119
2120/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2121///
Dan Gohman8c4f20b2009-06-24 14:49:00 +00002122const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS,
2123 const SCEV *RHS) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00002124 // X - Y --> X + -Y
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002125 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002126}
2127
2128/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2129/// input value to the specified type. If the type must be extended, it is zero
2130/// extended.
Dan Gohman161ea032009-07-07 17:06:11 +00002131const SCEV *
2132ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V,
Nick Lewycky37d04642009-04-23 05:15:08 +00002133 const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00002134 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002135 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2136 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00002137 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002138 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00002139 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002140 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002141 return getTruncateExpr(V, Ty);
2142 return getZeroExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002143}
2144
2145/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2146/// input value to the specified type. If the type must be extended, it is sign
2147/// extended.
Dan Gohman161ea032009-07-07 17:06:11 +00002148const SCEV *
2149ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
Nick Lewycky37d04642009-04-23 05:15:08 +00002150 const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00002151 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002152 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2153 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00002154 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002155 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00002156 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002157 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002158 return getTruncateExpr(V, Ty);
2159 return getSignExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002160}
2161
Dan Gohmanac959332009-05-13 03:46:30 +00002162/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2163/// input value to the specified type. If the type must be extended, it is zero
2164/// extended. The conversion must not be narrowing.
Dan Gohman161ea032009-07-07 17:06:11 +00002165const SCEV *
2166ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, const Type *Ty) {
Dan Gohmanac959332009-05-13 03:46:30 +00002167 const Type *SrcTy = V->getType();
2168 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2169 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2170 "Cannot noop or zero extend with non-integer arguments!");
2171 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2172 "getNoopOrZeroExtend cannot truncate!");
2173 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2174 return V; // No conversion
2175 return getZeroExtendExpr(V, Ty);
2176}
2177
2178/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2179/// input value to the specified type. If the type must be extended, it is sign
2180/// extended. The conversion must not be narrowing.
Dan Gohman161ea032009-07-07 17:06:11 +00002181const SCEV *
2182ScalarEvolution::getNoopOrSignExtend(const SCEV *V, const Type *Ty) {
Dan Gohmanac959332009-05-13 03:46:30 +00002183 const Type *SrcTy = V->getType();
2184 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2185 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2186 "Cannot noop or sign extend with non-integer arguments!");
2187 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2188 "getNoopOrSignExtend cannot truncate!");
2189 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2190 return V; // No conversion
2191 return getSignExtendExpr(V, Ty);
2192}
2193
Dan Gohmane1ca7e82009-06-13 15:56:47 +00002194/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2195/// the input value to the specified type. If the type must be extended,
2196/// it is extended with unspecified bits. The conversion must not be
2197/// narrowing.
Dan Gohman161ea032009-07-07 17:06:11 +00002198const SCEV *
2199ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, const Type *Ty) {
Dan Gohmane1ca7e82009-06-13 15:56:47 +00002200 const Type *SrcTy = V->getType();
2201 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2202 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2203 "Cannot noop or any extend with non-integer arguments!");
2204 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2205 "getNoopOrAnyExtend cannot truncate!");
2206 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2207 return V; // No conversion
2208 return getAnyExtendExpr(V, Ty);
2209}
2210
Dan Gohmanac959332009-05-13 03:46:30 +00002211/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2212/// input value to the specified type. The conversion must not be widening.
Dan Gohman161ea032009-07-07 17:06:11 +00002213const SCEV *
2214ScalarEvolution::getTruncateOrNoop(const SCEV *V, const Type *Ty) {
Dan Gohmanac959332009-05-13 03:46:30 +00002215 const Type *SrcTy = V->getType();
2216 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2217 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2218 "Cannot truncate or noop with non-integer arguments!");
2219 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2220 "getTruncateOrNoop cannot extend!");
2221 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2222 return V; // No conversion
2223 return getTruncateExpr(V, Ty);
2224}
2225
Dan Gohman8e8b5232009-06-22 00:31:57 +00002226/// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2227/// the types using zero-extension, and then perform a umax operation
2228/// with them.
Dan Gohman8c4f20b2009-06-24 14:49:00 +00002229const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2230 const SCEV *RHS) {
Dan Gohman161ea032009-07-07 17:06:11 +00002231 const SCEV *PromotedLHS = LHS;
2232 const SCEV *PromotedRHS = RHS;
Dan Gohman8e8b5232009-06-22 00:31:57 +00002233
2234 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2235 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2236 else
2237 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2238
2239 return getUMaxExpr(PromotedLHS, PromotedRHS);
2240}
2241
Dan Gohman9e62bb02009-06-22 15:03:27 +00002242/// getUMinFromMismatchedTypes - Promote the operands to the wider of
2243/// the types using zero-extension, and then perform a umin operation
2244/// with them.
Dan Gohman8c4f20b2009-06-24 14:49:00 +00002245const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2246 const SCEV *RHS) {
Dan Gohman161ea032009-07-07 17:06:11 +00002247 const SCEV *PromotedLHS = LHS;
2248 const SCEV *PromotedRHS = RHS;
Dan Gohman9e62bb02009-06-22 15:03:27 +00002249
2250 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2251 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2252 else
2253 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2254
2255 return getUMinExpr(PromotedLHS, PromotedRHS);
2256}
2257
Dan Gohman2aa3f042009-07-25 01:13:03 +00002258/// PushDefUseChildren - Push users of the given Instruction
2259/// onto the given Worklist.
2260static void
2261PushDefUseChildren(Instruction *I,
2262 SmallVectorImpl<Instruction *> &Worklist) {
2263 // Push the def-use children onto the Worklist stack.
2264 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2265 UI != UE; ++UI)
2266 Worklist.push_back(cast<Instruction>(UI));
2267}
2268
2269/// ForgetSymbolicValue - This looks up computed SCEV values for all
2270/// instructions that depend on the given instruction and removes them from
2271/// the Scalars map if they reference SymName. This is used during PHI
2272/// resolution.
Dan Gohman9bc642f2009-06-24 04:48:43 +00002273void
Dan Gohman2aa3f042009-07-25 01:13:03 +00002274ScalarEvolution::ForgetSymbolicName(Instruction *I, const SCEV *SymName) {
2275 SmallVector<Instruction *, 16> Worklist;
2276 PushDefUseChildren(I, Worklist);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002277
Dan Gohman2aa3f042009-07-25 01:13:03 +00002278 SmallPtrSet<Instruction *, 8> Visited;
2279 Visited.insert(I);
2280 while (!Worklist.empty()) {
2281 Instruction *I = Worklist.pop_back_val();
2282 if (!Visited.insert(I)) continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002283
Dan Gohman2aa3f042009-07-25 01:13:03 +00002284 std::map<SCEVCallbackVH, const SCEV*>::iterator It =
2285 Scalars.find(static_cast<Value *>(I));
2286 if (It != Scalars.end()) {
2287 // Short-circuit the def-use traversal if the symbolic name
2288 // ceases to appear in expressions.
2289 if (!It->second->hasOperand(SymName))
2290 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002291
Dan Gohman2aa3f042009-07-25 01:13:03 +00002292 // SCEVUnknown for a PHI either means that it has an unrecognized
2293 // structure, or it's a PHI that's in the progress of being computed
2294 // by createNodeForPHI. In the former case, additional loop trip
2295 // count information isn't going to change anything. In the later
2296 // case, createNodeForPHI will perform the necessary updates on its
2297 // own when it gets to that point.
2298 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(It->second))
2299 Scalars.erase(It);
2300 ValuesAtScopes.erase(I);
2301 }
2302
2303 PushDefUseChildren(I, Worklist);
2304 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002305}
2306
2307/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2308/// a loop header, making it a potential recurrence, or it doesn't.
2309///
Dan Gohman161ea032009-07-07 17:06:11 +00002310const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002311 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002312 if (const Loop *L = LI->getLoopFor(PN->getParent()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002313 if (L->getHeader() == PN->getParent()) {
2314 // If it lives in the loop header, it has two incoming values, one
2315 // from outside the loop, and one from inside.
2316 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
2317 unsigned BackEdge = IncomingEdge^1;
2318
2319 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohman161ea032009-07-07 17:06:11 +00002320 const SCEV *SymbolicName = getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002321 assert(Scalars.find(PN) == Scalars.end() &&
2322 "PHI node already processed?");
Dan Gohmanbff6b582009-05-04 22:30:44 +00002323 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002324
2325 // Using this symbolic name for the PHI, analyze the value coming around
2326 // the back-edge.
Dan Gohman2aa3f042009-07-25 01:13:03 +00002327 Value *BEValueV = PN->getIncomingValue(BackEdge);
2328 const SCEV *BEValue = getSCEV(BEValueV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002329
2330 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2331 // has a special value for the first iteration of the loop.
2332
2333 // If the value coming around the backedge is an add with the symbolic
2334 // value we just inserted, then we found a simple induction variable!
Dan Gohmanc76b5452009-05-04 22:02:23 +00002335 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002336 // If there is a single occurrence of the symbolic value, replace it
2337 // with a recurrence.
2338 unsigned FoundIndex = Add->getNumOperands();
2339 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2340 if (Add->getOperand(i) == SymbolicName)
2341 if (FoundIndex == e) {
2342 FoundIndex = i;
2343 break;
2344 }
2345
2346 if (FoundIndex != Add->getNumOperands()) {
2347 // Create an add with everything but the specified operand.
Dan Gohman161ea032009-07-07 17:06:11 +00002348 SmallVector<const SCEV *, 8> Ops;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002349 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2350 if (i != FoundIndex)
2351 Ops.push_back(Add->getOperand(i));
Dan Gohman161ea032009-07-07 17:06:11 +00002352 const SCEV *Accum = getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002353
2354 // This is not a valid addrec if the step amount is varying each
2355 // loop iteration, but is not itself an addrec in this loop.
2356 if (Accum->isLoopInvariant(L) ||
2357 (isa<SCEVAddRecExpr>(Accum) &&
2358 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
Dan Gohman9bc642f2009-06-24 04:48:43 +00002359 const SCEV *StartVal =
2360 getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohman1bc53162009-07-25 01:22:26 +00002361 const SCEVAddRecExpr *PHISCEV =
2362 cast<SCEVAddRecExpr>(getAddRecExpr(StartVal, Accum, L));
2363
2364 // If the increment doesn't overflow, then neither the addrec nor the
2365 // post-increment will overflow.
2366 if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV))
2367 if (OBO->getOperand(0) == PN &&
2368 getSCEV(OBO->getOperand(1)) ==
2369 PHISCEV->getStepRecurrence(*this)) {
2370 const SCEVAddRecExpr *PostInc = PHISCEV->getPostIncExpr(*this);
2371 if (OBO->hasNoUnsignedOverflow()) {
2372 const_cast<SCEVAddRecExpr *>(PHISCEV)
2373 ->setHasNoUnsignedOverflow(true);
2374 const_cast<SCEVAddRecExpr *>(PostInc)
2375 ->setHasNoUnsignedOverflow(true);
2376 }
2377 if (OBO->hasNoSignedOverflow()) {
2378 const_cast<SCEVAddRecExpr *>(PHISCEV)
2379 ->setHasNoSignedOverflow(true);
2380 const_cast<SCEVAddRecExpr *>(PostInc)
2381 ->setHasNoSignedOverflow(true);
2382 }
2383 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002384
2385 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohman2aa3f042009-07-25 01:13:03 +00002386 // to be symbolic. We now need to go back and purge all of the
2387 // entries for the scalars that use the symbolic expression.
2388 ForgetSymbolicName(PN, SymbolicName);
2389 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002390 return PHISCEV;
2391 }
2392 }
Dan Gohmanc76b5452009-05-04 22:02:23 +00002393 } else if (const SCEVAddRecExpr *AddRec =
2394 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002395 // Otherwise, this could be a loop like this:
2396 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2397 // In this case, j = {1,+,1} and BEValue is j.
2398 // Because the other in-value of i (0) fits the evolution of BEValue
2399 // i really is an addrec evolution.
2400 if (AddRec->getLoop() == L && AddRec->isAffine()) {
Dan Gohman161ea032009-07-07 17:06:11 +00002401 const SCEV *StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002402
2403 // If StartVal = j.start - j.stride, we can use StartVal as the
2404 // initial step of the addrec evolution.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002405 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman89f85052007-10-22 18:31:58 +00002406 AddRec->getOperand(1))) {
Dan Gohman161ea032009-07-07 17:06:11 +00002407 const SCEV *PHISCEV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002408 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002409
2410 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohman2aa3f042009-07-25 01:13:03 +00002411 // to be symbolic. We now need to go back and purge all of the
2412 // entries for the scalars that use the symbolic expression.
2413 ForgetSymbolicName(PN, SymbolicName);
2414 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002415 return PHISCEV;
2416 }
2417 }
2418 }
2419
2420 return SymbolicName;
2421 }
2422
Dan Gohman32f35cc2009-07-14 14:06:25 +00002423 // It's tempting to recognize PHIs with a unique incoming value, however
2424 // this leads passes like indvars to break LCSSA form. Fortunately, such
2425 // PHIs are rare, as instcombine zaps them.
2426
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002427 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002428 return getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002429}
2430
Dan Gohman509cf4d2009-05-08 20:26:55 +00002431/// createNodeForGEP - Expand GEP instructions into add and multiply
2432/// operations. This allows them to be analyzed by regular SCEV code.
2433///
Dan Gohman9545fb02009-07-17 20:47:02 +00002434const SCEV *ScalarEvolution::createNodeForGEP(Operator *GEP) {
Dan Gohman509cf4d2009-05-08 20:26:55 +00002435
2436 const Type *IntPtrTy = TD->getIntPtrType();
Dan Gohmanc7034fa2009-05-08 20:36:47 +00002437 Value *Base = GEP->getOperand(0);
Dan Gohmand586a4f2009-05-09 00:14:52 +00002438 // Don't attempt to analyze GEPs over unsized objects.
2439 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2440 return getUnknown(GEP);
Dan Gohman161ea032009-07-07 17:06:11 +00002441 const SCEV *TotalOffset = getIntegerSCEV(0, IntPtrTy);
Dan Gohmanc7034fa2009-05-08 20:36:47 +00002442 gep_type_iterator GTI = gep_type_begin(GEP);
2443 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
2444 E = GEP->op_end();
Dan Gohman509cf4d2009-05-08 20:26:55 +00002445 I != E; ++I) {
2446 Value *Index = *I;
2447 // Compute the (potentially symbolic) offset in bytes for this index.
2448 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2449 // For a struct, add the member offset.
2450 const StructLayout &SL = *TD->getStructLayout(STy);
2451 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
2452 uint64_t Offset = SL.getElementOffset(FieldNo);
Dan Gohman55e2d7e2009-07-13 21:35:55 +00002453 TotalOffset = getAddExpr(TotalOffset, getIntegerSCEV(Offset, IntPtrTy));
Dan Gohman509cf4d2009-05-08 20:26:55 +00002454 } else {
2455 // For an array, add the element offset, explicitly scaled.
Dan Gohman161ea032009-07-07 17:06:11 +00002456 const SCEV *LocalOffset = getSCEV(Index);
Dan Gohman509cf4d2009-05-08 20:26:55 +00002457 if (!isa<PointerType>(LocalOffset->getType()))
2458 // Getelementptr indicies are signed.
Dan Gohman55e2d7e2009-07-13 21:35:55 +00002459 LocalOffset = getTruncateOrSignExtend(LocalOffset, IntPtrTy);
Dan Gohman509cf4d2009-05-08 20:26:55 +00002460 LocalOffset =
2461 getMulExpr(LocalOffset,
Dan Gohman55e2d7e2009-07-13 21:35:55 +00002462 getIntegerSCEV(TD->getTypeAllocSize(*GTI), IntPtrTy));
Dan Gohman509cf4d2009-05-08 20:26:55 +00002463 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
2464 }
2465 }
2466 return getAddExpr(getSCEV(Base), TotalOffset);
2467}
2468
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002469/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2470/// guaranteed to end in (at every loop iteration). It is, at the same time,
2471/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2472/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohman6e923a72009-06-19 23:29:04 +00002473uint32_t
Dan Gohman161ea032009-07-07 17:06:11 +00002474ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00002475 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner6ecce2a2007-11-23 22:36:49 +00002476 return C->getValue()->getValue().countTrailingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002477
Dan Gohmanc76b5452009-05-04 22:02:23 +00002478 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohman6e923a72009-06-19 23:29:04 +00002479 return std::min(GetMinTrailingZeros(T->getOperand()),
2480 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002481
Dan Gohmanc76b5452009-05-04 22:02:23 +00002482 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohman6e923a72009-06-19 23:29:04 +00002483 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2484 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2485 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002486 }
2487
Dan Gohmanc76b5452009-05-04 22:02:23 +00002488 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohman6e923a72009-06-19 23:29:04 +00002489 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2490 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2491 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002492 }
2493
Dan Gohmanc76b5452009-05-04 22:02:23 +00002494 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002495 // The result is the min of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002496 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002497 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002498 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002499 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002500 }
2501
Dan Gohmanc76b5452009-05-04 22:02:23 +00002502 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002503 // The result is the sum of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002504 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2505 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002506 for (unsigned i = 1, e = M->getNumOperands();
2507 SumOpRes != BitWidth && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002508 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002509 BitWidth);
2510 return SumOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002511 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002512
Dan Gohmanc76b5452009-05-04 22:02:23 +00002513 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002514 // The result is the min of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002515 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002516 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002517 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002518 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002519 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002520
Dan Gohmanc76b5452009-05-04 22:02:23 +00002521 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewycky711640a2007-11-25 22:41:31 +00002522 // The result is the min of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002523 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky711640a2007-11-25 22:41:31 +00002524 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002525 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky711640a2007-11-25 22:41:31 +00002526 return MinOpRes;
2527 }
2528
Dan Gohmanc76b5452009-05-04 22:02:23 +00002529 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002530 // The result is the min of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002531 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002532 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002533 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002534 return MinOpRes;
2535 }
2536
Dan Gohman6e923a72009-06-19 23:29:04 +00002537 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2538 // For a SCEVUnknown, ask ValueTracking.
2539 unsigned BitWidth = getTypeSizeInBits(U->getType());
2540 APInt Mask = APInt::getAllOnesValue(BitWidth);
2541 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2542 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2543 return Zeros.countTrailingOnes();
2544 }
2545
2546 // SCEVUDivExpr
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002547 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002548}
2549
Dan Gohman55e2d7e2009-07-13 21:35:55 +00002550/// getUnsignedRange - Determine the unsigned range for a particular SCEV.
2551///
2552ConstantRange
2553ScalarEvolution::getUnsignedRange(const SCEV *S) {
Dan Gohman6e923a72009-06-19 23:29:04 +00002554
2555 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Dan Gohman55e2d7e2009-07-13 21:35:55 +00002556 return ConstantRange(C->getValue()->getValue());
Dan Gohman6e923a72009-06-19 23:29:04 +00002557
Dan Gohman55e2d7e2009-07-13 21:35:55 +00002558 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2559 ConstantRange X = getUnsignedRange(Add->getOperand(0));
2560 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2561 X = X.add(getUnsignedRange(Add->getOperand(i)));
2562 return X;
2563 }
2564
2565 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2566 ConstantRange X = getUnsignedRange(Mul->getOperand(0));
2567 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2568 X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
2569 return X;
2570 }
2571
2572 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2573 ConstantRange X = getUnsignedRange(SMax->getOperand(0));
2574 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2575 X = X.smax(getUnsignedRange(SMax->getOperand(i)));
2576 return X;
2577 }
2578
2579 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2580 ConstantRange X = getUnsignedRange(UMax->getOperand(0));
2581 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2582 X = X.umax(getUnsignedRange(UMax->getOperand(i)));
2583 return X;
2584 }
2585
2586 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2587 ConstantRange X = getUnsignedRange(UDiv->getLHS());
2588 ConstantRange Y = getUnsignedRange(UDiv->getRHS());
2589 return X.udiv(Y);
2590 }
2591
2592 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2593 ConstantRange X = getUnsignedRange(ZExt->getOperand());
2594 return X.zeroExtend(cast<IntegerType>(ZExt->getType())->getBitWidth());
2595 }
2596
2597 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2598 ConstantRange X = getUnsignedRange(SExt->getOperand());
2599 return X.signExtend(cast<IntegerType>(SExt->getType())->getBitWidth());
2600 }
2601
2602 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
2603 ConstantRange X = getUnsignedRange(Trunc->getOperand());
2604 return X.truncate(cast<IntegerType>(Trunc->getType())->getBitWidth());
2605 }
2606
2607 ConstantRange FullSet(getTypeSizeInBits(S->getType()), true);
2608
2609 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
2610 const SCEV *T = getBackedgeTakenCount(AddRec->getLoop());
2611 const SCEVConstant *Trip = dyn_cast<SCEVConstant>(T);
2612 if (!Trip) return FullSet;
2613
2614 // TODO: non-affine addrec
2615 if (AddRec->isAffine()) {
2616 const Type *Ty = AddRec->getType();
2617 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
2618 if (getTypeSizeInBits(MaxBECount->getType()) <= getTypeSizeInBits(Ty)) {
2619 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
2620
2621 const SCEV *Start = AddRec->getStart();
Dan Gohman13dca602009-07-21 00:42:47 +00002622 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohman55e2d7e2009-07-13 21:35:55 +00002623 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
2624
2625 // Check for overflow.
Dan Gohman13dca602009-07-21 00:42:47 +00002626 // TODO: This is very conservative.
2627 if (!(Step->isOne() &&
2628 isKnownPredicate(ICmpInst::ICMP_ULT, Start, End)) &&
2629 !(Step->isAllOnesValue() &&
2630 isKnownPredicate(ICmpInst::ICMP_UGT, Start, End)))
Dan Gohman55e2d7e2009-07-13 21:35:55 +00002631 return FullSet;
2632
2633 ConstantRange StartRange = getUnsignedRange(Start);
2634 ConstantRange EndRange = getUnsignedRange(End);
2635 APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
2636 EndRange.getUnsignedMin());
2637 APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
2638 EndRange.getUnsignedMax());
2639 if (Min.isMinValue() && Max.isMaxValue())
Dan Gohman56e18592009-07-20 22:41:51 +00002640 return FullSet;
Dan Gohman55e2d7e2009-07-13 21:35:55 +00002641 return ConstantRange(Min, Max+1);
2642 }
2643 }
Dan Gohman6e923a72009-06-19 23:29:04 +00002644 }
2645
2646 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2647 // For a SCEVUnknown, ask ValueTracking.
2648 unsigned BitWidth = getTypeSizeInBits(U->getType());
2649 APInt Mask = APInt::getAllOnesValue(BitWidth);
2650 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2651 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
Dan Gohman07620512009-07-20 22:34:18 +00002652 if (Ones == ~Zeros + 1)
2653 return FullSet;
2654 return ConstantRange(Ones, ~Zeros + 1);
Dan Gohman6e923a72009-06-19 23:29:04 +00002655 }
2656
Dan Gohman55e2d7e2009-07-13 21:35:55 +00002657 return FullSet;
Dan Gohman6e923a72009-06-19 23:29:04 +00002658}
2659
Dan Gohman55e2d7e2009-07-13 21:35:55 +00002660/// getSignedRange - Determine the signed range for a particular SCEV.
2661///
2662ConstantRange
2663ScalarEvolution::getSignedRange(const SCEV *S) {
Dan Gohman6e923a72009-06-19 23:29:04 +00002664
Dan Gohman55e2d7e2009-07-13 21:35:55 +00002665 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2666 return ConstantRange(C->getValue()->getValue());
2667
2668 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2669 ConstantRange X = getSignedRange(Add->getOperand(0));
2670 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2671 X = X.add(getSignedRange(Add->getOperand(i)));
2672 return X;
Dan Gohman6e923a72009-06-19 23:29:04 +00002673 }
2674
Dan Gohman55e2d7e2009-07-13 21:35:55 +00002675 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2676 ConstantRange X = getSignedRange(Mul->getOperand(0));
2677 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2678 X = X.multiply(getSignedRange(Mul->getOperand(i)));
2679 return X;
Dan Gohman6e923a72009-06-19 23:29:04 +00002680 }
2681
Dan Gohman55e2d7e2009-07-13 21:35:55 +00002682 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2683 ConstantRange X = getSignedRange(SMax->getOperand(0));
2684 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2685 X = X.smax(getSignedRange(SMax->getOperand(i)));
2686 return X;
2687 }
Dan Gohman61e0c4c2009-06-24 01:05:09 +00002688
Dan Gohman55e2d7e2009-07-13 21:35:55 +00002689 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2690 ConstantRange X = getSignedRange(UMax->getOperand(0));
2691 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2692 X = X.umax(getSignedRange(UMax->getOperand(i)));
2693 return X;
2694 }
Dan Gohman61e0c4c2009-06-24 01:05:09 +00002695
Dan Gohman55e2d7e2009-07-13 21:35:55 +00002696 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2697 ConstantRange X = getSignedRange(UDiv->getLHS());
2698 ConstantRange Y = getSignedRange(UDiv->getRHS());
2699 return X.udiv(Y);
2700 }
Dan Gohman61e0c4c2009-06-24 01:05:09 +00002701
Dan Gohman55e2d7e2009-07-13 21:35:55 +00002702 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2703 ConstantRange X = getSignedRange(ZExt->getOperand());
2704 return X.zeroExtend(cast<IntegerType>(ZExt->getType())->getBitWidth());
2705 }
2706
2707 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2708 ConstantRange X = getSignedRange(SExt->getOperand());
2709 return X.signExtend(cast<IntegerType>(SExt->getType())->getBitWidth());
2710 }
2711
2712 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
2713 ConstantRange X = getSignedRange(Trunc->getOperand());
2714 return X.truncate(cast<IntegerType>(Trunc->getType())->getBitWidth());
2715 }
2716
2717 ConstantRange FullSet(getTypeSizeInBits(S->getType()), true);
2718
2719 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
2720 const SCEV *T = getBackedgeTakenCount(AddRec->getLoop());
2721 const SCEVConstant *Trip = dyn_cast<SCEVConstant>(T);
2722 if (!Trip) return FullSet;
2723
2724 // TODO: non-affine addrec
2725 if (AddRec->isAffine()) {
2726 const Type *Ty = AddRec->getType();
2727 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
2728 if (getTypeSizeInBits(MaxBECount->getType()) <= getTypeSizeInBits(Ty)) {
2729 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
2730
2731 const SCEV *Start = AddRec->getStart();
2732 const SCEV *Step = AddRec->getStepRecurrence(*this);
2733 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
2734
2735 // Check for overflow.
Dan Gohman13dca602009-07-21 00:42:47 +00002736 // TODO: This is very conservative.
2737 if (!(Step->isOne() &&
Dan Gohman55e2d7e2009-07-13 21:35:55 +00002738 isKnownPredicate(ICmpInst::ICMP_SLT, Start, End)) &&
Dan Gohman13dca602009-07-21 00:42:47 +00002739 !(Step->isAllOnesValue() &&
Dan Gohman55e2d7e2009-07-13 21:35:55 +00002740 isKnownPredicate(ICmpInst::ICMP_SGT, Start, End)))
2741 return FullSet;
2742
2743 ConstantRange StartRange = getSignedRange(Start);
2744 ConstantRange EndRange = getSignedRange(End);
2745 APInt Min = APIntOps::smin(StartRange.getSignedMin(),
2746 EndRange.getSignedMin());
2747 APInt Max = APIntOps::smax(StartRange.getSignedMax(),
2748 EndRange.getSignedMax());
2749 if (Min.isMinSignedValue() && Max.isMaxSignedValue())
Dan Gohmandc87c862009-07-21 00:37:45 +00002750 return FullSet;
Dan Gohman55e2d7e2009-07-13 21:35:55 +00002751 return ConstantRange(Min, Max+1);
Dan Gohman61e0c4c2009-06-24 01:05:09 +00002752 }
Dan Gohman61e0c4c2009-06-24 01:05:09 +00002753 }
Dan Gohman61e0c4c2009-06-24 01:05:09 +00002754 }
2755
Dan Gohman6e923a72009-06-19 23:29:04 +00002756 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2757 // For a SCEVUnknown, ask ValueTracking.
Dan Gohman55e2d7e2009-07-13 21:35:55 +00002758 unsigned BitWidth = getTypeSizeInBits(U->getType());
2759 unsigned NS = ComputeNumSignBits(U->getValue(), TD);
2760 if (NS == 1)
2761 return FullSet;
2762 return
2763 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
2764 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1);
Dan Gohman6e923a72009-06-19 23:29:04 +00002765 }
2766
Dan Gohman55e2d7e2009-07-13 21:35:55 +00002767 return FullSet;
Dan Gohman6e923a72009-06-19 23:29:04 +00002768}
2769
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002770/// createSCEV - We know that there is no SCEV for the specified value.
2771/// Analyze the expression.
2772///
Dan Gohman161ea032009-07-07 17:06:11 +00002773const SCEV *ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002774 if (!isSCEVable(V->getType()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002775 return getUnknown(V);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002776
Dan Gohman3996f472008-06-22 19:56:46 +00002777 unsigned Opcode = Instruction::UserOp1;
2778 if (Instruction *I = dyn_cast<Instruction>(V))
2779 Opcode = I->getOpcode();
2780 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
2781 Opcode = CE->getOpcode();
Dan Gohman984c78a2009-06-24 00:54:57 +00002782 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2783 return getConstant(CI);
2784 else if (isa<ConstantPointerNull>(V))
2785 return getIntegerSCEV(0, V->getType());
2786 else if (isa<UndefValue>(V))
2787 return getIntegerSCEV(0, V->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002788 else
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002789 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002790
Dan Gohman9545fb02009-07-17 20:47:02 +00002791 Operator *U = cast<Operator>(V);
Dan Gohman3996f472008-06-22 19:56:46 +00002792 switch (Opcode) {
2793 case Instruction::Add:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002794 return getAddExpr(getSCEV(U->getOperand(0)),
2795 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002796 case Instruction::Mul:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002797 return getMulExpr(getSCEV(U->getOperand(0)),
2798 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002799 case Instruction::UDiv:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002800 return getUDivExpr(getSCEV(U->getOperand(0)),
2801 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002802 case Instruction::Sub:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002803 return getMinusSCEV(getSCEV(U->getOperand(0)),
2804 getSCEV(U->getOperand(1)));
Dan Gohman53bf64a2009-04-21 02:26:00 +00002805 case Instruction::And:
2806 // For an expression like x&255 that merely masks off the high bits,
2807 // use zext(trunc(x)) as the SCEV expression.
2808 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman91ae1e72009-04-25 17:05:40 +00002809 if (CI->isNullValue())
2810 return getSCEV(U->getOperand(1));
Dan Gohmanc7ebba12009-04-27 01:41:10 +00002811 if (CI->isAllOnesValue())
2812 return getSCEV(U->getOperand(0));
Dan Gohman53bf64a2009-04-21 02:26:00 +00002813 const APInt &A = CI->getValue();
Dan Gohmana7726c32009-06-16 19:52:01 +00002814
2815 // Instcombine's ShrinkDemandedConstant may strip bits out of
2816 // constants, obscuring what would otherwise be a low-bits mask.
2817 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
2818 // knew about to reconstruct a low-bits mask value.
2819 unsigned LZ = A.countLeadingZeros();
2820 unsigned BitWidth = A.getBitWidth();
2821 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
2822 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2823 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
2824
2825 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
2826
Dan Gohmanae1d7dd2009-06-17 23:54:37 +00002827 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
Dan Gohman53bf64a2009-04-21 02:26:00 +00002828 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002829 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
Dan Gohmana7726c32009-06-16 19:52:01 +00002830 IntegerType::get(BitWidth - LZ)),
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002831 U->getType());
Dan Gohman53bf64a2009-04-21 02:26:00 +00002832 }
2833 break;
Dan Gohmana7726c32009-06-16 19:52:01 +00002834
Dan Gohman3996f472008-06-22 19:56:46 +00002835 case Instruction::Or:
2836 // If the RHS of the Or is a constant, we may have something like:
2837 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
2838 // optimizations will transparently handle this case.
2839 //
2840 // In order for this transformation to be safe, the LHS must be of the
2841 // form X*(2^n) and the Or constant must be less than 2^n.
2842 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman161ea032009-07-07 17:06:11 +00002843 const SCEV *LHS = getSCEV(U->getOperand(0));
Dan Gohman3996f472008-06-22 19:56:46 +00002844 const APInt &CIVal = CI->getValue();
Dan Gohman6e923a72009-06-19 23:29:04 +00002845 if (GetMinTrailingZeros(LHS) >=
Dan Gohman3996f472008-06-22 19:56:46 +00002846 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002847 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002848 }
Dan Gohman3996f472008-06-22 19:56:46 +00002849 break;
2850 case Instruction::Xor:
Dan Gohman3996f472008-06-22 19:56:46 +00002851 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky7fd27892008-07-07 06:15:49 +00002852 // If the RHS of the xor is a signbit, then this is just an add.
2853 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman3996f472008-06-22 19:56:46 +00002854 if (CI->getValue().isSignBit())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002855 return getAddExpr(getSCEV(U->getOperand(0)),
2856 getSCEV(U->getOperand(1)));
Nick Lewycky7fd27892008-07-07 06:15:49 +00002857
2858 // If the RHS of xor is -1, then this is a not operation.
Dan Gohmanc897f752009-05-18 16:17:44 +00002859 if (CI->isAllOnesValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002860 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohmanfc78cff2009-05-18 16:29:04 +00002861
2862 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
2863 // This is a variant of the check for xor with -1, and it handles
2864 // the case where instcombine has trimmed non-demanded bits out
2865 // of an xor with -1.
2866 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
2867 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
2868 if (BO->getOpcode() == Instruction::And &&
2869 LCI->getValue() == CI->getValue())
2870 if (const SCEVZeroExtendExpr *Z =
Dan Gohmane49ae432009-06-17 01:22:39 +00002871 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
Dan Gohmaned1d8bb2009-06-18 00:00:20 +00002872 const Type *UTy = U->getType();
Dan Gohman161ea032009-07-07 17:06:11 +00002873 const SCEV *Z0 = Z->getOperand();
Dan Gohmaned1d8bb2009-06-18 00:00:20 +00002874 const Type *Z0Ty = Z0->getType();
2875 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
2876
2877 // If C is a low-bits mask, the zero extend is zerving to
2878 // mask off the high bits. Complement the operand and
2879 // re-apply the zext.
2880 if (APIntOps::isMask(Z0TySize, CI->getValue()))
2881 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
2882
2883 // If C is a single bit, it may be in the sign-bit position
2884 // before the zero-extend. In this case, represent the xor
2885 // using an add, which is equivalent, and re-apply the zext.
2886 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
2887 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
2888 Trunc.isSignBit())
2889 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
2890 UTy);
Dan Gohmane49ae432009-06-17 01:22:39 +00002891 }
Dan Gohman3996f472008-06-22 19:56:46 +00002892 }
2893 break;
2894
2895 case Instruction::Shl:
2896 // Turn shift left of a constant amount into a multiply.
2897 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2898 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Owen Andersoneacb44d2009-07-24 23:12:02 +00002899 Constant *X = ConstantInt::get(getContext(),
Dan Gohman3996f472008-06-22 19:56:46 +00002900 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002901 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman3996f472008-06-22 19:56:46 +00002902 }
2903 break;
2904
Nick Lewycky7fd27892008-07-07 06:15:49 +00002905 case Instruction::LShr:
Nick Lewycky35b56022009-01-13 09:18:58 +00002906 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky7fd27892008-07-07 06:15:49 +00002907 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2908 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Owen Andersoneacb44d2009-07-24 23:12:02 +00002909 Constant *X = ConstantInt::get(getContext(),
Nick Lewycky7fd27892008-07-07 06:15:49 +00002910 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002911 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky7fd27892008-07-07 06:15:49 +00002912 }
2913 break;
2914
Dan Gohman53bf64a2009-04-21 02:26:00 +00002915 case Instruction::AShr:
2916 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
2917 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
2918 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
2919 if (L->getOpcode() == Instruction::Shl &&
2920 L->getOperand(1) == U->getOperand(1)) {
Dan Gohman91ae1e72009-04-25 17:05:40 +00002921 unsigned BitWidth = getTypeSizeInBits(U->getType());
2922 uint64_t Amt = BitWidth - CI->getZExtValue();
2923 if (Amt == BitWidth)
2924 return getSCEV(L->getOperand(0)); // shift by zero --> noop
2925 if (Amt > BitWidth)
2926 return getIntegerSCEV(0, U->getType()); // value is undefined
Dan Gohman53bf64a2009-04-21 02:26:00 +00002927 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002928 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohman91ae1e72009-04-25 17:05:40 +00002929 IntegerType::get(Amt)),
Dan Gohman53bf64a2009-04-21 02:26:00 +00002930 U->getType());
2931 }
2932 break;
2933
Dan Gohman3996f472008-06-22 19:56:46 +00002934 case Instruction::Trunc:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002935 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002936
2937 case Instruction::ZExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002938 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002939
2940 case Instruction::SExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002941 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002942
2943 case Instruction::BitCast:
2944 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002945 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman3996f472008-06-22 19:56:46 +00002946 return getSCEV(U->getOperand(0));
2947 break;
2948
Dan Gohman2ec15e62009-07-20 17:43:30 +00002949 // It's tempting to handle inttoptr and ptrtoint, however this can
2950 // lead to pointer expressions which cannot be expanded to GEPs
2951 // (because they may overflow). For now, the only pointer-typed
2952 // expressions we handle are GEPs and address literals.
Dan Gohman01c2ee72009-04-16 03:18:22 +00002953
Dan Gohman509cf4d2009-05-08 20:26:55 +00002954 case Instruction::GetElementPtr:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002955 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohmanca5a39e2009-05-08 20:58:38 +00002956 return createNodeForGEP(U);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002957
Dan Gohman3996f472008-06-22 19:56:46 +00002958 case Instruction::PHI:
2959 return createNodeForPHI(cast<PHINode>(U));
2960
2961 case Instruction::Select:
2962 // This could be a smax or umax that was lowered earlier.
2963 // Try to recover it.
2964 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2965 Value *LHS = ICI->getOperand(0);
2966 Value *RHS = ICI->getOperand(1);
2967 switch (ICI->getPredicate()) {
2968 case ICmpInst::ICMP_SLT:
2969 case ICmpInst::ICMP_SLE:
2970 std::swap(LHS, RHS);
2971 // fall through
2972 case ICmpInst::ICMP_SGT:
2973 case ICmpInst::ICMP_SGE:
2974 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002975 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002976 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmand01fff82009-06-22 03:18:45 +00002977 return getSMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002978 break;
2979 case ICmpInst::ICMP_ULT:
2980 case ICmpInst::ICMP_ULE:
2981 std::swap(LHS, RHS);
2982 // fall through
2983 case ICmpInst::ICMP_UGT:
2984 case ICmpInst::ICMP_UGE:
2985 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002986 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002987 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmand01fff82009-06-22 03:18:45 +00002988 return getUMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002989 break;
Dan Gohmanf27dc692009-06-18 20:21:07 +00002990 case ICmpInst::ICMP_NE:
2991 // n != 0 ? n : 1 -> umax(n, 1)
2992 if (LHS == U->getOperand(1) &&
2993 isa<ConstantInt>(U->getOperand(2)) &&
2994 cast<ConstantInt>(U->getOperand(2))->isOne() &&
2995 isa<ConstantInt>(RHS) &&
2996 cast<ConstantInt>(RHS)->isZero())
2997 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(2)));
2998 break;
2999 case ICmpInst::ICMP_EQ:
3000 // n == 0 ? 1 : n -> umax(n, 1)
3001 if (LHS == U->getOperand(2) &&
3002 isa<ConstantInt>(U->getOperand(1)) &&
3003 cast<ConstantInt>(U->getOperand(1))->isOne() &&
3004 isa<ConstantInt>(RHS) &&
3005 cast<ConstantInt>(RHS)->isZero())
3006 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(1)));
3007 break;
Dan Gohman3996f472008-06-22 19:56:46 +00003008 default:
3009 break;
3010 }
3011 }
3012
3013 default: // We cannot analyze this expression.
3014 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003015 }
3016
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003017 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003018}
3019
3020
3021
3022//===----------------------------------------------------------------------===//
3023// Iteration Count Computation Code
3024//
3025
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003026/// getBackedgeTakenCount - If the specified loop has a predictable
3027/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
3028/// object. The backedge-taken count is the number of times the loop header
3029/// will be branched to from within the loop. This is one less than the
3030/// trip count of the loop, since it doesn't count the first iteration,
3031/// when the header is branched to from outside the loop.
3032///
3033/// Note that it is not valid to call this method on a loop without a
3034/// loop-invariant backedge-taken count (see
3035/// hasLoopInvariantBackedgeTakenCount).
3036///
Dan Gohman161ea032009-07-07 17:06:11 +00003037const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003038 return getBackedgeTakenInfo(L).Exact;
3039}
3040
3041/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
3042/// return the least SCEV value that is known never to be less than the
3043/// actual backedge taken count.
Dan Gohman161ea032009-07-07 17:06:11 +00003044const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003045 return getBackedgeTakenInfo(L).Max;
3046}
3047
Dan Gohmanb7d04aa2009-07-08 19:23:34 +00003048/// PushLoopPHIs - Push PHI nodes in the header of the given loop
3049/// onto the given Worklist.
3050static void
3051PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
3052 BasicBlock *Header = L->getHeader();
3053
3054 // Push all Loop-header PHIs onto the Worklist stack.
3055 for (BasicBlock::iterator I = Header->begin();
3056 PHINode *PN = dyn_cast<PHINode>(I); ++I)
3057 Worklist.push_back(PN);
3058}
3059
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003060const ScalarEvolution::BackedgeTakenInfo &
3061ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohmana9dba962009-04-27 20:16:15 +00003062 // Initially insert a CouldNotCompute for this loop. If the insertion
3063 // succeeds, procede to actually compute a backedge-taken count and
3064 // update the value. The temporary CouldNotCompute value tells SCEV
3065 // code elsewhere that it shouldn't attempt to request a new
3066 // backedge-taken count, which could result in infinite recursion.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003067 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohmana9dba962009-04-27 20:16:15 +00003068 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
3069 if (Pair.second) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003070 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003071 if (ItCount.Exact != getCouldNotCompute()) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003072 assert(ItCount.Exact->isLoopInvariant(L) &&
3073 ItCount.Max->isLoopInvariant(L) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003074 "Computed trip count isn't loop invariant for loop!");
3075 ++NumTripCountsComputed;
Dan Gohmana9dba962009-04-27 20:16:15 +00003076
Dan Gohmana9dba962009-04-27 20:16:15 +00003077 // Update the value in the map.
3078 Pair.first->second = ItCount;
Dan Gohman8e8b5232009-06-22 00:31:57 +00003079 } else {
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003080 if (ItCount.Max != getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003081 // Update the value in the map.
3082 Pair.first->second = ItCount;
3083 if (isa<PHINode>(L->getHeader()->begin()))
3084 // Only count loops that have phi nodes as not being computable.
3085 ++NumTripCountsNotComputed;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003086 }
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003087
3088 // Now that we know more about the trip count for this loop, forget any
3089 // existing SCEV values for PHI nodes in this loop since they are only
Dan Gohmanb7d04aa2009-07-08 19:23:34 +00003090 // conservative estimates made without the benefit of trip count
3091 // information. This is similar to the code in
3092 // forgetLoopBackedgeTakenCount, except that it handles SCEVUnknown PHI
3093 // nodes specially.
3094 if (ItCount.hasAnyInfo()) {
3095 SmallVector<Instruction *, 16> Worklist;
3096 PushLoopPHIs(L, Worklist);
3097
3098 SmallPtrSet<Instruction *, 8> Visited;
3099 while (!Worklist.empty()) {
3100 Instruction *I = Worklist.pop_back_val();
3101 if (!Visited.insert(I)) continue;
3102
3103 std::map<SCEVCallbackVH, const SCEV*>::iterator It =
3104 Scalars.find(static_cast<Value *>(I));
3105 if (It != Scalars.end()) {
3106 // SCEVUnknown for a PHI either means that it has an unrecognized
3107 // structure, or it's a PHI that's in the progress of being computed
Dan Gohman0fa91f32009-07-13 22:04:06 +00003108 // by createNodeForPHI. In the former case, additional loop trip
3109 // count information isn't going to change anything. In the later
3110 // case, createNodeForPHI will perform the necessary updates on its
3111 // own when it gets to that point.
Dan Gohmanb7d04aa2009-07-08 19:23:34 +00003112 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(It->second))
3113 Scalars.erase(It);
3114 ValuesAtScopes.erase(I);
3115 if (PHINode *PN = dyn_cast<PHINode>(I))
3116 ConstantEvolutionLoopExitValue.erase(PN);
3117 }
3118
3119 PushDefUseChildren(I, Worklist);
3120 }
3121 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003122 }
Dan Gohmana9dba962009-04-27 20:16:15 +00003123 return Pair.first->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003124}
3125
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003126/// forgetLoopBackedgeTakenCount - This method should be called by the
Dan Gohmanf3a060a2009-02-17 20:49:49 +00003127/// client when it has changed a loop in a way that may effect
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003128/// ScalarEvolution's ability to compute a trip count, or if the loop
3129/// is deleted.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003130void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003131 BackedgeTakenCounts.erase(L);
Dan Gohman94623022009-05-02 17:43:35 +00003132
Dan Gohmanbff6b582009-05-04 22:30:44 +00003133 SmallVector<Instruction *, 16> Worklist;
Dan Gohmanb7d04aa2009-07-08 19:23:34 +00003134 PushLoopPHIs(L, Worklist);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003135
Dan Gohmanb7d04aa2009-07-08 19:23:34 +00003136 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohmanbff6b582009-05-04 22:30:44 +00003137 while (!Worklist.empty()) {
3138 Instruction *I = Worklist.pop_back_val();
Dan Gohmanb7d04aa2009-07-08 19:23:34 +00003139 if (!Visited.insert(I)) continue;
3140
3141 std::map<SCEVCallbackVH, const SCEV*>::iterator It =
3142 Scalars.find(static_cast<Value *>(I));
3143 if (It != Scalars.end()) {
3144 Scalars.erase(It);
3145 ValuesAtScopes.erase(I);
3146 if (PHINode *PN = dyn_cast<PHINode>(I))
3147 ConstantEvolutionLoopExitValue.erase(PN);
3148 }
3149
3150 PushDefUseChildren(I, Worklist);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003151 }
Dan Gohmanf3a060a2009-02-17 20:49:49 +00003152}
3153
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003154/// ComputeBackedgeTakenCount - Compute the number of times the backedge
3155/// of the specified loop will execute.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003156ScalarEvolution::BackedgeTakenInfo
3157ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohman8e8b5232009-06-22 00:31:57 +00003158 SmallVector<BasicBlock*, 8> ExitingBlocks;
3159 L->getExitingBlocks(ExitingBlocks);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003160
Dan Gohman8e8b5232009-06-22 00:31:57 +00003161 // Examine all exits and pick the most conservative values.
Dan Gohman161ea032009-07-07 17:06:11 +00003162 const SCEV *BECount = getCouldNotCompute();
3163 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohman8e8b5232009-06-22 00:31:57 +00003164 bool CouldNotComputeBECount = false;
Dan Gohman8e8b5232009-06-22 00:31:57 +00003165 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
3166 BackedgeTakenInfo NewBTI =
3167 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003168
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003169 if (NewBTI.Exact == getCouldNotCompute()) {
Dan Gohman8e8b5232009-06-22 00:31:57 +00003170 // We couldn't compute an exact value for this exit, so
Dan Gohmanc6e8c832009-06-22 21:10:22 +00003171 // we won't be able to compute an exact value for the loop.
Dan Gohman8e8b5232009-06-22 00:31:57 +00003172 CouldNotComputeBECount = true;
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003173 BECount = getCouldNotCompute();
Dan Gohman8e8b5232009-06-22 00:31:57 +00003174 } else if (!CouldNotComputeBECount) {
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003175 if (BECount == getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003176 BECount = NewBTI.Exact;
Dan Gohman8e8b5232009-06-22 00:31:57 +00003177 else
Dan Gohman423ed6c2009-06-24 01:18:18 +00003178 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
Dan Gohman8e8b5232009-06-22 00:31:57 +00003179 }
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003180 if (MaxBECount == getCouldNotCompute())
Dan Gohman423ed6c2009-06-24 01:18:18 +00003181 MaxBECount = NewBTI.Max;
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003182 else if (NewBTI.Max != getCouldNotCompute())
Dan Gohman423ed6c2009-06-24 01:18:18 +00003183 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
Dan Gohman8e8b5232009-06-22 00:31:57 +00003184 }
3185
3186 return BackedgeTakenInfo(BECount, MaxBECount);
3187}
3188
3189/// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
3190/// of the specified loop will execute if it exits via the specified block.
3191ScalarEvolution::BackedgeTakenInfo
3192ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
3193 BasicBlock *ExitingBlock) {
3194
3195 // Okay, we've chosen an exiting block. See what condition causes us to
3196 // exit at this block.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003197 //
3198 // FIXME: we should be able to handle switch instructions (with a single exit)
3199 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003200 if (ExitBr == 0) return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003201 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Dan Gohman9bc642f2009-06-24 04:48:43 +00003202
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003203 // At this point, we know we have a conditional branch that determines whether
3204 // the loop is exited. However, we don't know if the branch is executed each
3205 // time through the loop. If not, then the execution count of the branch will
3206 // not be equal to the trip count of the loop.
3207 //
3208 // Currently we check for this by checking to see if the Exit branch goes to
3209 // the loop header. If so, we know it will always execute the same number of
3210 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohman8e8b5232009-06-22 00:31:57 +00003211 // loop header. This is common for un-rotated loops.
3212 //
3213 // If both of those tests fail, walk up the unique predecessor chain to the
3214 // header, stopping if there is an edge that doesn't exit the loop. If the
3215 // header is reached, the execution count of the branch will be equal to the
3216 // trip count of the loop.
3217 //
3218 // More extensive analysis could be done to handle more cases here.
3219 //
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003220 if (ExitBr->getSuccessor(0) != L->getHeader() &&
3221 ExitBr->getSuccessor(1) != L->getHeader() &&
Dan Gohman8e8b5232009-06-22 00:31:57 +00003222 ExitBr->getParent() != L->getHeader()) {
3223 // The simple checks failed, try climbing the unique predecessor chain
3224 // up to the header.
3225 bool Ok = false;
3226 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
3227 BasicBlock *Pred = BB->getUniquePredecessor();
3228 if (!Pred)
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003229 return getCouldNotCompute();
Dan Gohman8e8b5232009-06-22 00:31:57 +00003230 TerminatorInst *PredTerm = Pred->getTerminator();
3231 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
3232 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
3233 if (PredSucc == BB)
3234 continue;
3235 // If the predecessor has a successor that isn't BB and isn't
3236 // outside the loop, assume the worst.
3237 if (L->contains(PredSucc))
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003238 return getCouldNotCompute();
Dan Gohman8e8b5232009-06-22 00:31:57 +00003239 }
3240 if (Pred == L->getHeader()) {
3241 Ok = true;
3242 break;
3243 }
3244 BB = Pred;
3245 }
3246 if (!Ok)
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003247 return getCouldNotCompute();
Dan Gohman8e8b5232009-06-22 00:31:57 +00003248 }
3249
3250 // Procede to the next level to examine the exit condition expression.
3251 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
3252 ExitBr->getSuccessor(0),
3253 ExitBr->getSuccessor(1));
3254}
3255
3256/// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
3257/// backedge of the specified loop will execute if its exit condition
3258/// were a conditional branch of ExitCond, TBB, and FBB.
3259ScalarEvolution::BackedgeTakenInfo
3260ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
3261 Value *ExitCond,
3262 BasicBlock *TBB,
3263 BasicBlock *FBB) {
Dan Gohman423ed6c2009-06-24 01:18:18 +00003264 // Check if the controlling expression for this loop is an And or Or.
Dan Gohman8e8b5232009-06-22 00:31:57 +00003265 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
3266 if (BO->getOpcode() == Instruction::And) {
3267 // Recurse on the operands of the and.
3268 BackedgeTakenInfo BTI0 =
3269 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3270 BackedgeTakenInfo BTI1 =
3271 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman161ea032009-07-07 17:06:11 +00003272 const SCEV *BECount = getCouldNotCompute();
3273 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohman8e8b5232009-06-22 00:31:57 +00003274 if (L->contains(TBB)) {
3275 // Both conditions must be true for the loop to continue executing.
3276 // Choose the less conservative count.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003277 if (BTI0.Exact == getCouldNotCompute() ||
3278 BTI1.Exact == getCouldNotCompute())
3279 BECount = getCouldNotCompute();
Dan Gohmanac958b32009-06-22 15:09:28 +00003280 else
3281 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003282 if (BTI0.Max == getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003283 MaxBECount = BTI1.Max;
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003284 else if (BTI1.Max == getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003285 MaxBECount = BTI0.Max;
Dan Gohmanac958b32009-06-22 15:09:28 +00003286 else
3287 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohman8e8b5232009-06-22 00:31:57 +00003288 } else {
3289 // Both conditions must be true for the loop to exit.
3290 assert(L->contains(FBB) && "Loop block has no successor in loop!");
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003291 if (BTI0.Exact != getCouldNotCompute() &&
3292 BTI1.Exact != getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003293 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003294 if (BTI0.Max != getCouldNotCompute() &&
3295 BTI1.Max != getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003296 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3297 }
3298
3299 return BackedgeTakenInfo(BECount, MaxBECount);
3300 }
3301 if (BO->getOpcode() == Instruction::Or) {
3302 // Recurse on the operands of the or.
3303 BackedgeTakenInfo BTI0 =
3304 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3305 BackedgeTakenInfo BTI1 =
3306 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman161ea032009-07-07 17:06:11 +00003307 const SCEV *BECount = getCouldNotCompute();
3308 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohman8e8b5232009-06-22 00:31:57 +00003309 if (L->contains(FBB)) {
3310 // Both conditions must be false for the loop to continue executing.
3311 // Choose the less conservative count.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003312 if (BTI0.Exact == getCouldNotCompute() ||
3313 BTI1.Exact == getCouldNotCompute())
3314 BECount = getCouldNotCompute();
Dan Gohmanac958b32009-06-22 15:09:28 +00003315 else
3316 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003317 if (BTI0.Max == getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003318 MaxBECount = BTI1.Max;
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003319 else if (BTI1.Max == getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003320 MaxBECount = BTI0.Max;
Dan Gohmanac958b32009-06-22 15:09:28 +00003321 else
3322 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohman8e8b5232009-06-22 00:31:57 +00003323 } else {
3324 // Both conditions must be false for the loop to exit.
3325 assert(L->contains(TBB) && "Loop block has no successor in loop!");
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003326 if (BTI0.Exact != getCouldNotCompute() &&
3327 BTI1.Exact != getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003328 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003329 if (BTI0.Max != getCouldNotCompute() &&
3330 BTI1.Max != getCouldNotCompute())
Dan Gohman8e8b5232009-06-22 00:31:57 +00003331 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3332 }
3333
3334 return BackedgeTakenInfo(BECount, MaxBECount);
3335 }
3336 }
3337
3338 // With an icmp, it may be feasible to compute an exact backedge-taken count.
3339 // Procede to the next level to examine the icmp.
3340 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
3341 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003342
Eli Friedman459d7292009-05-09 12:32:42 +00003343 // If it's not an integer or pointer comparison then compute it the hard way.
Dan Gohman8e8b5232009-06-22 00:31:57 +00003344 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3345}
3346
3347/// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
3348/// backedge of the specified loop will execute if its exit condition
3349/// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
3350ScalarEvolution::BackedgeTakenInfo
3351ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
3352 ICmpInst *ExitCond,
3353 BasicBlock *TBB,
3354 BasicBlock *FBB) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003355
3356 // If the condition was exit on true, convert the condition to exit on false
3357 ICmpInst::Predicate Cond;
Dan Gohman8e8b5232009-06-22 00:31:57 +00003358 if (!L->contains(FBB))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003359 Cond = ExitCond->getPredicate();
3360 else
3361 Cond = ExitCond->getInversePredicate();
3362
3363 // Handle common loops like: for (X = "string"; *X; ++X)
3364 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
3365 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Dan Gohman161ea032009-07-07 17:06:11 +00003366 const SCEV *ItCnt =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003367 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohman8e8b5232009-06-22 00:31:57 +00003368 if (!isa<SCEVCouldNotCompute>(ItCnt)) {
3369 unsigned BitWidth = getTypeSizeInBits(ItCnt->getType());
3370 return BackedgeTakenInfo(ItCnt,
3371 isa<SCEVConstant>(ItCnt) ? ItCnt :
3372 getConstant(APInt::getMaxValue(BitWidth)-1));
3373 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003374 }
3375
Dan Gohman161ea032009-07-07 17:06:11 +00003376 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
3377 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003378
3379 // Try to evaluate any dependencies out of the loop.
Dan Gohmanaff14d62009-05-24 23:25:42 +00003380 LHS = getSCEVAtScope(LHS, L);
3381 RHS = getSCEVAtScope(RHS, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003382
Dan Gohman9bc642f2009-06-24 04:48:43 +00003383 // At this point, we would like to compute how many iterations of the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003384 // loop the predicate will return true for these inputs.
Dan Gohman2d96e352008-09-16 18:52:57 +00003385 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
3386 // If there is a loop-invariant, force it into the RHS.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003387 std::swap(LHS, RHS);
3388 Cond = ICmpInst::getSwappedPredicate(Cond);
3389 }
3390
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003391 // If we have a comparison of a chrec against a constant, try to use value
3392 // ranges to answer this query.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003393 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
3394 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003395 if (AddRec->getLoop() == L) {
Eli Friedman459d7292009-05-09 12:32:42 +00003396 // Form the constant range.
3397 ConstantRange CompRange(
3398 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003399
Dan Gohman161ea032009-07-07 17:06:11 +00003400 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedman459d7292009-05-09 12:32:42 +00003401 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003402 }
3403
3404 switch (Cond) {
3405 case ICmpInst::ICMP_NE: { // while (X != Y)
3406 // Convert to: while (X-Y != 0)
Dan Gohman161ea032009-07-07 17:06:11 +00003407 const SCEV *TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003408 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
3409 break;
3410 }
3411 case ICmpInst::ICMP_EQ: {
3412 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohman161ea032009-07-07 17:06:11 +00003413 const SCEV *TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003414 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
3415 break;
3416 }
3417 case ICmpInst::ICMP_SLT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003418 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
3419 if (BTI.hasAnyInfo()) return BTI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003420 break;
3421 }
3422 case ICmpInst::ICMP_SGT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003423 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3424 getNotSCEV(RHS), L, true);
3425 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyb7c28942007-08-06 19:21:00 +00003426 break;
3427 }
3428 case ICmpInst::ICMP_ULT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003429 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
3430 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyb7c28942007-08-06 19:21:00 +00003431 break;
3432 }
3433 case ICmpInst::ICMP_UGT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003434 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3435 getNotSCEV(RHS), L, false);
3436 if (BTI.hasAnyInfo()) return BTI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003437 break;
3438 }
3439 default:
3440#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00003441 errs() << "ComputeBackedgeTakenCount ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003442 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Dan Gohman13058cc2009-04-21 00:47:46 +00003443 errs() << "[unsigned] ";
3444 errs() << *LHS << " "
Dan Gohman9bc642f2009-06-24 04:48:43 +00003445 << Instruction::getOpcodeName(Instruction::ICmp)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003446 << " " << *RHS << "\n";
3447#endif
3448 break;
3449 }
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003450 return
Dan Gohman8e8b5232009-06-22 00:31:57 +00003451 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003452}
3453
3454static ConstantInt *
Dan Gohman89f85052007-10-22 18:31:58 +00003455EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
3456 ScalarEvolution &SE) {
Dan Gohman161ea032009-07-07 17:06:11 +00003457 const SCEV *InVal = SE.getConstant(C);
3458 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003459 assert(isa<SCEVConstant>(Val) &&
3460 "Evaluation of SCEV at constant didn't fold correctly?");
3461 return cast<SCEVConstant>(Val)->getValue();
3462}
3463
3464/// GetAddressedElementFromGlobal - Given a global variable with an initializer
3465/// and a GEP expression (missing the pointer index) indexing into it, return
3466/// the addressed element of the initializer or null if the index expression is
3467/// invalid.
3468static Constant *
Owen Anderson175b6542009-07-22 00:24:57 +00003469GetAddressedElementFromGlobal(LLVMContext &Context, GlobalVariable *GV,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003470 const std::vector<ConstantInt*> &Indices) {
3471 Constant *Init = GV->getInitializer();
3472 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
3473 uint64_t Idx = Indices[i]->getZExtValue();
3474 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
3475 assert(Idx < CS->getNumOperands() && "Bad struct index!");
3476 Init = cast<Constant>(CS->getOperand(Idx));
3477 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
3478 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
3479 Init = cast<Constant>(CA->getOperand(Idx));
3480 } else if (isa<ConstantAggregateZero>(Init)) {
3481 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
3482 assert(Idx < STy->getNumElements() && "Bad struct index!");
Owen Anderson175b6542009-07-22 00:24:57 +00003483 Init = Context.getNullValue(STy->getElementType(Idx));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003484 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
3485 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
Owen Anderson175b6542009-07-22 00:24:57 +00003486 Init = Context.getNullValue(ATy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003487 } else {
Edwin Törökbd448e32009-07-14 16:55:14 +00003488 llvm_unreachable("Unknown constant aggregate type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003489 }
3490 return 0;
3491 } else {
3492 return 0; // Unknown initializer type
3493 }
3494 }
3495 return Init;
3496}
3497
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003498/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
3499/// 'icmp op load X, cst', try to see if we can compute the backedge
3500/// execution count.
Dan Gohman9bc642f2009-06-24 04:48:43 +00003501const SCEV *
3502ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
3503 LoadInst *LI,
3504 Constant *RHS,
3505 const Loop *L,
3506 ICmpInst::Predicate predicate) {
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003507 if (LI->isVolatile()) return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003508
3509 // Check to see if the loaded pointer is a getelementptr of a global.
3510 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003511 if (!GEP) return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003512
3513 // Make sure that it is really a constant global we are gepping, with an
3514 // initializer, and make sure the first IDX is really 0.
3515 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
3516 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
3517 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
3518 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003519 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003520
3521 // Okay, we allow one non-constant index into the GEP instruction.
3522 Value *VarIdx = 0;
3523 std::vector<ConstantInt*> Indexes;
3524 unsigned VarIdxNum = 0;
3525 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
3526 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
3527 Indexes.push_back(CI);
3528 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003529 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003530 VarIdx = GEP->getOperand(i);
3531 VarIdxNum = i-2;
3532 Indexes.push_back(0);
3533 }
3534
3535 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
3536 // Check to see if X is a loop variant variable value now.
Dan Gohman161ea032009-07-07 17:06:11 +00003537 const SCEV *Idx = getSCEV(VarIdx);
Dan Gohmanaff14d62009-05-24 23:25:42 +00003538 Idx = getSCEVAtScope(Idx, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003539
3540 // We can only recognize very limited forms of loop index expressions, in
3541 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohmanbff6b582009-05-04 22:30:44 +00003542 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003543 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
3544 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
3545 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003546 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003547
3548 unsigned MaxSteps = MaxBruteForceIterations;
3549 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00003550 ConstantInt *ItCst = ConstantInt::get(
Owen Anderson9f5b2aa2009-07-14 23:09:55 +00003551 cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003552 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003553
3554 // Form the GEP offset.
3555 Indexes[VarIdxNum] = Val;
3556
Owen Anderson175b6542009-07-22 00:24:57 +00003557 Constant *Result = GetAddressedElementFromGlobal(getContext(), GV, Indexes);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003558 if (Result == 0) break; // Cannot compute!
3559
3560 // Evaluate the condition for this iteration.
3561 Result = ConstantExpr::getICmp(predicate, Result, RHS);
3562 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
3563 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
3564#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00003565 errs() << "\n***\n*** Computed loop count " << *ItCst
3566 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
3567 << "***\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003568#endif
3569 ++NumArrayLenItCounts;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003570 return getConstant(ItCst); // Found terminating iteration!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003571 }
3572 }
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003573 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003574}
3575
3576
3577/// CanConstantFold - Return true if we can constant fold an instruction of the
3578/// specified type, assuming that all operands were constants.
3579static bool CanConstantFold(const Instruction *I) {
3580 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
3581 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
3582 return true;
3583
3584 if (const CallInst *CI = dyn_cast<CallInst>(I))
3585 if (const Function *F = CI->getCalledFunction())
Dan Gohmane6e001f2008-01-31 01:05:10 +00003586 return canConstantFoldCallTo(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003587 return false;
3588}
3589
3590/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
3591/// in the loop that V is derived from. We allow arbitrary operations along the
3592/// way, but the operands of an operation must either be constants or a value
3593/// derived from a constant PHI. If this expression does not fit with these
3594/// constraints, return null.
3595static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
3596 // If this is not an instruction, or if this is an instruction outside of the
3597 // loop, it can't be derived from a loop PHI.
3598 Instruction *I = dyn_cast<Instruction>(V);
3599 if (I == 0 || !L->contains(I->getParent())) return 0;
3600
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00003601 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003602 if (L->getHeader() == I->getParent())
3603 return PN;
3604 else
3605 // We don't currently keep track of the control flow needed to evaluate
3606 // PHIs, so we cannot handle PHIs inside of loops.
3607 return 0;
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00003608 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003609
3610 // If we won't be able to constant fold this expression even if the operands
3611 // are constants, return early.
3612 if (!CanConstantFold(I)) return 0;
3613
3614 // Otherwise, we can evaluate this instruction if all of its operands are
3615 // constant or derived from a PHI node themselves.
3616 PHINode *PHI = 0;
3617 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
3618 if (!(isa<Constant>(I->getOperand(Op)) ||
3619 isa<GlobalValue>(I->getOperand(Op)))) {
3620 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
3621 if (P == 0) return 0; // Not evolving from PHI
3622 if (PHI == 0)
3623 PHI = P;
3624 else if (PHI != P)
3625 return 0; // Evolving from multiple different PHIs.
3626 }
3627
3628 // This is a expression evolving from a constant PHI!
3629 return PHI;
3630}
3631
3632/// EvaluateExpression - Given an expression that passes the
3633/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
3634/// in the loop has the value PHIVal. If we can't fold this expression for some
3635/// reason, return null.
3636static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
3637 if (isa<PHINode>(V)) return PHIVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003638 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman01c2ee72009-04-16 03:18:22 +00003639 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003640 Instruction *I = cast<Instruction>(V);
Owen Anderson175b6542009-07-22 00:24:57 +00003641 LLVMContext &Context = I->getParent()->getContext();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003642
3643 std::vector<Constant*> Operands;
3644 Operands.resize(I->getNumOperands());
3645
3646 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3647 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
3648 if (Operands[i] == 0) return 0;
3649 }
3650
Chris Lattnerd6e56912007-12-10 22:53:04 +00003651 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3652 return ConstantFoldCompareInstOperands(CI->getPredicate(),
Owen Andersond4d90a02009-07-06 18:42:36 +00003653 &Operands[0], Operands.size(),
3654 Context);
Chris Lattnerd6e56912007-12-10 22:53:04 +00003655 else
3656 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Owen Andersond4d90a02009-07-06 18:42:36 +00003657 &Operands[0], Operands.size(),
3658 Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003659}
3660
3661/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
3662/// in the header of its containing loop, we know the loop executes a
3663/// constant number of times, and the PHI node is just a recurrence
3664/// involving constants, fold it.
Dan Gohman9bc642f2009-06-24 04:48:43 +00003665Constant *
3666ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
3667 const APInt& BEs,
3668 const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003669 std::map<PHINode*, Constant*>::iterator I =
3670 ConstantEvolutionLoopExitValue.find(PN);
3671 if (I != ConstantEvolutionLoopExitValue.end())
3672 return I->second;
3673
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003674 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003675 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
3676
3677 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
3678
3679 // Since the loop is canonicalized, the PHI node must have two entries. One
3680 // entry must be a constant (coming in from outside of the loop), and the
3681 // second must be derived from the same PHI.
3682 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3683 Constant *StartCST =
3684 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
3685 if (StartCST == 0)
3686 return RetVal = 0; // Must be a constant.
3687
3688 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3689 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
3690 if (PN2 != PN)
3691 return RetVal = 0; // Not derived from same PHI.
3692
3693 // Execute the loop symbolically to determine the exit value.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003694 if (BEs.getActiveBits() >= 32)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003695 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
3696
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003697 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003698 unsigned IterationNum = 0;
3699 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
3700 if (IterationNum == NumIterations)
3701 return RetVal = PHIVal; // Got exit value!
3702
3703 // Compute the value of the PHI node for the next iteration.
3704 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3705 if (NextPHI == PHIVal)
3706 return RetVal = NextPHI; // Stopped evolving!
3707 if (NextPHI == 0)
3708 return 0; // Couldn't evaluate!
3709 PHIVal = NextPHI;
3710 }
3711}
3712
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003713/// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003714/// constant number of times (the condition evolves only from constants),
3715/// try to evaluate a few iterations of the loop until we get the exit
3716/// condition gets a value of ExitWhen (true or false). If we cannot
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003717/// evaluate the trip count of the loop, return getCouldNotCompute().
Dan Gohman9bc642f2009-06-24 04:48:43 +00003718const SCEV *
3719ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
3720 Value *Cond,
3721 bool ExitWhen) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003722 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003723 if (PN == 0) return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003724
3725 // Since the loop is canonicalized, the PHI node must have two entries. One
3726 // entry must be a constant (coming in from outside of the loop), and the
3727 // second must be derived from the same PHI.
3728 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3729 Constant *StartCST =
3730 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003731 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003732
3733 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3734 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003735 if (PN2 != PN) return getCouldNotCompute(); // Not derived from same PHI.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003736
3737 // Okay, we find a PHI node that defines the trip count of this loop. Execute
3738 // the loop symbolically to determine when the condition gets a value of
3739 // "ExitWhen".
3740 unsigned IterationNum = 0;
3741 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
3742 for (Constant *PHIVal = StartCST;
3743 IterationNum != MaxIterations; ++IterationNum) {
3744 ConstantInt *CondVal =
3745 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
3746
3747 // Couldn't symbolically evaluate.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003748 if (!CondVal) return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003749
3750 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003751 ++NumBruteForceTripCountsComputed;
Dan Gohman8fd520a2009-06-15 22:12:54 +00003752 return getConstant(Type::Int32Ty, IterationNum);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003753 }
3754
3755 // Compute the value of the PHI node for the next iteration.
3756 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3757 if (NextPHI == 0 || NextPHI == PHIVal)
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003758 return getCouldNotCompute();// Couldn't evaluate or not making progress...
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003759 PHIVal = NextPHI;
3760 }
3761
3762 // Too many iterations were needed to evaluate.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003763 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003764}
3765
Dan Gohmandd40e9a2009-05-08 20:38:54 +00003766/// getSCEVAtScope - Return a SCEV expression handle for the specified value
3767/// at the specified scope in the program. The L value specifies a loop
3768/// nest to evaluate the expression at, where null is the top-level or a
3769/// specified loop is immediately inside of the loop.
3770///
3771/// This method can be used to compute the exit value for a variable defined
3772/// in a loop by querying what the value will hold in the parent loop.
3773///
Dan Gohmanaff14d62009-05-24 23:25:42 +00003774/// In the case that a relevant loop exit value cannot be computed, the
3775/// original value V is returned.
Dan Gohman161ea032009-07-07 17:06:11 +00003776const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003777 // FIXME: this should be turned into a virtual method on SCEV!
3778
3779 if (isa<SCEVConstant>(V)) return V;
3780
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00003781 // If this instruction is evolved from a constant-evolving PHI, compute the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003782 // exit value from the loop without using SCEVs.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003783 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003784 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003785 const Loop *LI = (*this->LI)[I->getParent()];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003786 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
3787 if (PHINode *PN = dyn_cast<PHINode>(I))
3788 if (PN->getParent() == LI->getHeader()) {
3789 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003790 // to see if the loop that contains it has a known backedge-taken
3791 // count. If so, we may be able to force computation of the exit
3792 // value.
Dan Gohman161ea032009-07-07 17:06:11 +00003793 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohmanc76b5452009-05-04 22:02:23 +00003794 if (const SCEVConstant *BTCC =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003795 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003796 // Okay, we know how many times the containing loop executes. If
3797 // this is a constant evolving PHI node, get the final value at
3798 // the specified iteration number.
3799 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003800 BTCC->getValue()->getValue(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003801 LI);
Dan Gohman652caf12009-06-29 21:31:18 +00003802 if (RV) return getSCEV(RV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003803 }
3804 }
3805
3806 // Okay, this is an expression that we cannot symbolically evaluate
3807 // into a SCEV. Check to see if it's possible to symbolically evaluate
3808 // the arguments into constants, and if so, try to constant propagate the
3809 // result. This is particularly useful for computing loop exit values.
3810 if (CanConstantFold(I)) {
Dan Gohmanda0071e2009-05-08 20:47:27 +00003811 // Check to see if we've folded this instruction at this loop before.
3812 std::map<const Loop *, Constant *> &Values = ValuesAtScopes[I];
3813 std::pair<std::map<const Loop *, Constant *>::iterator, bool> Pair =
3814 Values.insert(std::make_pair(L, static_cast<Constant *>(0)));
3815 if (!Pair.second)
Dan Gohman652caf12009-06-29 21:31:18 +00003816 return Pair.first->second ? &*getSCEV(Pair.first->second) : V;
Dan Gohmanda0071e2009-05-08 20:47:27 +00003817
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003818 std::vector<Constant*> Operands;
3819 Operands.reserve(I->getNumOperands());
3820 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3821 Value *Op = I->getOperand(i);
3822 if (Constant *C = dyn_cast<Constant>(Op)) {
3823 Operands.push_back(C);
3824 } else {
Chris Lattner3fff4642007-11-23 08:46:22 +00003825 // If any of the operands is non-constant and if they are
Dan Gohman01c2ee72009-04-16 03:18:22 +00003826 // non-integer and non-pointer, don't even try to analyze them
3827 // with scev techniques.
Dan Gohman5e4eb762009-04-30 16:40:30 +00003828 if (!isSCEVable(Op->getType()))
Chris Lattner3fff4642007-11-23 08:46:22 +00003829 return V;
Dan Gohman01c2ee72009-04-16 03:18:22 +00003830
Dan Gohman55e2d7e2009-07-13 21:35:55 +00003831 const SCEV* OpV = getSCEVAtScope(Op, L);
Dan Gohmanc76b5452009-05-04 22:02:23 +00003832 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
Dan Gohman5e4eb762009-04-30 16:40:30 +00003833 Constant *C = SC->getValue();
3834 if (C->getType() != Op->getType())
3835 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3836 Op->getType(),
3837 false),
3838 C, Op->getType());
3839 Operands.push_back(C);
Dan Gohmanc76b5452009-05-04 22:02:23 +00003840 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
Dan Gohman5e4eb762009-04-30 16:40:30 +00003841 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
3842 if (C->getType() != Op->getType())
3843 C =
3844 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3845 Op->getType(),
3846 false),
3847 C, Op->getType());
3848 Operands.push_back(C);
3849 } else
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003850 return V;
3851 } else {
3852 return V;
3853 }
3854 }
3855 }
Dan Gohman9bc642f2009-06-24 04:48:43 +00003856
Chris Lattnerd6e56912007-12-10 22:53:04 +00003857 Constant *C;
3858 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3859 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
Owen Andersond4d90a02009-07-06 18:42:36 +00003860 &Operands[0], Operands.size(),
Owen Anderson175b6542009-07-22 00:24:57 +00003861 getContext());
Chris Lattnerd6e56912007-12-10 22:53:04 +00003862 else
3863 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Owen Anderson175b6542009-07-22 00:24:57 +00003864 &Operands[0], Operands.size(),
3865 getContext());
Dan Gohmanda0071e2009-05-08 20:47:27 +00003866 Pair.first->second = C;
Dan Gohman652caf12009-06-29 21:31:18 +00003867 return getSCEV(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003868 }
3869 }
3870
3871 // This is some other type of SCEVUnknown, just return it.
3872 return V;
3873 }
3874
Dan Gohmanc76b5452009-05-04 22:02:23 +00003875 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003876 // Avoid performing the look-up in the common case where the specified
3877 // expression has no loop-variant portions.
3878 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Dan Gohman161ea032009-07-07 17:06:11 +00003879 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003880 if (OpAtScope != Comm->getOperand(i)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003881 // Okay, at least one of these operands is loop variant but might be
3882 // foldable. Build a new instance of the folded commutative expression.
Dan Gohman9bc642f2009-06-24 04:48:43 +00003883 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
3884 Comm->op_begin()+i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003885 NewOps.push_back(OpAtScope);
3886
3887 for (++i; i != e; ++i) {
3888 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003889 NewOps.push_back(OpAtScope);
3890 }
3891 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003892 return getAddExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00003893 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003894 return getMulExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00003895 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003896 return getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00003897 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003898 return getUMaxExpr(NewOps);
Edwin Törökbd448e32009-07-14 16:55:14 +00003899 llvm_unreachable("Unknown commutative SCEV type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003900 }
3901 }
3902 // If we got here, all operands are loop invariant.
3903 return Comm;
3904 }
3905
Dan Gohmanc76b5452009-05-04 22:02:23 +00003906 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Dan Gohman161ea032009-07-07 17:06:11 +00003907 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
3908 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky35b56022009-01-13 09:18:58 +00003909 if (LHS == Div->getLHS() && RHS == Div->getRHS())
3910 return Div; // must be loop invariant
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003911 return getUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003912 }
3913
3914 // If this is a loop recurrence for a loop that does not contain L, then we
3915 // are dealing with the final value computed by the loop.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003916 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003917 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
3918 // To evaluate this recurrence, we need to know how many times the AddRec
3919 // loop iterates. Compute this now.
Dan Gohman161ea032009-07-07 17:06:11 +00003920 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc6475cb2009-06-27 21:21:31 +00003921 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003922
Eli Friedman7489ec92008-08-04 23:49:06 +00003923 // Then, evaluate the AddRec.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003924 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003925 }
Dan Gohmanaff14d62009-05-24 23:25:42 +00003926 return AddRec;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003927 }
3928
Dan Gohmanc76b5452009-05-04 22:02:23 +00003929 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohman161ea032009-07-07 17:06:11 +00003930 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman78d63c82009-04-29 22:29:01 +00003931 if (Op == Cast->getOperand())
3932 return Cast; // must be loop invariant
3933 return getZeroExtendExpr(Op, Cast->getType());
3934 }
3935
Dan Gohmanc76b5452009-05-04 22:02:23 +00003936 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohman161ea032009-07-07 17:06:11 +00003937 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman78d63c82009-04-29 22:29:01 +00003938 if (Op == Cast->getOperand())
3939 return Cast; // must be loop invariant
3940 return getSignExtendExpr(Op, Cast->getType());
3941 }
3942
Dan Gohmanc76b5452009-05-04 22:02:23 +00003943 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohman161ea032009-07-07 17:06:11 +00003944 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman78d63c82009-04-29 22:29:01 +00003945 if (Op == Cast->getOperand())
3946 return Cast; // must be loop invariant
3947 return getTruncateExpr(Op, Cast->getType());
3948 }
3949
Edwin Törökbd448e32009-07-14 16:55:14 +00003950 llvm_unreachable("Unknown SCEV type!");
Daniel Dunbara95d96c2009-05-18 16:43:04 +00003951 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003952}
3953
Dan Gohmandd40e9a2009-05-08 20:38:54 +00003954/// getSCEVAtScope - This is a convenience function which does
3955/// getSCEVAtScope(getSCEV(V), L).
Dan Gohman161ea032009-07-07 17:06:11 +00003956const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003957 return getSCEVAtScope(getSCEV(V), L);
3958}
3959
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003960/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
3961/// following equation:
3962///
3963/// A * X = B (mod N)
3964///
3965/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
3966/// A and B isn't important.
3967///
3968/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Dan Gohman161ea032009-07-07 17:06:11 +00003969static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003970 ScalarEvolution &SE) {
3971 uint32_t BW = A.getBitWidth();
3972 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
3973 assert(A != 0 && "A must be non-zero.");
3974
3975 // 1. D = gcd(A, N)
3976 //
3977 // The gcd of A and N may have only one prime factor: 2. The number of
3978 // trailing zeros in A is its multiplicity
3979 uint32_t Mult2 = A.countTrailingZeros();
3980 // D = 2^Mult2
3981
3982 // 2. Check if B is divisible by D.
3983 //
3984 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
3985 // is not less than multiplicity of this prime factor for D.
3986 if (B.countTrailingZeros() < Mult2)
Dan Gohman0ad08b02009-04-18 17:58:19 +00003987 return SE.getCouldNotCompute();
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003988
3989 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
3990 // modulo (N / D).
3991 //
3992 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
3993 // bit width during computations.
3994 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
3995 APInt Mod(BW + 1, 0);
3996 Mod.set(BW - Mult2); // Mod = N / D
3997 APInt I = AD.multiplicativeInverse(Mod);
3998
3999 // 4. Compute the minimum unsigned root of the equation:
4000 // I * (B / D) mod (N / D)
4001 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
4002
4003 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
4004 // bits.
4005 return SE.getConstant(Result.trunc(BW));
4006}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004007
4008/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
4009/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
4010/// might be the same) or two SCEVCouldNotCompute objects.
4011///
Dan Gohman161ea032009-07-07 17:06:11 +00004012static std::pair<const SCEV *,const SCEV *>
Dan Gohman89f85052007-10-22 18:31:58 +00004013SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004014 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohmanbff6b582009-05-04 22:30:44 +00004015 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
4016 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
4017 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004018
4019 // We currently can only solve this if the coefficients are constants.
4020 if (!LC || !MC || !NC) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00004021 const SCEV *CNC = SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004022 return std::make_pair(CNC, CNC);
4023 }
4024
4025 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
4026 const APInt &L = LC->getValue()->getValue();
4027 const APInt &M = MC->getValue()->getValue();
4028 const APInt &N = NC->getValue()->getValue();
4029 APInt Two(BitWidth, 2);
4030 APInt Four(BitWidth, 4);
4031
Dan Gohman9bc642f2009-06-24 04:48:43 +00004032 {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004033 using namespace APIntOps;
4034 const APInt& C = L;
4035 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
4036 // The B coefficient is M-N/2
4037 APInt B(M);
4038 B -= sdiv(N,Two);
4039
4040 // The A coefficient is N/2
4041 APInt A(N.sdiv(Two));
4042
4043 // Compute the B^2-4ac term.
4044 APInt SqrtTerm(B);
4045 SqrtTerm *= B;
4046 SqrtTerm -= Four * (A * C);
4047
4048 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
4049 // integer value or else APInt::sqrt() will assert.
4050 APInt SqrtVal(SqrtTerm.sqrt());
4051
Dan Gohman9bc642f2009-06-24 04:48:43 +00004052 // Compute the two solutions for the quadratic formula.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004053 // The divisions must be performed as signed divisions.
4054 APInt NegB(-B);
4055 APInt TwoA( A << 1 );
Nick Lewycky35776692008-11-03 02:43:49 +00004056 if (TwoA.isMinValue()) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00004057 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky35776692008-11-03 02:43:49 +00004058 return std::make_pair(CNC, CNC);
4059 }
4060
Owen Anderson175b6542009-07-22 00:24:57 +00004061 LLVMContext &Context = SE.getContext();
Owen Andersone755b092009-07-06 22:37:39 +00004062
4063 ConstantInt *Solution1 =
Owen Andersoneacb44d2009-07-24 23:12:02 +00004064 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
Owen Andersone755b092009-07-06 22:37:39 +00004065 ConstantInt *Solution2 =
Owen Andersoneacb44d2009-07-24 23:12:02 +00004066 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004067
Dan Gohman9bc642f2009-06-24 04:48:43 +00004068 return std::make_pair(SE.getConstant(Solution1),
Dan Gohman89f85052007-10-22 18:31:58 +00004069 SE.getConstant(Solution2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004070 } // end APIntOps namespace
4071}
4072
4073/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman0c850912009-06-06 14:37:11 +00004074/// value to zero will execute. If not computable, return CouldNotCompute.
Dan Gohman161ea032009-07-07 17:06:11 +00004075const SCEV *ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004076 // If the value is a constant
Dan Gohmanc76b5452009-05-04 22:02:23 +00004077 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004078 // If the value is already zero, the branch will execute zero times.
4079 if (C->getValue()->isZero()) return C;
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004080 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004081 }
4082
Dan Gohmanbff6b582009-05-04 22:30:44 +00004083 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004084 if (!AddRec || AddRec->getLoop() != L)
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004085 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004086
4087 if (AddRec->isAffine()) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00004088 // If this is an affine expression, the execution count of this branch is
4089 // the minimum unsigned root of the following equation:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004090 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00004091 // Start + Step*N = 0 (mod 2^BW)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004092 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00004093 // equivalent to:
4094 //
4095 // Step*N = -Start (mod 2^BW)
4096 //
4097 // where BW is the common bit width of Start and Step.
4098
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004099 // Get the initial value for the loop.
Dan Gohman9bc642f2009-06-24 04:48:43 +00004100 const SCEV *Start = getSCEVAtScope(AddRec->getStart(),
4101 L->getParentLoop());
4102 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1),
4103 L->getParentLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004104
Dan Gohmanc76b5452009-05-04 22:02:23 +00004105 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00004106 // For now we handle only constant steps.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004107
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00004108 // First, handle unitary steps.
4109 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004110 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00004111 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
4112 return Start; // N = Start (as unsigned)
4113
4114 // Then, try to solve the above equation provided that Start is constant.
Dan Gohmanc76b5452009-05-04 22:02:23 +00004115 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00004116 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004117 -StartC->getValue()->getValue(),
4118 *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004119 }
4120 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
4121 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
4122 // the quadratic equation to solve it.
Dan Gohman161ea032009-07-07 17:06:11 +00004123 std::pair<const SCEV *,const SCEV *> Roots = SolveQuadraticEquation(AddRec,
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004124 *this);
Dan Gohmanbff6b582009-05-04 22:30:44 +00004125 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4126 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004127 if (R1) {
4128#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00004129 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
4130 << " sol#2: " << *R2 << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004131#endif
4132 // Pick the smallest positive root value.
4133 if (ConstantInt *CB =
Owen Anderson175b6542009-07-22 00:24:57 +00004134 dyn_cast<ConstantInt>(getContext().getConstantExprICmp(ICmpInst::ICMP_ULT,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004135 R1->getValue(), R2->getValue()))) {
4136 if (CB->getZExtValue() == false)
4137 std::swap(R1, R2); // R1 is the minimum root now.
4138
4139 // We can only use this value if the chrec ends up with an exact zero
4140 // value at this index. When solving for "X*X != 5", for example, we
4141 // should not accept a root of 2.
Dan Gohman161ea032009-07-07 17:06:11 +00004142 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohman7b560c42008-06-18 16:23:07 +00004143 if (Val->isZero())
4144 return R1; // We found a quadratic root!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004145 }
4146 }
4147 }
4148
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004149 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004150}
4151
4152/// HowFarToNonZero - Return the number of times a backedge checking the
4153/// specified value for nonzero will execute. If not computable, return
Dan Gohman0c850912009-06-06 14:37:11 +00004154/// CouldNotCompute
Dan Gohman161ea032009-07-07 17:06:11 +00004155const SCEV *ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004156 // Loops that look like: while (X == 0) are very strange indeed. We don't
4157 // handle them yet except for the trivial case. This could be expanded in the
4158 // future as needed.
4159
4160 // If the value is a constant, check to see if it is known to be non-zero
4161 // already. If so, the backedge will execute zero times.
Dan Gohmanc76b5452009-05-04 22:02:23 +00004162 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewyckyf6805182008-02-21 09:14:53 +00004163 if (!C->getValue()->isNullValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004164 return getIntegerSCEV(0, C->getType());
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004165 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004166 }
4167
4168 // We could implement others, but I really doubt anyone writes loops like
4169 // this, and if they did, they would already be constant folded.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004170 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004171}
4172
Dan Gohmanab157b22009-05-18 15:36:09 +00004173/// getLoopPredecessor - If the given loop's header has exactly one unique
4174/// predecessor outside the loop, return it. Otherwise return null.
4175///
4176BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) {
4177 BasicBlock *Header = L->getHeader();
4178 BasicBlock *Pred = 0;
4179 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header);
4180 PI != E; ++PI)
4181 if (!L->contains(*PI)) {
4182 if (Pred && Pred != *PI) return 0; // Multiple predecessors.
4183 Pred = *PI;
4184 }
4185 return Pred;
4186}
4187
Dan Gohman1cddf972008-09-15 22:18:04 +00004188/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
4189/// (which may not be an immediate predecessor) which has exactly one
4190/// successor from which BB is reachable, or null if no such block is
4191/// found.
4192///
4193BasicBlock *
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004194ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman1116ea72009-04-30 20:48:53 +00004195 // If the block has a unique predecessor, then there is no path from the
4196 // predecessor to the block that does not go through the direct edge
4197 // from the predecessor to the block.
Dan Gohman1cddf972008-09-15 22:18:04 +00004198 if (BasicBlock *Pred = BB->getSinglePredecessor())
4199 return Pred;
4200
4201 // A loop's header is defined to be a block that dominates the loop.
Dan Gohmanab157b22009-05-18 15:36:09 +00004202 // If the header has a unique predecessor outside the loop, it must be
4203 // a block that has exactly one successor that can reach the loop.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004204 if (Loop *L = LI->getLoopFor(BB))
Dan Gohmanab157b22009-05-18 15:36:09 +00004205 return getLoopPredecessor(L);
Dan Gohman1cddf972008-09-15 22:18:04 +00004206
4207 return 0;
4208}
4209
Dan Gohmanbc1e3472009-06-20 00:35:32 +00004210/// HasSameValue - SCEV structural equivalence is usually sufficient for
4211/// testing whether two expressions are equal, however for the purposes of
4212/// looking for a condition guarding a loop, it can be useful to be a little
4213/// more general, since a front-end may have replicated the controlling
4214/// expression.
4215///
Dan Gohman161ea032009-07-07 17:06:11 +00004216static bool HasSameValue(const SCEV *A, const SCEV *B) {
Dan Gohmanbc1e3472009-06-20 00:35:32 +00004217 // Quick check to see if they are the same SCEV.
4218 if (A == B) return true;
4219
4220 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
4221 // two different instructions with the same value. Check for this case.
4222 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
4223 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
4224 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
4225 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
4226 if (AI->isIdenticalTo(BI))
4227 return true;
4228
4229 // Otherwise assume they may have a different value.
4230 return false;
4231}
4232
Dan Gohman55e2d7e2009-07-13 21:35:55 +00004233bool ScalarEvolution::isKnownNegative(const SCEV *S) {
4234 return getSignedRange(S).getSignedMax().isNegative();
4235}
4236
4237bool ScalarEvolution::isKnownPositive(const SCEV *S) {
4238 return getSignedRange(S).getSignedMin().isStrictlyPositive();
4239}
4240
4241bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
4242 return !getSignedRange(S).getSignedMin().isNegative();
4243}
4244
4245bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
4246 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
4247}
4248
4249bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
4250 return isKnownNegative(S) || isKnownPositive(S);
4251}
4252
4253bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
4254 const SCEV *LHS, const SCEV *RHS) {
4255
4256 if (HasSameValue(LHS, RHS))
4257 return ICmpInst::isTrueWhenEqual(Pred);
4258
4259 switch (Pred) {
4260 default:
Dan Gohman2d4f5b12009-07-16 17:34:36 +00004261 llvm_unreachable("Unexpected ICmpInst::Predicate value!");
Dan Gohman55e2d7e2009-07-13 21:35:55 +00004262 break;
4263 case ICmpInst::ICMP_SGT:
4264 Pred = ICmpInst::ICMP_SLT;
4265 std::swap(LHS, RHS);
4266 case ICmpInst::ICMP_SLT: {
4267 ConstantRange LHSRange = getSignedRange(LHS);
4268 ConstantRange RHSRange = getSignedRange(RHS);
4269 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
4270 return true;
4271 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
4272 return false;
Dan Gohman55e2d7e2009-07-13 21:35:55 +00004273 break;
4274 }
4275 case ICmpInst::ICMP_SGE:
4276 Pred = ICmpInst::ICMP_SLE;
4277 std::swap(LHS, RHS);
4278 case ICmpInst::ICMP_SLE: {
4279 ConstantRange LHSRange = getSignedRange(LHS);
4280 ConstantRange RHSRange = getSignedRange(RHS);
4281 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
4282 return true;
4283 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
4284 return false;
Dan Gohman55e2d7e2009-07-13 21:35:55 +00004285 break;
4286 }
4287 case ICmpInst::ICMP_UGT:
4288 Pred = ICmpInst::ICMP_ULT;
4289 std::swap(LHS, RHS);
4290 case ICmpInst::ICMP_ULT: {
4291 ConstantRange LHSRange = getUnsignedRange(LHS);
4292 ConstantRange RHSRange = getUnsignedRange(RHS);
4293 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
4294 return true;
4295 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
4296 return false;
Dan Gohman55e2d7e2009-07-13 21:35:55 +00004297 break;
4298 }
4299 case ICmpInst::ICMP_UGE:
4300 Pred = ICmpInst::ICMP_ULE;
4301 std::swap(LHS, RHS);
4302 case ICmpInst::ICMP_ULE: {
4303 ConstantRange LHSRange = getUnsignedRange(LHS);
4304 ConstantRange RHSRange = getUnsignedRange(RHS);
4305 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
4306 return true;
4307 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
4308 return false;
Dan Gohman55e2d7e2009-07-13 21:35:55 +00004309 break;
4310 }
4311 case ICmpInst::ICMP_NE: {
4312 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
4313 return true;
4314 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
4315 return true;
4316
4317 const SCEV *Diff = getMinusSCEV(LHS, RHS);
4318 if (isKnownNonZero(Diff))
4319 return true;
4320 break;
4321 }
4322 case ICmpInst::ICMP_EQ:
Dan Gohman44e675f2009-07-20 23:54:43 +00004323 // The check at the top of the function catches the case where
4324 // the values are known to be equal.
Dan Gohman55e2d7e2009-07-13 21:35:55 +00004325 break;
4326 }
4327 return false;
4328}
4329
4330/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
4331/// protected by a conditional between LHS and RHS. This is used to
4332/// to eliminate casts.
4333bool
4334ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
4335 ICmpInst::Predicate Pred,
4336 const SCEV *LHS, const SCEV *RHS) {
4337 // Interpret a null as meaning no loop, where there is obviously no guard
4338 // (interprocedural conditions notwithstanding).
4339 if (!L) return true;
4340
4341 BasicBlock *Latch = L->getLoopLatch();
4342 if (!Latch)
4343 return false;
4344
4345 BranchInst *LoopContinuePredicate =
4346 dyn_cast<BranchInst>(Latch->getTerminator());
4347 if (!LoopContinuePredicate ||
4348 LoopContinuePredicate->isUnconditional())
4349 return false;
4350
Dan Gohman920446d2009-07-21 23:03:19 +00004351 return isImpliedCond(LoopContinuePredicate->getCondition(), Pred, LHS, RHS,
4352 LoopContinuePredicate->getSuccessor(0) != L->getHeader());
Dan Gohman55e2d7e2009-07-13 21:35:55 +00004353}
4354
4355/// isLoopGuardedByCond - Test whether entry to the loop is protected
4356/// by a conditional between LHS and RHS. This is used to help avoid max
4357/// expressions in loop trip counts, and to eliminate casts.
4358bool
4359ScalarEvolution::isLoopGuardedByCond(const Loop *L,
4360 ICmpInst::Predicate Pred,
4361 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman8b938182009-05-18 16:03:58 +00004362 // Interpret a null as meaning no loop, where there is obviously no guard
4363 // (interprocedural conditions notwithstanding).
4364 if (!L) return false;
4365
Dan Gohmanab157b22009-05-18 15:36:09 +00004366 BasicBlock *Predecessor = getLoopPredecessor(L);
4367 BasicBlock *PredecessorDest = L->getHeader();
Nick Lewycky1b020bf2008-07-12 07:41:32 +00004368
Dan Gohmanab157b22009-05-18 15:36:09 +00004369 // Starting at the loop predecessor, climb up the predecessor chain, as long
4370 // as there are predecessors that can be found that have unique successors
Dan Gohman1cddf972008-09-15 22:18:04 +00004371 // leading to the original header.
Dan Gohmanab157b22009-05-18 15:36:09 +00004372 for (; Predecessor;
4373 PredecessorDest = Predecessor,
4374 Predecessor = getPredecessorWithUniqueSuccessorForBB(Predecessor)) {
Dan Gohmanab678fb2008-08-12 20:17:31 +00004375
4376 BranchInst *LoopEntryPredicate =
Dan Gohmanab157b22009-05-18 15:36:09 +00004377 dyn_cast<BranchInst>(Predecessor->getTerminator());
Dan Gohmanab678fb2008-08-12 20:17:31 +00004378 if (!LoopEntryPredicate ||
4379 LoopEntryPredicate->isUnconditional())
4380 continue;
4381
Dan Gohman920446d2009-07-21 23:03:19 +00004382 if (isImpliedCond(LoopEntryPredicate->getCondition(), Pred, LHS, RHS,
4383 LoopEntryPredicate->getSuccessor(0) != PredecessorDest))
Dan Gohmanab678fb2008-08-12 20:17:31 +00004384 return true;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00004385 }
4386
Dan Gohmanab678fb2008-08-12 20:17:31 +00004387 return false;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00004388}
4389
Dan Gohman920446d2009-07-21 23:03:19 +00004390/// isImpliedCond - Test whether the condition described by Pred, LHS,
4391/// and RHS is true whenever the given Cond value evaluates to true.
4392bool ScalarEvolution::isImpliedCond(Value *CondValue,
4393 ICmpInst::Predicate Pred,
4394 const SCEV *LHS, const SCEV *RHS,
4395 bool Inverse) {
Dan Gohman423ed6c2009-06-24 01:18:18 +00004396 // Recursivly handle And and Or conditions.
4397 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CondValue)) {
4398 if (BO->getOpcode() == Instruction::And) {
4399 if (!Inverse)
Dan Gohman920446d2009-07-21 23:03:19 +00004400 return isImpliedCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4401 isImpliedCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
Dan Gohman423ed6c2009-06-24 01:18:18 +00004402 } else if (BO->getOpcode() == Instruction::Or) {
4403 if (Inverse)
Dan Gohman920446d2009-07-21 23:03:19 +00004404 return isImpliedCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4405 isImpliedCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
Dan Gohman423ed6c2009-06-24 01:18:18 +00004406 }
4407 }
4408
4409 ICmpInst *ICI = dyn_cast<ICmpInst>(CondValue);
4410 if (!ICI) return false;
4411
Dan Gohman55e2d7e2009-07-13 21:35:55 +00004412 // Bail if the ICmp's operands' types are wider than the needed type
4413 // before attempting to call getSCEV on them. This avoids infinite
4414 // recursion, since the analysis of widening casts can require loop
4415 // exit condition information for overflow checking, which would
4416 // lead back here.
4417 if (getTypeSizeInBits(LHS->getType()) <
Dan Gohman920446d2009-07-21 23:03:19 +00004418 getTypeSizeInBits(ICI->getOperand(0)->getType()))
Dan Gohman55e2d7e2009-07-13 21:35:55 +00004419 return false;
4420
Dan Gohman920446d2009-07-21 23:03:19 +00004421 // Now that we found a conditional branch that dominates the loop, check to
4422 // see if it is the comparison we are looking for.
4423 ICmpInst::Predicate FoundPred;
4424 if (Inverse)
4425 FoundPred = ICI->getInversePredicate();
4426 else
4427 FoundPred = ICI->getPredicate();
4428
4429 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
4430 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
Dan Gohman55e2d7e2009-07-13 21:35:55 +00004431
4432 // Balance the types. The case where FoundLHS' type is wider than
4433 // LHS' type is checked for above.
4434 if (getTypeSizeInBits(LHS->getType()) >
4435 getTypeSizeInBits(FoundLHS->getType())) {
4436 if (CmpInst::isSigned(Pred)) {
4437 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
4438 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
4439 } else {
4440 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
4441 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
4442 }
4443 }
4444
Dan Gohman920446d2009-07-21 23:03:19 +00004445 // Canonicalize the query to match the way instcombine will have
4446 // canonicalized the comparison.
4447 // First, put a constant operand on the right.
4448 if (isa<SCEVConstant>(LHS)) {
4449 std::swap(LHS, RHS);
4450 Pred = ICmpInst::getSwappedPredicate(Pred);
4451 }
4452 // Then, canonicalize comparisons with boundary cases.
4453 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
4454 const APInt &RA = RC->getValue()->getValue();
4455 switch (Pred) {
4456 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4457 case ICmpInst::ICMP_EQ:
4458 case ICmpInst::ICMP_NE:
4459 break;
4460 case ICmpInst::ICMP_UGE:
4461 if ((RA - 1).isMinValue()) {
4462 Pred = ICmpInst::ICMP_NE;
4463 RHS = getConstant(RA - 1);
4464 break;
4465 }
4466 if (RA.isMaxValue()) {
4467 Pred = ICmpInst::ICMP_EQ;
4468 break;
4469 }
4470 if (RA.isMinValue()) return true;
4471 break;
4472 case ICmpInst::ICMP_ULE:
4473 if ((RA + 1).isMaxValue()) {
4474 Pred = ICmpInst::ICMP_NE;
4475 RHS = getConstant(RA + 1);
4476 break;
4477 }
4478 if (RA.isMinValue()) {
4479 Pred = ICmpInst::ICMP_EQ;
4480 break;
4481 }
4482 if (RA.isMaxValue()) return true;
4483 break;
4484 case ICmpInst::ICMP_SGE:
4485 if ((RA - 1).isMinSignedValue()) {
4486 Pred = ICmpInst::ICMP_NE;
4487 RHS = getConstant(RA - 1);
4488 break;
4489 }
4490 if (RA.isMaxSignedValue()) {
4491 Pred = ICmpInst::ICMP_EQ;
4492 break;
4493 }
4494 if (RA.isMinSignedValue()) return true;
4495 break;
4496 case ICmpInst::ICMP_SLE:
4497 if ((RA + 1).isMaxSignedValue()) {
4498 Pred = ICmpInst::ICMP_NE;
4499 RHS = getConstant(RA + 1);
4500 break;
4501 }
4502 if (RA.isMinSignedValue()) {
4503 Pred = ICmpInst::ICMP_EQ;
4504 break;
4505 }
4506 if (RA.isMaxSignedValue()) return true;
4507 break;
4508 case ICmpInst::ICMP_UGT:
4509 if (RA.isMinValue()) {
4510 Pred = ICmpInst::ICMP_NE;
4511 break;
4512 }
4513 if ((RA + 1).isMaxValue()) {
4514 Pred = ICmpInst::ICMP_EQ;
4515 RHS = getConstant(RA + 1);
4516 break;
4517 }
4518 if (RA.isMaxValue()) return false;
4519 break;
4520 case ICmpInst::ICMP_ULT:
4521 if (RA.isMaxValue()) {
4522 Pred = ICmpInst::ICMP_NE;
4523 break;
4524 }
4525 if ((RA - 1).isMinValue()) {
4526 Pred = ICmpInst::ICMP_EQ;
4527 RHS = getConstant(RA - 1);
4528 break;
4529 }
4530 if (RA.isMinValue()) return false;
4531 break;
4532 case ICmpInst::ICMP_SGT:
4533 if (RA.isMinSignedValue()) {
4534 Pred = ICmpInst::ICMP_NE;
4535 break;
4536 }
4537 if ((RA + 1).isMaxSignedValue()) {
4538 Pred = ICmpInst::ICMP_EQ;
4539 RHS = getConstant(RA + 1);
4540 break;
4541 }
4542 if (RA.isMaxSignedValue()) return false;
4543 break;
4544 case ICmpInst::ICMP_SLT:
4545 if (RA.isMaxSignedValue()) {
4546 Pred = ICmpInst::ICMP_NE;
4547 break;
4548 }
4549 if ((RA - 1).isMinSignedValue()) {
4550 Pred = ICmpInst::ICMP_EQ;
4551 RHS = getConstant(RA - 1);
4552 break;
4553 }
4554 if (RA.isMinSignedValue()) return false;
4555 break;
4556 }
4557 }
4558
4559 // Check to see if we can make the LHS or RHS match.
4560 if (LHS == FoundRHS || RHS == FoundLHS) {
4561 if (isa<SCEVConstant>(RHS)) {
4562 std::swap(FoundLHS, FoundRHS);
4563 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
4564 } else {
4565 std::swap(LHS, RHS);
4566 Pred = ICmpInst::getSwappedPredicate(Pred);
4567 }
4568 }
4569
4570 // Check whether the found predicate is the same as the desired predicate.
4571 if (FoundPred == Pred)
4572 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
4573
4574 // Check whether swapping the found predicate makes it the same as the
4575 // desired predicate.
4576 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
4577 if (isa<SCEVConstant>(RHS))
4578 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
4579 else
4580 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
4581 RHS, LHS, FoundLHS, FoundRHS);
4582 }
4583
4584 // Check whether the actual condition is beyond sufficient.
4585 if (FoundPred == ICmpInst::ICMP_EQ)
4586 if (ICmpInst::isTrueWhenEqual(Pred))
4587 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
4588 return true;
4589 if (Pred == ICmpInst::ICMP_NE)
4590 if (!ICmpInst::isTrueWhenEqual(FoundPred))
4591 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
4592 return true;
4593
4594 // Otherwise assume the worst.
4595 return false;
Dan Gohman55e2d7e2009-07-13 21:35:55 +00004596}
4597
Dan Gohman920446d2009-07-21 23:03:19 +00004598/// isImpliedCondOperands - Test whether the condition described by Pred,
4599/// LHS, and RHS is true whenever the condition desribed by Pred, FoundLHS,
4600/// and FoundRHS is true.
4601bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
4602 const SCEV *LHS, const SCEV *RHS,
4603 const SCEV *FoundLHS,
4604 const SCEV *FoundRHS) {
4605 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
4606 FoundLHS, FoundRHS) ||
4607 // ~x < ~y --> x > y
4608 isImpliedCondOperandsHelper(Pred, LHS, RHS,
4609 getNotSCEV(FoundRHS),
4610 getNotSCEV(FoundLHS));
4611}
4612
4613/// isImpliedCondOperandsHelper - Test whether the condition described by
4614/// Pred, LHS, and RHS is true whenever the condition desribed by Pred,
4615/// FoundLHS, and FoundRHS is true.
Dan Gohman55e2d7e2009-07-13 21:35:55 +00004616bool
Dan Gohman920446d2009-07-21 23:03:19 +00004617ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
4618 const SCEV *LHS, const SCEV *RHS,
4619 const SCEV *FoundLHS,
4620 const SCEV *FoundRHS) {
Dan Gohman55e2d7e2009-07-13 21:35:55 +00004621 switch (Pred) {
Dan Gohman2d4f5b12009-07-16 17:34:36 +00004622 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4623 case ICmpInst::ICMP_EQ:
4624 case ICmpInst::ICMP_NE:
4625 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
4626 return true;
4627 break;
Dan Gohman55e2d7e2009-07-13 21:35:55 +00004628 case ICmpInst::ICMP_SLT:
Dan Gohman2d4f5b12009-07-16 17:34:36 +00004629 case ICmpInst::ICMP_SLE:
Dan Gohman55e2d7e2009-07-13 21:35:55 +00004630 if (isKnownPredicate(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
4631 isKnownPredicate(ICmpInst::ICMP_SGE, RHS, FoundRHS))
4632 return true;
4633 break;
4634 case ICmpInst::ICMP_SGT:
Dan Gohman2d4f5b12009-07-16 17:34:36 +00004635 case ICmpInst::ICMP_SGE:
Dan Gohman55e2d7e2009-07-13 21:35:55 +00004636 if (isKnownPredicate(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
4637 isKnownPredicate(ICmpInst::ICMP_SLE, RHS, FoundRHS))
4638 return true;
4639 break;
4640 case ICmpInst::ICMP_ULT:
Dan Gohman2d4f5b12009-07-16 17:34:36 +00004641 case ICmpInst::ICMP_ULE:
Dan Gohman55e2d7e2009-07-13 21:35:55 +00004642 if (isKnownPredicate(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
4643 isKnownPredicate(ICmpInst::ICMP_UGE, RHS, FoundRHS))
4644 return true;
4645 break;
4646 case ICmpInst::ICMP_UGT:
Dan Gohman2d4f5b12009-07-16 17:34:36 +00004647 case ICmpInst::ICMP_UGE:
Dan Gohman55e2d7e2009-07-13 21:35:55 +00004648 if (isKnownPredicate(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
4649 isKnownPredicate(ICmpInst::ICMP_ULE, RHS, FoundRHS))
4650 return true;
4651 break;
4652 }
4653
4654 return false;
Dan Gohman423ed6c2009-06-24 01:18:18 +00004655}
4656
Dan Gohmand2b62c42009-06-21 23:46:38 +00004657/// getBECount - Subtract the end and start values and divide by the step,
4658/// rounding up, to get the number of times the backedge is executed. Return
4659/// CouldNotCompute if an intermediate computation overflows.
Dan Gohman161ea032009-07-07 17:06:11 +00004660const SCEV *ScalarEvolution::getBECount(const SCEV *Start,
Dan Gohman69eacc72009-07-13 22:05:32 +00004661 const SCEV *End,
4662 const SCEV *Step) {
Dan Gohmand2b62c42009-06-21 23:46:38 +00004663 const Type *Ty = Start->getType();
Dan Gohman161ea032009-07-07 17:06:11 +00004664 const SCEV *NegOne = getIntegerSCEV(-1, Ty);
4665 const SCEV *Diff = getMinusSCEV(End, Start);
4666 const SCEV *RoundUp = getAddExpr(Step, NegOne);
Dan Gohmand2b62c42009-06-21 23:46:38 +00004667
4668 // Add an adjustment to the difference between End and Start so that
4669 // the division will effectively round up.
Dan Gohman161ea032009-07-07 17:06:11 +00004670 const SCEV *Add = getAddExpr(Diff, RoundUp);
Dan Gohmand2b62c42009-06-21 23:46:38 +00004671
4672 // Check Add for unsigned overflow.
4673 // TODO: More sophisticated things could be done here.
Owen Anderson175b6542009-07-22 00:24:57 +00004674 const Type *WideTy = getContext().getIntegerType(getTypeSizeInBits(Ty) + 1);
Dan Gohman55e2d7e2009-07-13 21:35:55 +00004675 const SCEV *EDiff = getZeroExtendExpr(Diff, WideTy);
4676 const SCEV *ERoundUp = getZeroExtendExpr(RoundUp, WideTy);
4677 const SCEV *OperandExtendedAdd = getAddExpr(EDiff, ERoundUp);
Dan Gohmand2b62c42009-06-21 23:46:38 +00004678 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004679 return getCouldNotCompute();
Dan Gohmand2b62c42009-06-21 23:46:38 +00004680
4681 return getUDivExpr(Add, Step);
4682}
4683
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004684/// HowManyLessThans - Return the number of times a backedge containing the
4685/// specified less-than comparison will execute. If not computable, return
Dan Gohman0c850912009-06-06 14:37:11 +00004686/// CouldNotCompute.
Dan Gohman9bc642f2009-06-24 04:48:43 +00004687ScalarEvolution::BackedgeTakenInfo
4688ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
4689 const Loop *L, bool isSigned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004690 // Only handle: "ADDREC < LoopInvariant".
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004691 if (!RHS->isLoopInvariant(L)) return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004692
Dan Gohmanbff6b582009-05-04 22:30:44 +00004693 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004694 if (!AddRec || AddRec->getLoop() != L)
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004695 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004696
4697 if (AddRec->isAffine()) {
Nick Lewycky35b56022009-01-13 09:18:58 +00004698 // FORNOW: We only support unit strides.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004699 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
Dan Gohman161ea032009-07-07 17:06:11 +00004700 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004701
4702 // TODO: handle non-constant strides.
4703 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
4704 if (!CStep || CStep->isZero())
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004705 return getCouldNotCompute();
Dan Gohmanf8bc8e82009-05-18 15:22:39 +00004706 if (CStep->isOne()) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004707 // With unit stride, the iteration never steps past the limit value.
4708 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
4709 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
4710 // Test whether a positive iteration iteration can step past the limit
4711 // value and past the maximum value for its type in a single step.
4712 if (isSigned) {
4713 APInt Max = APInt::getSignedMaxValue(BitWidth);
4714 if ((Max - CStep->getValue()->getValue())
4715 .slt(CLimit->getValue()->getValue()))
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004716 return getCouldNotCompute();
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004717 } else {
4718 APInt Max = APInt::getMaxValue(BitWidth);
4719 if ((Max - CStep->getValue()->getValue())
4720 .ult(CLimit->getValue()->getValue()))
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004721 return getCouldNotCompute();
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004722 }
4723 } else
4724 // TODO: handle non-constant limit values below.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004725 return getCouldNotCompute();
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004726 } else
4727 // TODO: handle negative strides below.
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004728 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004729
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004730 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
4731 // m. So, we count the number of iterations in which {n,+,s} < m is true.
4732 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicz1377a542008-02-13 12:21:32 +00004733 // treat m-n as signed nor unsigned due to overflow possibility.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004734
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00004735 // First, we get the value of the LHS in the first iteration: n
Dan Gohman161ea032009-07-07 17:06:11 +00004736 const SCEV *Start = AddRec->getOperand(0);
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00004737
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004738 // Determine the minimum constant start value.
Dan Gohman55e2d7e2009-07-13 21:35:55 +00004739 const SCEV *MinStart = getConstant(isSigned ?
4740 getSignedRange(Start).getSignedMin() :
4741 getUnsignedRange(Start).getUnsignedMin());
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00004742
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004743 // If we know that the condition is true in order to enter the loop,
4744 // then we know that it will run exactly (m-n)/s times. Otherwise, we
Dan Gohmanc8a29272009-05-24 23:45:28 +00004745 // only know that it will execute (max(m,n)-n)/s times. In both cases,
4746 // the division must round up.
Dan Gohman161ea032009-07-07 17:06:11 +00004747 const SCEV *End = RHS;
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004748 if (!isLoopGuardedByCond(L,
Dan Gohman55e2d7e2009-07-13 21:35:55 +00004749 isSigned ? ICmpInst::ICMP_SLT :
4750 ICmpInst::ICMP_ULT,
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004751 getMinusSCEV(Start, Step), RHS))
4752 End = isSigned ? getSMaxExpr(RHS, Start)
4753 : getUMaxExpr(RHS, Start);
4754
4755 // Determine the maximum constant end value.
Dan Gohman55e2d7e2009-07-13 21:35:55 +00004756 const SCEV *MaxEnd = getConstant(isSigned ?
4757 getSignedRange(End).getSignedMax() :
4758 getUnsignedRange(End).getUnsignedMax());
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004759
4760 // Finally, we subtract these two values and divide, rounding up, to get
4761 // the number of times the backedge is executed.
Dan Gohman161ea032009-07-07 17:06:11 +00004762 const SCEV *BECount = getBECount(Start, End, Step);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004763
4764 // The maximum backedge count is similar, except using the minimum start
4765 // value and the maximum end value.
Dan Gohman161ea032009-07-07 17:06:11 +00004766 const SCEV *MaxBECount = getBECount(MinStart, MaxEnd, Step);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004767
4768 return BackedgeTakenInfo(BECount, MaxBECount);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004769 }
4770
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004771 return getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004772}
4773
4774/// getNumIterationsInRange - Return the number of iterations of this loop that
4775/// produce values in the specified constant range. Another way of looking at
4776/// this is that it returns the first iteration number where the value is not in
4777/// the condition, thus computing the exit count. If the iteration count can't
4778/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman161ea032009-07-07 17:06:11 +00004779const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
Dan Gohman9bc642f2009-06-24 04:48:43 +00004780 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004781 if (Range.isFullSet()) // Infinite loop.
Dan Gohman0ad08b02009-04-18 17:58:19 +00004782 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004783
4784 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohmanc76b5452009-05-04 22:02:23 +00004785 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004786 if (!SC->getValue()->isZero()) {
Dan Gohman161ea032009-07-07 17:06:11 +00004787 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00004788 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
Dan Gohman161ea032009-07-07 17:06:11 +00004789 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohmanc76b5452009-05-04 22:02:23 +00004790 if (const SCEVAddRecExpr *ShiftedAddRec =
4791 dyn_cast<SCEVAddRecExpr>(Shifted))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004792 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman89f85052007-10-22 18:31:58 +00004793 Range.subtract(SC->getValue()->getValue()), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004794 // This is strange and shouldn't happen.
Dan Gohman0ad08b02009-04-18 17:58:19 +00004795 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004796 }
4797
4798 // The only time we can solve this is when we have all constant indices.
4799 // Otherwise, we cannot determine the overflow conditions.
4800 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
4801 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohman0ad08b02009-04-18 17:58:19 +00004802 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004803
4804
4805 // Okay at this point we know that all elements of the chrec are constants and
4806 // that the start element is zero.
4807
4808 // First check to see if the range contains zero. If not, the first
4809 // iteration exits.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00004810 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00004811 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman8fd520a2009-06-15 22:12:54 +00004812 return SE.getIntegerSCEV(0, getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004813
4814 if (isAffine()) {
4815 // If this is an affine expression then we have this situation:
4816 // Solve {0,+,A} in Range === Ax in Range
4817
4818 // We know that zero is in the range. If A is positive then we know that
4819 // the upper value of the range must be the first possible exit value.
4820 // If A is negative then the lower of the range is the last possible loop
4821 // value. Also note that we already checked for a full range.
Dan Gohman01c2ee72009-04-16 03:18:22 +00004822 APInt One(BitWidth,1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004823 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
4824 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
4825
4826 // The exit value should be (End+A)/A.
Nick Lewyckya0facae2007-09-27 14:12:54 +00004827 APInt ExitVal = (End + A).udiv(A);
Owen Andersoneacb44d2009-07-24 23:12:02 +00004828 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004829
4830 // Evaluate at the exit value. If we really did fall out of the valid
4831 // range, then we computed our trip count, otherwise wrap around or other
4832 // things must have happened.
Dan Gohman89f85052007-10-22 18:31:58 +00004833 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004834 if (Range.contains(Val->getValue()))
Dan Gohman0ad08b02009-04-18 17:58:19 +00004835 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004836
4837 // Ensure that the previous value is in the range. This is a sanity check.
4838 assert(Range.contains(
Dan Gohman9bc642f2009-06-24 04:48:43 +00004839 EvaluateConstantChrecAtConstant(this,
Owen Andersoneacb44d2009-07-24 23:12:02 +00004840 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004841 "Linear scev computation is off in a bad way!");
Dan Gohman89f85052007-10-22 18:31:58 +00004842 return SE.getConstant(ExitValue);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004843 } else if (isQuadratic()) {
4844 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
4845 // quadratic equation to solve it. To do this, we must frame our problem in
4846 // terms of figuring out when zero is crossed, instead of when
4847 // Range.getUpper() is crossed.
Dan Gohman161ea032009-07-07 17:06:11 +00004848 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00004849 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Dan Gohman161ea032009-07-07 17:06:11 +00004850 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004851
4852 // Next, solve the constructed addrec
Dan Gohman161ea032009-07-07 17:06:11 +00004853 std::pair<const SCEV *,const SCEV *> Roots =
Dan Gohman89f85052007-10-22 18:31:58 +00004854 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohmanbff6b582009-05-04 22:30:44 +00004855 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4856 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004857 if (R1) {
4858 // Pick the smallest positive root value.
4859 if (ConstantInt *CB =
Owen Andersone755b092009-07-06 22:37:39 +00004860 dyn_cast<ConstantInt>(
Owen Anderson175b6542009-07-22 00:24:57 +00004861 SE.getContext().getConstantExprICmp(ICmpInst::ICMP_ULT,
Owen Andersone755b092009-07-06 22:37:39 +00004862 R1->getValue(), R2->getValue()))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004863 if (CB->getZExtValue() == false)
4864 std::swap(R1, R2); // R1 is the minimum root now.
4865
4866 // Make sure the root is not off by one. The returned iteration should
4867 // not be in the range, but the previous one should be. When solving
4868 // for "X*X < 5", for example, we should not return a root of 2.
4869 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00004870 R1->getValue(),
4871 SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004872 if (Range.contains(R1Val->getValue())) {
4873 // The next iteration must be out of the range...
Owen Andersone755b092009-07-06 22:37:39 +00004874 ConstantInt *NextVal =
Owen Andersoneacb44d2009-07-24 23:12:02 +00004875 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004876
Dan Gohman89f85052007-10-22 18:31:58 +00004877 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004878 if (!Range.contains(R1Val->getValue()))
Dan Gohman89f85052007-10-22 18:31:58 +00004879 return SE.getConstant(NextVal);
Dan Gohman0ad08b02009-04-18 17:58:19 +00004880 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004881 }
4882
4883 // If R1 was not in the range, then it is a good return value. Make
4884 // sure that R1-1 WAS in the range though, just in case.
Owen Andersone755b092009-07-06 22:37:39 +00004885 ConstantInt *NextVal =
Owen Andersoneacb44d2009-07-24 23:12:02 +00004886 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()-1);
Dan Gohman89f85052007-10-22 18:31:58 +00004887 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004888 if (Range.contains(R1Val->getValue()))
4889 return R1;
Dan Gohman0ad08b02009-04-18 17:58:19 +00004890 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004891 }
4892 }
4893 }
4894
Dan Gohman0ad08b02009-04-18 17:58:19 +00004895 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004896}
4897
4898
4899
4900//===----------------------------------------------------------------------===//
Dan Gohmanbff6b582009-05-04 22:30:44 +00004901// SCEVCallbackVH Class Implementation
4902//===----------------------------------------------------------------------===//
4903
Dan Gohman999d14e2009-05-19 19:22:47 +00004904void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohman31b69c12009-07-13 22:20:53 +00004905 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohmanbff6b582009-05-04 22:30:44 +00004906 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
4907 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00004908 if (Instruction *I = dyn_cast<Instruction>(getValPtr()))
4909 SE->ValuesAtScopes.erase(I);
Dan Gohmanbff6b582009-05-04 22:30:44 +00004910 SE->Scalars.erase(getValPtr());
4911 // this now dangles!
4912}
4913
Dan Gohman999d14e2009-05-19 19:22:47 +00004914void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *) {
Dan Gohman31b69c12009-07-13 22:20:53 +00004915 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohmanbff6b582009-05-04 22:30:44 +00004916
4917 // Forget all the expressions associated with users of the old value,
4918 // so that future queries will recompute the expressions using the new
4919 // value.
4920 SmallVector<User *, 16> Worklist;
Dan Gohman6b9da312009-07-14 14:34:04 +00004921 SmallPtrSet<User *, 8> Visited;
Dan Gohmanbff6b582009-05-04 22:30:44 +00004922 Value *Old = getValPtr();
4923 bool DeleteOld = false;
4924 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
4925 UI != UE; ++UI)
4926 Worklist.push_back(*UI);
4927 while (!Worklist.empty()) {
4928 User *U = Worklist.pop_back_val();
4929 // Deleting the Old value will cause this to dangle. Postpone
4930 // that until everything else is done.
4931 if (U == Old) {
4932 DeleteOld = true;
4933 continue;
4934 }
Dan Gohman6b9da312009-07-14 14:34:04 +00004935 if (!Visited.insert(U))
4936 continue;
Dan Gohmanbff6b582009-05-04 22:30:44 +00004937 if (PHINode *PN = dyn_cast<PHINode>(U))
4938 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00004939 if (Instruction *I = dyn_cast<Instruction>(U))
4940 SE->ValuesAtScopes.erase(I);
Dan Gohman6b9da312009-07-14 14:34:04 +00004941 SE->Scalars.erase(U);
4942 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
4943 UI != UE; ++UI)
4944 Worklist.push_back(*UI);
Dan Gohmanbff6b582009-05-04 22:30:44 +00004945 }
Dan Gohman6b9da312009-07-14 14:34:04 +00004946 // Delete the Old value if it (indirectly) references itself.
Dan Gohmanbff6b582009-05-04 22:30:44 +00004947 if (DeleteOld) {
4948 if (PHINode *PN = dyn_cast<PHINode>(Old))
4949 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00004950 if (Instruction *I = dyn_cast<Instruction>(Old))
4951 SE->ValuesAtScopes.erase(I);
Dan Gohmanbff6b582009-05-04 22:30:44 +00004952 SE->Scalars.erase(Old);
4953 // this now dangles!
4954 }
4955 // this may dangle!
4956}
4957
Dan Gohman999d14e2009-05-19 19:22:47 +00004958ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohmanbff6b582009-05-04 22:30:44 +00004959 : CallbackVH(V), SE(se) {}
4960
4961//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004962// ScalarEvolution Class Implementation
4963//===----------------------------------------------------------------------===//
4964
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004965ScalarEvolution::ScalarEvolution()
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004966 : FunctionPass(&ID) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004967}
4968
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004969bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004970 this->F = &F;
4971 LI = &getAnalysis<LoopInfo>();
4972 TD = getAnalysisIfAvailable<TargetData>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004973 return false;
4974}
4975
4976void ScalarEvolution::releaseMemory() {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004977 Scalars.clear();
4978 BackedgeTakenCounts.clear();
4979 ConstantEvolutionLoopExitValue.clear();
Dan Gohmanda0071e2009-05-08 20:47:27 +00004980 ValuesAtScopes.clear();
Dan Gohmanc6475cb2009-06-27 21:21:31 +00004981 UniqueSCEVs.clear();
4982 SCEVAllocator.Reset();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004983}
4984
4985void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
4986 AU.setPreservesAll();
4987 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman01c2ee72009-04-16 03:18:22 +00004988}
4989
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004990bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00004991 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004992}
4993
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004994static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004995 const Loop *L) {
4996 // Print all inner loops first
4997 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
4998 PrintLoopInfo(OS, SE, *I);
4999
Nick Lewyckye5da1912008-01-02 02:49:20 +00005000 OS << "Loop " << L->getHeader()->getName() << ": ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005001
Devang Patel02451fa2007-08-21 00:31:24 +00005002 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005003 L->getExitBlocks(ExitBlocks);
5004 if (ExitBlocks.size() != 1)
Nick Lewyckye5da1912008-01-02 02:49:20 +00005005 OS << "<multiple exits> ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005006
Dan Gohman76d5a0d2009-02-24 18:55:53 +00005007 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
5008 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005009 } else {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00005010 OS << "Unpredictable backedge-taken count. ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005011 }
5012
Nick Lewyckye5da1912008-01-02 02:49:20 +00005013 OS << "\n";
Dan Gohmanb6b9e9e2009-06-24 00:33:16 +00005014 OS << "Loop " << L->getHeader()->getName() << ": ";
5015
5016 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
5017 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
5018 } else {
5019 OS << "Unpredictable max backedge-taken count. ";
5020 }
5021
5022 OS << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005023}
5024
Dan Gohman13058cc2009-04-21 00:47:46 +00005025void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00005026 // ScalarEvolution's implementaiton of the print method is to print
5027 // out SCEV values of all instructions that are interesting. Doing
5028 // this potentially causes it to create new SCEV objects though,
5029 // which technically conflicts with the const qualifier. This isn't
Dan Gohmanac2a9d62009-07-10 20:25:29 +00005030 // observable from outside the class though, so casting away the
5031 // const isn't dangerous.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00005032 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005033
Dan Gohmanffd36ba2009-04-21 23:15:49 +00005034 OS << "Classifying expressions for: " << F->getName() << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005035 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohman43d37e92009-04-30 01:30:18 +00005036 if (isSCEVable(I->getType())) {
Dan Gohman12668ad2009-07-13 23:03:05 +00005037 OS << *I << '\n';
Dan Gohmanabe991f2008-09-14 17:21:12 +00005038 OS << " --> ";
Dan Gohman161ea032009-07-07 17:06:11 +00005039 const SCEV *SV = SE.getSCEV(&*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005040 SV->print(OS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005041
Dan Gohman8db598a2009-06-19 17:49:54 +00005042 const Loop *L = LI->getLoopFor((*I).getParent());
5043
Dan Gohman161ea032009-07-07 17:06:11 +00005044 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohman8db598a2009-06-19 17:49:54 +00005045 if (AtUse != SV) {
5046 OS << " --> ";
5047 AtUse->print(OS);
5048 }
5049
5050 if (L) {
Dan Gohmane5b60842009-06-18 00:37:45 +00005051 OS << "\t\t" "Exits: ";
Dan Gohman161ea032009-07-07 17:06:11 +00005052 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohmanaff14d62009-05-24 23:25:42 +00005053 if (!ExitValue->isLoopInvariant(L)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005054 OS << "<<Unknown>>";
5055 } else {
5056 OS << *ExitValue;
5057 }
5058 }
5059
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005060 OS << "\n";
5061 }
5062
Dan Gohmanffd36ba2009-04-21 23:15:49 +00005063 OS << "Determining loop execution counts for: " << F->getName() << "\n";
5064 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
5065 PrintLoopInfo(OS, &SE, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005066}
Dan Gohman13058cc2009-04-21 00:47:46 +00005067
5068void ScalarEvolution::print(std::ostream &o, const Module *M) const {
5069 raw_os_ostream OS(o);
5070 print(OS, M);
5071}