blob: 3a2674875c772b498f981914fd4020d8c0846169 [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 {
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000787
788/// NarrowIVDefUse - Record a link in the Narrow IV def-use chain along with the
789/// WideIV that computes the same value as the Narrow IV def. This avoids
790/// caching Use* pointers.
791struct NarrowIVDefUse {
792 Instruction *NarrowDef;
793 Instruction *NarrowUse;
794 Instruction *WideDef;
795
796 NarrowIVDefUse(): NarrowDef(0), NarrowUse(0), WideDef(0) {}
797
798 NarrowIVDefUse(Instruction *ND, Instruction *NU, Instruction *WD):
799 NarrowDef(ND), NarrowUse(NU), WideDef(WD) {}
800};
801
Andrew Trickf85092c2011-05-20 18:25:42 +0000802/// WidenIV - The goal of this transform is to remove sign and zero extends
803/// without creating any new induction variables. To do this, it creates a new
804/// phi of the wider type and redirects all users, either removing extends or
805/// inserting truncs whenever we stop propagating the type.
806///
807class WidenIV {
Andrew Trick2fabd462011-06-21 03:22:38 +0000808 // Parameters
Andrew Trickf85092c2011-05-20 18:25:42 +0000809 PHINode *OrigPhi;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000810 Type *WideType;
Andrew Trickf85092c2011-05-20 18:25:42 +0000811 bool IsSigned;
812
Andrew Trick2fabd462011-06-21 03:22:38 +0000813 // Context
814 LoopInfo *LI;
815 Loop *L;
Andrew Trickf85092c2011-05-20 18:25:42 +0000816 ScalarEvolution *SE;
Andrew Trick2fabd462011-06-21 03:22:38 +0000817 DominatorTree *DT;
Andrew Trickf85092c2011-05-20 18:25:42 +0000818
Andrew Trick2fabd462011-06-21 03:22:38 +0000819 // Result
Andrew Trickf85092c2011-05-20 18:25:42 +0000820 PHINode *WidePhi;
821 Instruction *WideInc;
822 const SCEV *WideIncExpr;
Andrew Trick2fabd462011-06-21 03:22:38 +0000823 SmallVectorImpl<WeakVH> &DeadInsts;
Andrew Trickf85092c2011-05-20 18:25:42 +0000824
Andrew Trick2fabd462011-06-21 03:22:38 +0000825 SmallPtrSet<Instruction*,16> Widened;
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000826 SmallVector<NarrowIVDefUse, 8> NarrowIVUsers;
Andrew Trickf85092c2011-05-20 18:25:42 +0000827
828public:
Andrew Trick2fabd462011-06-21 03:22:38 +0000829 WidenIV(PHINode *PN, const WideIVInfo &WI, LoopInfo *LInfo,
830 ScalarEvolution *SEv, DominatorTree *DTree,
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000831 SmallVectorImpl<WeakVH> &DI) :
Andrew Trickf85092c2011-05-20 18:25:42 +0000832 OrigPhi(PN),
Andrew Trick2fabd462011-06-21 03:22:38 +0000833 WideType(WI.WidestNativeType),
834 IsSigned(WI.IsSigned),
Andrew Trickf85092c2011-05-20 18:25:42 +0000835 LI(LInfo),
836 L(LI->getLoopFor(OrigPhi->getParent())),
837 SE(SEv),
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000838 DT(DTree),
Andrew Trickf85092c2011-05-20 18:25:42 +0000839 WidePhi(0),
840 WideInc(0),
Andrew Trick2fabd462011-06-21 03:22:38 +0000841 WideIncExpr(0),
842 DeadInsts(DI) {
Andrew Trickf85092c2011-05-20 18:25:42 +0000843 assert(L->getHeader() == OrigPhi->getParent() && "Phi must be an IV");
844 }
845
Andrew Trick2fabd462011-06-21 03:22:38 +0000846 PHINode *CreateWideIV(SCEVExpander &Rewriter);
Andrew Trickf85092c2011-05-20 18:25:42 +0000847
848protected:
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000849 Instruction *CloneIVUser(NarrowIVDefUse DU);
Andrew Trickf85092c2011-05-20 18:25:42 +0000850
Andrew Tricke0dc2fa2011-07-05 18:19:39 +0000851 const SCEVAddRecExpr *GetWideRecurrence(Instruction *NarrowUse);
852
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000853 Instruction *WidenIVUse(NarrowIVDefUse DU);
Andrew Trick4b029152011-07-02 02:34:25 +0000854
855 void pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef);
Andrew Trickf85092c2011-05-20 18:25:42 +0000856};
857} // anonymous namespace
858
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000859static Value *getExtend( Value *NarrowOper, Type *WideType,
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000860 bool IsSigned, IRBuilder<> &Builder) {
861 return IsSigned ? Builder.CreateSExt(NarrowOper, WideType) :
862 Builder.CreateZExt(NarrowOper, WideType);
Andrew Trickf85092c2011-05-20 18:25:42 +0000863}
864
865/// CloneIVUser - Instantiate a wide operation to replace a narrow
866/// operation. This only needs to handle operations that can evaluation to
867/// SCEVAddRec. It can safely return 0 for any operation we decide not to clone.
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000868Instruction *WidenIV::CloneIVUser(NarrowIVDefUse DU) {
869 unsigned Opcode = DU.NarrowUse->getOpcode();
Andrew Trickf85092c2011-05-20 18:25:42 +0000870 switch (Opcode) {
871 default:
872 return 0;
873 case Instruction::Add:
874 case Instruction::Mul:
875 case Instruction::UDiv:
876 case Instruction::Sub:
877 case Instruction::And:
878 case Instruction::Or:
879 case Instruction::Xor:
880 case Instruction::Shl:
881 case Instruction::LShr:
882 case Instruction::AShr:
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000883 DEBUG(dbgs() << "Cloning IVUser: " << *DU.NarrowUse << "\n");
Andrew Trickf85092c2011-05-20 18:25:42 +0000884
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000885 IRBuilder<> Builder(DU.NarrowUse);
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000886
887 // Replace NarrowDef operands with WideDef. Otherwise, we don't know
888 // anything about the narrow operand yet so must insert a [sz]ext. It is
889 // probably loop invariant and will be folded or hoisted. If it actually
890 // comes from a widened IV, it should be removed during a future call to
891 // WidenIVUse.
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000892 Value *LHS = (DU.NarrowUse->getOperand(0) == DU.NarrowDef) ? DU.WideDef :
893 getExtend(DU.NarrowUse->getOperand(0), WideType, IsSigned, Builder);
894 Value *RHS = (DU.NarrowUse->getOperand(1) == DU.NarrowDef) ? DU.WideDef :
895 getExtend(DU.NarrowUse->getOperand(1), WideType, IsSigned, Builder);
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000896
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000897 BinaryOperator *NarrowBO = cast<BinaryOperator>(DU.NarrowUse);
Andrew Trickf85092c2011-05-20 18:25:42 +0000898 BinaryOperator *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(),
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000899 LHS, RHS,
Andrew Trickf85092c2011-05-20 18:25:42 +0000900 NarrowBO->getName());
Andrew Trickf85092c2011-05-20 18:25:42 +0000901 Builder.Insert(WideBO);
Andrew Trick6e0ce242011-06-30 19:02:17 +0000902 if (const OverflowingBinaryOperator *OBO =
903 dyn_cast<OverflowingBinaryOperator>(NarrowBO)) {
904 if (OBO->hasNoUnsignedWrap()) WideBO->setHasNoUnsignedWrap();
905 if (OBO->hasNoSignedWrap()) WideBO->setHasNoSignedWrap();
906 }
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000907 return WideBO;
Andrew Trickf85092c2011-05-20 18:25:42 +0000908 }
909 llvm_unreachable(0);
910}
911
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000912/// HoistStep - Attempt to hoist an IV increment above a potential use.
913///
914/// To successfully hoist, two criteria must be met:
915/// - IncV operands dominate InsertPos and
916/// - InsertPos dominates IncV
917///
918/// Meeting the second condition means that we don't need to check all of IncV's
919/// existing uses (it's moving up in the domtree).
920///
921/// This does not yet recursively hoist the operands, although that would
922/// not be difficult.
923static bool HoistStep(Instruction *IncV, Instruction *InsertPos,
924 const DominatorTree *DT)
925{
926 if (DT->dominates(IncV, InsertPos))
927 return true;
928
929 if (!DT->dominates(InsertPos->getParent(), IncV->getParent()))
930 return false;
931
932 if (IncV->mayHaveSideEffects())
933 return false;
934
935 // Attempt to hoist IncV
936 for (User::op_iterator OI = IncV->op_begin(), OE = IncV->op_end();
937 OI != OE; ++OI) {
938 Instruction *OInst = dyn_cast<Instruction>(OI);
939 if (OInst && !DT->dominates(OInst, InsertPos))
940 return false;
941 }
942 IncV->moveBefore(InsertPos);
943 return true;
944}
945
Andrew Tricke0dc2fa2011-07-05 18:19:39 +0000946// GetWideRecurrence - Is this instruction potentially interesting from IVUsers'
947// perspective after widening it's type? In other words, can the extend be
948// safely hoisted out of the loop with SCEV reducing the value to a recurrence
949// on the same loop. If so, return the sign or zero extended
950// recurrence. Otherwise return NULL.
951const SCEVAddRecExpr *WidenIV::GetWideRecurrence(Instruction *NarrowUse) {
952 if (!SE->isSCEVable(NarrowUse->getType()))
953 return 0;
954
955 const SCEV *NarrowExpr = SE->getSCEV(NarrowUse);
956 if (SE->getTypeSizeInBits(NarrowExpr->getType())
957 >= SE->getTypeSizeInBits(WideType)) {
958 // NarrowUse implicitly widens its operand. e.g. a gep with a narrow
959 // index. So don't follow this use.
960 return 0;
961 }
962
963 const SCEV *WideExpr = IsSigned ?
964 SE->getSignExtendExpr(NarrowExpr, WideType) :
965 SE->getZeroExtendExpr(NarrowExpr, WideType);
966 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(WideExpr);
967 if (!AddRec || AddRec->getLoop() != L)
968 return 0;
969
970 return AddRec;
971}
972
Andrew Trickf85092c2011-05-20 18:25:42 +0000973/// WidenIVUse - Determine whether an individual user of the narrow IV can be
974/// widened. If so, return the wide clone of the user.
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000975Instruction *WidenIV::WidenIVUse(NarrowIVDefUse DU) {
Andrew Trickcc359d92011-06-29 23:03:57 +0000976
Andrew Trick4b029152011-07-02 02:34:25 +0000977 // Stop traversing the def-use chain at inner-loop phis or post-loop phis.
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000978 if (isa<PHINode>(DU.NarrowUse) &&
979 LI->getLoopFor(DU.NarrowUse->getParent()) != L)
Andrew Trickf85092c2011-05-20 18:25:42 +0000980 return 0;
981
Andrew Trickf85092c2011-05-20 18:25:42 +0000982 // Our raison d'etre! Eliminate sign and zero extension.
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000983 if (IsSigned ? isa<SExtInst>(DU.NarrowUse) : isa<ZExtInst>(DU.NarrowUse)) {
984 Value *NewDef = DU.WideDef;
985 if (DU.NarrowUse->getType() != WideType) {
986 unsigned CastWidth = SE->getTypeSizeInBits(DU.NarrowUse->getType());
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000987 unsigned IVWidth = SE->getTypeSizeInBits(WideType);
988 if (CastWidth < IVWidth) {
989 // The cast isn't as wide as the IV, so insert a Trunc.
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000990 IRBuilder<> Builder(DU.NarrowUse);
991 NewDef = Builder.CreateTrunc(DU.WideDef, DU.NarrowUse->getType());
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000992 }
993 else {
994 // A wider extend was hidden behind a narrower one. This may induce
995 // another round of IV widening in which the intermediate IV becomes
996 // dead. It should be very rare.
997 DEBUG(dbgs() << "INDVARS: New IV " << *WidePhi
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000998 << " not wide enough to subsume " << *DU.NarrowUse << "\n");
999 DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef);
1000 NewDef = DU.NarrowUse;
Andrew Trick03d3d3b2011-05-25 04:42:22 +00001001 }
1002 }
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001003 if (NewDef != DU.NarrowUse) {
1004 DEBUG(dbgs() << "INDVARS: eliminating " << *DU.NarrowUse
1005 << " replaced by " << *DU.WideDef << "\n");
Andrew Trick03d3d3b2011-05-25 04:42:22 +00001006 ++NumElimExt;
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001007 DU.NarrowUse->replaceAllUsesWith(NewDef);
1008 DeadInsts.push_back(DU.NarrowUse);
Andrew Trick03d3d3b2011-05-25 04:42:22 +00001009 }
Andrew Trick2fabd462011-06-21 03:22:38 +00001010 // Now that the extend is gone, we want to expose it's uses for potential
1011 // further simplification. We don't need to directly inform SimplifyIVUsers
1012 // of the new users, because their parent IV will be processed later as a
1013 // new loop phi. If we preserved IVUsers analysis, we would also want to
1014 // push the uses of WideDef here.
Andrew Trickf85092c2011-05-20 18:25:42 +00001015
1016 // No further widening is needed. The deceased [sz]ext had done it for us.
1017 return 0;
1018 }
Andrew Trick4b029152011-07-02 02:34:25 +00001019
1020 // Does this user itself evaluate to a recurrence after widening?
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001021 const SCEVAddRecExpr *WideAddRec = GetWideRecurrence(DU.NarrowUse);
Andrew Trickf85092c2011-05-20 18:25:42 +00001022 if (!WideAddRec) {
1023 // This user does not evaluate to a recurence after widening, so don't
1024 // follow it. Instead insert a Trunc to kill off the original use,
1025 // eventually isolating the original narrow IV so it can be removed.
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001026 Use *U = std::find(DU.NarrowUse->op_begin(), DU.NarrowUse->op_end(),
1027 DU.NarrowDef);
1028 IRBuilder<> Builder(*U);
1029 Value *Trunc = Builder.CreateTrunc(DU.WideDef, DU.NarrowDef->getType());
1030 DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, Trunc);
Andrew Trickf85092c2011-05-20 18:25:42 +00001031 return 0;
1032 }
Andrew Trickfc933c02011-07-18 20:32:31 +00001033 // Assume block terminators cannot evaluate to a recurrence. We can't to
Andrew Trick4b029152011-07-02 02:34:25 +00001034 // insert a Trunc after a terminator if there happens to be a critical edge.
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001035 assert(DU.NarrowUse != DU.NarrowUse->getParent()->getTerminator() &&
Andrew Trick4b029152011-07-02 02:34:25 +00001036 "SCEV is not expected to evaluate a block terminator");
Andrew Trickcc359d92011-06-29 23:03:57 +00001037
Andrew Trickfcdc9a42011-05-26 00:46:11 +00001038 // Reuse the IV increment that SCEVExpander created as long as it dominates
1039 // NarrowUse.
Andrew Trickf85092c2011-05-20 18:25:42 +00001040 Instruction *WideUse = 0;
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001041 if (WideAddRec == WideIncExpr && HoistStep(WideInc, DU.NarrowUse, DT)) {
Andrew Trickf85092c2011-05-20 18:25:42 +00001042 WideUse = WideInc;
1043 }
1044 else {
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001045 WideUse = CloneIVUser(DU);
Andrew Trickf85092c2011-05-20 18:25:42 +00001046 if (!WideUse)
1047 return 0;
1048 }
Andrew Trick4b029152011-07-02 02:34:25 +00001049 // Evaluation of WideAddRec ensured that the narrow expression could be
1050 // extended outside the loop without overflow. This suggests that the wide use
Andrew Trickf85092c2011-05-20 18:25:42 +00001051 // evaluates to the same expression as the extended narrow use, but doesn't
1052 // absolutely guarantee it. Hence the following failsafe check. In rare cases
Andrew Trick2fabd462011-06-21 03:22:38 +00001053 // where it fails, we simply throw away the newly created wide use.
Andrew Trickf85092c2011-05-20 18:25:42 +00001054 if (WideAddRec != SE->getSCEV(WideUse)) {
1055 DEBUG(dbgs() << "Wide use expression mismatch: " << *WideUse
1056 << ": " << *SE->getSCEV(WideUse) << " != " << *WideAddRec << "\n");
1057 DeadInsts.push_back(WideUse);
1058 return 0;
1059 }
1060
1061 // Returning WideUse pushes it on the worklist.
1062 return WideUse;
1063}
1064
Andrew Trick4b029152011-07-02 02:34:25 +00001065/// pushNarrowIVUsers - Add eligible users of NarrowDef to NarrowIVUsers.
1066///
1067void WidenIV::pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef) {
1068 for (Value::use_iterator UI = NarrowDef->use_begin(),
1069 UE = NarrowDef->use_end(); UI != UE; ++UI) {
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001070 Instruction *NarrowUse = cast<Instruction>(*UI);
Andrew Trick4b029152011-07-02 02:34:25 +00001071
1072 // Handle data flow merges and bizarre phi cycles.
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001073 if (!Widened.insert(NarrowUse))
Andrew Trick4b029152011-07-02 02:34:25 +00001074 continue;
1075
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001076 NarrowIVUsers.push_back(NarrowIVDefUse(NarrowDef, NarrowUse, WideDef));
Andrew Trick4b029152011-07-02 02:34:25 +00001077 }
1078}
1079
Andrew Trickf85092c2011-05-20 18:25:42 +00001080/// CreateWideIV - Process a single induction variable. First use the
1081/// SCEVExpander to create a wide induction variable that evaluates to the same
1082/// recurrence as the original narrow IV. Then use a worklist to forward
Andrew Trick2fabd462011-06-21 03:22:38 +00001083/// traverse the narrow IV's def-use chain. After WidenIVUse has processed all
Andrew Trickf85092c2011-05-20 18:25:42 +00001084/// interesting IV users, the narrow IV will be isolated for removal by
1085/// DeleteDeadPHIs.
1086///
1087/// It would be simpler to delete uses as they are processed, but we must avoid
1088/// invalidating SCEV expressions.
1089///
Andrew Trick2fabd462011-06-21 03:22:38 +00001090PHINode *WidenIV::CreateWideIV(SCEVExpander &Rewriter) {
Andrew Trickf85092c2011-05-20 18:25:42 +00001091 // Is this phi an induction variable?
1092 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(OrigPhi));
1093 if (!AddRec)
Andrew Trick2fabd462011-06-21 03:22:38 +00001094 return NULL;
Andrew Trickf85092c2011-05-20 18:25:42 +00001095
1096 // Widen the induction variable expression.
1097 const SCEV *WideIVExpr = IsSigned ?
1098 SE->getSignExtendExpr(AddRec, WideType) :
1099 SE->getZeroExtendExpr(AddRec, WideType);
1100
1101 assert(SE->getEffectiveSCEVType(WideIVExpr->getType()) == WideType &&
1102 "Expect the new IV expression to preserve its type");
1103
1104 // Can the IV be extended outside the loop without overflow?
1105 AddRec = dyn_cast<SCEVAddRecExpr>(WideIVExpr);
1106 if (!AddRec || AddRec->getLoop() != L)
Andrew Trick2fabd462011-06-21 03:22:38 +00001107 return NULL;
Andrew Trickf85092c2011-05-20 18:25:42 +00001108
Andrew Trick2fabd462011-06-21 03:22:38 +00001109 // An AddRec must have loop-invariant operands. Since this AddRec is
Andrew Trickf85092c2011-05-20 18:25:42 +00001110 // materialized by a loop header phi, the expression cannot have any post-loop
1111 // operands, so they must dominate the loop header.
1112 assert(SE->properlyDominates(AddRec->getStart(), L->getHeader()) &&
1113 SE->properlyDominates(AddRec->getStepRecurrence(*SE), L->getHeader())
1114 && "Loop header phi recurrence inputs do not dominate the loop");
1115
1116 // The rewriter provides a value for the desired IV expression. This may
1117 // either find an existing phi or materialize a new one. Either way, we
1118 // expect a well-formed cyclic phi-with-increments. i.e. any operand not part
1119 // of the phi-SCC dominates the loop entry.
1120 Instruction *InsertPt = L->getHeader()->begin();
1121 WidePhi = cast<PHINode>(Rewriter.expandCodeFor(AddRec, WideType, InsertPt));
1122
1123 // Remembering the WideIV increment generated by SCEVExpander allows
1124 // WidenIVUse to reuse it when widening the narrow IV's increment. We don't
1125 // employ a general reuse mechanism because the call above is the only call to
1126 // SCEVExpander. Henceforth, we produce 1-to-1 narrow to wide uses.
Andrew Trickfcdc9a42011-05-26 00:46:11 +00001127 if (BasicBlock *LatchBlock = L->getLoopLatch()) {
1128 WideInc =
1129 cast<Instruction>(WidePhi->getIncomingValueForBlock(LatchBlock));
1130 WideIncExpr = SE->getSCEV(WideInc);
1131 }
Andrew Trickf85092c2011-05-20 18:25:42 +00001132
1133 DEBUG(dbgs() << "Wide IV: " << *WidePhi << "\n");
1134 ++NumWidened;
1135
1136 // Traverse the def-use chain using a worklist starting at the original IV.
Andrew Trick4b029152011-07-02 02:34:25 +00001137 assert(Widened.empty() && NarrowIVUsers.empty() && "expect initial state" );
Andrew Trickf85092c2011-05-20 18:25:42 +00001138
Andrew Trick4b029152011-07-02 02:34:25 +00001139 Widened.insert(OrigPhi);
1140 pushNarrowIVUsers(OrigPhi, WidePhi);
1141
Andrew Trickf85092c2011-05-20 18:25:42 +00001142 while (!NarrowIVUsers.empty()) {
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001143 NarrowIVDefUse DU = NarrowIVUsers.pop_back_val();
Andrew Trickf85092c2011-05-20 18:25:42 +00001144
Andrew Trickfcdc9a42011-05-26 00:46:11 +00001145 // Process a def-use edge. This may replace the use, so don't hold a
1146 // use_iterator across it.
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001147 Instruction *WideUse = WidenIVUse(DU);
Andrew Trickf85092c2011-05-20 18:25:42 +00001148
Andrew Trickfcdc9a42011-05-26 00:46:11 +00001149 // Follow all def-use edges from the previous narrow use.
Andrew Trick4b029152011-07-02 02:34:25 +00001150 if (WideUse)
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001151 pushNarrowIVUsers(DU.NarrowUse, WideUse);
Andrew Trick4b029152011-07-02 02:34:25 +00001152
Andrew Trickfcdc9a42011-05-26 00:46:11 +00001153 // WidenIVUse may have removed the def-use edge.
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001154 if (DU.NarrowDef->use_empty())
1155 DeadInsts.push_back(DU.NarrowDef);
Andrew Trickf85092c2011-05-20 18:25:42 +00001156 }
Andrew Trick2fabd462011-06-21 03:22:38 +00001157 return WidePhi;
Andrew Trickf85092c2011-05-20 18:25:42 +00001158}
1159
Andrew Trick1a54bb22011-07-12 00:08:50 +00001160//===----------------------------------------------------------------------===//
1161// Simplification of IV users based on SCEV evaluation.
1162//===----------------------------------------------------------------------===//
1163
Andrew Trickaeee4612011-05-12 00:04:28 +00001164void IndVarSimplify::EliminateIVComparison(ICmpInst *ICmp, Value *IVOperand) {
1165 unsigned IVOperIdx = 0;
1166 ICmpInst::Predicate Pred = ICmp->getPredicate();
1167 if (IVOperand != ICmp->getOperand(0)) {
1168 // Swapped
1169 assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
1170 IVOperIdx = 1;
1171 Pred = ICmpInst::getSwappedPredicate(Pred);
Dan Gohmana590b792010-04-13 01:46:36 +00001172 }
Andrew Trickaeee4612011-05-12 00:04:28 +00001173
1174 // Get the SCEVs for the ICmp operands.
1175 const SCEV *S = SE->getSCEV(ICmp->getOperand(IVOperIdx));
1176 const SCEV *X = SE->getSCEV(ICmp->getOperand(1 - IVOperIdx));
1177
1178 // Simplify unnecessary loops away.
1179 const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
1180 S = SE->getSCEVAtScope(S, ICmpLoop);
1181 X = SE->getSCEVAtScope(X, ICmpLoop);
1182
1183 // If the condition is always true or always false, replace it with
1184 // a constant value.
1185 if (SE->isKnownPredicate(Pred, S, X))
1186 ICmp->replaceAllUsesWith(ConstantInt::getTrue(ICmp->getContext()));
1187 else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X))
1188 ICmp->replaceAllUsesWith(ConstantInt::getFalse(ICmp->getContext()));
1189 else
1190 return;
1191
1192 DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
Andrew Trick03d3d3b2011-05-25 04:42:22 +00001193 ++NumElimCmp;
Andrew Trick074397d2011-05-20 03:37:48 +00001194 Changed = true;
Andrew Trickaeee4612011-05-12 00:04:28 +00001195 DeadInsts.push_back(ICmp);
1196}
1197
1198void IndVarSimplify::EliminateIVRemainder(BinaryOperator *Rem,
1199 Value *IVOperand,
Andrew Trick4417e532011-06-21 15:43:52 +00001200 bool IsSigned) {
Andrew Trickaeee4612011-05-12 00:04:28 +00001201 // We're only interested in the case where we know something about
1202 // the numerator.
1203 if (IVOperand != Rem->getOperand(0))
1204 return;
1205
1206 // Get the SCEVs for the ICmp operands.
1207 const SCEV *S = SE->getSCEV(Rem->getOperand(0));
1208 const SCEV *X = SE->getSCEV(Rem->getOperand(1));
1209
1210 // Simplify unnecessary loops away.
1211 const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent());
1212 S = SE->getSCEVAtScope(S, ICmpLoop);
1213 X = SE->getSCEVAtScope(X, ICmpLoop);
1214
1215 // i % n --> i if i is in [0,n).
Andrew Trick074397d2011-05-20 03:37:48 +00001216 if ((!IsSigned || SE->isKnownNonNegative(S)) &&
1217 SE->isKnownPredicate(IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
Andrew Trickaeee4612011-05-12 00:04:28 +00001218 S, X))
1219 Rem->replaceAllUsesWith(Rem->getOperand(0));
1220 else {
1221 // (i+1) % n --> (i+1)==n?0:(i+1) if i is in [0,n).
1222 const SCEV *LessOne =
1223 SE->getMinusSCEV(S, SE->getConstant(S->getType(), 1));
Andrew Trick074397d2011-05-20 03:37:48 +00001224 if (IsSigned && !SE->isKnownNonNegative(LessOne))
Andrew Trickaeee4612011-05-12 00:04:28 +00001225 return;
1226
Andrew Trick074397d2011-05-20 03:37:48 +00001227 if (!SE->isKnownPredicate(IsSigned ?
Andrew Trickaeee4612011-05-12 00:04:28 +00001228 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
1229 LessOne, X))
1230 return;
1231
1232 ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ,
1233 Rem->getOperand(0), Rem->getOperand(1),
1234 "tmp");
1235 SelectInst *Sel =
1236 SelectInst::Create(ICmp,
1237 ConstantInt::get(Rem->getType(), 0),
1238 Rem->getOperand(0), "tmp", Rem);
1239 Rem->replaceAllUsesWith(Sel);
1240 }
1241
1242 // Inform IVUsers about the new users.
Andrew Trick2fabd462011-06-21 03:22:38 +00001243 if (IU) {
1244 if (Instruction *I = dyn_cast<Instruction>(Rem->getOperand(0)))
Andrew Trick4417e532011-06-21 15:43:52 +00001245 IU->AddUsersIfInteresting(I);
Andrew Trick2fabd462011-06-21 03:22:38 +00001246 }
Andrew Trickaeee4612011-05-12 00:04:28 +00001247 DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
Andrew Trick03d3d3b2011-05-25 04:42:22 +00001248 ++NumElimRem;
Andrew Trick074397d2011-05-20 03:37:48 +00001249 Changed = true;
Andrew Trickaeee4612011-05-12 00:04:28 +00001250 DeadInsts.push_back(Rem);
Dan Gohmana590b792010-04-13 01:46:36 +00001251}
1252
Andrew Trick2fabd462011-06-21 03:22:38 +00001253/// EliminateIVUser - Eliminate an operation that consumes a simple IV and has
1254/// no observable side-effect given the range of IV values.
1255bool IndVarSimplify::EliminateIVUser(Instruction *UseInst,
1256 Instruction *IVOperand) {
1257 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
1258 EliminateIVComparison(ICmp, IVOperand);
1259 return true;
1260 }
1261 if (BinaryOperator *Rem = dyn_cast<BinaryOperator>(UseInst)) {
1262 bool IsSigned = Rem->getOpcode() == Instruction::SRem;
1263 if (IsSigned || Rem->getOpcode() == Instruction::URem) {
Andrew Trick4417e532011-06-21 15:43:52 +00001264 EliminateIVRemainder(Rem, IVOperand, IsSigned);
Andrew Trick2fabd462011-06-21 03:22:38 +00001265 return true;
1266 }
1267 }
1268
1269 // Eliminate any operation that SCEV can prove is an identity function.
1270 if (!SE->isSCEVable(UseInst->getType()) ||
Andrew Trick11745d42011-06-29 03:13:40 +00001271 (UseInst->getType() != IVOperand->getType()) ||
Andrew Trick2fabd462011-06-21 03:22:38 +00001272 (SE->getSCEV(UseInst) != SE->getSCEV(IVOperand)))
1273 return false;
1274
Andrew Trick2fabd462011-06-21 03:22:38 +00001275 DEBUG(dbgs() << "INDVARS: Eliminated identity: " << *UseInst << '\n');
Andrew Trick60ac7192011-06-30 01:27:23 +00001276
1277 UseInst->replaceAllUsesWith(IVOperand);
Andrew Trick2fabd462011-06-21 03:22:38 +00001278 ++NumElimIdentity;
1279 Changed = true;
1280 DeadInsts.push_back(UseInst);
1281 return true;
1282}
1283
1284/// pushIVUsers - Add all uses of Def to the current IV's worklist.
1285///
Andrew Trick15832f62011-06-28 02:49:20 +00001286static void pushIVUsers(
1287 Instruction *Def,
1288 SmallPtrSet<Instruction*,16> &Simplified,
1289 SmallVectorImpl< std::pair<Instruction*,Instruction*> > &SimpleIVUsers) {
Andrew Trick2fabd462011-06-21 03:22:38 +00001290
1291 for (Value::use_iterator UI = Def->use_begin(), E = Def->use_end();
1292 UI != E; ++UI) {
1293 Instruction *User = cast<Instruction>(*UI);
1294
1295 // Avoid infinite or exponential worklist processing.
1296 // Also ensure unique worklist users.
Andrew Trick60ac7192011-06-30 01:27:23 +00001297 // If Def is a LoopPhi, it may not be in the Simplified set, so check for
1298 // self edges first.
1299 if (User != Def && Simplified.insert(User))
Andrew Trick2fabd462011-06-21 03:22:38 +00001300 SimpleIVUsers.push_back(std::make_pair(User, Def));
1301 }
1302}
1303
1304/// isSimpleIVUser - Return true if this instruction generates a simple SCEV
1305/// expression in terms of that IV.
1306///
1307/// This is similar to IVUsers' isInsteresting() but processes each instruction
1308/// non-recursively when the operand is already known to be a simpleIVUser.
1309///
Andrew Trick1a54bb22011-07-12 00:08:50 +00001310static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE) {
Andrew Trick2fabd462011-06-21 03:22:38 +00001311 if (!SE->isSCEVable(I->getType()))
1312 return false;
1313
1314 // Get the symbolic expression for this instruction.
1315 const SCEV *S = SE->getSCEV(I);
1316
1317 // Only consider affine recurrences.
1318 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S);
1319 if (AR && AR->getLoop() == L)
1320 return true;
1321
1322 return false;
1323}
1324
1325/// SimplifyIVUsersNoRewrite - Iteratively perform simplification on a worklist
1326/// of IV users. Each successive simplification may push more users which may
1327/// themselves be candidates for simplification.
1328///
1329/// The "NoRewrite" algorithm does not require IVUsers analysis. Instead, it
1330/// simplifies instructions in-place during analysis. Rather than rewriting
1331/// induction variables bottom-up from their users, it transforms a chain of
1332/// IVUsers top-down, updating the IR only when it encouters a clear
1333/// optimization opportunitiy. A SCEVExpander "Rewriter" instance is still
1334/// needed, but only used to generate a new IV (phi) of wider type for sign/zero
1335/// extend elimination.
1336///
1337/// Once DisableIVRewrite is default, LSR will be the only client of IVUsers.
1338///
1339void IndVarSimplify::SimplifyIVUsersNoRewrite(Loop *L, SCEVExpander &Rewriter) {
Andrew Trick15832f62011-06-28 02:49:20 +00001340 std::map<PHINode *, WideIVInfo> WideIVMap;
1341
Andrew Trick2fabd462011-06-21 03:22:38 +00001342 SmallVector<PHINode*, 8> LoopPhis;
1343 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
1344 LoopPhis.push_back(cast<PHINode>(I));
1345 }
Andrew Trick15832f62011-06-28 02:49:20 +00001346 // Each round of simplification iterates through the SimplifyIVUsers worklist
1347 // for all current phis, then determines whether any IVs can be
1348 // widened. Widening adds new phis to LoopPhis, inducing another round of
1349 // simplification on the wide IVs.
Andrew Trick2fabd462011-06-21 03:22:38 +00001350 while (!LoopPhis.empty()) {
Andrew Trick15832f62011-06-28 02:49:20 +00001351 // Evaluate as many IV expressions as possible before widening any IVs. This
Andrew Trick99a92f62011-06-28 16:45:04 +00001352 // forces SCEV to set no-wrap flags before evaluating sign/zero
Andrew Trick15832f62011-06-28 02:49:20 +00001353 // extension. The first time SCEV attempts to normalize sign/zero extension,
1354 // the result becomes final. So for the most predictable results, we delay
1355 // evaluation of sign/zero extend evaluation until needed, and avoid running
1356 // other SCEV based analysis prior to SimplifyIVUsersNoRewrite.
1357 do {
1358 PHINode *CurrIV = LoopPhis.pop_back_val();
Andrew Trick2fabd462011-06-21 03:22:38 +00001359
Andrew Trick15832f62011-06-28 02:49:20 +00001360 // Information about sign/zero extensions of CurrIV.
1361 WideIVInfo WI;
Andrew Trick2fabd462011-06-21 03:22:38 +00001362
Andrew Trick15832f62011-06-28 02:49:20 +00001363 // Instructions processed by SimplifyIVUsers for CurrIV.
1364 SmallPtrSet<Instruction*,16> Simplified;
Andrew Trick2fabd462011-06-21 03:22:38 +00001365
Andrew Trick037d1c02011-07-06 20:50:43 +00001366 // Use-def pairs if IV users waiting to be processed for CurrIV.
Andrew Trick15832f62011-06-28 02:49:20 +00001367 SmallVector<std::pair<Instruction*, Instruction*>, 8> SimpleIVUsers;
Andrew Trick2fabd462011-06-21 03:22:38 +00001368
Andrew Trick60ac7192011-06-30 01:27:23 +00001369 // Push users of the current LoopPhi. In rare cases, pushIVUsers may be
1370 // called multiple times for the same LoopPhi. This is the proper thing to
1371 // do for loop header phis that use each other.
Andrew Trick15832f62011-06-28 02:49:20 +00001372 pushIVUsers(CurrIV, Simplified, SimpleIVUsers);
1373
1374 while (!SimpleIVUsers.empty()) {
1375 Instruction *UseInst, *Operand;
1376 tie(UseInst, Operand) = SimpleIVUsers.pop_back_val();
Andrew Trick6e0ce242011-06-30 19:02:17 +00001377 // Bypass back edges to avoid extra work.
1378 if (UseInst == CurrIV) continue;
Andrew Trick15832f62011-06-28 02:49:20 +00001379
1380 if (EliminateIVUser(UseInst, Operand)) {
1381 pushIVUsers(Operand, Simplified, SimpleIVUsers);
1382 continue;
Andrew Trick2fabd462011-06-21 03:22:38 +00001383 }
Andrew Trick15832f62011-06-28 02:49:20 +00001384 if (CastInst *Cast = dyn_cast<CastInst>(UseInst)) {
1385 bool IsSigned = Cast->getOpcode() == Instruction::SExt;
1386 if (IsSigned || Cast->getOpcode() == Instruction::ZExt) {
1387 CollectExtend(Cast, IsSigned, WI, SE, TD);
1388 }
1389 continue;
1390 }
Andrew Trick1a54bb22011-07-12 00:08:50 +00001391 if (isSimpleIVUser(UseInst, L, SE)) {
Andrew Trick15832f62011-06-28 02:49:20 +00001392 pushIVUsers(UseInst, Simplified, SimpleIVUsers);
1393 }
Andrew Trick2fabd462011-06-21 03:22:38 +00001394 }
Andrew Trick15832f62011-06-28 02:49:20 +00001395 if (WI.WidestNativeType) {
1396 WideIVMap[CurrIV] = WI;
Andrew Trick2fabd462011-06-21 03:22:38 +00001397 }
Andrew Trick15832f62011-06-28 02:49:20 +00001398 } while(!LoopPhis.empty());
1399
1400 for (std::map<PHINode *, WideIVInfo>::const_iterator I = WideIVMap.begin(),
1401 E = WideIVMap.end(); I != E; ++I) {
1402 WidenIV Widener(I->first, I->second, LI, SE, DT, DeadInsts);
Andrew Trick2fabd462011-06-21 03:22:38 +00001403 if (PHINode *WidePhi = Widener.CreateWideIV(Rewriter)) {
1404 Changed = true;
1405 LoopPhis.push_back(WidePhi);
1406 }
1407 }
Andrew Trick15832f62011-06-28 02:49:20 +00001408 WideIVMap.clear();
Andrew Trick2fabd462011-06-21 03:22:38 +00001409 }
1410}
1411
Andrew Trick037d1c02011-07-06 20:50:43 +00001412/// SimplifyCongruentIVs - Check for congruent phis in this loop header and
1413/// populate ExprToIVMap for use later.
1414///
1415void IndVarSimplify::SimplifyCongruentIVs(Loop *L) {
Andrew Trick6f684b02011-07-16 01:06:48 +00001416 DenseMap<const SCEV *, PHINode *> ExprToIVMap;
Andrew Trick037d1c02011-07-06 20:50:43 +00001417 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
1418 PHINode *Phi = cast<PHINode>(I);
Andrew Trick1a54bb22011-07-12 00:08:50 +00001419 if (!SE->isSCEVable(Phi->getType()))
1420 continue;
1421
Andrew Trick037d1c02011-07-06 20:50:43 +00001422 const SCEV *S = SE->getSCEV(Phi);
Andrew Trick6f684b02011-07-16 01:06:48 +00001423 DenseMap<const SCEV *, PHINode *>::const_iterator Pos;
Andrew Trick037d1c02011-07-06 20:50:43 +00001424 bool Inserted;
1425 tie(Pos, Inserted) = ExprToIVMap.insert(std::make_pair(S, Phi));
1426 if (Inserted)
1427 continue;
1428 PHINode *OrigPhi = Pos->second;
Andrew Trickf22d9572011-07-20 02:08:58 +00001429
1430 // If one phi derives from the other via GEPs, types may differ.
1431 if (OrigPhi->getType() != Phi->getType())
1432 continue;
1433
Andrew Trick037d1c02011-07-06 20:50:43 +00001434 // Replacing the congruent phi is sufficient because acyclic redundancy
1435 // elimination, CSE/GVN, should handle the rest. However, once SCEV proves
1436 // that a phi is congruent, it's almost certain to be the head of an IV
1437 // user cycle that is isomorphic with the original phi. So it's worth
1438 // eagerly cleaning up the common case of a single IV increment.
1439 if (BasicBlock *LatchBlock = L->getLoopLatch()) {
1440 Instruction *OrigInc =
1441 cast<Instruction>(OrigPhi->getIncomingValueForBlock(LatchBlock));
1442 Instruction *IsomorphicInc =
1443 cast<Instruction>(Phi->getIncomingValueForBlock(LatchBlock));
1444 if (OrigInc != IsomorphicInc &&
Andrew Trickf22d9572011-07-20 02:08:58 +00001445 OrigInc->getType() == IsomorphicInc->getType() &&
Andrew Trick037d1c02011-07-06 20:50:43 +00001446 SE->getSCEV(OrigInc) == SE->getSCEV(IsomorphicInc) &&
1447 HoistStep(OrigInc, IsomorphicInc, DT)) {
1448 DEBUG(dbgs() << "INDVARS: Eliminated congruent iv.inc: "
1449 << *IsomorphicInc << '\n');
1450 IsomorphicInc->replaceAllUsesWith(OrigInc);
1451 DeadInsts.push_back(IsomorphicInc);
1452 }
1453 }
1454 DEBUG(dbgs() << "INDVARS: Eliminated congruent iv: " << *Phi << '\n');
1455 ++NumElimIV;
1456 Phi->replaceAllUsesWith(OrigPhi);
1457 DeadInsts.push_back(Phi);
1458 }
1459}
1460
Andrew Trick1a54bb22011-07-12 00:08:50 +00001461//===----------------------------------------------------------------------===//
1462// LinearFunctionTestReplace and its kin. Rewrite the loop exit condition.
1463//===----------------------------------------------------------------------===//
1464
Andrew Trick5241b792011-07-18 18:21:35 +00001465// Check for expressions that ScalarEvolution generates to compute
1466// BackedgeTakenInfo. If these expressions have not been reduced, then expanding
1467// them may incur additional cost (albeit in the loop preheader).
1468static bool isHighCostExpansion(const SCEV *S, BranchInst *BI,
1469 ScalarEvolution *SE) {
1470 // If the backedge-taken count is a UDiv, it's very likely a UDiv that
1471 // ScalarEvolution's HowFarToZero or HowManyLessThans produced to compute a
1472 // precise expression, rather than a UDiv from the user's code. If we can't
1473 // find a UDiv in the code with some simple searching, assume the former and
1474 // forego rewriting the loop.
1475 if (isa<SCEVUDivExpr>(S)) {
1476 ICmpInst *OrigCond = dyn_cast<ICmpInst>(BI->getCondition());
1477 if (!OrigCond) return true;
1478 const SCEV *R = SE->getSCEV(OrigCond->getOperand(1));
1479 R = SE->getMinusSCEV(R, SE->getConstant(R->getType(), 1));
1480 if (R != S) {
1481 const SCEV *L = SE->getSCEV(OrigCond->getOperand(0));
1482 L = SE->getMinusSCEV(L, SE->getConstant(L->getType(), 1));
1483 if (L != S)
1484 return true;
1485 }
1486 }
1487
Andrew Trickfc933c02011-07-18 20:32:31 +00001488 if (!DisableIVRewrite || ForceLFTR)
Andrew Trick5241b792011-07-18 18:21:35 +00001489 return false;
1490
1491 // Recurse past add expressions, which commonly occur in the
1492 // BackedgeTakenCount. They may already exist in program code, and if not,
1493 // they are not too expensive rematerialize.
1494 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
1495 for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
1496 I != E; ++I) {
1497 if (isHighCostExpansion(*I, BI, SE))
1498 return true;
1499 }
1500 return false;
1501 }
1502
1503 // HowManyLessThans uses a Max expression whenever the loop is not guarded by
1504 // the exit condition.
1505 if (isa<SCEVSMaxExpr>(S) || isa<SCEVUMaxExpr>(S))
1506 return true;
1507
1508 // If we haven't recognized an expensive SCEV patter, assume its an expression
1509 // produced by program code.
1510 return false;
1511}
1512
Andrew Trick1a54bb22011-07-12 00:08:50 +00001513/// canExpandBackedgeTakenCount - Return true if this loop's backedge taken
1514/// count expression can be safely and cheaply expanded into an instruction
1515/// sequence that can be used by LinearFunctionTestReplace.
1516static bool canExpandBackedgeTakenCount(Loop *L, ScalarEvolution *SE) {
1517 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
1518 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount) ||
1519 BackedgeTakenCount->isZero())
1520 return false;
1521
1522 if (!L->getExitingBlock())
1523 return false;
1524
1525 // Can't rewrite non-branch yet.
1526 BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator());
1527 if (!BI)
1528 return false;
1529
Andrew Trick5241b792011-07-18 18:21:35 +00001530 if (isHighCostExpansion(BackedgeTakenCount, BI, SE))
1531 return false;
1532
Andrew Trick1a54bb22011-07-12 00:08:50 +00001533 return true;
1534}
1535
1536/// getBackedgeIVType - Get the widest type used by the loop test after peeking
1537/// through Truncs.
1538///
Andrew Trickfc933c02011-07-18 20:32:31 +00001539/// TODO: Unnecessary when ForceLFTR is removed.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001540static Type *getBackedgeIVType(Loop *L) {
Andrew Trick1a54bb22011-07-12 00:08:50 +00001541 if (!L->getExitingBlock())
1542 return 0;
1543
1544 // Can't rewrite non-branch yet.
1545 BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator());
1546 if (!BI)
1547 return 0;
1548
1549 ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition());
1550 if (!Cond)
1551 return 0;
1552
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001553 Type *Ty = 0;
Andrew Trick1a54bb22011-07-12 00:08:50 +00001554 for(User::op_iterator OI = Cond->op_begin(), OE = Cond->op_end();
1555 OI != OE; ++OI) {
1556 assert((!Ty || Ty == (*OI)->getType()) && "bad icmp operand types");
1557 TruncInst *Trunc = dyn_cast<TruncInst>(*OI);
1558 if (!Trunc)
1559 continue;
1560
1561 return Trunc->getSrcTy();
1562 }
1563 return Ty;
1564}
1565
Andrew Trickfc933c02011-07-18 20:32:31 +00001566/// isLoopInvariant - Perform a quick domtree based check for loop invariance
1567/// assuming that V is used within the loop. LoopInfo::isLoopInvariant() seems
1568/// gratuitous for this purpose.
1569static bool isLoopInvariant(Value *V, Loop *L, DominatorTree *DT) {
1570 Instruction *Inst = dyn_cast<Instruction>(V);
1571 if (!Inst)
1572 return true;
1573
1574 return DT->properlyDominates(Inst->getParent(), L->getHeader());
1575}
1576
1577/// getLoopPhiForCounter - Return the loop header phi IFF IncV adds a loop
1578/// invariant value to the phi.
1579static PHINode *getLoopPhiForCounter(Value *IncV, Loop *L, DominatorTree *DT) {
1580 Instruction *IncI = dyn_cast<Instruction>(IncV);
1581 if (!IncI)
1582 return 0;
1583
1584 switch (IncI->getOpcode()) {
1585 case Instruction::Add:
1586 case Instruction::Sub:
1587 break;
1588 case Instruction::GetElementPtr:
1589 // An IV counter must preserve its type.
1590 if (IncI->getNumOperands() == 2)
1591 break;
1592 default:
1593 return 0;
1594 }
1595
1596 PHINode *Phi = dyn_cast<PHINode>(IncI->getOperand(0));
1597 if (Phi && Phi->getParent() == L->getHeader()) {
1598 if (isLoopInvariant(IncI->getOperand(1), L, DT))
1599 return Phi;
1600 return 0;
1601 }
1602 if (IncI->getOpcode() == Instruction::GetElementPtr)
1603 return 0;
1604
1605 // Allow add/sub to be commuted.
1606 Phi = dyn_cast<PHINode>(IncI->getOperand(1));
1607 if (Phi && Phi->getParent() == L->getHeader()) {
1608 if (isLoopInvariant(IncI->getOperand(0), L, DT))
1609 return Phi;
1610 }
1611 return 0;
1612}
1613
1614/// needsLFTR - LinearFunctionTestReplace policy. Return true unless we can show
1615/// that the current exit test is already sufficiently canonical.
1616static bool needsLFTR(Loop *L, DominatorTree *DT) {
1617 assert(L->getExitingBlock() && "expected loop exit");
1618
1619 BasicBlock *LatchBlock = L->getLoopLatch();
1620 // Don't bother with LFTR if the loop is not properly simplified.
1621 if (!LatchBlock)
1622 return false;
1623
1624 BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator());
1625 assert(BI && "expected exit branch");
1626
1627 // Do LFTR to simplify the exit condition to an ICMP.
1628 ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition());
1629 if (!Cond)
1630 return true;
1631
1632 // Do LFTR to simplify the exit ICMP to EQ/NE
1633 ICmpInst::Predicate Pred = Cond->getPredicate();
1634 if (Pred != ICmpInst::ICMP_NE && Pred != ICmpInst::ICMP_EQ)
1635 return true;
1636
1637 // Look for a loop invariant RHS
1638 Value *LHS = Cond->getOperand(0);
1639 Value *RHS = Cond->getOperand(1);
1640 if (!isLoopInvariant(RHS, L, DT)) {
1641 if (!isLoopInvariant(LHS, L, DT))
1642 return true;
1643 std::swap(LHS, RHS);
1644 }
1645 // Look for a simple IV counter LHS
1646 PHINode *Phi = dyn_cast<PHINode>(LHS);
1647 if (!Phi)
1648 Phi = getLoopPhiForCounter(LHS, L, DT);
1649
1650 if (!Phi)
1651 return true;
1652
1653 // Do LFTR if the exit condition's IV is *not* a simple counter.
1654 Value *IncV = Phi->getIncomingValueForBlock(L->getLoopLatch());
1655 return Phi != getLoopPhiForCounter(IncV, L, DT);
1656}
1657
1658/// AlmostDeadIV - Return true if this IV has any uses other than the (soon to
1659/// be rewritten) loop exit test.
1660static bool AlmostDeadIV(PHINode *Phi, BasicBlock *LatchBlock, Value *Cond) {
1661 int LatchIdx = Phi->getBasicBlockIndex(LatchBlock);
1662 Value *IncV = Phi->getIncomingValue(LatchIdx);
1663
1664 for (Value::use_iterator UI = Phi->use_begin(), UE = Phi->use_end();
1665 UI != UE; ++UI) {
1666 if (*UI != Cond && *UI != IncV) return false;
1667 }
1668
1669 for (Value::use_iterator UI = IncV->use_begin(), UE = IncV->use_end();
1670 UI != UE; ++UI) {
1671 if (*UI != Cond && *UI != Phi) return false;
1672 }
1673 return true;
1674}
1675
1676/// FindLoopCounter - Find an affine IV in canonical form.
1677///
1678/// FIXME: Accept -1 stride and set IVLimit = IVInit - BECount
1679///
1680/// FIXME: Accept non-unit stride as long as SCEV can reduce BECount * Stride.
1681/// This is difficult in general for SCEV because of potential overflow. But we
1682/// could at least handle constant BECounts.
1683static PHINode *
1684FindLoopCounter(Loop *L, const SCEV *BECount,
1685 ScalarEvolution *SE, DominatorTree *DT, const TargetData *TD) {
1686 // I'm not sure how BECount could be a pointer type, but we definitely don't
1687 // want to LFTR that.
1688 if (BECount->getType()->isPointerTy())
1689 return 0;
1690
1691 uint64_t BCWidth = SE->getTypeSizeInBits(BECount->getType());
1692
1693 Value *Cond =
1694 cast<BranchInst>(L->getExitingBlock()->getTerminator())->getCondition();
1695
1696 // Loop over all of the PHI nodes, looking for a simple counter.
1697 PHINode *BestPhi = 0;
1698 const SCEV *BestInit = 0;
1699 BasicBlock *LatchBlock = L->getLoopLatch();
1700 assert(LatchBlock && "needsLFTR should guarantee a loop latch");
1701
1702 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
1703 PHINode *Phi = cast<PHINode>(I);
1704 if (!SE->isSCEVable(Phi->getType()))
1705 continue;
1706
1707 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Phi));
1708 if (!AR || AR->getLoop() != L || !AR->isAffine())
1709 continue;
1710
1711 // AR may be a pointer type, while BECount is an integer type.
1712 // AR may be wider than BECount. With eq/ne tests overflow is immaterial.
1713 // AR may not be a narrower type, or we may never exit.
1714 uint64_t PhiWidth = SE->getTypeSizeInBits(AR->getType());
1715 if (PhiWidth < BCWidth || (TD && !TD->isLegalInteger(PhiWidth)))
1716 continue;
1717
1718 const SCEV *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*SE));
1719 if (!Step || !Step->isOne())
1720 continue;
1721
1722 int LatchIdx = Phi->getBasicBlockIndex(LatchBlock);
1723 Value *IncV = Phi->getIncomingValue(LatchIdx);
1724 if (getLoopPhiForCounter(IncV, L, DT) != Phi)
1725 continue;
1726
1727 const SCEV *Init = AR->getStart();
1728
1729 if (BestPhi && !AlmostDeadIV(BestPhi, LatchBlock, Cond)) {
1730 // Don't force a live loop counter if another IV can be used.
1731 if (AlmostDeadIV(Phi, LatchBlock, Cond))
1732 continue;
1733
1734 // Prefer to count-from-zero. This is a more "canonical" counter form. It
1735 // also prefers integer to pointer IVs.
1736 if (BestInit->isZero() != Init->isZero()) {
1737 if (BestInit->isZero())
1738 continue;
1739 }
1740 // If two IVs both count from zero or both count from nonzero then the
1741 // narrower is likely a dead phi that has been widened. Use the wider phi
1742 // to allow the other to be eliminated.
1743 if (PhiWidth <= SE->getTypeSizeInBits(BestPhi->getType()))
1744 continue;
1745 }
1746 BestPhi = Phi;
1747 BestInit = Init;
1748 }
1749 return BestPhi;
1750}
1751
Andrew Trick1a54bb22011-07-12 00:08:50 +00001752/// LinearFunctionTestReplace - This method rewrites the exit condition of the
1753/// loop to be a canonical != comparison against the incremented loop induction
1754/// variable. This pass is able to rewrite the exit tests of any loop where the
1755/// SCEV analysis can determine a loop-invariant trip count of the loop, which
1756/// is actually a much broader range than just linear tests.
Andrew Trickfc933c02011-07-18 20:32:31 +00001757Value *IndVarSimplify::
Andrew Trick1a54bb22011-07-12 00:08:50 +00001758LinearFunctionTestReplace(Loop *L,
1759 const SCEV *BackedgeTakenCount,
1760 PHINode *IndVar,
1761 SCEVExpander &Rewriter) {
1762 assert(canExpandBackedgeTakenCount(L, SE) && "precondition");
1763 BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator());
1764
Andrew Trickfc933c02011-07-18 20:32:31 +00001765 // In DisableIVRewrite mode, IndVar is not necessarily a canonical IV. In this
1766 // mode, LFTR can ignore IV overflow and truncate to the width of
1767 // BECount. This avoids materializing the add(zext(add)) expression.
1768 Type *CntTy = DisableIVRewrite ?
1769 BackedgeTakenCount->getType() : IndVar->getType();
1770
1771 const SCEV *IVLimit = BackedgeTakenCount;
1772
Andrew Trick1a54bb22011-07-12 00:08:50 +00001773 // If the exiting block is not the same as the backedge block, we must compare
1774 // against the preincremented value, otherwise we prefer to compare against
1775 // the post-incremented value.
1776 Value *CmpIndVar;
Andrew Trick1a54bb22011-07-12 00:08:50 +00001777 if (L->getExitingBlock() == L->getLoopLatch()) {
1778 // Add one to the "backedge-taken" count to get the trip count.
1779 // If this addition may overflow, we have to be more pessimistic and
1780 // cast the induction variable before doing the add.
Andrew Trick1a54bb22011-07-12 00:08:50 +00001781 const SCEV *N =
Andrew Trickfc933c02011-07-18 20:32:31 +00001782 SE->getAddExpr(IVLimit, SE->getConstant(IVLimit->getType(), 1));
1783 if (CntTy == IVLimit->getType())
1784 IVLimit = N;
1785 else {
1786 const SCEV *Zero = SE->getConstant(IVLimit->getType(), 0);
1787 if ((isa<SCEVConstant>(N) && !N->isZero()) ||
1788 SE->isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) {
1789 // No overflow. Cast the sum.
1790 IVLimit = SE->getTruncateOrZeroExtend(N, CntTy);
1791 } else {
1792 // Potential overflow. Cast before doing the add.
1793 IVLimit = SE->getTruncateOrZeroExtend(IVLimit, CntTy);
1794 IVLimit = SE->getAddExpr(IVLimit, SE->getConstant(CntTy, 1));
1795 }
Andrew Trick1a54bb22011-07-12 00:08:50 +00001796 }
Andrew Trick1a54bb22011-07-12 00:08:50 +00001797 // The BackedgeTaken expression contains the number of times that the
1798 // backedge branches to the loop header. This is one less than the
1799 // number of times the loop executes, so use the incremented indvar.
1800 CmpIndVar = IndVar->getIncomingValueForBlock(L->getExitingBlock());
1801 } else {
1802 // We have to use the preincremented value...
Andrew Trickfc933c02011-07-18 20:32:31 +00001803 IVLimit = SE->getTruncateOrZeroExtend(IVLimit, CntTy);
Andrew Trick1a54bb22011-07-12 00:08:50 +00001804 CmpIndVar = IndVar;
1805 }
1806
Andrew Trickfc933c02011-07-18 20:32:31 +00001807 // For unit stride, IVLimit = Start + BECount with 2's complement overflow.
1808 // So for, non-zero start compute the IVLimit here.
1809 bool isPtrIV = false;
1810 Type *CmpTy = CntTy;
1811 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(IndVar));
1812 assert(AR && AR->getLoop() == L && AR->isAffine() && "bad loop counter");
1813 if (!AR->getStart()->isZero()) {
1814 assert(AR->getStepRecurrence(*SE)->isOne() && "only handles unit stride");
1815 const SCEV *IVInit = AR->getStart();
1816
1817 // For pointer types, sign extend BECount in order to materialize a GEP.
1818 // Note that for DisableIVRewrite, we never run SCEVExpander on a
1819 // pointer type, because we must preserve the existing GEPs. Instead we
1820 // directly generate a GEP later.
1821 if (IVInit->getType()->isPointerTy()) {
1822 isPtrIV = true;
1823 CmpTy = SE->getEffectiveSCEVType(IVInit->getType());
1824 IVLimit = SE->getTruncateOrSignExtend(IVLimit, CmpTy);
1825 }
1826 // For integer types, truncate the IV before computing IVInit + BECount.
1827 else {
1828 if (SE->getTypeSizeInBits(IVInit->getType())
1829 > SE->getTypeSizeInBits(CmpTy))
1830 IVInit = SE->getTruncateExpr(IVInit, CmpTy);
1831
1832 IVLimit = SE->getAddExpr(IVInit, IVLimit);
1833 }
1834 }
Andrew Trick1a54bb22011-07-12 00:08:50 +00001835 // Expand the code for the iteration count.
Andrew Trickfc933c02011-07-18 20:32:31 +00001836 IRBuilder<> Builder(BI);
1837
1838 assert(SE->isLoopInvariant(IVLimit, L) &&
Andrew Trick1a54bb22011-07-12 00:08:50 +00001839 "Computed iteration count is not loop invariant!");
Andrew Trickfc933c02011-07-18 20:32:31 +00001840 Value *ExitCnt = Rewriter.expandCodeFor(IVLimit, CmpTy, BI);
1841
1842 // Create a gep for IVInit + IVLimit from on an existing pointer base.
1843 assert(isPtrIV == IndVar->getType()->isPointerTy() &&
1844 "IndVar type must match IVInit type");
1845 if (isPtrIV) {
1846 Value *IVStart = IndVar->getIncomingValueForBlock(L->getLoopPreheader());
1847 assert(AR->getStart() == SE->getSCEV(IVStart) && "bad loop counter");
Andrew Trick41e0d4e2011-07-18 21:15:03 +00001848 assert(SE->getSizeOfExpr(
1849 cast<PointerType>(IVStart->getType())->getElementType())->isOne()
1850 && "unit stride pointer IV must be i8*");
Andrew Trickfc933c02011-07-18 20:32:31 +00001851
1852 Builder.SetInsertPoint(L->getLoopPreheader()->getTerminator());
1853 ExitCnt = Builder.CreateGEP(IVStart, ExitCnt, "lftr.limit");
1854 Builder.SetInsertPoint(BI);
1855 }
Andrew Trick1a54bb22011-07-12 00:08:50 +00001856
1857 // Insert a new icmp_ne or icmp_eq instruction before the branch.
Andrew Trickfc933c02011-07-18 20:32:31 +00001858 ICmpInst::Predicate P;
Andrew Trick1a54bb22011-07-12 00:08:50 +00001859 if (L->contains(BI->getSuccessor(0)))
Andrew Trickfc933c02011-07-18 20:32:31 +00001860 P = ICmpInst::ICMP_NE;
Andrew Trick1a54bb22011-07-12 00:08:50 +00001861 else
Andrew Trickfc933c02011-07-18 20:32:31 +00001862 P = ICmpInst::ICMP_EQ;
Andrew Trick1a54bb22011-07-12 00:08:50 +00001863
1864 DEBUG(dbgs() << "INDVARS: Rewriting loop exit condition to:\n"
1865 << " LHS:" << *CmpIndVar << '\n'
1866 << " op:\t"
Andrew Trickfc933c02011-07-18 20:32:31 +00001867 << (P == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
1868 << " RHS:\t" << *ExitCnt << "\n"
1869 << " Expr:\t" << *IVLimit << "\n");
Andrew Trick1a54bb22011-07-12 00:08:50 +00001870
Andrew Trickfc933c02011-07-18 20:32:31 +00001871 if (SE->getTypeSizeInBits(CmpIndVar->getType())
1872 > SE->getTypeSizeInBits(CmpTy)) {
1873 CmpIndVar = Builder.CreateTrunc(CmpIndVar, CmpTy, "lftr.wideiv");
1874 }
1875
1876 Value *Cond = Builder.CreateICmp(P, CmpIndVar, ExitCnt, "exitcond");
Andrew Trick1a54bb22011-07-12 00:08:50 +00001877 Value *OrigCond = BI->getCondition();
1878 // It's tempting to use replaceAllUsesWith here to fully replace the old
1879 // comparison, but that's not immediately safe, since users of the old
1880 // comparison may not be dominated by the new comparison. Instead, just
1881 // update the branch to use the new comparison; in the common case this
1882 // will make old comparison dead.
1883 BI->setCondition(Cond);
1884 DeadInsts.push_back(OrigCond);
1885
1886 ++NumLFTR;
1887 Changed = true;
1888 return Cond;
1889}
1890
1891//===----------------------------------------------------------------------===//
1892// SinkUnusedInvariants. A late subpass to cleanup loop preheaders.
1893//===----------------------------------------------------------------------===//
1894
1895/// If there's a single exit block, sink any loop-invariant values that
1896/// were defined in the preheader but not used inside the loop into the
1897/// exit block to reduce register pressure in the loop.
1898void IndVarSimplify::SinkUnusedInvariants(Loop *L) {
1899 BasicBlock *ExitBlock = L->getExitBlock();
1900 if (!ExitBlock) return;
1901
1902 BasicBlock *Preheader = L->getLoopPreheader();
1903 if (!Preheader) return;
1904
1905 Instruction *InsertPt = ExitBlock->getFirstNonPHI();
1906 BasicBlock::iterator I = Preheader->getTerminator();
1907 while (I != Preheader->begin()) {
1908 --I;
1909 // New instructions were inserted at the end of the preheader.
1910 if (isa<PHINode>(I))
1911 break;
1912
1913 // Don't move instructions which might have side effects, since the side
1914 // effects need to complete before instructions inside the loop. Also don't
1915 // move instructions which might read memory, since the loop may modify
1916 // memory. Note that it's okay if the instruction might have undefined
1917 // behavior: LoopSimplify guarantees that the preheader dominates the exit
1918 // block.
1919 if (I->mayHaveSideEffects() || I->mayReadFromMemory())
1920 continue;
1921
1922 // Skip debug info intrinsics.
1923 if (isa<DbgInfoIntrinsic>(I))
1924 continue;
1925
1926 // Don't sink static AllocaInsts out of the entry block, which would
1927 // turn them into dynamic allocas!
1928 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
1929 if (AI->isStaticAlloca())
1930 continue;
1931
1932 // Determine if there is a use in or before the loop (direct or
1933 // otherwise).
1934 bool UsedInLoop = false;
1935 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
1936 UI != UE; ++UI) {
1937 User *U = *UI;
1938 BasicBlock *UseBB = cast<Instruction>(U)->getParent();
1939 if (PHINode *P = dyn_cast<PHINode>(U)) {
1940 unsigned i =
1941 PHINode::getIncomingValueNumForOperand(UI.getOperandNo());
1942 UseBB = P->getIncomingBlock(i);
1943 }
1944 if (UseBB == Preheader || L->contains(UseBB)) {
1945 UsedInLoop = true;
1946 break;
1947 }
1948 }
1949
1950 // If there is, the def must remain in the preheader.
1951 if (UsedInLoop)
1952 continue;
1953
1954 // Otherwise, sink it to the exit block.
1955 Instruction *ToMove = I;
1956 bool Done = false;
1957
1958 if (I != Preheader->begin()) {
1959 // Skip debug info intrinsics.
1960 do {
1961 --I;
1962 } while (isa<DbgInfoIntrinsic>(I) && I != Preheader->begin());
1963
1964 if (isa<DbgInfoIntrinsic>(I) && I == Preheader->begin())
1965 Done = true;
1966 } else {
1967 Done = true;
1968 }
1969
1970 ToMove->moveBefore(InsertPt);
1971 if (Done) break;
1972 InsertPt = ToMove;
1973 }
1974}
1975
1976//===----------------------------------------------------------------------===//
1977// IndVarSimplify driver. Manage several subpasses of IV simplification.
1978//===----------------------------------------------------------------------===//
1979
Dan Gohmanc2390b12009-02-12 22:19:27 +00001980bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
Dan Gohmana5283822010-06-18 01:35:11 +00001981 // If LoopSimplify form is not available, stay out of trouble. Some notes:
1982 // - LSR currently only supports LoopSimplify-form loops. Indvars'
1983 // canonicalization can be a pessimization without LSR to "clean up"
1984 // afterwards.
1985 // - We depend on having a preheader; in particular,
1986 // Loop::getCanonicalInductionVariable only supports loops with preheaders,
1987 // and we're in trouble if we can't find the induction variable even when
1988 // we've manually inserted one.
1989 if (!L->isLoopSimplifyForm())
1990 return false;
1991
Andrew Trick2fabd462011-06-21 03:22:38 +00001992 if (!DisableIVRewrite)
1993 IU = &getAnalysis<IVUsers>();
Devang Patel5ee99972007-03-07 06:39:01 +00001994 LI = &getAnalysis<LoopInfo>();
1995 SE = &getAnalysis<ScalarEvolution>();
Dan Gohmande53dc02009-06-27 05:16:57 +00001996 DT = &getAnalysis<DominatorTree>();
Andrew Trick37da4082011-05-04 02:10:13 +00001997 TD = getAnalysisIfAvailable<TargetData>();
1998
Andrew Trickb12a7542011-03-17 23:51:11 +00001999 DeadInsts.clear();
Devang Patel5ee99972007-03-07 06:39:01 +00002000 Changed = false;
Dan Gohman60f8a632009-02-17 20:49:49 +00002001
Dan Gohman2d1be872009-04-16 03:18:22 +00002002 // If there are any floating-point recurrences, attempt to
Dan Gohman60f8a632009-02-17 20:49:49 +00002003 // transform them to use integer recurrences.
2004 RewriteNonIntegerIVs(L);
2005
Dan Gohman0bba49c2009-07-07 17:06:11 +00002006 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
Chris Lattner9caed542007-03-04 01:00:28 +00002007
Dan Gohman667d7872009-06-26 22:53:46 +00002008 // Create a rewriter object which we'll use to transform the code with.
Andrew Trick5e7645b2011-06-28 05:07:32 +00002009 SCEVExpander Rewriter(*SE, "indvars");
Andrew Trick156d4602011-06-27 23:17:44 +00002010
2011 // Eliminate redundant IV users.
Andrew Trick15832f62011-06-28 02:49:20 +00002012 //
2013 // Simplification works best when run before other consumers of SCEV. We
2014 // attempt to avoid evaluating SCEVs for sign/zero extend operations until
2015 // other expressions involving loop IVs have been evaluated. This helps SCEV
Andrew Trick99a92f62011-06-28 16:45:04 +00002016 // set no-wrap flags before normalizing sign/zero extension.
Andrew Trick156d4602011-06-27 23:17:44 +00002017 if (DisableIVRewrite) {
Andrew Trick37da4082011-05-04 02:10:13 +00002018 Rewriter.disableCanonicalMode();
Andrew Trick156d4602011-06-27 23:17:44 +00002019 SimplifyIVUsersNoRewrite(L, Rewriter);
2020 }
Andrew Trick37da4082011-05-04 02:10:13 +00002021
Chris Lattner40bf8b42004-04-02 20:24:31 +00002022 // Check to see if this loop has a computable loop-invariant execution count.
2023 // If so, this means that we can compute the final value of any expressions
2024 // that are recurrent in the loop, and substitute the exit values from the
2025 // loop into any instructions outside of the loop that use the final values of
2026 // the current expressions.
Chris Lattner3dec1f22002-05-10 15:38:35 +00002027 //
Dan Gohman46bdfb02009-02-24 18:55:53 +00002028 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount))
Dan Gohman454d26d2010-02-22 04:11:59 +00002029 RewriteLoopExitValues(L, Rewriter);
Chris Lattner6148c022001-12-03 17:28:42 +00002030
Andrew Trickf85092c2011-05-20 18:25:42 +00002031 // Eliminate redundant IV users.
Andrew Trick156d4602011-06-27 23:17:44 +00002032 if (!DisableIVRewrite)
Andrew Trick2fabd462011-06-21 03:22:38 +00002033 SimplifyIVUsers(Rewriter);
Dan Gohmana590b792010-04-13 01:46:36 +00002034
Andrew Trick6f684b02011-07-16 01:06:48 +00002035 // Eliminate redundant IV cycles.
Andrew Trick037d1c02011-07-06 20:50:43 +00002036 if (DisableIVRewrite)
2037 SimplifyCongruentIVs(L);
2038
Dan Gohman81db61a2009-05-12 02:17:14 +00002039 // Compute the type of the largest recurrence expression, and decide whether
2040 // a canonical induction variable should be inserted.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002041 Type *LargestType = 0;
Dan Gohman81db61a2009-05-12 02:17:14 +00002042 bool NeedCannIV = false;
Andrew Trickfc933c02011-07-18 20:32:31 +00002043 bool ReuseIVForExit = DisableIVRewrite && !ForceLFTR;
Andrew Trick03d3d3b2011-05-25 04:42:22 +00002044 bool ExpandBECount = canExpandBackedgeTakenCount(L, SE);
Andrew Trickfc933c02011-07-18 20:32:31 +00002045 if (ExpandBECount && !ReuseIVForExit) {
Dan Gohman81db61a2009-05-12 02:17:14 +00002046 // If we have a known trip count and a single exit block, we'll be
2047 // rewriting the loop exit test condition below, which requires a
2048 // canonical induction variable.
Andrew Trick4dfdf242011-05-03 22:24:10 +00002049 NeedCannIV = true;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002050 Type *Ty = BackedgeTakenCount->getType();
Andrew Trick03d3d3b2011-05-25 04:42:22 +00002051 if (DisableIVRewrite) {
2052 // In this mode, SimplifyIVUsers may have already widened the IV used by
2053 // the backedge test and inserted a Trunc on the compare's operand. Get
2054 // the wider type to avoid creating a redundant narrow IV only used by the
2055 // loop test.
2056 LargestType = getBackedgeIVType(L);
2057 }
Andrew Trick4dfdf242011-05-03 22:24:10 +00002058 if (!LargestType ||
2059 SE->getTypeSizeInBits(Ty) >
2060 SE->getTypeSizeInBits(LargestType))
2061 LargestType = SE->getEffectiveSCEVType(Ty);
Chris Lattnerf50af082004-04-17 18:08:33 +00002062 }
Andrew Trick37da4082011-05-04 02:10:13 +00002063 if (!DisableIVRewrite) {
2064 for (IVUsers::const_iterator I = IU->begin(), E = IU->end(); I != E; ++I) {
2065 NeedCannIV = true;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002066 Type *Ty =
Andrew Trick37da4082011-05-04 02:10:13 +00002067 SE->getEffectiveSCEVType(I->getOperandValToReplace()->getType());
2068 if (!LargestType ||
2069 SE->getTypeSizeInBits(Ty) >
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002070 SE->getTypeSizeInBits(LargestType))
Andrew Trick37da4082011-05-04 02:10:13 +00002071 LargestType = Ty;
2072 }
Chris Lattner6148c022001-12-03 17:28:42 +00002073 }
2074
Dan Gohmanf451cb82010-02-10 16:03:48 +00002075 // Now that we know the largest of the induction variable expressions
Dan Gohman81db61a2009-05-12 02:17:14 +00002076 // in this loop, insert a canonical induction variable of the largest size.
Dan Gohman43ef3fb2010-07-20 17:18:52 +00002077 PHINode *IndVar = 0;
Dan Gohman81db61a2009-05-12 02:17:14 +00002078 if (NeedCannIV) {
Dan Gohman85669632010-02-25 06:57:05 +00002079 // Check to see if the loop already has any canonical-looking induction
2080 // variables. If any are present and wider than the planned canonical
2081 // induction variable, temporarily remove them, so that the Rewriter
2082 // doesn't attempt to reuse them.
2083 SmallVector<PHINode *, 2> OldCannIVs;
2084 while (PHINode *OldCannIV = L->getCanonicalInductionVariable()) {
Dan Gohman4d8414f2009-06-13 16:25:49 +00002085 if (SE->getTypeSizeInBits(OldCannIV->getType()) >
2086 SE->getTypeSizeInBits(LargestType))
2087 OldCannIV->removeFromParent();
2088 else
Dan Gohman85669632010-02-25 06:57:05 +00002089 break;
2090 OldCannIVs.push_back(OldCannIV);
Dan Gohman4d8414f2009-06-13 16:25:49 +00002091 }
2092
Dan Gohman667d7872009-06-26 22:53:46 +00002093 IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L, LargestType);
Dan Gohman4d8414f2009-06-13 16:25:49 +00002094
Dan Gohmanc2390b12009-02-12 22:19:27 +00002095 ++NumInserted;
2096 Changed = true;
David Greenef67ef312010-01-05 01:27:06 +00002097 DEBUG(dbgs() << "INDVARS: New CanIV: " << *IndVar << '\n');
Dan Gohman4d8414f2009-06-13 16:25:49 +00002098
2099 // Now that the official induction variable is established, reinsert
Dan Gohman85669632010-02-25 06:57:05 +00002100 // any old canonical-looking variables after it so that the IR remains
2101 // consistent. They will be deleted as part of the dead-PHI deletion at
Dan Gohman4d8414f2009-06-13 16:25:49 +00002102 // the end of the pass.
Dan Gohman85669632010-02-25 06:57:05 +00002103 while (!OldCannIVs.empty()) {
2104 PHINode *OldCannIV = OldCannIVs.pop_back_val();
2105 OldCannIV->insertBefore(L->getHeader()->getFirstNonPHI());
2106 }
Dan Gohmand19534a2007-06-15 14:38:12 +00002107 }
Andrew Trickfc933c02011-07-18 20:32:31 +00002108 else if (ExpandBECount && ReuseIVForExit && needsLFTR(L, DT)) {
2109 IndVar = FindLoopCounter(L, BackedgeTakenCount, SE, DT, TD);
2110 }
Dan Gohmanc2390b12009-02-12 22:19:27 +00002111 // If we have a trip count expression, rewrite the loop's exit condition
2112 // using it. We can currently only handle loops with a single exit.
Andrew Trickfc933c02011-07-18 20:32:31 +00002113 Value *NewICmp = 0;
2114 if (ExpandBECount && IndVar) {
Andrew Trick56147692011-07-16 01:18:53 +00002115 // Check preconditions for proper SCEVExpander operation. SCEV does not
2116 // express SCEVExpander's dependencies, such as LoopSimplify. Instead any
2117 // pass that uses the SCEVExpander must do it. This does not work well for
2118 // loop passes because SCEVExpander makes assumptions about all loops, while
2119 // LoopPassManager only forces the current loop to be simplified.
2120 //
2121 // FIXME: SCEV expansion has no way to bail out, so the caller must
2122 // explicitly check any assumptions made by SCEV. Brittle.
2123 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(BackedgeTakenCount);
2124 if (!AR || AR->getLoop()->getLoopPreheader())
2125 NewICmp =
2126 LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar, Rewriter);
Chris Lattnerfcb81f52004-04-22 14:59:40 +00002127 }
Andrew Trickb12a7542011-03-17 23:51:11 +00002128 // Rewrite IV-derived expressions.
Andrew Trick37da4082011-05-04 02:10:13 +00002129 if (!DisableIVRewrite)
2130 RewriteIVExpressions(L, Rewriter);
Dan Gohmanc2390b12009-02-12 22:19:27 +00002131
Andrew Trickb12a7542011-03-17 23:51:11 +00002132 // Clear the rewriter cache, because values that are in the rewriter's cache
2133 // can be deleted in the loop below, causing the AssertingVH in the cache to
2134 // trigger.
2135 Rewriter.clear();
2136
2137 // Now that we're done iterating through lists, clean up any instructions
2138 // which are now dead.
2139 while (!DeadInsts.empty())
2140 if (Instruction *Inst =
2141 dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val()))
2142 RecursivelyDeleteTriviallyDeadInstructions(Inst);
2143
Dan Gohman667d7872009-06-26 22:53:46 +00002144 // The Rewriter may not be used from this point on.
Torok Edwin3d431382009-05-24 20:08:21 +00002145
Dan Gohman81db61a2009-05-12 02:17:14 +00002146 // Loop-invariant instructions in the preheader that aren't used in the
2147 // loop may be sunk below the loop to reduce register pressure.
Dan Gohman667d7872009-06-26 22:53:46 +00002148 SinkUnusedInvariants(L);
Dan Gohman81db61a2009-05-12 02:17:14 +00002149
2150 // For completeness, inform IVUsers of the IV use in the newly-created
2151 // loop exit test instruction.
Andrew Trickfc933c02011-07-18 20:32:31 +00002152 if (IU && NewICmp) {
2153 ICmpInst *NewICmpInst = dyn_cast<ICmpInst>(NewICmp);
2154 if (NewICmpInst)
2155 IU->AddUsersIfInteresting(cast<Instruction>(NewICmpInst->getOperand(0)));
2156 }
Dan Gohman81db61a2009-05-12 02:17:14 +00002157 // Clean up dead instructions.
Dan Gohman9fff2182010-01-05 16:31:45 +00002158 Changed |= DeleteDeadPHIs(L->getHeader());
Dan Gohman81db61a2009-05-12 02:17:14 +00002159 // Check a post-condition.
Andrew Trickf6a0dba2011-07-18 18:44:20 +00002160 assert(L->isLCSSAForm(*DT) &&
2161 "Indvars did not leave the loop in lcssa form!");
2162
2163 // Verify that LFTR, and any other change have not interfered with SCEV's
2164 // ability to compute trip count.
2165#ifndef NDEBUG
2166 if (DisableIVRewrite && !isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
2167 SE->forgetLoop(L);
2168 const SCEV *NewBECount = SE->getBackedgeTakenCount(L);
2169 if (SE->getTypeSizeInBits(BackedgeTakenCount->getType()) <
2170 SE->getTypeSizeInBits(NewBECount->getType()))
2171 NewBECount = SE->getTruncateOrNoop(NewBECount,
2172 BackedgeTakenCount->getType());
2173 else
2174 BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount,
2175 NewBECount->getType());
2176 assert(BackedgeTakenCount == NewBECount && "indvars must preserve SCEV");
2177 }
2178#endif
2179
Devang Patel5ee99972007-03-07 06:39:01 +00002180 return Changed;
Chris Lattner6148c022001-12-03 17:28:42 +00002181}