blob: d7b11b8546028d3966fcf0c8fb3747e02f07b9fc [file] [log] [blame]
Chris Lattner6148c022001-12-03 17:28:42 +00001//===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner6148c022001-12-03 17:28:42 +00009//
Chris Lattner40bf8b42004-04-02 20:24:31 +000010// This transformation analyzes and transforms the induction variables (and
11// computations derived from them) into simpler forms suitable for subsequent
12// analysis and transformation.
13//
Reid Spencer47a53ac2006-08-18 09:01:07 +000014// This transformation makes the following changes to each loop with an
Chris Lattner40bf8b42004-04-02 20:24:31 +000015// identifiable induction variable:
16// 1. All loops are transformed to have a SINGLE canonical induction variable
17// which starts at zero and steps by one.
18// 2. The canonical induction variable is guaranteed to be the first PHI node
19// in the loop header block.
Dan Gohmanea73f3c2009-06-14 22:38:41 +000020// 3. The canonical induction variable is guaranteed to be in a wide enough
21// type so that IV expressions need not be (directly) zero-extended or
22// sign-extended.
23// 4. Any pointer arithmetic recurrences are raised to use array subscripts.
Chris Lattner40bf8b42004-04-02 20:24:31 +000024//
25// If the trip count of a loop is computable, this pass also makes the following
26// changes:
27// 1. The exit condition for the loop is canonicalized to compare the
28// induction value against the exit value. This turns loops like:
29// 'for (i = 7; i*i < 1000; ++i)' into 'for (i = 0; i != 25; ++i)'
30// 2. Any use outside of the loop of an expression derived from the indvar
31// is changed to compute the derived value outside of the loop, eliminating
32// the dependence on the exit value of the induction variable. If the only
33// purpose of the loop is to compute the exit value of some derived
34// expression, this transformation will make the loop dead.
35//
36// This transformation should be followed by strength reduction after all of the
Dan Gohmanc2c4cbf2009-05-19 20:38:47 +000037// desired loop transformations have been performed.
Chris Lattner6148c022001-12-03 17:28:42 +000038//
39//===----------------------------------------------------------------------===//
40
Chris Lattner0e5f4992006-12-19 21:40:18 +000041#define DEBUG_TYPE "indvars"
Chris Lattner022103b2002-05-07 20:03:00 +000042#include "llvm/Transforms/Scalar.h"
Chris Lattner40bf8b42004-04-02 20:24:31 +000043#include "llvm/BasicBlock.h"
Chris Lattner59fdaee2004-04-15 15:21:43 +000044#include "llvm/Constants.h"
Chris Lattner18b3c972003-12-22 05:02:01 +000045#include "llvm/Instructions.h"
Devang Patel7b9f6b12010-03-15 22:23:03 +000046#include "llvm/IntrinsicInst.h"
Owen Andersond672ecb2009-07-03 00:17:18 +000047#include "llvm/LLVMContext.h"
Chris Lattner40bf8b42004-04-02 20:24:31 +000048#include "llvm/Type.h"
Dan Gohman81db61a2009-05-12 02:17:14 +000049#include "llvm/Analysis/Dominators.h"
50#include "llvm/Analysis/IVUsers.h"
Nate Begeman36f891b2005-07-30 00:12:19 +000051#include "llvm/Analysis/ScalarEvolutionExpander.h"
John Criswell47df12d2003-12-18 17:19:19 +000052#include "llvm/Analysis/LoopInfo.h"
Devang Patel5ee99972007-03-07 06:39:01 +000053#include "llvm/Analysis/LoopPass.h"
Chris Lattner455889a2002-02-12 22:39:50 +000054#include "llvm/Support/CFG.h"
Andrew Trick56caa092011-06-28 03:01:46 +000055#include "llvm/Support/CommandLine.h"
Chris Lattneree4f13a2007-01-07 01:14:12 +000056#include "llvm/Support/Debug.h"
Chris Lattnerbdff5482009-08-23 04:37:46 +000057#include "llvm/Support/raw_ostream.h"
John Criswell47df12d2003-12-18 17:19:19 +000058#include "llvm/Transforms/Utils/Local.h"
Dan Gohman81db61a2009-05-12 02:17:14 +000059#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Andrew Trick37da4082011-05-04 02:10:13 +000060#include "llvm/Target/TargetData.h"
Andrew Trick037d1c02011-07-06 20:50:43 +000061#include "llvm/ADT/DenseMap.h"
Reid Spencera54b7cb2007-01-12 07:05:14 +000062#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000063#include "llvm/ADT/Statistic.h"
Dan Gohman81db61a2009-05-12 02:17:14 +000064#include "llvm/ADT/STLExtras.h"
John Criswell47df12d2003-12-18 17:19:19 +000065using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000066
Andrew Trick2fabd462011-06-21 03:22:38 +000067STATISTIC(NumRemoved , "Number of aux indvars removed");
68STATISTIC(NumWidened , "Number of indvars widened");
69STATISTIC(NumInserted , "Number of canonical indvars added");
70STATISTIC(NumReplaced , "Number of exit values replaced");
71STATISTIC(NumLFTR , "Number of loop exit tests replaced");
72STATISTIC(NumElimIdentity, "Number of IV identities eliminated");
73STATISTIC(NumElimExt , "Number of IV sign/zero extends eliminated");
74STATISTIC(NumElimRem , "Number of IV remainder operations eliminated");
75STATISTIC(NumElimCmp , "Number of IV comparisons eliminated");
Andrew Trick037d1c02011-07-06 20:50:43 +000076STATISTIC(NumElimIV , "Number of congruent IVs eliminated");
Chris Lattner3324e712003-12-22 03:58:44 +000077
Andrew Trick56caa092011-06-28 03:01:46 +000078static cl::opt<bool> DisableIVRewrite(
79 "disable-iv-rewrite", cl::Hidden,
80 cl::desc("Disable canonical induction variable rewriting"));
Andrew Trick37da4082011-05-04 02:10:13 +000081
Andrew Trickfc933c02011-07-18 20:32:31 +000082// Temporary flag for use with -disable-iv-rewrite to force a canonical IV for
83// LFTR purposes.
84static cl::opt<bool> ForceLFTR(
85 "force-lftr", cl::Hidden,
86 cl::desc("Enable forced linear function test replacement"));
87
Chris Lattner0e5f4992006-12-19 21:40:18 +000088namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000089 class IndVarSimplify : public LoopPass {
Dan Gohman81db61a2009-05-12 02:17:14 +000090 IVUsers *IU;
Chris Lattner40bf8b42004-04-02 20:24:31 +000091 LoopInfo *LI;
92 ScalarEvolution *SE;
Dan Gohmande53dc02009-06-27 05:16:57 +000093 DominatorTree *DT;
Andrew Trick37da4082011-05-04 02:10:13 +000094 TargetData *TD;
Andrew Trick2fabd462011-06-21 03:22:38 +000095
Andrew Trickb12a7542011-03-17 23:51:11 +000096 SmallVector<WeakVH, 16> DeadInsts;
Chris Lattner15cad752003-12-23 07:47:09 +000097 bool Changed;
Chris Lattner3324e712003-12-22 03:58:44 +000098 public:
Devang Patel794fd752007-05-01 21:15:47 +000099
Dan Gohman5668cf72009-07-15 01:26:32 +0000100 static char ID; // Pass identification, replacement for typeid
Andrew Trick2fabd462011-06-21 03:22:38 +0000101 IndVarSimplify() : LoopPass(ID), IU(0), LI(0), SE(0), DT(0), TD(0),
Andrew Trick15832f62011-06-28 02:49:20 +0000102 Changed(false) {
Owen Anderson081c34b2010-10-19 17:21:58 +0000103 initializeIndVarSimplifyPass(*PassRegistry::getPassRegistry());
104 }
Devang Patel794fd752007-05-01 21:15:47 +0000105
Dan Gohman5668cf72009-07-15 01:26:32 +0000106 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
Dan Gohman60f8a632009-02-17 20:49:49 +0000107
Dan Gohman5668cf72009-07-15 01:26:32 +0000108 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
109 AU.addRequired<DominatorTree>();
110 AU.addRequired<LoopInfo>();
111 AU.addRequired<ScalarEvolution>();
112 AU.addRequiredID(LoopSimplifyID);
113 AU.addRequiredID(LCSSAID);
Andrew Trick56caa092011-06-28 03:01:46 +0000114 if (!DisableIVRewrite)
115 AU.addRequired<IVUsers>();
Dan Gohman5668cf72009-07-15 01:26:32 +0000116 AU.addPreserved<ScalarEvolution>();
117 AU.addPreservedID(LoopSimplifyID);
118 AU.addPreservedID(LCSSAID);
Andrew Trick2fabd462011-06-21 03:22:38 +0000119 if (!DisableIVRewrite)
120 AU.addPreserved<IVUsers>();
Dan Gohman5668cf72009-07-15 01:26:32 +0000121 AU.setPreservesCFG();
122 }
Chris Lattner15cad752003-12-23 07:47:09 +0000123
Chris Lattner40bf8b42004-04-02 20:24:31 +0000124 private:
Andrew Trick037d1c02011-07-06 20:50:43 +0000125 virtual void releaseMemory() {
Andrew Trick037d1c02011-07-06 20:50:43 +0000126 DeadInsts.clear();
127 }
128
Andrew Trickb12a7542011-03-17 23:51:11 +0000129 bool isValidRewrite(Value *FromVal, Value *ToVal);
Devang Patel5ee99972007-03-07 06:39:01 +0000130
Andrew Trick1a54bb22011-07-12 00:08:50 +0000131 void HandleFloatingPointIV(Loop *L, PHINode *PH);
132 void RewriteNonIntegerIVs(Loop *L);
133
134 void RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter);
135
Andrew Trickf85092c2011-05-20 18:25:42 +0000136 void SimplifyIVUsers(SCEVExpander &Rewriter);
Andrew Trick2fabd462011-06-21 03:22:38 +0000137 void SimplifyIVUsersNoRewrite(Loop *L, SCEVExpander &Rewriter);
138
139 bool EliminateIVUser(Instruction *UseInst, Instruction *IVOperand);
Andrew Trickaeee4612011-05-12 00:04:28 +0000140 void EliminateIVComparison(ICmpInst *ICmp, Value *IVOperand);
141 void EliminateIVRemainder(BinaryOperator *Rem,
142 Value *IVOperand,
Andrew Trick4417e532011-06-21 15:43:52 +0000143 bool IsSigned);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000144
Andrew Trick037d1c02011-07-06 20:50:43 +0000145 void SimplifyCongruentIVs(Loop *L);
146
Dan Gohman454d26d2010-02-22 04:11:59 +0000147 void RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter);
Devang Pateld22a8492008-09-09 21:41:07 +0000148
Andrew Trickfc933c02011-07-18 20:32:31 +0000149 Value *LinearFunctionTestReplace(Loop *L, const SCEV *BackedgeTakenCount,
150 PHINode *IndVar, SCEVExpander &Rewriter);
Dan Gohman81db61a2009-05-12 02:17:14 +0000151
Andrew Trick1a54bb22011-07-12 00:08:50 +0000152 void SinkUnusedInvariants(Loop *L);
Chris Lattner3324e712003-12-22 03:58:44 +0000153 };
Chris Lattner5e761402002-09-10 05:24:05 +0000154}
Chris Lattner394437f2001-12-04 04:32:29 +0000155
Dan Gohman844731a2008-05-13 00:00:25 +0000156char IndVarSimplify::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000157INITIALIZE_PASS_BEGIN(IndVarSimplify, "indvars",
Andrew Trick37da4082011-05-04 02:10:13 +0000158 "Induction Variable Simplification", false, false)
Owen Anderson2ab36d32010-10-12 19:48:12 +0000159INITIALIZE_PASS_DEPENDENCY(DominatorTree)
160INITIALIZE_PASS_DEPENDENCY(LoopInfo)
161INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
162INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
163INITIALIZE_PASS_DEPENDENCY(LCSSA)
164INITIALIZE_PASS_DEPENDENCY(IVUsers)
165INITIALIZE_PASS_END(IndVarSimplify, "indvars",
Andrew Trick37da4082011-05-04 02:10:13 +0000166 "Induction Variable Simplification", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000167
Daniel Dunbar394f0442008-10-22 23:32:42 +0000168Pass *llvm::createIndVarSimplifyPass() {
Chris Lattner3324e712003-12-22 03:58:44 +0000169 return new IndVarSimplify();
Chris Lattner394437f2001-12-04 04:32:29 +0000170}
171
Andrew Trickb12a7542011-03-17 23:51:11 +0000172/// isValidRewrite - Return true if the SCEV expansion generated by the
173/// rewriter can replace the original value. SCEV guarantees that it
174/// produces the same value, but the way it is produced may be illegal IR.
175/// Ideally, this function will only be called for verification.
176bool IndVarSimplify::isValidRewrite(Value *FromVal, Value *ToVal) {
177 // If an SCEV expression subsumed multiple pointers, its expansion could
178 // reassociate the GEP changing the base pointer. This is illegal because the
179 // final address produced by a GEP chain must be inbounds relative to its
180 // underlying object. Otherwise basic alias analysis, among other things,
181 // could fail in a dangerous way. Ultimately, SCEV will be improved to avoid
182 // producing an expression involving multiple pointers. Until then, we must
183 // bail out here.
184 //
185 // Retrieve the pointer operand of the GEP. Don't use GetUnderlyingObject
186 // because it understands lcssa phis while SCEV does not.
187 Value *FromPtr = FromVal;
188 Value *ToPtr = ToVal;
189 if (GEPOperator *GEP = dyn_cast<GEPOperator>(FromVal)) {
190 FromPtr = GEP->getPointerOperand();
191 }
192 if (GEPOperator *GEP = dyn_cast<GEPOperator>(ToVal)) {
193 ToPtr = GEP->getPointerOperand();
194 }
195 if (FromPtr != FromVal || ToPtr != ToVal) {
196 // Quickly check the common case
197 if (FromPtr == ToPtr)
198 return true;
199
200 // SCEV may have rewritten an expression that produces the GEP's pointer
201 // operand. That's ok as long as the pointer operand has the same base
202 // pointer. Unlike GetUnderlyingObject(), getPointerBase() will find the
203 // base of a recurrence. This handles the case in which SCEV expansion
204 // converts a pointer type recurrence into a nonrecurrent pointer base
205 // indexed by an integer recurrence.
206 const SCEV *FromBase = SE->getPointerBase(SE->getSCEV(FromPtr));
207 const SCEV *ToBase = SE->getPointerBase(SE->getSCEV(ToPtr));
208 if (FromBase == ToBase)
209 return true;
210
211 DEBUG(dbgs() << "INDVARS: GEP rewrite bail out "
212 << *FromBase << " != " << *ToBase << "\n");
213
214 return false;
215 }
216 return true;
217}
218
Andrew Trick1a54bb22011-07-12 00:08:50 +0000219//===----------------------------------------------------------------------===//
220// RewriteNonIntegerIVs and helpers. Prefer integer IVs.
221//===----------------------------------------------------------------------===//
Andrew Trick4dfdf242011-05-03 22:24:10 +0000222
Andrew Trick1a54bb22011-07-12 00:08:50 +0000223/// ConvertToSInt - Convert APF to an integer, if possible.
224static bool ConvertToSInt(const APFloat &APF, int64_t &IntVal) {
225 bool isExact = false;
226 if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
Andrew Trick4dfdf242011-05-03 22:24:10 +0000227 return false;
Andrew Trick1a54bb22011-07-12 00:08:50 +0000228 // See if we can convert this to an int64_t
229 uint64_t UIntVal;
230 if (APF.convertToInteger(&UIntVal, 64, true, APFloat::rmTowardZero,
231 &isExact) != APFloat::opOK || !isExact)
Andrew Trick4dfdf242011-05-03 22:24:10 +0000232 return false;
Andrew Trick1a54bb22011-07-12 00:08:50 +0000233 IntVal = UIntVal;
Andrew Trick4dfdf242011-05-03 22:24:10 +0000234 return true;
235}
236
Andrew Trick1a54bb22011-07-12 00:08:50 +0000237/// HandleFloatingPointIV - If the loop has floating induction variable
238/// then insert corresponding integer induction variable if possible.
239/// For example,
240/// for(double i = 0; i < 10000; ++i)
241/// bar(i)
242/// is converted into
243/// for(int i = 0; i < 10000; ++i)
244/// bar((double)i);
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000245///
Andrew Trick1a54bb22011-07-12 00:08:50 +0000246void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PN) {
247 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
248 unsigned BackEdge = IncomingEdge^1;
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000249
Andrew Trick1a54bb22011-07-12 00:08:50 +0000250 // Check incoming value.
251 ConstantFP *InitValueVal =
252 dyn_cast<ConstantFP>(PN->getIncomingValue(IncomingEdge));
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000253
Andrew Trick1a54bb22011-07-12 00:08:50 +0000254 int64_t InitValue;
255 if (!InitValueVal || !ConvertToSInt(InitValueVal->getValueAPF(), InitValue))
256 return;
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000257
Andrew Trick1a54bb22011-07-12 00:08:50 +0000258 // Check IV increment. Reject this PN if increment operation is not
259 // an add or increment value can not be represented by an integer.
260 BinaryOperator *Incr =
261 dyn_cast<BinaryOperator>(PN->getIncomingValue(BackEdge));
262 if (Incr == 0 || Incr->getOpcode() != Instruction::FAdd) return;
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000263
Andrew Trick1a54bb22011-07-12 00:08:50 +0000264 // If this is not an add of the PHI with a constantfp, or if the constant fp
265 // is not an integer, bail out.
266 ConstantFP *IncValueVal = dyn_cast<ConstantFP>(Incr->getOperand(1));
267 int64_t IncValue;
268 if (IncValueVal == 0 || Incr->getOperand(0) != PN ||
269 !ConvertToSInt(IncValueVal->getValueAPF(), IncValue))
270 return;
271
272 // Check Incr uses. One user is PN and the other user is an exit condition
273 // used by the conditional terminator.
274 Value::use_iterator IncrUse = Incr->use_begin();
275 Instruction *U1 = cast<Instruction>(*IncrUse++);
276 if (IncrUse == Incr->use_end()) return;
277 Instruction *U2 = cast<Instruction>(*IncrUse++);
278 if (IncrUse != Incr->use_end()) return;
279
280 // Find exit condition, which is an fcmp. If it doesn't exist, or if it isn't
281 // only used by a branch, we can't transform it.
282 FCmpInst *Compare = dyn_cast<FCmpInst>(U1);
283 if (!Compare)
284 Compare = dyn_cast<FCmpInst>(U2);
285 if (Compare == 0 || !Compare->hasOneUse() ||
286 !isa<BranchInst>(Compare->use_back()))
287 return;
288
289 BranchInst *TheBr = cast<BranchInst>(Compare->use_back());
290
291 // We need to verify that the branch actually controls the iteration count
292 // of the loop. If not, the new IV can overflow and no one will notice.
293 // The branch block must be in the loop and one of the successors must be out
294 // of the loop.
295 assert(TheBr->isConditional() && "Can't use fcmp if not conditional");
296 if (!L->contains(TheBr->getParent()) ||
297 (L->contains(TheBr->getSuccessor(0)) &&
298 L->contains(TheBr->getSuccessor(1))))
299 return;
300
301
302 // If it isn't a comparison with an integer-as-fp (the exit value), we can't
303 // transform it.
304 ConstantFP *ExitValueVal = dyn_cast<ConstantFP>(Compare->getOperand(1));
305 int64_t ExitValue;
306 if (ExitValueVal == 0 ||
307 !ConvertToSInt(ExitValueVal->getValueAPF(), ExitValue))
308 return;
309
310 // Find new predicate for integer comparison.
311 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
312 switch (Compare->getPredicate()) {
313 default: return; // Unknown comparison.
314 case CmpInst::FCMP_OEQ:
315 case CmpInst::FCMP_UEQ: NewPred = CmpInst::ICMP_EQ; break;
316 case CmpInst::FCMP_ONE:
317 case CmpInst::FCMP_UNE: NewPred = CmpInst::ICMP_NE; break;
318 case CmpInst::FCMP_OGT:
319 case CmpInst::FCMP_UGT: NewPred = CmpInst::ICMP_SGT; break;
320 case CmpInst::FCMP_OGE:
321 case CmpInst::FCMP_UGE: NewPred = CmpInst::ICMP_SGE; break;
322 case CmpInst::FCMP_OLT:
323 case CmpInst::FCMP_ULT: NewPred = CmpInst::ICMP_SLT; break;
324 case CmpInst::FCMP_OLE:
325 case CmpInst::FCMP_ULE: NewPred = CmpInst::ICMP_SLE; break;
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000326 }
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000327
Andrew Trick1a54bb22011-07-12 00:08:50 +0000328 // We convert the floating point induction variable to a signed i32 value if
329 // we can. This is only safe if the comparison will not overflow in a way
330 // that won't be trapped by the integer equivalent operations. Check for this
331 // now.
332 // TODO: We could use i64 if it is native and the range requires it.
Dan Gohmanca9b7032010-04-12 21:13:43 +0000333
Andrew Trick1a54bb22011-07-12 00:08:50 +0000334 // The start/stride/exit values must all fit in signed i32.
335 if (!isInt<32>(InitValue) || !isInt<32>(IncValue) || !isInt<32>(ExitValue))
336 return;
337
338 // If not actually striding (add x, 0.0), avoid touching the code.
339 if (IncValue == 0)
340 return;
341
342 // Positive and negative strides have different safety conditions.
343 if (IncValue > 0) {
344 // If we have a positive stride, we require the init to be less than the
345 // exit value and an equality or less than comparison.
346 if (InitValue >= ExitValue ||
347 NewPred == CmpInst::ICMP_SGT || NewPred == CmpInst::ICMP_SGE)
348 return;
349
350 uint32_t Range = uint32_t(ExitValue-InitValue);
351 if (NewPred == CmpInst::ICMP_SLE) {
352 // Normalize SLE -> SLT, check for infinite loop.
353 if (++Range == 0) return; // Range overflows.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000354 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000355
Andrew Trick1a54bb22011-07-12 00:08:50 +0000356 unsigned Leftover = Range % uint32_t(IncValue);
357
358 // If this is an equality comparison, we require that the strided value
359 // exactly land on the exit value, otherwise the IV condition will wrap
360 // around and do things the fp IV wouldn't.
361 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
362 Leftover != 0)
363 return;
364
365 // If the stride would wrap around the i32 before exiting, we can't
366 // transform the IV.
367 if (Leftover != 0 && int32_t(ExitValue+IncValue) < ExitValue)
368 return;
369
Chris Lattnerd2440572004-04-15 20:26:22 +0000370 } else {
Andrew Trick1a54bb22011-07-12 00:08:50 +0000371 // If we have a negative stride, we require the init to be greater than the
372 // exit value and an equality or greater than comparison.
373 if (InitValue >= ExitValue ||
374 NewPred == CmpInst::ICMP_SLT || NewPred == CmpInst::ICMP_SLE)
375 return;
376
377 uint32_t Range = uint32_t(InitValue-ExitValue);
378 if (NewPred == CmpInst::ICMP_SGE) {
379 // Normalize SGE -> SGT, check for infinite loop.
380 if (++Range == 0) return; // Range overflows.
381 }
382
383 unsigned Leftover = Range % uint32_t(-IncValue);
384
385 // If this is an equality comparison, we require that the strided value
386 // exactly land on the exit value, otherwise the IV condition will wrap
387 // around and do things the fp IV wouldn't.
388 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
389 Leftover != 0)
390 return;
391
392 // If the stride would wrap around the i32 before exiting, we can't
393 // transform the IV.
394 if (Leftover != 0 && int32_t(ExitValue+IncValue) > ExitValue)
395 return;
Chris Lattnerd2440572004-04-15 20:26:22 +0000396 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000397
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000398 IntegerType *Int32Ty = Type::getInt32Ty(PN->getContext());
Chris Lattner40bf8b42004-04-02 20:24:31 +0000399
Andrew Trick1a54bb22011-07-12 00:08:50 +0000400 // Insert new integer induction variable.
401 PHINode *NewPHI = PHINode::Create(Int32Ty, 2, PN->getName()+".int", PN);
402 NewPHI->addIncoming(ConstantInt::get(Int32Ty, InitValue),
403 PN->getIncomingBlock(IncomingEdge));
Chris Lattner40bf8b42004-04-02 20:24:31 +0000404
Andrew Trick1a54bb22011-07-12 00:08:50 +0000405 Value *NewAdd =
406 BinaryOperator::CreateAdd(NewPHI, ConstantInt::get(Int32Ty, IncValue),
407 Incr->getName()+".int", Incr);
408 NewPHI->addIncoming(NewAdd, PN->getIncomingBlock(BackEdge));
Dan Gohmanc2390b12009-02-12 22:19:27 +0000409
Andrew Trick1a54bb22011-07-12 00:08:50 +0000410 ICmpInst *NewCompare = new ICmpInst(TheBr, NewPred, NewAdd,
411 ConstantInt::get(Int32Ty, ExitValue),
412 Compare->getName());
Dan Gohman81db61a2009-05-12 02:17:14 +0000413
Andrew Trick1a54bb22011-07-12 00:08:50 +0000414 // In the following deletions, PN may become dead and may be deleted.
415 // Use a WeakVH to observe whether this happens.
416 WeakVH WeakPH = PN;
417
418 // Delete the old floating point exit comparison. The branch starts using the
419 // new comparison.
420 NewCompare->takeName(Compare);
421 Compare->replaceAllUsesWith(NewCompare);
422 RecursivelyDeleteTriviallyDeadInstructions(Compare);
423
424 // Delete the old floating point increment.
425 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
426 RecursivelyDeleteTriviallyDeadInstructions(Incr);
427
428 // If the FP induction variable still has uses, this is because something else
429 // in the loop uses its value. In order to canonicalize the induction
430 // variable, we chose to eliminate the IV and rewrite it in terms of an
431 // int->fp cast.
432 //
433 // We give preference to sitofp over uitofp because it is faster on most
434 // platforms.
435 if (WeakPH) {
436 Value *Conv = new SIToFPInst(NewPHI, PN->getType(), "indvar.conv",
437 PN->getParent()->getFirstNonPHI());
438 PN->replaceAllUsesWith(Conv);
439 RecursivelyDeleteTriviallyDeadInstructions(PN);
440 }
441
442 // Add a new IVUsers entry for the newly-created integer PHI.
443 if (IU)
444 IU->AddUsersIfInteresting(NewPHI);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000445}
446
Andrew Trick1a54bb22011-07-12 00:08:50 +0000447void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) {
448 // First step. Check to see if there are any floating-point recurrences.
449 // If there are, change them into integer recurrences, permitting analysis by
450 // the SCEV routines.
451 //
452 BasicBlock *Header = L->getHeader();
453
454 SmallVector<WeakVH, 8> PHIs;
455 for (BasicBlock::iterator I = Header->begin();
456 PHINode *PN = dyn_cast<PHINode>(I); ++I)
457 PHIs.push_back(PN);
458
459 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
460 if (PHINode *PN = dyn_cast_or_null<PHINode>(&*PHIs[i]))
461 HandleFloatingPointIV(L, PN);
462
463 // If the loop previously had floating-point IV, ScalarEvolution
464 // may not have been able to compute a trip count. Now that we've done some
465 // re-writing, the trip count may be computable.
466 if (Changed)
467 SE->forgetLoop(L);
468}
469
470//===----------------------------------------------------------------------===//
471// RewriteLoopExitValues - Optimize IV users outside the loop.
472// As a side effect, reduces the amount of IV processing within the loop.
473//===----------------------------------------------------------------------===//
474
Chris Lattner40bf8b42004-04-02 20:24:31 +0000475/// RewriteLoopExitValues - Check to see if this loop has a computable
476/// loop-invariant execution count. If so, this means that we can compute the
477/// final value of any expressions that are recurrent in the loop, and
478/// substitute the exit values from the loop into any instructions outside of
479/// the loop that use the final values of the current expressions.
Dan Gohman81db61a2009-05-12 02:17:14 +0000480///
481/// This is mostly redundant with the regular IndVarSimplify activities that
482/// happen later, except that it's more powerful in some cases, because it's
483/// able to brute-force evaluate arbitrary instructions as long as they have
484/// constant operands at the beginning of the loop.
Chris Lattnerf1859892011-01-09 02:16:18 +0000485void IndVarSimplify::RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000486 // Verify the input to the pass in already in LCSSA form.
Dan Gohmanbbf81d82010-03-10 19:38:49 +0000487 assert(L->isLCSSAForm(*DT));
Dan Gohman81db61a2009-05-12 02:17:14 +0000488
Devang Patelb7211a22007-08-21 00:31:24 +0000489 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattner9f3d7382007-03-04 03:43:23 +0000490 L->getUniqueExitBlocks(ExitBlocks);
Misha Brukmanfd939082005-04-21 23:48:37 +0000491
Chris Lattner9f3d7382007-03-04 03:43:23 +0000492 // Find all values that are computed inside the loop, but used outside of it.
493 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
494 // the exit blocks of the loop to find them.
495 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
496 BasicBlock *ExitBB = ExitBlocks[i];
Dan Gohmancafb8132009-02-17 19:13:57 +0000497
Chris Lattner9f3d7382007-03-04 03:43:23 +0000498 // If there are no PHI nodes in this exit block, then no values defined
499 // inside the loop are used on this path, skip it.
500 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
501 if (!PN) continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000502
Chris Lattner9f3d7382007-03-04 03:43:23 +0000503 unsigned NumPreds = PN->getNumIncomingValues();
Dan Gohmancafb8132009-02-17 19:13:57 +0000504
Chris Lattner9f3d7382007-03-04 03:43:23 +0000505 // Iterate over all of the PHI nodes.
506 BasicBlock::iterator BBI = ExitBB->begin();
507 while ((PN = dyn_cast<PHINode>(BBI++))) {
Torok Edwin3790fb02009-05-24 19:36:09 +0000508 if (PN->use_empty())
509 continue; // dead use, don't replace it
Dan Gohman814f2b22010-02-18 21:34:02 +0000510
511 // SCEV only supports integer expressions for now.
512 if (!PN->getType()->isIntegerTy() && !PN->getType()->isPointerTy())
513 continue;
514
Dale Johannesen45a2d7d2010-02-19 07:14:22 +0000515 // It's necessary to tell ScalarEvolution about this explicitly so that
516 // it can walk the def-use list and forget all SCEVs, as it may not be
517 // watching the PHI itself. Once the new exit value is in place, there
518 // may not be a def-use connection between the loop and every instruction
519 // which got a SCEVAddRecExpr for that loop.
520 SE->forgetValue(PN);
521
Chris Lattner9f3d7382007-03-04 03:43:23 +0000522 // Iterate over all of the values in all the PHI nodes.
523 for (unsigned i = 0; i != NumPreds; ++i) {
524 // If the value being merged in is not integer or is not defined
525 // in the loop, skip it.
526 Value *InVal = PN->getIncomingValue(i);
Dan Gohman814f2b22010-02-18 21:34:02 +0000527 if (!isa<Instruction>(InVal))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000528 continue;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000529
Chris Lattner9f3d7382007-03-04 03:43:23 +0000530 // If this pred is for a subloop, not L itself, skip it.
Dan Gohmancafb8132009-02-17 19:13:57 +0000531 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
Chris Lattner9f3d7382007-03-04 03:43:23 +0000532 continue; // The Block is in a subloop, skip it.
533
534 // Check that InVal is defined in the loop.
535 Instruction *Inst = cast<Instruction>(InVal);
Dan Gohman92329c72009-12-18 01:24:09 +0000536 if (!L->contains(Inst))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000537 continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000538
Chris Lattner9f3d7382007-03-04 03:43:23 +0000539 // Okay, this instruction has a user outside of the current loop
540 // and varies predictably *inside* the loop. Evaluate the value it
541 // contains when the loop exits, if possible.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000542 const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
Dan Gohman17ead4f2010-11-17 21:23:15 +0000543 if (!SE->isLoopInvariant(ExitValue, L))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000544 continue;
Chris Lattner9caed542007-03-04 01:00:28 +0000545
Dan Gohman667d7872009-06-26 22:53:46 +0000546 Value *ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), Inst);
Dan Gohmancafb8132009-02-17 19:13:57 +0000547
David Greenef67ef312010-01-05 01:27:06 +0000548 DEBUG(dbgs() << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal << '\n'
Chris Lattnerbdff5482009-08-23 04:37:46 +0000549 << " LoopVal = " << *Inst << "\n");
Chris Lattner9f3d7382007-03-04 03:43:23 +0000550
Andrew Trickb12a7542011-03-17 23:51:11 +0000551 if (!isValidRewrite(Inst, ExitVal)) {
552 DeadInsts.push_back(ExitVal);
553 continue;
554 }
555 Changed = true;
556 ++NumReplaced;
557
Chris Lattner9f3d7382007-03-04 03:43:23 +0000558 PN->setIncomingValue(i, ExitVal);
Dan Gohmancafb8132009-02-17 19:13:57 +0000559
Dan Gohman81db61a2009-05-12 02:17:14 +0000560 // If this instruction is dead now, delete it.
561 RecursivelyDeleteTriviallyDeadInstructions(Inst);
Dan Gohmancafb8132009-02-17 19:13:57 +0000562
Dan Gohman65d1e2b2009-07-14 01:09:02 +0000563 if (NumPreds == 1) {
564 // Completely replace a single-pred PHI. This is safe, because the
565 // NewVal won't be variant in the loop, so we don't need an LCSSA phi
566 // node anymore.
Chris Lattner9f3d7382007-03-04 03:43:23 +0000567 PN->replaceAllUsesWith(ExitVal);
Dan Gohman81db61a2009-05-12 02:17:14 +0000568 RecursivelyDeleteTriviallyDeadInstructions(PN);
Chris Lattnerc9838f22007-03-03 22:48:48 +0000569 }
570 }
Dan Gohman65d1e2b2009-07-14 01:09:02 +0000571 if (NumPreds != 1) {
Dan Gohman667d7872009-06-26 22:53:46 +0000572 // Clone the PHI and delete the original one. This lets IVUsers and
573 // any other maps purge the original user from their records.
Devang Patel50b6e332009-10-27 22:16:29 +0000574 PHINode *NewPN = cast<PHINode>(PN->clone());
Dan Gohman667d7872009-06-26 22:53:46 +0000575 NewPN->takeName(PN);
576 NewPN->insertBefore(PN);
577 PN->replaceAllUsesWith(NewPN);
578 PN->eraseFromParent();
579 }
Chris Lattnerc9838f22007-03-03 22:48:48 +0000580 }
581 }
Dan Gohman472fdf72010-03-20 03:53:53 +0000582
583 // The insertion point instruction may have been deleted; clear it out
584 // so that the rewriter doesn't trip over it later.
585 Rewriter.clearInsertPoint();
Chris Lattner40bf8b42004-04-02 20:24:31 +0000586}
587
Andrew Trick1a54bb22011-07-12 00:08:50 +0000588//===----------------------------------------------------------------------===//
589// Rewrite IV users based on a canonical IV.
590// To be replaced by -disable-iv-rewrite.
591//===----------------------------------------------------------------------===//
Dale Johannesenc671d892009-04-15 23:31:51 +0000592
Andrew Trick2fabd462011-06-21 03:22:38 +0000593/// SimplifyIVUsers - Iteratively perform simplification on IVUsers within this
594/// loop. IVUsers is treated as a worklist. Each successive simplification may
595/// push more users which may themselves be candidates for simplification.
596///
597/// This is the old approach to IV simplification to be replaced by
598/// SimplifyIVUsersNoRewrite.
599///
600void IndVarSimplify::SimplifyIVUsers(SCEVExpander &Rewriter) {
601 // Each round of simplification involves a round of eliminating operations
602 // followed by a round of widening IVs. A single IVUsers worklist is used
603 // across all rounds. The inner loop advances the user. If widening exposes
604 // more uses, then another pass through the outer loop is triggered.
605 for (IVUsers::iterator I = IU->begin(); I != IU->end(); ++I) {
606 Instruction *UseInst = I->getUser();
607 Value *IVOperand = I->getOperandValToReplace();
608
609 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
610 EliminateIVComparison(ICmp, IVOperand);
611 continue;
612 }
613 if (BinaryOperator *Rem = dyn_cast<BinaryOperator>(UseInst)) {
614 bool IsSigned = Rem->getOpcode() == Instruction::SRem;
615 if (IsSigned || Rem->getOpcode() == Instruction::URem) {
Andrew Trick4417e532011-06-21 15:43:52 +0000616 EliminateIVRemainder(Rem, IVOperand, IsSigned);
Andrew Trick2fabd462011-06-21 03:22:38 +0000617 continue;
618 }
619 }
620 }
621}
622
Andrew Trick1a54bb22011-07-12 00:08:50 +0000623// FIXME: It is an extremely bad idea to indvar substitute anything more
624// complex than affine induction variables. Doing so will put expensive
625// polynomial evaluations inside of the loop, and the str reduction pass
626// currently can only reduce affine polynomials. For now just disable
627// indvar subst on anything more complex than an affine addrec, unless
628// it can be expanded to a trivial value.
629static bool isSafe(const SCEV *S, const Loop *L, ScalarEvolution *SE) {
630 // Loop-invariant values are safe.
631 if (SE->isLoopInvariant(S, L)) return true;
632
633 // Affine addrecs are safe. Non-affine are not, because LSR doesn't know how
634 // to transform them into efficient code.
635 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
636 return AR->isAffine();
637
638 // An add is safe it all its operands are safe.
639 if (const SCEVCommutativeExpr *Commutative = dyn_cast<SCEVCommutativeExpr>(S)) {
640 for (SCEVCommutativeExpr::op_iterator I = Commutative->op_begin(),
641 E = Commutative->op_end(); I != E; ++I)
642 if (!isSafe(*I, L, SE)) return false;
643 return true;
644 }
645
646 // A cast is safe if its operand is.
647 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
648 return isSafe(C->getOperand(), L, SE);
649
650 // A udiv is safe if its operands are.
651 if (const SCEVUDivExpr *UD = dyn_cast<SCEVUDivExpr>(S))
652 return isSafe(UD->getLHS(), L, SE) &&
653 isSafe(UD->getRHS(), L, SE);
654
655 // SCEVUnknown is always safe.
656 if (isa<SCEVUnknown>(S))
657 return true;
658
659 // Nothing else is safe.
660 return false;
661}
662
663void IndVarSimplify::RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter) {
664 // Rewrite all induction variable expressions in terms of the canonical
665 // induction variable.
666 //
667 // If there were induction variables of other sizes or offsets, manually
668 // add the offsets to the primary induction variable and cast, avoiding
669 // the need for the code evaluation methods to insert induction variables
670 // of different sizes.
671 for (IVUsers::iterator UI = IU->begin(), E = IU->end(); UI != E; ++UI) {
672 Value *Op = UI->getOperandValToReplace();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000673 Type *UseTy = Op->getType();
Andrew Trick1a54bb22011-07-12 00:08:50 +0000674 Instruction *User = UI->getUser();
675
676 // Compute the final addrec to expand into code.
677 const SCEV *AR = IU->getReplacementExpr(*UI);
678
679 // Evaluate the expression out of the loop, if possible.
680 if (!L->contains(UI->getUser())) {
681 const SCEV *ExitVal = SE->getSCEVAtScope(AR, L->getParentLoop());
682 if (SE->isLoopInvariant(ExitVal, L))
683 AR = ExitVal;
684 }
685
686 // FIXME: It is an extremely bad idea to indvar substitute anything more
687 // complex than affine induction variables. Doing so will put expensive
688 // polynomial evaluations inside of the loop, and the str reduction pass
689 // currently can only reduce affine polynomials. For now just disable
690 // indvar subst on anything more complex than an affine addrec, unless
691 // it can be expanded to a trivial value.
692 if (!isSafe(AR, L, SE))
693 continue;
694
695 // Determine the insertion point for this user. By default, insert
696 // immediately before the user. The SCEVExpander class will automatically
697 // hoist loop invariants out of the loop. For PHI nodes, there may be
698 // multiple uses, so compute the nearest common dominator for the
699 // incoming blocks.
700 Instruction *InsertPt = User;
701 if (PHINode *PHI = dyn_cast<PHINode>(InsertPt))
702 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
703 if (PHI->getIncomingValue(i) == Op) {
704 if (InsertPt == User)
705 InsertPt = PHI->getIncomingBlock(i)->getTerminator();
706 else
707 InsertPt =
708 DT->findNearestCommonDominator(InsertPt->getParent(),
709 PHI->getIncomingBlock(i))
710 ->getTerminator();
711 }
712
713 // Now expand it into actual Instructions and patch it into place.
714 Value *NewVal = Rewriter.expandCodeFor(AR, UseTy, InsertPt);
715
716 DEBUG(dbgs() << "INDVARS: Rewrote IV '" << *AR << "' " << *Op << '\n'
717 << " into = " << *NewVal << "\n");
718
719 if (!isValidRewrite(Op, NewVal)) {
720 DeadInsts.push_back(NewVal);
721 continue;
722 }
723 // Inform ScalarEvolution that this value is changing. The change doesn't
724 // affect its value, but it does potentially affect which use lists the
725 // value will be on after the replacement, which affects ScalarEvolution's
726 // ability to walk use lists and drop dangling pointers when a value is
727 // deleted.
728 SE->forgetValue(User);
729
730 // Patch the new value into place.
731 if (Op->hasName())
732 NewVal->takeName(Op);
733 if (Instruction *NewValI = dyn_cast<Instruction>(NewVal))
734 NewValI->setDebugLoc(User->getDebugLoc());
735 User->replaceUsesOfWith(Op, NewVal);
736 UI->setOperandValToReplace(NewVal);
737
738 ++NumRemoved;
739 Changed = true;
740
741 // The old value may be dead now.
742 DeadInsts.push_back(Op);
743 }
744}
745
746//===----------------------------------------------------------------------===//
747// IV Widening - Extend the width of an IV to cover its widest uses.
748//===----------------------------------------------------------------------===//
749
Andrew Trickf85092c2011-05-20 18:25:42 +0000750namespace {
751 // Collect information about induction variables that are used by sign/zero
752 // extend operations. This information is recorded by CollectExtend and
753 // provides the input to WidenIV.
754 struct WideIVInfo {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000755 Type *WidestNativeType; // Widest integer type created [sz]ext
Andrew Trickf85092c2011-05-20 18:25:42 +0000756 bool IsSigned; // Was an sext user seen before a zext?
757
758 WideIVInfo() : WidestNativeType(0), IsSigned(false) {}
759 };
Andrew Trickf85092c2011-05-20 18:25:42 +0000760}
761
762/// CollectExtend - Update information about the induction variable that is
763/// extended by this sign or zero extend operation. This is used to determine
764/// the final width of the IV before actually widening it.
Andrew Trick2fabd462011-06-21 03:22:38 +0000765static void CollectExtend(CastInst *Cast, bool IsSigned, WideIVInfo &WI,
766 ScalarEvolution *SE, const TargetData *TD) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000767 Type *Ty = Cast->getType();
Andrew Trickf85092c2011-05-20 18:25:42 +0000768 uint64_t Width = SE->getTypeSizeInBits(Ty);
769 if (TD && !TD->isLegalInteger(Width))
770 return;
771
Andrew Trick2fabd462011-06-21 03:22:38 +0000772 if (!WI.WidestNativeType) {
773 WI.WidestNativeType = SE->getEffectiveSCEVType(Ty);
774 WI.IsSigned = IsSigned;
Andrew Trickf85092c2011-05-20 18:25:42 +0000775 return;
776 }
777
778 // We extend the IV to satisfy the sign of its first user, arbitrarily.
Andrew Trick2fabd462011-06-21 03:22:38 +0000779 if (WI.IsSigned != IsSigned)
Andrew Trickf85092c2011-05-20 18:25:42 +0000780 return;
781
Andrew Trick2fabd462011-06-21 03:22:38 +0000782 if (Width > SE->getTypeSizeInBits(WI.WidestNativeType))
783 WI.WidestNativeType = SE->getEffectiveSCEVType(Ty);
Andrew Trickf85092c2011-05-20 18:25:42 +0000784}
785
786namespace {
787/// WidenIV - The goal of this transform is to remove sign and zero extends
788/// without creating any new induction variables. To do this, it creates a new
789/// phi of the wider type and redirects all users, either removing extends or
790/// inserting truncs whenever we stop propagating the type.
791///
792class WidenIV {
Andrew Trick2fabd462011-06-21 03:22:38 +0000793 // Parameters
Andrew Trickf85092c2011-05-20 18:25:42 +0000794 PHINode *OrigPhi;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000795 Type *WideType;
Andrew Trickf85092c2011-05-20 18:25:42 +0000796 bool IsSigned;
797
Andrew Trick2fabd462011-06-21 03:22:38 +0000798 // Context
799 LoopInfo *LI;
800 Loop *L;
Andrew Trickf85092c2011-05-20 18:25:42 +0000801 ScalarEvolution *SE;
Andrew Trick2fabd462011-06-21 03:22:38 +0000802 DominatorTree *DT;
Andrew Trickf85092c2011-05-20 18:25:42 +0000803
Andrew Trick2fabd462011-06-21 03:22:38 +0000804 // Result
Andrew Trickf85092c2011-05-20 18:25:42 +0000805 PHINode *WidePhi;
806 Instruction *WideInc;
807 const SCEV *WideIncExpr;
Andrew Trick2fabd462011-06-21 03:22:38 +0000808 SmallVectorImpl<WeakVH> &DeadInsts;
Andrew Trickf85092c2011-05-20 18:25:42 +0000809
Andrew Trick2fabd462011-06-21 03:22:38 +0000810 SmallPtrSet<Instruction*,16> Widened;
Andrew Trick4b029152011-07-02 02:34:25 +0000811 SmallVector<std::pair<Use *, Instruction *>, 8> NarrowIVUsers;
Andrew Trickf85092c2011-05-20 18:25:42 +0000812
813public:
Andrew Trick2fabd462011-06-21 03:22:38 +0000814 WidenIV(PHINode *PN, const WideIVInfo &WI, LoopInfo *LInfo,
815 ScalarEvolution *SEv, DominatorTree *DTree,
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000816 SmallVectorImpl<WeakVH> &DI) :
Andrew Trickf85092c2011-05-20 18:25:42 +0000817 OrigPhi(PN),
Andrew Trick2fabd462011-06-21 03:22:38 +0000818 WideType(WI.WidestNativeType),
819 IsSigned(WI.IsSigned),
Andrew Trickf85092c2011-05-20 18:25:42 +0000820 LI(LInfo),
821 L(LI->getLoopFor(OrigPhi->getParent())),
822 SE(SEv),
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000823 DT(DTree),
Andrew Trickf85092c2011-05-20 18:25:42 +0000824 WidePhi(0),
825 WideInc(0),
Andrew Trick2fabd462011-06-21 03:22:38 +0000826 WideIncExpr(0),
827 DeadInsts(DI) {
Andrew Trickf85092c2011-05-20 18:25:42 +0000828 assert(L->getHeader() == OrigPhi->getParent() && "Phi must be an IV");
829 }
830
Andrew Trick2fabd462011-06-21 03:22:38 +0000831 PHINode *CreateWideIV(SCEVExpander &Rewriter);
Andrew Trickf85092c2011-05-20 18:25:42 +0000832
833protected:
Andrew Trickf85092c2011-05-20 18:25:42 +0000834 Instruction *CloneIVUser(Instruction *NarrowUse,
835 Instruction *NarrowDef,
836 Instruction *WideDef);
837
Andrew Tricke0dc2fa2011-07-05 18:19:39 +0000838 const SCEVAddRecExpr *GetWideRecurrence(Instruction *NarrowUse);
839
Andrew Trickcc359d92011-06-29 23:03:57 +0000840 Instruction *WidenIVUse(Use &NarrowDefUse, Instruction *NarrowDef,
Andrew Trickf85092c2011-05-20 18:25:42 +0000841 Instruction *WideDef);
Andrew Trick4b029152011-07-02 02:34:25 +0000842
843 void pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef);
Andrew Trickf85092c2011-05-20 18:25:42 +0000844};
845} // anonymous namespace
846
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000847static Value *getExtend( Value *NarrowOper, Type *WideType,
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000848 bool IsSigned, IRBuilder<> &Builder) {
849 return IsSigned ? Builder.CreateSExt(NarrowOper, WideType) :
850 Builder.CreateZExt(NarrowOper, WideType);
Andrew Trickf85092c2011-05-20 18:25:42 +0000851}
852
853/// CloneIVUser - Instantiate a wide operation to replace a narrow
854/// operation. This only needs to handle operations that can evaluation to
855/// SCEVAddRec. It can safely return 0 for any operation we decide not to clone.
856Instruction *WidenIV::CloneIVUser(Instruction *NarrowUse,
857 Instruction *NarrowDef,
858 Instruction *WideDef) {
859 unsigned Opcode = NarrowUse->getOpcode();
860 switch (Opcode) {
861 default:
862 return 0;
863 case Instruction::Add:
864 case Instruction::Mul:
865 case Instruction::UDiv:
866 case Instruction::Sub:
867 case Instruction::And:
868 case Instruction::Or:
869 case Instruction::Xor:
870 case Instruction::Shl:
871 case Instruction::LShr:
872 case Instruction::AShr:
873 DEBUG(dbgs() << "Cloning IVUser: " << *NarrowUse << "\n");
874
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000875 IRBuilder<> Builder(NarrowUse);
876
877 // Replace NarrowDef operands with WideDef. Otherwise, we don't know
878 // anything about the narrow operand yet so must insert a [sz]ext. It is
879 // probably loop invariant and will be folded or hoisted. If it actually
880 // comes from a widened IV, it should be removed during a future call to
881 // WidenIVUse.
882 Value *LHS = (NarrowUse->getOperand(0) == NarrowDef) ? WideDef :
883 getExtend(NarrowUse->getOperand(0), WideType, IsSigned, Builder);
884 Value *RHS = (NarrowUse->getOperand(1) == NarrowDef) ? WideDef :
885 getExtend(NarrowUse->getOperand(1), WideType, IsSigned, Builder);
886
Andrew Trickf85092c2011-05-20 18:25:42 +0000887 BinaryOperator *NarrowBO = cast<BinaryOperator>(NarrowUse);
888 BinaryOperator *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(),
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000889 LHS, RHS,
Andrew Trickf85092c2011-05-20 18:25:42 +0000890 NarrowBO->getName());
Andrew Trickf85092c2011-05-20 18:25:42 +0000891 Builder.Insert(WideBO);
Andrew Trick6e0ce242011-06-30 19:02:17 +0000892 if (const OverflowingBinaryOperator *OBO =
893 dyn_cast<OverflowingBinaryOperator>(NarrowBO)) {
894 if (OBO->hasNoUnsignedWrap()) WideBO->setHasNoUnsignedWrap();
895 if (OBO->hasNoSignedWrap()) WideBO->setHasNoSignedWrap();
896 }
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000897 return WideBO;
Andrew Trickf85092c2011-05-20 18:25:42 +0000898 }
899 llvm_unreachable(0);
900}
901
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000902/// HoistStep - Attempt to hoist an IV increment above a potential use.
903///
904/// To successfully hoist, two criteria must be met:
905/// - IncV operands dominate InsertPos and
906/// - InsertPos dominates IncV
907///
908/// Meeting the second condition means that we don't need to check all of IncV's
909/// existing uses (it's moving up in the domtree).
910///
911/// This does not yet recursively hoist the operands, although that would
912/// not be difficult.
913static bool HoistStep(Instruction *IncV, Instruction *InsertPos,
914 const DominatorTree *DT)
915{
916 if (DT->dominates(IncV, InsertPos))
917 return true;
918
919 if (!DT->dominates(InsertPos->getParent(), IncV->getParent()))
920 return false;
921
922 if (IncV->mayHaveSideEffects())
923 return false;
924
925 // Attempt to hoist IncV
926 for (User::op_iterator OI = IncV->op_begin(), OE = IncV->op_end();
927 OI != OE; ++OI) {
928 Instruction *OInst = dyn_cast<Instruction>(OI);
929 if (OInst && !DT->dominates(OInst, InsertPos))
930 return false;
931 }
932 IncV->moveBefore(InsertPos);
933 return true;
934}
935
Andrew Tricke0dc2fa2011-07-05 18:19:39 +0000936// GetWideRecurrence - Is this instruction potentially interesting from IVUsers'
937// perspective after widening it's type? In other words, can the extend be
938// safely hoisted out of the loop with SCEV reducing the value to a recurrence
939// on the same loop. If so, return the sign or zero extended
940// recurrence. Otherwise return NULL.
941const SCEVAddRecExpr *WidenIV::GetWideRecurrence(Instruction *NarrowUse) {
942 if (!SE->isSCEVable(NarrowUse->getType()))
943 return 0;
944
945 const SCEV *NarrowExpr = SE->getSCEV(NarrowUse);
946 if (SE->getTypeSizeInBits(NarrowExpr->getType())
947 >= SE->getTypeSizeInBits(WideType)) {
948 // NarrowUse implicitly widens its operand. e.g. a gep with a narrow
949 // index. So don't follow this use.
950 return 0;
951 }
952
953 const SCEV *WideExpr = IsSigned ?
954 SE->getSignExtendExpr(NarrowExpr, WideType) :
955 SE->getZeroExtendExpr(NarrowExpr, WideType);
956 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(WideExpr);
957 if (!AddRec || AddRec->getLoop() != L)
958 return 0;
959
960 return AddRec;
961}
962
Andrew Trickf85092c2011-05-20 18:25:42 +0000963/// WidenIVUse - Determine whether an individual user of the narrow IV can be
964/// widened. If so, return the wide clone of the user.
Andrew Trickcc359d92011-06-29 23:03:57 +0000965Instruction *WidenIV::WidenIVUse(Use &NarrowDefUse, Instruction *NarrowDef,
Andrew Trickf85092c2011-05-20 18:25:42 +0000966 Instruction *WideDef) {
Andrew Trickcc359d92011-06-29 23:03:57 +0000967 Instruction *NarrowUse = cast<Instruction>(NarrowDefUse.getUser());
968
Andrew Trick4b029152011-07-02 02:34:25 +0000969 // Stop traversing the def-use chain at inner-loop phis or post-loop phis.
Andrew Trickf85092c2011-05-20 18:25:42 +0000970 if (isa<PHINode>(NarrowUse) && LI->getLoopFor(NarrowUse->getParent()) != L)
971 return 0;
972
Andrew Trickf85092c2011-05-20 18:25:42 +0000973 // Our raison d'etre! Eliminate sign and zero extension.
974 if (IsSigned ? isa<SExtInst>(NarrowUse) : isa<ZExtInst>(NarrowUse)) {
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000975 Value *NewDef = WideDef;
976 if (NarrowUse->getType() != WideType) {
977 unsigned CastWidth = SE->getTypeSizeInBits(NarrowUse->getType());
978 unsigned IVWidth = SE->getTypeSizeInBits(WideType);
979 if (CastWidth < IVWidth) {
980 // The cast isn't as wide as the IV, so insert a Trunc.
Andrew Trickcc359d92011-06-29 23:03:57 +0000981 IRBuilder<> Builder(NarrowDefUse);
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000982 NewDef = Builder.CreateTrunc(WideDef, NarrowUse->getType());
983 }
984 else {
985 // A wider extend was hidden behind a narrower one. This may induce
986 // another round of IV widening in which the intermediate IV becomes
987 // dead. It should be very rare.
988 DEBUG(dbgs() << "INDVARS: New IV " << *WidePhi
989 << " not wide enough to subsume " << *NarrowUse << "\n");
990 NarrowUse->replaceUsesOfWith(NarrowDef, WideDef);
991 NewDef = NarrowUse;
992 }
993 }
994 if (NewDef != NarrowUse) {
995 DEBUG(dbgs() << "INDVARS: eliminating " << *NarrowUse
996 << " replaced by " << *WideDef << "\n");
997 ++NumElimExt;
998 NarrowUse->replaceAllUsesWith(NewDef);
999 DeadInsts.push_back(NarrowUse);
1000 }
Andrew Trick2fabd462011-06-21 03:22:38 +00001001 // Now that the extend is gone, we want to expose it's uses for potential
1002 // further simplification. We don't need to directly inform SimplifyIVUsers
1003 // of the new users, because their parent IV will be processed later as a
1004 // new loop phi. If we preserved IVUsers analysis, we would also want to
1005 // push the uses of WideDef here.
Andrew Trickf85092c2011-05-20 18:25:42 +00001006
1007 // No further widening is needed. The deceased [sz]ext had done it for us.
1008 return 0;
1009 }
Andrew Trick4b029152011-07-02 02:34:25 +00001010
1011 // Does this user itself evaluate to a recurrence after widening?
Andrew Tricke0dc2fa2011-07-05 18:19:39 +00001012 const SCEVAddRecExpr *WideAddRec = GetWideRecurrence(NarrowUse);
Andrew Trickf85092c2011-05-20 18:25:42 +00001013 if (!WideAddRec) {
1014 // This user does not evaluate to a recurence after widening, so don't
1015 // follow it. Instead insert a Trunc to kill off the original use,
1016 // eventually isolating the original narrow IV so it can be removed.
Andrew Trickcc359d92011-06-29 23:03:57 +00001017 IRBuilder<> Builder(NarrowDefUse);
Andrew Trick03d3d3b2011-05-25 04:42:22 +00001018 Value *Trunc = Builder.CreateTrunc(WideDef, NarrowDef->getType());
Andrew Trickf85092c2011-05-20 18:25:42 +00001019 NarrowUse->replaceUsesOfWith(NarrowDef, Trunc);
1020 return 0;
1021 }
Andrew Trickfc933c02011-07-18 20:32:31 +00001022 // Assume block terminators cannot evaluate to a recurrence. We can't to
Andrew Trick4b029152011-07-02 02:34:25 +00001023 // insert a Trunc after a terminator if there happens to be a critical edge.
Andrew Trickcc359d92011-06-29 23:03:57 +00001024 assert(NarrowUse != NarrowUse->getParent()->getTerminator() &&
Andrew Trick4b029152011-07-02 02:34:25 +00001025 "SCEV is not expected to evaluate a block terminator");
Andrew Trickcc359d92011-06-29 23:03:57 +00001026
Andrew Trickfcdc9a42011-05-26 00:46:11 +00001027 // Reuse the IV increment that SCEVExpander created as long as it dominates
1028 // NarrowUse.
Andrew Trickf85092c2011-05-20 18:25:42 +00001029 Instruction *WideUse = 0;
Andrew Trickfcdc9a42011-05-26 00:46:11 +00001030 if (WideAddRec == WideIncExpr && HoistStep(WideInc, NarrowUse, DT)) {
Andrew Trickf85092c2011-05-20 18:25:42 +00001031 WideUse = WideInc;
1032 }
1033 else {
1034 WideUse = CloneIVUser(NarrowUse, NarrowDef, WideDef);
1035 if (!WideUse)
1036 return 0;
1037 }
Andrew Trick4b029152011-07-02 02:34:25 +00001038 // Evaluation of WideAddRec ensured that the narrow expression could be
1039 // extended outside the loop without overflow. This suggests that the wide use
Andrew Trickf85092c2011-05-20 18:25:42 +00001040 // evaluates to the same expression as the extended narrow use, but doesn't
1041 // absolutely guarantee it. Hence the following failsafe check. In rare cases
Andrew Trick2fabd462011-06-21 03:22:38 +00001042 // where it fails, we simply throw away the newly created wide use.
Andrew Trickf85092c2011-05-20 18:25:42 +00001043 if (WideAddRec != SE->getSCEV(WideUse)) {
1044 DEBUG(dbgs() << "Wide use expression mismatch: " << *WideUse
1045 << ": " << *SE->getSCEV(WideUse) << " != " << *WideAddRec << "\n");
1046 DeadInsts.push_back(WideUse);
1047 return 0;
1048 }
1049
1050 // Returning WideUse pushes it on the worklist.
1051 return WideUse;
1052}
1053
Andrew Trick4b029152011-07-02 02:34:25 +00001054/// pushNarrowIVUsers - Add eligible users of NarrowDef to NarrowIVUsers.
1055///
1056void WidenIV::pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef) {
1057 for (Value::use_iterator UI = NarrowDef->use_begin(),
1058 UE = NarrowDef->use_end(); UI != UE; ++UI) {
1059 Use &U = UI.getUse();
1060
1061 // Handle data flow merges and bizarre phi cycles.
1062 if (!Widened.insert(cast<Instruction>(U.getUser())))
1063 continue;
1064
1065 NarrowIVUsers.push_back(std::make_pair(&UI.getUse(), WideDef));
1066 }
1067}
1068
Andrew Trickf85092c2011-05-20 18:25:42 +00001069/// CreateWideIV - Process a single induction variable. First use the
1070/// SCEVExpander to create a wide induction variable that evaluates to the same
1071/// recurrence as the original narrow IV. Then use a worklist to forward
Andrew Trick2fabd462011-06-21 03:22:38 +00001072/// traverse the narrow IV's def-use chain. After WidenIVUse has processed all
Andrew Trickf85092c2011-05-20 18:25:42 +00001073/// interesting IV users, the narrow IV will be isolated for removal by
1074/// DeleteDeadPHIs.
1075///
1076/// It would be simpler to delete uses as they are processed, but we must avoid
1077/// invalidating SCEV expressions.
1078///
Andrew Trick2fabd462011-06-21 03:22:38 +00001079PHINode *WidenIV::CreateWideIV(SCEVExpander &Rewriter) {
Andrew Trickf85092c2011-05-20 18:25:42 +00001080 // Is this phi an induction variable?
1081 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(OrigPhi));
1082 if (!AddRec)
Andrew Trick2fabd462011-06-21 03:22:38 +00001083 return NULL;
Andrew Trickf85092c2011-05-20 18:25:42 +00001084
1085 // Widen the induction variable expression.
1086 const SCEV *WideIVExpr = IsSigned ?
1087 SE->getSignExtendExpr(AddRec, WideType) :
1088 SE->getZeroExtendExpr(AddRec, WideType);
1089
1090 assert(SE->getEffectiveSCEVType(WideIVExpr->getType()) == WideType &&
1091 "Expect the new IV expression to preserve its type");
1092
1093 // Can the IV be extended outside the loop without overflow?
1094 AddRec = dyn_cast<SCEVAddRecExpr>(WideIVExpr);
1095 if (!AddRec || AddRec->getLoop() != L)
Andrew Trick2fabd462011-06-21 03:22:38 +00001096 return NULL;
Andrew Trickf85092c2011-05-20 18:25:42 +00001097
Andrew Trick2fabd462011-06-21 03:22:38 +00001098 // An AddRec must have loop-invariant operands. Since this AddRec is
Andrew Trickf85092c2011-05-20 18:25:42 +00001099 // materialized by a loop header phi, the expression cannot have any post-loop
1100 // operands, so they must dominate the loop header.
1101 assert(SE->properlyDominates(AddRec->getStart(), L->getHeader()) &&
1102 SE->properlyDominates(AddRec->getStepRecurrence(*SE), L->getHeader())
1103 && "Loop header phi recurrence inputs do not dominate the loop");
1104
1105 // The rewriter provides a value for the desired IV expression. This may
1106 // either find an existing phi or materialize a new one. Either way, we
1107 // expect a well-formed cyclic phi-with-increments. i.e. any operand not part
1108 // of the phi-SCC dominates the loop entry.
1109 Instruction *InsertPt = L->getHeader()->begin();
1110 WidePhi = cast<PHINode>(Rewriter.expandCodeFor(AddRec, WideType, InsertPt));
1111
1112 // Remembering the WideIV increment generated by SCEVExpander allows
1113 // WidenIVUse to reuse it when widening the narrow IV's increment. We don't
1114 // employ a general reuse mechanism because the call above is the only call to
1115 // SCEVExpander. Henceforth, we produce 1-to-1 narrow to wide uses.
Andrew Trickfcdc9a42011-05-26 00:46:11 +00001116 if (BasicBlock *LatchBlock = L->getLoopLatch()) {
1117 WideInc =
1118 cast<Instruction>(WidePhi->getIncomingValueForBlock(LatchBlock));
1119 WideIncExpr = SE->getSCEV(WideInc);
1120 }
Andrew Trickf85092c2011-05-20 18:25:42 +00001121
1122 DEBUG(dbgs() << "Wide IV: " << *WidePhi << "\n");
1123 ++NumWidened;
1124
1125 // Traverse the def-use chain using a worklist starting at the original IV.
Andrew Trick4b029152011-07-02 02:34:25 +00001126 assert(Widened.empty() && NarrowIVUsers.empty() && "expect initial state" );
Andrew Trickf85092c2011-05-20 18:25:42 +00001127
Andrew Trick4b029152011-07-02 02:34:25 +00001128 Widened.insert(OrigPhi);
1129 pushNarrowIVUsers(OrigPhi, WidePhi);
1130
Andrew Trickf85092c2011-05-20 18:25:42 +00001131 while (!NarrowIVUsers.empty()) {
Andrew Trickcc359d92011-06-29 23:03:57 +00001132 Use *UsePtr;
Andrew Trickfcdc9a42011-05-26 00:46:11 +00001133 Instruction *WideDef;
Andrew Trickcc359d92011-06-29 23:03:57 +00001134 tie(UsePtr, WideDef) = NarrowIVUsers.pop_back_val();
1135 Use &NarrowDefUse = *UsePtr;
Andrew Trickf85092c2011-05-20 18:25:42 +00001136
Andrew Trickfcdc9a42011-05-26 00:46:11 +00001137 // Process a def-use edge. This may replace the use, so don't hold a
1138 // use_iterator across it.
Andrew Trickcc359d92011-06-29 23:03:57 +00001139 Instruction *NarrowDef = cast<Instruction>(NarrowDefUse.get());
1140 Instruction *WideUse = WidenIVUse(NarrowDefUse, NarrowDef, WideDef);
Andrew Trickf85092c2011-05-20 18:25:42 +00001141
Andrew Trickfcdc9a42011-05-26 00:46:11 +00001142 // Follow all def-use edges from the previous narrow use.
Andrew Trick4b029152011-07-02 02:34:25 +00001143 if (WideUse)
1144 pushNarrowIVUsers(cast<Instruction>(NarrowDefUse.getUser()), WideUse);
1145
Andrew Trickfcdc9a42011-05-26 00:46:11 +00001146 // WidenIVUse may have removed the def-use edge.
1147 if (NarrowDef->use_empty())
1148 DeadInsts.push_back(NarrowDef);
Andrew Trickf85092c2011-05-20 18:25:42 +00001149 }
Andrew Trick2fabd462011-06-21 03:22:38 +00001150 return WidePhi;
Andrew Trickf85092c2011-05-20 18:25:42 +00001151}
1152
Andrew Trick1a54bb22011-07-12 00:08:50 +00001153//===----------------------------------------------------------------------===//
1154// Simplification of IV users based on SCEV evaluation.
1155//===----------------------------------------------------------------------===//
1156
Andrew Trickaeee4612011-05-12 00:04:28 +00001157void IndVarSimplify::EliminateIVComparison(ICmpInst *ICmp, Value *IVOperand) {
1158 unsigned IVOperIdx = 0;
1159 ICmpInst::Predicate Pred = ICmp->getPredicate();
1160 if (IVOperand != ICmp->getOperand(0)) {
1161 // Swapped
1162 assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
1163 IVOperIdx = 1;
1164 Pred = ICmpInst::getSwappedPredicate(Pred);
Dan Gohmana590b792010-04-13 01:46:36 +00001165 }
Andrew Trickaeee4612011-05-12 00:04:28 +00001166
1167 // Get the SCEVs for the ICmp operands.
1168 const SCEV *S = SE->getSCEV(ICmp->getOperand(IVOperIdx));
1169 const SCEV *X = SE->getSCEV(ICmp->getOperand(1 - IVOperIdx));
1170
1171 // Simplify unnecessary loops away.
1172 const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
1173 S = SE->getSCEVAtScope(S, ICmpLoop);
1174 X = SE->getSCEVAtScope(X, ICmpLoop);
1175
1176 // If the condition is always true or always false, replace it with
1177 // a constant value.
1178 if (SE->isKnownPredicate(Pred, S, X))
1179 ICmp->replaceAllUsesWith(ConstantInt::getTrue(ICmp->getContext()));
1180 else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X))
1181 ICmp->replaceAllUsesWith(ConstantInt::getFalse(ICmp->getContext()));
1182 else
1183 return;
1184
1185 DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
Andrew Trick03d3d3b2011-05-25 04:42:22 +00001186 ++NumElimCmp;
Andrew Trick074397d2011-05-20 03:37:48 +00001187 Changed = true;
Andrew Trickaeee4612011-05-12 00:04:28 +00001188 DeadInsts.push_back(ICmp);
1189}
1190
1191void IndVarSimplify::EliminateIVRemainder(BinaryOperator *Rem,
1192 Value *IVOperand,
Andrew Trick4417e532011-06-21 15:43:52 +00001193 bool IsSigned) {
Andrew Trickaeee4612011-05-12 00:04:28 +00001194 // We're only interested in the case where we know something about
1195 // the numerator.
1196 if (IVOperand != Rem->getOperand(0))
1197 return;
1198
1199 // Get the SCEVs for the ICmp operands.
1200 const SCEV *S = SE->getSCEV(Rem->getOperand(0));
1201 const SCEV *X = SE->getSCEV(Rem->getOperand(1));
1202
1203 // Simplify unnecessary loops away.
1204 const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent());
1205 S = SE->getSCEVAtScope(S, ICmpLoop);
1206 X = SE->getSCEVAtScope(X, ICmpLoop);
1207
1208 // i % n --> i if i is in [0,n).
Andrew Trick074397d2011-05-20 03:37:48 +00001209 if ((!IsSigned || SE->isKnownNonNegative(S)) &&
1210 SE->isKnownPredicate(IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
Andrew Trickaeee4612011-05-12 00:04:28 +00001211 S, X))
1212 Rem->replaceAllUsesWith(Rem->getOperand(0));
1213 else {
1214 // (i+1) % n --> (i+1)==n?0:(i+1) if i is in [0,n).
1215 const SCEV *LessOne =
1216 SE->getMinusSCEV(S, SE->getConstant(S->getType(), 1));
Andrew Trick074397d2011-05-20 03:37:48 +00001217 if (IsSigned && !SE->isKnownNonNegative(LessOne))
Andrew Trickaeee4612011-05-12 00:04:28 +00001218 return;
1219
Andrew Trick074397d2011-05-20 03:37:48 +00001220 if (!SE->isKnownPredicate(IsSigned ?
Andrew Trickaeee4612011-05-12 00:04:28 +00001221 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
1222 LessOne, X))
1223 return;
1224
1225 ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ,
1226 Rem->getOperand(0), Rem->getOperand(1),
1227 "tmp");
1228 SelectInst *Sel =
1229 SelectInst::Create(ICmp,
1230 ConstantInt::get(Rem->getType(), 0),
1231 Rem->getOperand(0), "tmp", Rem);
1232 Rem->replaceAllUsesWith(Sel);
1233 }
1234
1235 // Inform IVUsers about the new users.
Andrew Trick2fabd462011-06-21 03:22:38 +00001236 if (IU) {
1237 if (Instruction *I = dyn_cast<Instruction>(Rem->getOperand(0)))
Andrew Trick4417e532011-06-21 15:43:52 +00001238 IU->AddUsersIfInteresting(I);
Andrew Trick2fabd462011-06-21 03:22:38 +00001239 }
Andrew Trickaeee4612011-05-12 00:04:28 +00001240 DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
Andrew Trick03d3d3b2011-05-25 04:42:22 +00001241 ++NumElimRem;
Andrew Trick074397d2011-05-20 03:37:48 +00001242 Changed = true;
Andrew Trickaeee4612011-05-12 00:04:28 +00001243 DeadInsts.push_back(Rem);
Dan Gohmana590b792010-04-13 01:46:36 +00001244}
1245
Andrew Trick2fabd462011-06-21 03:22:38 +00001246/// EliminateIVUser - Eliminate an operation that consumes a simple IV and has
1247/// no observable side-effect given the range of IV values.
1248bool IndVarSimplify::EliminateIVUser(Instruction *UseInst,
1249 Instruction *IVOperand) {
1250 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
1251 EliminateIVComparison(ICmp, IVOperand);
1252 return true;
1253 }
1254 if (BinaryOperator *Rem = dyn_cast<BinaryOperator>(UseInst)) {
1255 bool IsSigned = Rem->getOpcode() == Instruction::SRem;
1256 if (IsSigned || Rem->getOpcode() == Instruction::URem) {
Andrew Trick4417e532011-06-21 15:43:52 +00001257 EliminateIVRemainder(Rem, IVOperand, IsSigned);
Andrew Trick2fabd462011-06-21 03:22:38 +00001258 return true;
1259 }
1260 }
1261
1262 // Eliminate any operation that SCEV can prove is an identity function.
1263 if (!SE->isSCEVable(UseInst->getType()) ||
Andrew Trick11745d42011-06-29 03:13:40 +00001264 (UseInst->getType() != IVOperand->getType()) ||
Andrew Trick2fabd462011-06-21 03:22:38 +00001265 (SE->getSCEV(UseInst) != SE->getSCEV(IVOperand)))
1266 return false;
1267
Andrew Trick2fabd462011-06-21 03:22:38 +00001268 DEBUG(dbgs() << "INDVARS: Eliminated identity: " << *UseInst << '\n');
Andrew Trick60ac7192011-06-30 01:27:23 +00001269
1270 UseInst->replaceAllUsesWith(IVOperand);
Andrew Trick2fabd462011-06-21 03:22:38 +00001271 ++NumElimIdentity;
1272 Changed = true;
1273 DeadInsts.push_back(UseInst);
1274 return true;
1275}
1276
1277/// pushIVUsers - Add all uses of Def to the current IV's worklist.
1278///
Andrew Trick15832f62011-06-28 02:49:20 +00001279static void pushIVUsers(
1280 Instruction *Def,
1281 SmallPtrSet<Instruction*,16> &Simplified,
1282 SmallVectorImpl< std::pair<Instruction*,Instruction*> > &SimpleIVUsers) {
Andrew Trick2fabd462011-06-21 03:22:38 +00001283
1284 for (Value::use_iterator UI = Def->use_begin(), E = Def->use_end();
1285 UI != E; ++UI) {
1286 Instruction *User = cast<Instruction>(*UI);
1287
1288 // Avoid infinite or exponential worklist processing.
1289 // Also ensure unique worklist users.
Andrew Trick60ac7192011-06-30 01:27:23 +00001290 // If Def is a LoopPhi, it may not be in the Simplified set, so check for
1291 // self edges first.
1292 if (User != Def && Simplified.insert(User))
Andrew Trick2fabd462011-06-21 03:22:38 +00001293 SimpleIVUsers.push_back(std::make_pair(User, Def));
1294 }
1295}
1296
1297/// isSimpleIVUser - Return true if this instruction generates a simple SCEV
1298/// expression in terms of that IV.
1299///
1300/// This is similar to IVUsers' isInsteresting() but processes each instruction
1301/// non-recursively when the operand is already known to be a simpleIVUser.
1302///
Andrew Trick1a54bb22011-07-12 00:08:50 +00001303static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE) {
Andrew Trick2fabd462011-06-21 03:22:38 +00001304 if (!SE->isSCEVable(I->getType()))
1305 return false;
1306
1307 // Get the symbolic expression for this instruction.
1308 const SCEV *S = SE->getSCEV(I);
1309
1310 // Only consider affine recurrences.
1311 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S);
1312 if (AR && AR->getLoop() == L)
1313 return true;
1314
1315 return false;
1316}
1317
1318/// SimplifyIVUsersNoRewrite - Iteratively perform simplification on a worklist
1319/// of IV users. Each successive simplification may push more users which may
1320/// themselves be candidates for simplification.
1321///
1322/// The "NoRewrite" algorithm does not require IVUsers analysis. Instead, it
1323/// simplifies instructions in-place during analysis. Rather than rewriting
1324/// induction variables bottom-up from their users, it transforms a chain of
1325/// IVUsers top-down, updating the IR only when it encouters a clear
1326/// optimization opportunitiy. A SCEVExpander "Rewriter" instance is still
1327/// needed, but only used to generate a new IV (phi) of wider type for sign/zero
1328/// extend elimination.
1329///
1330/// Once DisableIVRewrite is default, LSR will be the only client of IVUsers.
1331///
1332void IndVarSimplify::SimplifyIVUsersNoRewrite(Loop *L, SCEVExpander &Rewriter) {
Andrew Trick15832f62011-06-28 02:49:20 +00001333 std::map<PHINode *, WideIVInfo> WideIVMap;
1334
Andrew Trick2fabd462011-06-21 03:22:38 +00001335 SmallVector<PHINode*, 8> LoopPhis;
1336 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
1337 LoopPhis.push_back(cast<PHINode>(I));
1338 }
Andrew Trick15832f62011-06-28 02:49:20 +00001339 // Each round of simplification iterates through the SimplifyIVUsers worklist
1340 // for all current phis, then determines whether any IVs can be
1341 // widened. Widening adds new phis to LoopPhis, inducing another round of
1342 // simplification on the wide IVs.
Andrew Trick2fabd462011-06-21 03:22:38 +00001343 while (!LoopPhis.empty()) {
Andrew Trick15832f62011-06-28 02:49:20 +00001344 // Evaluate as many IV expressions as possible before widening any IVs. This
Andrew Trick99a92f62011-06-28 16:45:04 +00001345 // forces SCEV to set no-wrap flags before evaluating sign/zero
Andrew Trick15832f62011-06-28 02:49:20 +00001346 // extension. The first time SCEV attempts to normalize sign/zero extension,
1347 // the result becomes final. So for the most predictable results, we delay
1348 // evaluation of sign/zero extend evaluation until needed, and avoid running
1349 // other SCEV based analysis prior to SimplifyIVUsersNoRewrite.
1350 do {
1351 PHINode *CurrIV = LoopPhis.pop_back_val();
Andrew Trick2fabd462011-06-21 03:22:38 +00001352
Andrew Trick15832f62011-06-28 02:49:20 +00001353 // Information about sign/zero extensions of CurrIV.
1354 WideIVInfo WI;
Andrew Trick2fabd462011-06-21 03:22:38 +00001355
Andrew Trick15832f62011-06-28 02:49:20 +00001356 // Instructions processed by SimplifyIVUsers for CurrIV.
1357 SmallPtrSet<Instruction*,16> Simplified;
Andrew Trick2fabd462011-06-21 03:22:38 +00001358
Andrew Trick037d1c02011-07-06 20:50:43 +00001359 // Use-def pairs if IV users waiting to be processed for CurrIV.
Andrew Trick15832f62011-06-28 02:49:20 +00001360 SmallVector<std::pair<Instruction*, Instruction*>, 8> SimpleIVUsers;
Andrew Trick2fabd462011-06-21 03:22:38 +00001361
Andrew Trick60ac7192011-06-30 01:27:23 +00001362 // Push users of the current LoopPhi. In rare cases, pushIVUsers may be
1363 // called multiple times for the same LoopPhi. This is the proper thing to
1364 // do for loop header phis that use each other.
Andrew Trick15832f62011-06-28 02:49:20 +00001365 pushIVUsers(CurrIV, Simplified, SimpleIVUsers);
1366
1367 while (!SimpleIVUsers.empty()) {
1368 Instruction *UseInst, *Operand;
1369 tie(UseInst, Operand) = SimpleIVUsers.pop_back_val();
Andrew Trick6e0ce242011-06-30 19:02:17 +00001370 // Bypass back edges to avoid extra work.
1371 if (UseInst == CurrIV) continue;
Andrew Trick15832f62011-06-28 02:49:20 +00001372
1373 if (EliminateIVUser(UseInst, Operand)) {
1374 pushIVUsers(Operand, Simplified, SimpleIVUsers);
1375 continue;
Andrew Trick2fabd462011-06-21 03:22:38 +00001376 }
Andrew Trick15832f62011-06-28 02:49:20 +00001377 if (CastInst *Cast = dyn_cast<CastInst>(UseInst)) {
1378 bool IsSigned = Cast->getOpcode() == Instruction::SExt;
1379 if (IsSigned || Cast->getOpcode() == Instruction::ZExt) {
1380 CollectExtend(Cast, IsSigned, WI, SE, TD);
1381 }
1382 continue;
1383 }
Andrew Trick1a54bb22011-07-12 00:08:50 +00001384 if (isSimpleIVUser(UseInst, L, SE)) {
Andrew Trick15832f62011-06-28 02:49:20 +00001385 pushIVUsers(UseInst, Simplified, SimpleIVUsers);
1386 }
Andrew Trick2fabd462011-06-21 03:22:38 +00001387 }
Andrew Trick15832f62011-06-28 02:49:20 +00001388 if (WI.WidestNativeType) {
1389 WideIVMap[CurrIV] = WI;
Andrew Trick2fabd462011-06-21 03:22:38 +00001390 }
Andrew Trick15832f62011-06-28 02:49:20 +00001391 } while(!LoopPhis.empty());
1392
1393 for (std::map<PHINode *, WideIVInfo>::const_iterator I = WideIVMap.begin(),
1394 E = WideIVMap.end(); I != E; ++I) {
1395 WidenIV Widener(I->first, I->second, LI, SE, DT, DeadInsts);
Andrew Trick2fabd462011-06-21 03:22:38 +00001396 if (PHINode *WidePhi = Widener.CreateWideIV(Rewriter)) {
1397 Changed = true;
1398 LoopPhis.push_back(WidePhi);
1399 }
1400 }
Andrew Trick15832f62011-06-28 02:49:20 +00001401 WideIVMap.clear();
Andrew Trick2fabd462011-06-21 03:22:38 +00001402 }
1403}
1404
Andrew Trick037d1c02011-07-06 20:50:43 +00001405/// SimplifyCongruentIVs - Check for congruent phis in this loop header and
1406/// populate ExprToIVMap for use later.
1407///
1408void IndVarSimplify::SimplifyCongruentIVs(Loop *L) {
Andrew Trick6f684b02011-07-16 01:06:48 +00001409 DenseMap<const SCEV *, PHINode *> ExprToIVMap;
Andrew Trick037d1c02011-07-06 20:50:43 +00001410 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
1411 PHINode *Phi = cast<PHINode>(I);
Andrew Trick1a54bb22011-07-12 00:08:50 +00001412 if (!SE->isSCEVable(Phi->getType()))
1413 continue;
1414
Andrew Trick037d1c02011-07-06 20:50:43 +00001415 const SCEV *S = SE->getSCEV(Phi);
Andrew Trick6f684b02011-07-16 01:06:48 +00001416 DenseMap<const SCEV *, PHINode *>::const_iterator Pos;
Andrew Trick037d1c02011-07-06 20:50:43 +00001417 bool Inserted;
1418 tie(Pos, Inserted) = ExprToIVMap.insert(std::make_pair(S, Phi));
1419 if (Inserted)
1420 continue;
1421 PHINode *OrigPhi = Pos->second;
1422 // Replacing the congruent phi is sufficient because acyclic redundancy
1423 // elimination, CSE/GVN, should handle the rest. However, once SCEV proves
1424 // that a phi is congruent, it's almost certain to be the head of an IV
1425 // user cycle that is isomorphic with the original phi. So it's worth
1426 // eagerly cleaning up the common case of a single IV increment.
1427 if (BasicBlock *LatchBlock = L->getLoopLatch()) {
1428 Instruction *OrigInc =
1429 cast<Instruction>(OrigPhi->getIncomingValueForBlock(LatchBlock));
1430 Instruction *IsomorphicInc =
1431 cast<Instruction>(Phi->getIncomingValueForBlock(LatchBlock));
1432 if (OrigInc != IsomorphicInc &&
1433 SE->getSCEV(OrigInc) == SE->getSCEV(IsomorphicInc) &&
1434 HoistStep(OrigInc, IsomorphicInc, DT)) {
1435 DEBUG(dbgs() << "INDVARS: Eliminated congruent iv.inc: "
1436 << *IsomorphicInc << '\n');
1437 IsomorphicInc->replaceAllUsesWith(OrigInc);
1438 DeadInsts.push_back(IsomorphicInc);
1439 }
1440 }
1441 DEBUG(dbgs() << "INDVARS: Eliminated congruent iv: " << *Phi << '\n');
1442 ++NumElimIV;
1443 Phi->replaceAllUsesWith(OrigPhi);
1444 DeadInsts.push_back(Phi);
1445 }
1446}
1447
Andrew Trick1a54bb22011-07-12 00:08:50 +00001448//===----------------------------------------------------------------------===//
1449// LinearFunctionTestReplace and its kin. Rewrite the loop exit condition.
1450//===----------------------------------------------------------------------===//
1451
Andrew Trick5241b792011-07-18 18:21:35 +00001452// Check for expressions that ScalarEvolution generates to compute
1453// BackedgeTakenInfo. If these expressions have not been reduced, then expanding
1454// them may incur additional cost (albeit in the loop preheader).
1455static bool isHighCostExpansion(const SCEV *S, BranchInst *BI,
1456 ScalarEvolution *SE) {
1457 // If the backedge-taken count is a UDiv, it's very likely a UDiv that
1458 // ScalarEvolution's HowFarToZero or HowManyLessThans produced to compute a
1459 // precise expression, rather than a UDiv from the user's code. If we can't
1460 // find a UDiv in the code with some simple searching, assume the former and
1461 // forego rewriting the loop.
1462 if (isa<SCEVUDivExpr>(S)) {
1463 ICmpInst *OrigCond = dyn_cast<ICmpInst>(BI->getCondition());
1464 if (!OrigCond) return true;
1465 const SCEV *R = SE->getSCEV(OrigCond->getOperand(1));
1466 R = SE->getMinusSCEV(R, SE->getConstant(R->getType(), 1));
1467 if (R != S) {
1468 const SCEV *L = SE->getSCEV(OrigCond->getOperand(0));
1469 L = SE->getMinusSCEV(L, SE->getConstant(L->getType(), 1));
1470 if (L != S)
1471 return true;
1472 }
1473 }
1474
Andrew Trickfc933c02011-07-18 20:32:31 +00001475 if (!DisableIVRewrite || ForceLFTR)
Andrew Trick5241b792011-07-18 18:21:35 +00001476 return false;
1477
1478 // Recurse past add expressions, which commonly occur in the
1479 // BackedgeTakenCount. They may already exist in program code, and if not,
1480 // they are not too expensive rematerialize.
1481 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
1482 for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
1483 I != E; ++I) {
1484 if (isHighCostExpansion(*I, BI, SE))
1485 return true;
1486 }
1487 return false;
1488 }
1489
1490 // HowManyLessThans uses a Max expression whenever the loop is not guarded by
1491 // the exit condition.
1492 if (isa<SCEVSMaxExpr>(S) || isa<SCEVUMaxExpr>(S))
1493 return true;
1494
1495 // If we haven't recognized an expensive SCEV patter, assume its an expression
1496 // produced by program code.
1497 return false;
1498}
1499
Andrew Trick1a54bb22011-07-12 00:08:50 +00001500/// canExpandBackedgeTakenCount - Return true if this loop's backedge taken
1501/// count expression can be safely and cheaply expanded into an instruction
1502/// sequence that can be used by LinearFunctionTestReplace.
1503static bool canExpandBackedgeTakenCount(Loop *L, ScalarEvolution *SE) {
1504 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
1505 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount) ||
1506 BackedgeTakenCount->isZero())
1507 return false;
1508
1509 if (!L->getExitingBlock())
1510 return false;
1511
1512 // Can't rewrite non-branch yet.
1513 BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator());
1514 if (!BI)
1515 return false;
1516
Andrew Trick5241b792011-07-18 18:21:35 +00001517 if (isHighCostExpansion(BackedgeTakenCount, BI, SE))
1518 return false;
1519
Andrew Trick1a54bb22011-07-12 00:08:50 +00001520 return true;
1521}
1522
1523/// getBackedgeIVType - Get the widest type used by the loop test after peeking
1524/// through Truncs.
1525///
Andrew Trickfc933c02011-07-18 20:32:31 +00001526/// TODO: Unnecessary when ForceLFTR is removed.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001527static Type *getBackedgeIVType(Loop *L) {
Andrew Trick1a54bb22011-07-12 00:08:50 +00001528 if (!L->getExitingBlock())
1529 return 0;
1530
1531 // Can't rewrite non-branch yet.
1532 BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator());
1533 if (!BI)
1534 return 0;
1535
1536 ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition());
1537 if (!Cond)
1538 return 0;
1539
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001540 Type *Ty = 0;
Andrew Trick1a54bb22011-07-12 00:08:50 +00001541 for(User::op_iterator OI = Cond->op_begin(), OE = Cond->op_end();
1542 OI != OE; ++OI) {
1543 assert((!Ty || Ty == (*OI)->getType()) && "bad icmp operand types");
1544 TruncInst *Trunc = dyn_cast<TruncInst>(*OI);
1545 if (!Trunc)
1546 continue;
1547
1548 return Trunc->getSrcTy();
1549 }
1550 return Ty;
1551}
1552
Andrew Trickfc933c02011-07-18 20:32:31 +00001553/// isLoopInvariant - Perform a quick domtree based check for loop invariance
1554/// assuming that V is used within the loop. LoopInfo::isLoopInvariant() seems
1555/// gratuitous for this purpose.
1556static bool isLoopInvariant(Value *V, Loop *L, DominatorTree *DT) {
1557 Instruction *Inst = dyn_cast<Instruction>(V);
1558 if (!Inst)
1559 return true;
1560
1561 return DT->properlyDominates(Inst->getParent(), L->getHeader());
1562}
1563
1564/// getLoopPhiForCounter - Return the loop header phi IFF IncV adds a loop
1565/// invariant value to the phi.
1566static PHINode *getLoopPhiForCounter(Value *IncV, Loop *L, DominatorTree *DT) {
1567 Instruction *IncI = dyn_cast<Instruction>(IncV);
1568 if (!IncI)
1569 return 0;
1570
1571 switch (IncI->getOpcode()) {
1572 case Instruction::Add:
1573 case Instruction::Sub:
1574 break;
1575 case Instruction::GetElementPtr:
1576 // An IV counter must preserve its type.
1577 if (IncI->getNumOperands() == 2)
1578 break;
1579 default:
1580 return 0;
1581 }
1582
1583 PHINode *Phi = dyn_cast<PHINode>(IncI->getOperand(0));
1584 if (Phi && Phi->getParent() == L->getHeader()) {
1585 if (isLoopInvariant(IncI->getOperand(1), L, DT))
1586 return Phi;
1587 return 0;
1588 }
1589 if (IncI->getOpcode() == Instruction::GetElementPtr)
1590 return 0;
1591
1592 // Allow add/sub to be commuted.
1593 Phi = dyn_cast<PHINode>(IncI->getOperand(1));
1594 if (Phi && Phi->getParent() == L->getHeader()) {
1595 if (isLoopInvariant(IncI->getOperand(0), L, DT))
1596 return Phi;
1597 }
1598 return 0;
1599}
1600
1601/// needsLFTR - LinearFunctionTestReplace policy. Return true unless we can show
1602/// that the current exit test is already sufficiently canonical.
1603static bool needsLFTR(Loop *L, DominatorTree *DT) {
1604 assert(L->getExitingBlock() && "expected loop exit");
1605
1606 BasicBlock *LatchBlock = L->getLoopLatch();
1607 // Don't bother with LFTR if the loop is not properly simplified.
1608 if (!LatchBlock)
1609 return false;
1610
1611 BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator());
1612 assert(BI && "expected exit branch");
1613
1614 // Do LFTR to simplify the exit condition to an ICMP.
1615 ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition());
1616 if (!Cond)
1617 return true;
1618
1619 // Do LFTR to simplify the exit ICMP to EQ/NE
1620 ICmpInst::Predicate Pred = Cond->getPredicate();
1621 if (Pred != ICmpInst::ICMP_NE && Pred != ICmpInst::ICMP_EQ)
1622 return true;
1623
1624 // Look for a loop invariant RHS
1625 Value *LHS = Cond->getOperand(0);
1626 Value *RHS = Cond->getOperand(1);
1627 if (!isLoopInvariant(RHS, L, DT)) {
1628 if (!isLoopInvariant(LHS, L, DT))
1629 return true;
1630 std::swap(LHS, RHS);
1631 }
1632 // Look for a simple IV counter LHS
1633 PHINode *Phi = dyn_cast<PHINode>(LHS);
1634 if (!Phi)
1635 Phi = getLoopPhiForCounter(LHS, L, DT);
1636
1637 if (!Phi)
1638 return true;
1639
1640 // Do LFTR if the exit condition's IV is *not* a simple counter.
1641 Value *IncV = Phi->getIncomingValueForBlock(L->getLoopLatch());
1642 return Phi != getLoopPhiForCounter(IncV, L, DT);
1643}
1644
1645/// AlmostDeadIV - Return true if this IV has any uses other than the (soon to
1646/// be rewritten) loop exit test.
1647static bool AlmostDeadIV(PHINode *Phi, BasicBlock *LatchBlock, Value *Cond) {
1648 int LatchIdx = Phi->getBasicBlockIndex(LatchBlock);
1649 Value *IncV = Phi->getIncomingValue(LatchIdx);
1650
1651 for (Value::use_iterator UI = Phi->use_begin(), UE = Phi->use_end();
1652 UI != UE; ++UI) {
1653 if (*UI != Cond && *UI != IncV) return false;
1654 }
1655
1656 for (Value::use_iterator UI = IncV->use_begin(), UE = IncV->use_end();
1657 UI != UE; ++UI) {
1658 if (*UI != Cond && *UI != Phi) return false;
1659 }
1660 return true;
1661}
1662
1663/// FindLoopCounter - Find an affine IV in canonical form.
1664///
1665/// FIXME: Accept -1 stride and set IVLimit = IVInit - BECount
1666///
1667/// FIXME: Accept non-unit stride as long as SCEV can reduce BECount * Stride.
1668/// This is difficult in general for SCEV because of potential overflow. But we
1669/// could at least handle constant BECounts.
1670static PHINode *
1671FindLoopCounter(Loop *L, const SCEV *BECount,
1672 ScalarEvolution *SE, DominatorTree *DT, const TargetData *TD) {
1673 // I'm not sure how BECount could be a pointer type, but we definitely don't
1674 // want to LFTR that.
1675 if (BECount->getType()->isPointerTy())
1676 return 0;
1677
1678 uint64_t BCWidth = SE->getTypeSizeInBits(BECount->getType());
1679
1680 Value *Cond =
1681 cast<BranchInst>(L->getExitingBlock()->getTerminator())->getCondition();
1682
1683 // Loop over all of the PHI nodes, looking for a simple counter.
1684 PHINode *BestPhi = 0;
1685 const SCEV *BestInit = 0;
1686 BasicBlock *LatchBlock = L->getLoopLatch();
1687 assert(LatchBlock && "needsLFTR should guarantee a loop latch");
1688
1689 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
1690 PHINode *Phi = cast<PHINode>(I);
1691 if (!SE->isSCEVable(Phi->getType()))
1692 continue;
1693
1694 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Phi));
1695 if (!AR || AR->getLoop() != L || !AR->isAffine())
1696 continue;
1697
1698 // AR may be a pointer type, while BECount is an integer type.
1699 // AR may be wider than BECount. With eq/ne tests overflow is immaterial.
1700 // AR may not be a narrower type, or we may never exit.
1701 uint64_t PhiWidth = SE->getTypeSizeInBits(AR->getType());
1702 if (PhiWidth < BCWidth || (TD && !TD->isLegalInteger(PhiWidth)))
1703 continue;
1704
1705 const SCEV *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*SE));
1706 if (!Step || !Step->isOne())
1707 continue;
1708
1709 int LatchIdx = Phi->getBasicBlockIndex(LatchBlock);
1710 Value *IncV = Phi->getIncomingValue(LatchIdx);
1711 if (getLoopPhiForCounter(IncV, L, DT) != Phi)
1712 continue;
1713
1714 const SCEV *Init = AR->getStart();
1715
1716 if (BestPhi && !AlmostDeadIV(BestPhi, LatchBlock, Cond)) {
1717 // Don't force a live loop counter if another IV can be used.
1718 if (AlmostDeadIV(Phi, LatchBlock, Cond))
1719 continue;
1720
1721 // Prefer to count-from-zero. This is a more "canonical" counter form. It
1722 // also prefers integer to pointer IVs.
1723 if (BestInit->isZero() != Init->isZero()) {
1724 if (BestInit->isZero())
1725 continue;
1726 }
1727 // If two IVs both count from zero or both count from nonzero then the
1728 // narrower is likely a dead phi that has been widened. Use the wider phi
1729 // to allow the other to be eliminated.
1730 if (PhiWidth <= SE->getTypeSizeInBits(BestPhi->getType()))
1731 continue;
1732 }
1733 BestPhi = Phi;
1734 BestInit = Init;
1735 }
1736 return BestPhi;
1737}
1738
Andrew Trick1a54bb22011-07-12 00:08:50 +00001739/// LinearFunctionTestReplace - This method rewrites the exit condition of the
1740/// loop to be a canonical != comparison against the incremented loop induction
1741/// variable. This pass is able to rewrite the exit tests of any loop where the
1742/// SCEV analysis can determine a loop-invariant trip count of the loop, which
1743/// is actually a much broader range than just linear tests.
Andrew Trickfc933c02011-07-18 20:32:31 +00001744Value *IndVarSimplify::
Andrew Trick1a54bb22011-07-12 00:08:50 +00001745LinearFunctionTestReplace(Loop *L,
1746 const SCEV *BackedgeTakenCount,
1747 PHINode *IndVar,
1748 SCEVExpander &Rewriter) {
1749 assert(canExpandBackedgeTakenCount(L, SE) && "precondition");
1750 BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator());
1751
Andrew Trickfc933c02011-07-18 20:32:31 +00001752 // In DisableIVRewrite mode, IndVar is not necessarily a canonical IV. In this
1753 // mode, LFTR can ignore IV overflow and truncate to the width of
1754 // BECount. This avoids materializing the add(zext(add)) expression.
1755 Type *CntTy = DisableIVRewrite ?
1756 BackedgeTakenCount->getType() : IndVar->getType();
1757
1758 const SCEV *IVLimit = BackedgeTakenCount;
1759
Andrew Trick1a54bb22011-07-12 00:08:50 +00001760 // If the exiting block is not the same as the backedge block, we must compare
1761 // against the preincremented value, otherwise we prefer to compare against
1762 // the post-incremented value.
1763 Value *CmpIndVar;
Andrew Trick1a54bb22011-07-12 00:08:50 +00001764 if (L->getExitingBlock() == L->getLoopLatch()) {
1765 // Add one to the "backedge-taken" count to get the trip count.
1766 // If this addition may overflow, we have to be more pessimistic and
1767 // cast the induction variable before doing the add.
Andrew Trick1a54bb22011-07-12 00:08:50 +00001768 const SCEV *N =
Andrew Trickfc933c02011-07-18 20:32:31 +00001769 SE->getAddExpr(IVLimit, SE->getConstant(IVLimit->getType(), 1));
1770 if (CntTy == IVLimit->getType())
1771 IVLimit = N;
1772 else {
1773 const SCEV *Zero = SE->getConstant(IVLimit->getType(), 0);
1774 if ((isa<SCEVConstant>(N) && !N->isZero()) ||
1775 SE->isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) {
1776 // No overflow. Cast the sum.
1777 IVLimit = SE->getTruncateOrZeroExtend(N, CntTy);
1778 } else {
1779 // Potential overflow. Cast before doing the add.
1780 IVLimit = SE->getTruncateOrZeroExtend(IVLimit, CntTy);
1781 IVLimit = SE->getAddExpr(IVLimit, SE->getConstant(CntTy, 1));
1782 }
Andrew Trick1a54bb22011-07-12 00:08:50 +00001783 }
Andrew Trick1a54bb22011-07-12 00:08:50 +00001784 // The BackedgeTaken expression contains the number of times that the
1785 // backedge branches to the loop header. This is one less than the
1786 // number of times the loop executes, so use the incremented indvar.
1787 CmpIndVar = IndVar->getIncomingValueForBlock(L->getExitingBlock());
1788 } else {
1789 // We have to use the preincremented value...
Andrew Trickfc933c02011-07-18 20:32:31 +00001790 IVLimit = SE->getTruncateOrZeroExtend(IVLimit, CntTy);
Andrew Trick1a54bb22011-07-12 00:08:50 +00001791 CmpIndVar = IndVar;
1792 }
1793
Andrew Trickfc933c02011-07-18 20:32:31 +00001794 // For unit stride, IVLimit = Start + BECount with 2's complement overflow.
1795 // So for, non-zero start compute the IVLimit here.
1796 bool isPtrIV = false;
1797 Type *CmpTy = CntTy;
1798 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(IndVar));
1799 assert(AR && AR->getLoop() == L && AR->isAffine() && "bad loop counter");
1800 if (!AR->getStart()->isZero()) {
1801 assert(AR->getStepRecurrence(*SE)->isOne() && "only handles unit stride");
1802 const SCEV *IVInit = AR->getStart();
1803
1804 // For pointer types, sign extend BECount in order to materialize a GEP.
1805 // Note that for DisableIVRewrite, we never run SCEVExpander on a
1806 // pointer type, because we must preserve the existing GEPs. Instead we
1807 // directly generate a GEP later.
1808 if (IVInit->getType()->isPointerTy()) {
1809 isPtrIV = true;
1810 CmpTy = SE->getEffectiveSCEVType(IVInit->getType());
1811 IVLimit = SE->getTruncateOrSignExtend(IVLimit, CmpTy);
1812 }
1813 // For integer types, truncate the IV before computing IVInit + BECount.
1814 else {
1815 if (SE->getTypeSizeInBits(IVInit->getType())
1816 > SE->getTypeSizeInBits(CmpTy))
1817 IVInit = SE->getTruncateExpr(IVInit, CmpTy);
1818
1819 IVLimit = SE->getAddExpr(IVInit, IVLimit);
1820 }
1821 }
Andrew Trick1a54bb22011-07-12 00:08:50 +00001822 // Expand the code for the iteration count.
Andrew Trickfc933c02011-07-18 20:32:31 +00001823 IRBuilder<> Builder(BI);
1824
1825 assert(SE->isLoopInvariant(IVLimit, L) &&
Andrew Trick1a54bb22011-07-12 00:08:50 +00001826 "Computed iteration count is not loop invariant!");
Andrew Trickfc933c02011-07-18 20:32:31 +00001827 Value *ExitCnt = Rewriter.expandCodeFor(IVLimit, CmpTy, BI);
1828
1829 // Create a gep for IVInit + IVLimit from on an existing pointer base.
1830 assert(isPtrIV == IndVar->getType()->isPointerTy() &&
1831 "IndVar type must match IVInit type");
1832 if (isPtrIV) {
1833 Value *IVStart = IndVar->getIncomingValueForBlock(L->getLoopPreheader());
1834 assert(AR->getStart() == SE->getSCEV(IVStart) && "bad loop counter");
1835 const PointerType *PointerTy = cast<PointerType>(IVStart->getType());
1836 assert(SE->getSizeOfExpr(PointerTy->getElementType())->isOne() &&
1837 "unit stride pointer IV must be i8*");
1838
1839 Builder.SetInsertPoint(L->getLoopPreheader()->getTerminator());
1840 ExitCnt = Builder.CreateGEP(IVStart, ExitCnt, "lftr.limit");
1841 Builder.SetInsertPoint(BI);
1842 }
Andrew Trick1a54bb22011-07-12 00:08:50 +00001843
1844 // Insert a new icmp_ne or icmp_eq instruction before the branch.
Andrew Trickfc933c02011-07-18 20:32:31 +00001845 ICmpInst::Predicate P;
Andrew Trick1a54bb22011-07-12 00:08:50 +00001846 if (L->contains(BI->getSuccessor(0)))
Andrew Trickfc933c02011-07-18 20:32:31 +00001847 P = ICmpInst::ICMP_NE;
Andrew Trick1a54bb22011-07-12 00:08:50 +00001848 else
Andrew Trickfc933c02011-07-18 20:32:31 +00001849 P = ICmpInst::ICMP_EQ;
Andrew Trick1a54bb22011-07-12 00:08:50 +00001850
1851 DEBUG(dbgs() << "INDVARS: Rewriting loop exit condition to:\n"
1852 << " LHS:" << *CmpIndVar << '\n'
1853 << " op:\t"
Andrew Trickfc933c02011-07-18 20:32:31 +00001854 << (P == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
1855 << " RHS:\t" << *ExitCnt << "\n"
1856 << " Expr:\t" << *IVLimit << "\n");
Andrew Trick1a54bb22011-07-12 00:08:50 +00001857
Andrew Trickfc933c02011-07-18 20:32:31 +00001858 if (SE->getTypeSizeInBits(CmpIndVar->getType())
1859 > SE->getTypeSizeInBits(CmpTy)) {
1860 CmpIndVar = Builder.CreateTrunc(CmpIndVar, CmpTy, "lftr.wideiv");
1861 }
1862
1863 Value *Cond = Builder.CreateICmp(P, CmpIndVar, ExitCnt, "exitcond");
Andrew Trick1a54bb22011-07-12 00:08:50 +00001864 Value *OrigCond = BI->getCondition();
1865 // It's tempting to use replaceAllUsesWith here to fully replace the old
1866 // comparison, but that's not immediately safe, since users of the old
1867 // comparison may not be dominated by the new comparison. Instead, just
1868 // update the branch to use the new comparison; in the common case this
1869 // will make old comparison dead.
1870 BI->setCondition(Cond);
1871 DeadInsts.push_back(OrigCond);
1872
1873 ++NumLFTR;
1874 Changed = true;
1875 return Cond;
1876}
1877
1878//===----------------------------------------------------------------------===//
1879// SinkUnusedInvariants. A late subpass to cleanup loop preheaders.
1880//===----------------------------------------------------------------------===//
1881
1882/// If there's a single exit block, sink any loop-invariant values that
1883/// were defined in the preheader but not used inside the loop into the
1884/// exit block to reduce register pressure in the loop.
1885void IndVarSimplify::SinkUnusedInvariants(Loop *L) {
1886 BasicBlock *ExitBlock = L->getExitBlock();
1887 if (!ExitBlock) return;
1888
1889 BasicBlock *Preheader = L->getLoopPreheader();
1890 if (!Preheader) return;
1891
1892 Instruction *InsertPt = ExitBlock->getFirstNonPHI();
1893 BasicBlock::iterator I = Preheader->getTerminator();
1894 while (I != Preheader->begin()) {
1895 --I;
1896 // New instructions were inserted at the end of the preheader.
1897 if (isa<PHINode>(I))
1898 break;
1899
1900 // Don't move instructions which might have side effects, since the side
1901 // effects need to complete before instructions inside the loop. Also don't
1902 // move instructions which might read memory, since the loop may modify
1903 // memory. Note that it's okay if the instruction might have undefined
1904 // behavior: LoopSimplify guarantees that the preheader dominates the exit
1905 // block.
1906 if (I->mayHaveSideEffects() || I->mayReadFromMemory())
1907 continue;
1908
1909 // Skip debug info intrinsics.
1910 if (isa<DbgInfoIntrinsic>(I))
1911 continue;
1912
1913 // Don't sink static AllocaInsts out of the entry block, which would
1914 // turn them into dynamic allocas!
1915 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
1916 if (AI->isStaticAlloca())
1917 continue;
1918
1919 // Determine if there is a use in or before the loop (direct or
1920 // otherwise).
1921 bool UsedInLoop = false;
1922 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
1923 UI != UE; ++UI) {
1924 User *U = *UI;
1925 BasicBlock *UseBB = cast<Instruction>(U)->getParent();
1926 if (PHINode *P = dyn_cast<PHINode>(U)) {
1927 unsigned i =
1928 PHINode::getIncomingValueNumForOperand(UI.getOperandNo());
1929 UseBB = P->getIncomingBlock(i);
1930 }
1931 if (UseBB == Preheader || L->contains(UseBB)) {
1932 UsedInLoop = true;
1933 break;
1934 }
1935 }
1936
1937 // If there is, the def must remain in the preheader.
1938 if (UsedInLoop)
1939 continue;
1940
1941 // Otherwise, sink it to the exit block.
1942 Instruction *ToMove = I;
1943 bool Done = false;
1944
1945 if (I != Preheader->begin()) {
1946 // Skip debug info intrinsics.
1947 do {
1948 --I;
1949 } while (isa<DbgInfoIntrinsic>(I) && I != Preheader->begin());
1950
1951 if (isa<DbgInfoIntrinsic>(I) && I == Preheader->begin())
1952 Done = true;
1953 } else {
1954 Done = true;
1955 }
1956
1957 ToMove->moveBefore(InsertPt);
1958 if (Done) break;
1959 InsertPt = ToMove;
1960 }
1961}
1962
1963//===----------------------------------------------------------------------===//
1964// IndVarSimplify driver. Manage several subpasses of IV simplification.
1965//===----------------------------------------------------------------------===//
1966
Dan Gohmanc2390b12009-02-12 22:19:27 +00001967bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
Dan Gohmana5283822010-06-18 01:35:11 +00001968 // If LoopSimplify form is not available, stay out of trouble. Some notes:
1969 // - LSR currently only supports LoopSimplify-form loops. Indvars'
1970 // canonicalization can be a pessimization without LSR to "clean up"
1971 // afterwards.
1972 // - We depend on having a preheader; in particular,
1973 // Loop::getCanonicalInductionVariable only supports loops with preheaders,
1974 // and we're in trouble if we can't find the induction variable even when
1975 // we've manually inserted one.
1976 if (!L->isLoopSimplifyForm())
1977 return false;
1978
Andrew Trick2fabd462011-06-21 03:22:38 +00001979 if (!DisableIVRewrite)
1980 IU = &getAnalysis<IVUsers>();
Devang Patel5ee99972007-03-07 06:39:01 +00001981 LI = &getAnalysis<LoopInfo>();
1982 SE = &getAnalysis<ScalarEvolution>();
Dan Gohmande53dc02009-06-27 05:16:57 +00001983 DT = &getAnalysis<DominatorTree>();
Andrew Trick37da4082011-05-04 02:10:13 +00001984 TD = getAnalysisIfAvailable<TargetData>();
1985
Andrew Trickb12a7542011-03-17 23:51:11 +00001986 DeadInsts.clear();
Devang Patel5ee99972007-03-07 06:39:01 +00001987 Changed = false;
Dan Gohman60f8a632009-02-17 20:49:49 +00001988
Dan Gohman2d1be872009-04-16 03:18:22 +00001989 // If there are any floating-point recurrences, attempt to
Dan Gohman60f8a632009-02-17 20:49:49 +00001990 // transform them to use integer recurrences.
1991 RewriteNonIntegerIVs(L);
1992
Dan Gohman0bba49c2009-07-07 17:06:11 +00001993 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
Chris Lattner9caed542007-03-04 01:00:28 +00001994
Dan Gohman667d7872009-06-26 22:53:46 +00001995 // Create a rewriter object which we'll use to transform the code with.
Andrew Trick5e7645b2011-06-28 05:07:32 +00001996 SCEVExpander Rewriter(*SE, "indvars");
Andrew Trick156d4602011-06-27 23:17:44 +00001997
1998 // Eliminate redundant IV users.
Andrew Trick15832f62011-06-28 02:49:20 +00001999 //
2000 // Simplification works best when run before other consumers of SCEV. We
2001 // attempt to avoid evaluating SCEVs for sign/zero extend operations until
2002 // other expressions involving loop IVs have been evaluated. This helps SCEV
Andrew Trick99a92f62011-06-28 16:45:04 +00002003 // set no-wrap flags before normalizing sign/zero extension.
Andrew Trick156d4602011-06-27 23:17:44 +00002004 if (DisableIVRewrite) {
Andrew Trick37da4082011-05-04 02:10:13 +00002005 Rewriter.disableCanonicalMode();
Andrew Trick156d4602011-06-27 23:17:44 +00002006 SimplifyIVUsersNoRewrite(L, Rewriter);
2007 }
Andrew Trick37da4082011-05-04 02:10:13 +00002008
Chris Lattner40bf8b42004-04-02 20:24:31 +00002009 // Check to see if this loop has a computable loop-invariant execution count.
2010 // If so, this means that we can compute the final value of any expressions
2011 // that are recurrent in the loop, and substitute the exit values from the
2012 // loop into any instructions outside of the loop that use the final values of
2013 // the current expressions.
Chris Lattner3dec1f22002-05-10 15:38:35 +00002014 //
Dan Gohman46bdfb02009-02-24 18:55:53 +00002015 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount))
Dan Gohman454d26d2010-02-22 04:11:59 +00002016 RewriteLoopExitValues(L, Rewriter);
Chris Lattner6148c022001-12-03 17:28:42 +00002017
Andrew Trickf85092c2011-05-20 18:25:42 +00002018 // Eliminate redundant IV users.
Andrew Trick156d4602011-06-27 23:17:44 +00002019 if (!DisableIVRewrite)
Andrew Trick2fabd462011-06-21 03:22:38 +00002020 SimplifyIVUsers(Rewriter);
Dan Gohmana590b792010-04-13 01:46:36 +00002021
Andrew Trick6f684b02011-07-16 01:06:48 +00002022 // Eliminate redundant IV cycles.
Andrew Trick037d1c02011-07-06 20:50:43 +00002023 if (DisableIVRewrite)
2024 SimplifyCongruentIVs(L);
2025
Dan Gohman81db61a2009-05-12 02:17:14 +00002026 // Compute the type of the largest recurrence expression, and decide whether
2027 // a canonical induction variable should be inserted.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002028 Type *LargestType = 0;
Dan Gohman81db61a2009-05-12 02:17:14 +00002029 bool NeedCannIV = false;
Andrew Trickfc933c02011-07-18 20:32:31 +00002030 bool ReuseIVForExit = DisableIVRewrite && !ForceLFTR;
Andrew Trick03d3d3b2011-05-25 04:42:22 +00002031 bool ExpandBECount = canExpandBackedgeTakenCount(L, SE);
Andrew Trickfc933c02011-07-18 20:32:31 +00002032 if (ExpandBECount && !ReuseIVForExit) {
Dan Gohman81db61a2009-05-12 02:17:14 +00002033 // If we have a known trip count and a single exit block, we'll be
2034 // rewriting the loop exit test condition below, which requires a
2035 // canonical induction variable.
Andrew Trick4dfdf242011-05-03 22:24:10 +00002036 NeedCannIV = true;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002037 Type *Ty = BackedgeTakenCount->getType();
Andrew Trick03d3d3b2011-05-25 04:42:22 +00002038 if (DisableIVRewrite) {
2039 // In this mode, SimplifyIVUsers may have already widened the IV used by
2040 // the backedge test and inserted a Trunc on the compare's operand. Get
2041 // the wider type to avoid creating a redundant narrow IV only used by the
2042 // loop test.
2043 LargestType = getBackedgeIVType(L);
2044 }
Andrew Trick4dfdf242011-05-03 22:24:10 +00002045 if (!LargestType ||
2046 SE->getTypeSizeInBits(Ty) >
2047 SE->getTypeSizeInBits(LargestType))
2048 LargestType = SE->getEffectiveSCEVType(Ty);
Chris Lattnerf50af082004-04-17 18:08:33 +00002049 }
Andrew Trick37da4082011-05-04 02:10:13 +00002050 if (!DisableIVRewrite) {
2051 for (IVUsers::const_iterator I = IU->begin(), E = IU->end(); I != E; ++I) {
2052 NeedCannIV = true;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002053 Type *Ty =
Andrew Trick37da4082011-05-04 02:10:13 +00002054 SE->getEffectiveSCEVType(I->getOperandValToReplace()->getType());
2055 if (!LargestType ||
2056 SE->getTypeSizeInBits(Ty) >
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002057 SE->getTypeSizeInBits(LargestType))
Andrew Trick37da4082011-05-04 02:10:13 +00002058 LargestType = Ty;
2059 }
Chris Lattner6148c022001-12-03 17:28:42 +00002060 }
2061
Dan Gohmanf451cb82010-02-10 16:03:48 +00002062 // Now that we know the largest of the induction variable expressions
Dan Gohman81db61a2009-05-12 02:17:14 +00002063 // in this loop, insert a canonical induction variable of the largest size.
Dan Gohman43ef3fb2010-07-20 17:18:52 +00002064 PHINode *IndVar = 0;
Dan Gohman81db61a2009-05-12 02:17:14 +00002065 if (NeedCannIV) {
Dan Gohman85669632010-02-25 06:57:05 +00002066 // Check to see if the loop already has any canonical-looking induction
2067 // variables. If any are present and wider than the planned canonical
2068 // induction variable, temporarily remove them, so that the Rewriter
2069 // doesn't attempt to reuse them.
2070 SmallVector<PHINode *, 2> OldCannIVs;
2071 while (PHINode *OldCannIV = L->getCanonicalInductionVariable()) {
Dan Gohman4d8414f2009-06-13 16:25:49 +00002072 if (SE->getTypeSizeInBits(OldCannIV->getType()) >
2073 SE->getTypeSizeInBits(LargestType))
2074 OldCannIV->removeFromParent();
2075 else
Dan Gohman85669632010-02-25 06:57:05 +00002076 break;
2077 OldCannIVs.push_back(OldCannIV);
Dan Gohman4d8414f2009-06-13 16:25:49 +00002078 }
2079
Dan Gohman667d7872009-06-26 22:53:46 +00002080 IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L, LargestType);
Dan Gohman4d8414f2009-06-13 16:25:49 +00002081
Dan Gohmanc2390b12009-02-12 22:19:27 +00002082 ++NumInserted;
2083 Changed = true;
David Greenef67ef312010-01-05 01:27:06 +00002084 DEBUG(dbgs() << "INDVARS: New CanIV: " << *IndVar << '\n');
Dan Gohman4d8414f2009-06-13 16:25:49 +00002085
2086 // Now that the official induction variable is established, reinsert
Dan Gohman85669632010-02-25 06:57:05 +00002087 // any old canonical-looking variables after it so that the IR remains
2088 // consistent. They will be deleted as part of the dead-PHI deletion at
Dan Gohman4d8414f2009-06-13 16:25:49 +00002089 // the end of the pass.
Dan Gohman85669632010-02-25 06:57:05 +00002090 while (!OldCannIVs.empty()) {
2091 PHINode *OldCannIV = OldCannIVs.pop_back_val();
2092 OldCannIV->insertBefore(L->getHeader()->getFirstNonPHI());
2093 }
Dan Gohmand19534a2007-06-15 14:38:12 +00002094 }
Andrew Trickfc933c02011-07-18 20:32:31 +00002095 else if (ExpandBECount && ReuseIVForExit && needsLFTR(L, DT)) {
2096 IndVar = FindLoopCounter(L, BackedgeTakenCount, SE, DT, TD);
2097 }
Dan Gohmanc2390b12009-02-12 22:19:27 +00002098 // If we have a trip count expression, rewrite the loop's exit condition
2099 // using it. We can currently only handle loops with a single exit.
Andrew Trickfc933c02011-07-18 20:32:31 +00002100 Value *NewICmp = 0;
2101 if (ExpandBECount && IndVar) {
Andrew Trick56147692011-07-16 01:18:53 +00002102 // Check preconditions for proper SCEVExpander operation. SCEV does not
2103 // express SCEVExpander's dependencies, such as LoopSimplify. Instead any
2104 // pass that uses the SCEVExpander must do it. This does not work well for
2105 // loop passes because SCEVExpander makes assumptions about all loops, while
2106 // LoopPassManager only forces the current loop to be simplified.
2107 //
2108 // FIXME: SCEV expansion has no way to bail out, so the caller must
2109 // explicitly check any assumptions made by SCEV. Brittle.
2110 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(BackedgeTakenCount);
2111 if (!AR || AR->getLoop()->getLoopPreheader())
2112 NewICmp =
2113 LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar, Rewriter);
Chris Lattnerfcb81f52004-04-22 14:59:40 +00002114 }
Andrew Trickb12a7542011-03-17 23:51:11 +00002115 // Rewrite IV-derived expressions.
Andrew Trick37da4082011-05-04 02:10:13 +00002116 if (!DisableIVRewrite)
2117 RewriteIVExpressions(L, Rewriter);
Dan Gohmanc2390b12009-02-12 22:19:27 +00002118
Andrew Trickb12a7542011-03-17 23:51:11 +00002119 // Clear the rewriter cache, because values that are in the rewriter's cache
2120 // can be deleted in the loop below, causing the AssertingVH in the cache to
2121 // trigger.
2122 Rewriter.clear();
2123
2124 // Now that we're done iterating through lists, clean up any instructions
2125 // which are now dead.
2126 while (!DeadInsts.empty())
2127 if (Instruction *Inst =
2128 dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val()))
2129 RecursivelyDeleteTriviallyDeadInstructions(Inst);
2130
Dan Gohman667d7872009-06-26 22:53:46 +00002131 // The Rewriter may not be used from this point on.
Torok Edwin3d431382009-05-24 20:08:21 +00002132
Dan Gohman81db61a2009-05-12 02:17:14 +00002133 // Loop-invariant instructions in the preheader that aren't used in the
2134 // loop may be sunk below the loop to reduce register pressure.
Dan Gohman667d7872009-06-26 22:53:46 +00002135 SinkUnusedInvariants(L);
Dan Gohman81db61a2009-05-12 02:17:14 +00002136
2137 // For completeness, inform IVUsers of the IV use in the newly-created
2138 // loop exit test instruction.
Andrew Trickfc933c02011-07-18 20:32:31 +00002139 if (IU && NewICmp) {
2140 ICmpInst *NewICmpInst = dyn_cast<ICmpInst>(NewICmp);
2141 if (NewICmpInst)
2142 IU->AddUsersIfInteresting(cast<Instruction>(NewICmpInst->getOperand(0)));
2143 }
Dan Gohman81db61a2009-05-12 02:17:14 +00002144 // Clean up dead instructions.
Dan Gohman9fff2182010-01-05 16:31:45 +00002145 Changed |= DeleteDeadPHIs(L->getHeader());
Dan Gohman81db61a2009-05-12 02:17:14 +00002146 // Check a post-condition.
Andrew Trickf6a0dba2011-07-18 18:44:20 +00002147 assert(L->isLCSSAForm(*DT) &&
2148 "Indvars did not leave the loop in lcssa form!");
2149
2150 // Verify that LFTR, and any other change have not interfered with SCEV's
2151 // ability to compute trip count.
2152#ifndef NDEBUG
2153 if (DisableIVRewrite && !isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
2154 SE->forgetLoop(L);
2155 const SCEV *NewBECount = SE->getBackedgeTakenCount(L);
2156 if (SE->getTypeSizeInBits(BackedgeTakenCount->getType()) <
2157 SE->getTypeSizeInBits(NewBECount->getType()))
2158 NewBECount = SE->getTruncateOrNoop(NewBECount,
2159 BackedgeTakenCount->getType());
2160 else
2161 BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount,
2162 NewBECount->getType());
2163 assert(BackedgeTakenCount == NewBECount && "indvars must preserve SCEV");
2164 }
2165#endif
2166
Devang Patel5ee99972007-03-07 06:39:01 +00002167 return Changed;
Chris Lattner6148c022001-12-03 17:28:42 +00002168}