blob: e40d72979ee8dfc31cbe67e19beb8e6d48e41c5b [file] [log] [blame]
Chris Lattner476e6df2001-12-03 17:28:42 +00001//===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-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 Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner476e6df2001-12-03 17:28:42 +00009//
Chris Lattnere61b67d2004-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 Spencer5495fe82006-08-18 09:01:07 +000014// This transformation makes the following changes to each loop with an
Chris Lattnere61b67d2004-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 Gohman9b4c85f2009-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 Lattnere61b67d2004-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 Gohman67587ce2009-05-19 20:38:47 +000037// desired loop transformations have been performed.
Chris Lattner476e6df2001-12-03 17:28:42 +000038//
39//===----------------------------------------------------------------------===//
40
Chris Lattner79a42ac2006-12-19 21:40:18 +000041#define DEBUG_TYPE "indvars"
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +000042#include "llvm/Transforms/Scalar.h"
Chris Lattnere61b67d2004-04-02 20:24:31 +000043#include "llvm/BasicBlock.h"
Chris Lattner0cec5cb2004-04-15 15:21:43 +000044#include "llvm/Constants.h"
Chris Lattner6449dce2003-12-22 05:02:01 +000045#include "llvm/Instructions.h"
Devang Patel45c15052010-03-15 22:23:03 +000046#include "llvm/IntrinsicInst.h"
Owen Andersonb5618da2009-07-03 00:17:18 +000047#include "llvm/LLVMContext.h"
Chris Lattnere61b67d2004-04-02 20:24:31 +000048#include "llvm/Type.h"
Dan Gohmand76d71a2009-05-12 02:17:14 +000049#include "llvm/Analysis/Dominators.h"
50#include "llvm/Analysis/IVUsers.h"
Nate Begeman2bca4d92005-07-30 00:12:19 +000051#include "llvm/Analysis/ScalarEvolutionExpander.h"
John Criswellb22e9b42003-12-18 17:19:19 +000052#include "llvm/Analysis/LoopInfo.h"
Devang Patel2ac57e12007-03-07 06:39:01 +000053#include "llvm/Analysis/LoopPass.h"
Chris Lattner83d485b2002-02-12 22:39:50 +000054#include "llvm/Support/CFG.h"
Andrew Trick56b315a2011-06-28 03:01:46 +000055#include "llvm/Support/CommandLine.h"
Chris Lattner08165592007-01-07 01:14:12 +000056#include "llvm/Support/Debug.h"
Chris Lattnerb25de3f2009-08-23 04:37:46 +000057#include "llvm/Support/raw_ostream.h"
John Criswellb22e9b42003-12-18 17:19:19 +000058#include "llvm/Transforms/Utils/Local.h"
Dan Gohmand76d71a2009-05-12 02:17:14 +000059#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Andrew Trick1abe2962011-05-04 02:10:13 +000060#include "llvm/Target/TargetData.h"
Andrew Trick32390552011-07-06 20:50:43 +000061#include "llvm/ADT/DenseMap.h"
Reid Spencer7a9c62b2007-01-12 07:05:14 +000062#include "llvm/ADT/SmallVector.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000063#include "llvm/ADT/Statistic.h"
Dan Gohmand76d71a2009-05-12 02:17:14 +000064#include "llvm/ADT/STLExtras.h"
John Criswellb22e9b42003-12-18 17:19:19 +000065using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000066
Andrew Trick69d44522011-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");
Andrew Trick6d45a012011-08-06 07:00:37 +000073STATISTIC(NumElimOperand, "Number of IV operands folded into a use");
Andrew Trick69d44522011-06-21 03:22:38 +000074STATISTIC(NumElimExt , "Number of IV sign/zero extends eliminated");
75STATISTIC(NumElimRem , "Number of IV remainder operations eliminated");
76STATISTIC(NumElimCmp , "Number of IV comparisons eliminated");
Andrew Trick32390552011-07-06 20:50:43 +000077STATISTIC(NumElimIV , "Number of congruent IVs eliminated");
Chris Lattnerd3678bc2003-12-22 03:58:44 +000078
Andrew Trick56b315a2011-06-28 03:01:46 +000079static cl::opt<bool> DisableIVRewrite(
80 "disable-iv-rewrite", cl::Hidden,
81 cl::desc("Disable canonical induction variable rewriting"));
Andrew Trick1abe2962011-05-04 02:10:13 +000082
Andrew Trick7da24172011-07-18 20:32:31 +000083// Temporary flag for use with -disable-iv-rewrite to force a canonical IV for
84// LFTR purposes.
85static cl::opt<bool> ForceLFTR(
86 "force-lftr", cl::Hidden,
87 cl::desc("Enable forced linear function test replacement"));
88
Chris Lattner79a42ac2006-12-19 21:40:18 +000089namespace {
Chris Lattner2dd09db2009-09-02 06:11:42 +000090 class IndVarSimplify : public LoopPass {
Dan Gohmand76d71a2009-05-12 02:17:14 +000091 IVUsers *IU;
Chris Lattnere61b67d2004-04-02 20:24:31 +000092 LoopInfo *LI;
93 ScalarEvolution *SE;
Dan Gohmanfe174b62009-06-27 05:16:57 +000094 DominatorTree *DT;
Andrew Trick1abe2962011-05-04 02:10:13 +000095 TargetData *TD;
Andrew Trick69d44522011-06-21 03:22:38 +000096
Andrew Trick87716c92011-03-17 23:51:11 +000097 SmallVector<WeakVH, 16> DeadInsts;
Chris Lattner7e755e42003-12-23 07:47:09 +000098 bool Changed;
Chris Lattnerd3678bc2003-12-22 03:58:44 +000099 public:
Devang Patel09f162c2007-05-01 21:15:47 +0000100
Dan Gohmanb0f8e992009-07-15 01:26:32 +0000101 static char ID; // Pass identification, replacement for typeid
Andrew Trick69d44522011-06-21 03:22:38 +0000102 IndVarSimplify() : LoopPass(ID), IU(0), LI(0), SE(0), DT(0), TD(0),
Andrew Trick8a3c39c2011-06-28 02:49:20 +0000103 Changed(false) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000104 initializeIndVarSimplifyPass(*PassRegistry::getPassRegistry());
105 }
Devang Patel09f162c2007-05-01 21:15:47 +0000106
Dan Gohmanb0f8e992009-07-15 01:26:32 +0000107 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
Dan Gohman43300342009-02-17 20:49:49 +0000108
Dan Gohmanb0f8e992009-07-15 01:26:32 +0000109 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
110 AU.addRequired<DominatorTree>();
111 AU.addRequired<LoopInfo>();
112 AU.addRequired<ScalarEvolution>();
113 AU.addRequiredID(LoopSimplifyID);
114 AU.addRequiredID(LCSSAID);
Andrew Trick56b315a2011-06-28 03:01:46 +0000115 if (!DisableIVRewrite)
116 AU.addRequired<IVUsers>();
Dan Gohmanb0f8e992009-07-15 01:26:32 +0000117 AU.addPreserved<ScalarEvolution>();
118 AU.addPreservedID(LoopSimplifyID);
119 AU.addPreservedID(LCSSAID);
Andrew Trick69d44522011-06-21 03:22:38 +0000120 if (!DisableIVRewrite)
121 AU.addPreserved<IVUsers>();
Dan Gohmanb0f8e992009-07-15 01:26:32 +0000122 AU.setPreservesCFG();
123 }
Chris Lattner7e755e42003-12-23 07:47:09 +0000124
Chris Lattnere61b67d2004-04-02 20:24:31 +0000125 private:
Andrew Trick32390552011-07-06 20:50:43 +0000126 virtual void releaseMemory() {
Andrew Trick32390552011-07-06 20:50:43 +0000127 DeadInsts.clear();
128 }
129
Andrew Trick87716c92011-03-17 23:51:11 +0000130 bool isValidRewrite(Value *FromVal, Value *ToVal);
Devang Patel2ac57e12007-03-07 06:39:01 +0000131
Andrew Trickcdc22972011-07-12 00:08:50 +0000132 void HandleFloatingPointIV(Loop *L, PHINode *PH);
133 void RewriteNonIntegerIVs(Loop *L);
134
135 void RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter);
136
Andrew Trickf44aadf2011-05-20 18:25:42 +0000137 void SimplifyIVUsers(SCEVExpander &Rewriter);
Andrew Trick69d44522011-06-21 03:22:38 +0000138 void SimplifyIVUsersNoRewrite(Loop *L, SCEVExpander &Rewriter);
139
140 bool EliminateIVUser(Instruction *UseInst, Instruction *IVOperand);
Andrew Trick81683ed2011-05-12 00:04:28 +0000141 void EliminateIVComparison(ICmpInst *ICmp, Value *IVOperand);
142 void EliminateIVRemainder(BinaryOperator *Rem,
143 Value *IVOperand,
Andrew Trickfc4ccb22011-06-21 15:43:52 +0000144 bool IsSigned);
Chris Lattnere61b67d2004-04-02 20:24:31 +0000145
Andrew Trick6d45a012011-08-06 07:00:37 +0000146 bool FoldIVUser(Instruction *UseInst, Instruction *IVOperand);
147
Andrew Trick32390552011-07-06 20:50:43 +0000148 void SimplifyCongruentIVs(Loop *L);
149
Dan Gohman8c16b382010-02-22 04:11:59 +0000150 void RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter);
Devang Patel92b032f2008-09-09 21:41:07 +0000151
Andrew Trick7da24172011-07-18 20:32:31 +0000152 Value *LinearFunctionTestReplace(Loop *L, const SCEV *BackedgeTakenCount,
153 PHINode *IndVar, SCEVExpander &Rewriter);
Dan Gohmand76d71a2009-05-12 02:17:14 +0000154
Andrew Trickcdc22972011-07-12 00:08:50 +0000155 void SinkUnusedInvariants(Loop *L);
Chris Lattnerd3678bc2003-12-22 03:58:44 +0000156 };
Chris Lattner4184bcc2002-09-10 05:24:05 +0000157}
Chris Lattner91daaab2001-12-04 04:32:29 +0000158
Dan Gohmand78c4002008-05-13 00:00:25 +0000159char IndVarSimplify::ID = 0;
Owen Anderson8ac477f2010-10-12 19:48:12 +0000160INITIALIZE_PASS_BEGIN(IndVarSimplify, "indvars",
Andrew Trick1abe2962011-05-04 02:10:13 +0000161 "Induction Variable Simplification", false, false)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000162INITIALIZE_PASS_DEPENDENCY(DominatorTree)
163INITIALIZE_PASS_DEPENDENCY(LoopInfo)
164INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
165INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
166INITIALIZE_PASS_DEPENDENCY(LCSSA)
167INITIALIZE_PASS_DEPENDENCY(IVUsers)
168INITIALIZE_PASS_END(IndVarSimplify, "indvars",
Andrew Trick1abe2962011-05-04 02:10:13 +0000169 "Induction Variable Simplification", false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +0000170
Daniel Dunbar7f39e2d2008-10-22 23:32:42 +0000171Pass *llvm::createIndVarSimplifyPass() {
Chris Lattnerd3678bc2003-12-22 03:58:44 +0000172 return new IndVarSimplify();
Chris Lattner91daaab2001-12-04 04:32:29 +0000173}
174
Andrew Trick87716c92011-03-17 23:51:11 +0000175/// isValidRewrite - Return true if the SCEV expansion generated by the
176/// rewriter can replace the original value. SCEV guarantees that it
177/// produces the same value, but the way it is produced may be illegal IR.
178/// Ideally, this function will only be called for verification.
179bool IndVarSimplify::isValidRewrite(Value *FromVal, Value *ToVal) {
180 // If an SCEV expression subsumed multiple pointers, its expansion could
181 // reassociate the GEP changing the base pointer. This is illegal because the
182 // final address produced by a GEP chain must be inbounds relative to its
183 // underlying object. Otherwise basic alias analysis, among other things,
184 // could fail in a dangerous way. Ultimately, SCEV will be improved to avoid
185 // producing an expression involving multiple pointers. Until then, we must
186 // bail out here.
187 //
188 // Retrieve the pointer operand of the GEP. Don't use GetUnderlyingObject
189 // because it understands lcssa phis while SCEV does not.
190 Value *FromPtr = FromVal;
191 Value *ToPtr = ToVal;
192 if (GEPOperator *GEP = dyn_cast<GEPOperator>(FromVal)) {
193 FromPtr = GEP->getPointerOperand();
194 }
195 if (GEPOperator *GEP = dyn_cast<GEPOperator>(ToVal)) {
196 ToPtr = GEP->getPointerOperand();
197 }
198 if (FromPtr != FromVal || ToPtr != ToVal) {
199 // Quickly check the common case
200 if (FromPtr == ToPtr)
201 return true;
202
203 // SCEV may have rewritten an expression that produces the GEP's pointer
204 // operand. That's ok as long as the pointer operand has the same base
205 // pointer. Unlike GetUnderlyingObject(), getPointerBase() will find the
206 // base of a recurrence. This handles the case in which SCEV expansion
207 // converts a pointer type recurrence into a nonrecurrent pointer base
208 // indexed by an integer recurrence.
209 const SCEV *FromBase = SE->getPointerBase(SE->getSCEV(FromPtr));
210 const SCEV *ToBase = SE->getPointerBase(SE->getSCEV(ToPtr));
211 if (FromBase == ToBase)
212 return true;
213
214 DEBUG(dbgs() << "INDVARS: GEP rewrite bail out "
215 << *FromBase << " != " << *ToBase << "\n");
216
217 return false;
218 }
219 return true;
220}
221
Andrew Trick638b3552011-07-20 05:32:06 +0000222/// Determine the insertion point for this user. By default, insert immediately
223/// before the user. SCEVExpander or LICM will hoist loop invariants out of the
224/// loop. For PHI nodes, there may be multiple uses, so compute the nearest
225/// common dominator for the incoming blocks.
226static Instruction *getInsertPointForUses(Instruction *User, Value *Def,
227 DominatorTree *DT) {
228 PHINode *PHI = dyn_cast<PHINode>(User);
229 if (!PHI)
230 return User;
231
232 Instruction *InsertPt = 0;
233 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i) {
234 if (PHI->getIncomingValue(i) != Def)
235 continue;
236
237 BasicBlock *InsertBB = PHI->getIncomingBlock(i);
238 if (!InsertPt) {
239 InsertPt = InsertBB->getTerminator();
240 continue;
241 }
242 InsertBB = DT->findNearestCommonDominator(InsertPt->getParent(), InsertBB);
243 InsertPt = InsertBB->getTerminator();
244 }
245 assert(InsertPt && "Missing phi operand");
Jay Foad50bfbab2011-07-20 08:15:21 +0000246 assert((!isa<Instruction>(Def) ||
247 DT->dominates(cast<Instruction>(Def), InsertPt)) &&
Andrew Trick638b3552011-07-20 05:32:06 +0000248 "def does not dominate all uses");
249 return InsertPt;
250}
251
Andrew Trickcdc22972011-07-12 00:08:50 +0000252//===----------------------------------------------------------------------===//
253// RewriteNonIntegerIVs and helpers. Prefer integer IVs.
254//===----------------------------------------------------------------------===//
Andrew Trick38c4e342011-05-03 22:24:10 +0000255
Andrew Trickcdc22972011-07-12 00:08:50 +0000256/// ConvertToSInt - Convert APF to an integer, if possible.
257static bool ConvertToSInt(const APFloat &APF, int64_t &IntVal) {
258 bool isExact = false;
259 if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
Andrew Trick38c4e342011-05-03 22:24:10 +0000260 return false;
Andrew Trickcdc22972011-07-12 00:08:50 +0000261 // See if we can convert this to an int64_t
262 uint64_t UIntVal;
263 if (APF.convertToInteger(&UIntVal, 64, true, APFloat::rmTowardZero,
264 &isExact) != APFloat::opOK || !isExact)
Andrew Trick38c4e342011-05-03 22:24:10 +0000265 return false;
Andrew Trickcdc22972011-07-12 00:08:50 +0000266 IntVal = UIntVal;
Andrew Trick38c4e342011-05-03 22:24:10 +0000267 return true;
268}
269
Andrew Trickcdc22972011-07-12 00:08:50 +0000270/// HandleFloatingPointIV - If the loop has floating induction variable
271/// then insert corresponding integer induction variable if possible.
272/// For example,
273/// for(double i = 0; i < 10000; ++i)
274/// bar(i)
275/// is converted into
276/// for(int i = 0; i < 10000; ++i)
277/// bar((double)i);
Andrew Trickeb3c36e2011-05-25 04:42:22 +0000278///
Andrew Trickcdc22972011-07-12 00:08:50 +0000279void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PN) {
280 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
281 unsigned BackEdge = IncomingEdge^1;
Andrew Trickeb3c36e2011-05-25 04:42:22 +0000282
Andrew Trickcdc22972011-07-12 00:08:50 +0000283 // Check incoming value.
284 ConstantFP *InitValueVal =
285 dyn_cast<ConstantFP>(PN->getIncomingValue(IncomingEdge));
Andrew Trickeb3c36e2011-05-25 04:42:22 +0000286
Andrew Trickcdc22972011-07-12 00:08:50 +0000287 int64_t InitValue;
288 if (!InitValueVal || !ConvertToSInt(InitValueVal->getValueAPF(), InitValue))
289 return;
Andrew Trickeb3c36e2011-05-25 04:42:22 +0000290
Andrew Trickcdc22972011-07-12 00:08:50 +0000291 // Check IV increment. Reject this PN if increment operation is not
292 // an add or increment value can not be represented by an integer.
293 BinaryOperator *Incr =
294 dyn_cast<BinaryOperator>(PN->getIncomingValue(BackEdge));
295 if (Incr == 0 || Incr->getOpcode() != Instruction::FAdd) return;
Andrew Trickeb3c36e2011-05-25 04:42:22 +0000296
Andrew Trickcdc22972011-07-12 00:08:50 +0000297 // If this is not an add of the PHI with a constantfp, or if the constant fp
298 // is not an integer, bail out.
299 ConstantFP *IncValueVal = dyn_cast<ConstantFP>(Incr->getOperand(1));
300 int64_t IncValue;
301 if (IncValueVal == 0 || Incr->getOperand(0) != PN ||
302 !ConvertToSInt(IncValueVal->getValueAPF(), IncValue))
303 return;
304
305 // Check Incr uses. One user is PN and the other user is an exit condition
306 // used by the conditional terminator.
307 Value::use_iterator IncrUse = Incr->use_begin();
308 Instruction *U1 = cast<Instruction>(*IncrUse++);
309 if (IncrUse == Incr->use_end()) return;
310 Instruction *U2 = cast<Instruction>(*IncrUse++);
311 if (IncrUse != Incr->use_end()) return;
312
313 // Find exit condition, which is an fcmp. If it doesn't exist, or if it isn't
314 // only used by a branch, we can't transform it.
315 FCmpInst *Compare = dyn_cast<FCmpInst>(U1);
316 if (!Compare)
317 Compare = dyn_cast<FCmpInst>(U2);
318 if (Compare == 0 || !Compare->hasOneUse() ||
319 !isa<BranchInst>(Compare->use_back()))
320 return;
321
322 BranchInst *TheBr = cast<BranchInst>(Compare->use_back());
323
324 // We need to verify that the branch actually controls the iteration count
325 // of the loop. If not, the new IV can overflow and no one will notice.
326 // The branch block must be in the loop and one of the successors must be out
327 // of the loop.
328 assert(TheBr->isConditional() && "Can't use fcmp if not conditional");
329 if (!L->contains(TheBr->getParent()) ||
330 (L->contains(TheBr->getSuccessor(0)) &&
331 L->contains(TheBr->getSuccessor(1))))
332 return;
333
334
335 // If it isn't a comparison with an integer-as-fp (the exit value), we can't
336 // transform it.
337 ConstantFP *ExitValueVal = dyn_cast<ConstantFP>(Compare->getOperand(1));
338 int64_t ExitValue;
339 if (ExitValueVal == 0 ||
340 !ConvertToSInt(ExitValueVal->getValueAPF(), ExitValue))
341 return;
342
343 // Find new predicate for integer comparison.
344 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
345 switch (Compare->getPredicate()) {
346 default: return; // Unknown comparison.
347 case CmpInst::FCMP_OEQ:
348 case CmpInst::FCMP_UEQ: NewPred = CmpInst::ICMP_EQ; break;
349 case CmpInst::FCMP_ONE:
350 case CmpInst::FCMP_UNE: NewPred = CmpInst::ICMP_NE; break;
351 case CmpInst::FCMP_OGT:
352 case CmpInst::FCMP_UGT: NewPred = CmpInst::ICMP_SGT; break;
353 case CmpInst::FCMP_OGE:
354 case CmpInst::FCMP_UGE: NewPred = CmpInst::ICMP_SGE; break;
355 case CmpInst::FCMP_OLT:
356 case CmpInst::FCMP_ULT: NewPred = CmpInst::ICMP_SLT; break;
357 case CmpInst::FCMP_OLE:
358 case CmpInst::FCMP_ULE: NewPred = CmpInst::ICMP_SLE; break;
Andrew Trickeb3c36e2011-05-25 04:42:22 +0000359 }
Andrew Trickeb3c36e2011-05-25 04:42:22 +0000360
Andrew Trickcdc22972011-07-12 00:08:50 +0000361 // We convert the floating point induction variable to a signed i32 value if
362 // we can. This is only safe if the comparison will not overflow in a way
363 // that won't be trapped by the integer equivalent operations. Check for this
364 // now.
365 // TODO: We could use i64 if it is native and the range requires it.
Dan Gohman4a645b82010-04-12 21:13:43 +0000366
Andrew Trickcdc22972011-07-12 00:08:50 +0000367 // The start/stride/exit values must all fit in signed i32.
368 if (!isInt<32>(InitValue) || !isInt<32>(IncValue) || !isInt<32>(ExitValue))
369 return;
370
371 // If not actually striding (add x, 0.0), avoid touching the code.
372 if (IncValue == 0)
373 return;
374
375 // Positive and negative strides have different safety conditions.
376 if (IncValue > 0) {
377 // If we have a positive stride, we require the init to be less than the
378 // exit value and an equality or less than comparison.
379 if (InitValue >= ExitValue ||
380 NewPred == CmpInst::ICMP_SGT || NewPred == CmpInst::ICMP_SGE)
381 return;
382
383 uint32_t Range = uint32_t(ExitValue-InitValue);
384 if (NewPred == CmpInst::ICMP_SLE) {
385 // Normalize SLE -> SLT, check for infinite loop.
386 if (++Range == 0) return; // Range overflows.
Dan Gohmaneb6be652009-02-12 22:19:27 +0000387 }
Chris Lattner0cec5cb2004-04-15 15:21:43 +0000388
Andrew Trickcdc22972011-07-12 00:08:50 +0000389 unsigned Leftover = Range % uint32_t(IncValue);
390
391 // If this is an equality comparison, we require that the strided value
392 // exactly land on the exit value, otherwise the IV condition will wrap
393 // around and do things the fp IV wouldn't.
394 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
395 Leftover != 0)
396 return;
397
398 // If the stride would wrap around the i32 before exiting, we can't
399 // transform the IV.
400 if (Leftover != 0 && int32_t(ExitValue+IncValue) < ExitValue)
401 return;
402
Chris Lattnerd7a559e2004-04-15 20:26:22 +0000403 } else {
Andrew Trickcdc22972011-07-12 00:08:50 +0000404 // If we have a negative stride, we require the init to be greater than the
405 // exit value and an equality or greater than comparison.
406 if (InitValue >= ExitValue ||
407 NewPred == CmpInst::ICMP_SLT || NewPred == CmpInst::ICMP_SLE)
408 return;
409
410 uint32_t Range = uint32_t(InitValue-ExitValue);
411 if (NewPred == CmpInst::ICMP_SGE) {
412 // Normalize SGE -> SGT, check for infinite loop.
413 if (++Range == 0) return; // Range overflows.
414 }
415
416 unsigned Leftover = Range % uint32_t(-IncValue);
417
418 // If this is an equality comparison, we require that the strided value
419 // exactly land on the exit value, otherwise the IV condition will wrap
420 // around and do things the fp IV wouldn't.
421 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
422 Leftover != 0)
423 return;
424
425 // If the stride would wrap around the i32 before exiting, we can't
426 // transform the IV.
427 if (Leftover != 0 && int32_t(ExitValue+IncValue) > ExitValue)
428 return;
Chris Lattnerd7a559e2004-04-15 20:26:22 +0000429 }
Chris Lattner0cec5cb2004-04-15 15:21:43 +0000430
Chris Lattner229907c2011-07-18 04:54:35 +0000431 IntegerType *Int32Ty = Type::getInt32Ty(PN->getContext());
Chris Lattnere61b67d2004-04-02 20:24:31 +0000432
Andrew Trickcdc22972011-07-12 00:08:50 +0000433 // Insert new integer induction variable.
434 PHINode *NewPHI = PHINode::Create(Int32Ty, 2, PN->getName()+".int", PN);
435 NewPHI->addIncoming(ConstantInt::get(Int32Ty, InitValue),
436 PN->getIncomingBlock(IncomingEdge));
Chris Lattnere61b67d2004-04-02 20:24:31 +0000437
Andrew Trickcdc22972011-07-12 00:08:50 +0000438 Value *NewAdd =
439 BinaryOperator::CreateAdd(NewPHI, ConstantInt::get(Int32Ty, IncValue),
440 Incr->getName()+".int", Incr);
441 NewPHI->addIncoming(NewAdd, PN->getIncomingBlock(BackEdge));
Dan Gohmaneb6be652009-02-12 22:19:27 +0000442
Andrew Trickcdc22972011-07-12 00:08:50 +0000443 ICmpInst *NewCompare = new ICmpInst(TheBr, NewPred, NewAdd,
444 ConstantInt::get(Int32Ty, ExitValue),
445 Compare->getName());
Dan Gohmand76d71a2009-05-12 02:17:14 +0000446
Andrew Trickcdc22972011-07-12 00:08:50 +0000447 // In the following deletions, PN may become dead and may be deleted.
448 // Use a WeakVH to observe whether this happens.
449 WeakVH WeakPH = PN;
450
451 // Delete the old floating point exit comparison. The branch starts using the
452 // new comparison.
453 NewCompare->takeName(Compare);
454 Compare->replaceAllUsesWith(NewCompare);
455 RecursivelyDeleteTriviallyDeadInstructions(Compare);
456
457 // Delete the old floating point increment.
458 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
459 RecursivelyDeleteTriviallyDeadInstructions(Incr);
460
461 // If the FP induction variable still has uses, this is because something else
462 // in the loop uses its value. In order to canonicalize the induction
463 // variable, we chose to eliminate the IV and rewrite it in terms of an
464 // int->fp cast.
465 //
466 // We give preference to sitofp over uitofp because it is faster on most
467 // platforms.
468 if (WeakPH) {
469 Value *Conv = new SIToFPInst(NewPHI, PN->getType(), "indvar.conv",
470 PN->getParent()->getFirstNonPHI());
471 PN->replaceAllUsesWith(Conv);
472 RecursivelyDeleteTriviallyDeadInstructions(PN);
473 }
474
475 // Add a new IVUsers entry for the newly-created integer PHI.
476 if (IU)
477 IU->AddUsersIfInteresting(NewPHI);
Chris Lattnere61b67d2004-04-02 20:24:31 +0000478}
479
Andrew Trickcdc22972011-07-12 00:08:50 +0000480void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) {
481 // First step. Check to see if there are any floating-point recurrences.
482 // If there are, change them into integer recurrences, permitting analysis by
483 // the SCEV routines.
484 //
485 BasicBlock *Header = L->getHeader();
486
487 SmallVector<WeakVH, 8> PHIs;
488 for (BasicBlock::iterator I = Header->begin();
489 PHINode *PN = dyn_cast<PHINode>(I); ++I)
490 PHIs.push_back(PN);
491
492 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
493 if (PHINode *PN = dyn_cast_or_null<PHINode>(&*PHIs[i]))
494 HandleFloatingPointIV(L, PN);
495
496 // If the loop previously had floating-point IV, ScalarEvolution
497 // may not have been able to compute a trip count. Now that we've done some
498 // re-writing, the trip count may be computable.
499 if (Changed)
500 SE->forgetLoop(L);
501}
502
503//===----------------------------------------------------------------------===//
504// RewriteLoopExitValues - Optimize IV users outside the loop.
505// As a side effect, reduces the amount of IV processing within the loop.
506//===----------------------------------------------------------------------===//
507
Chris Lattnere61b67d2004-04-02 20:24:31 +0000508/// RewriteLoopExitValues - Check to see if this loop has a computable
509/// loop-invariant execution count. If so, this means that we can compute the
510/// final value of any expressions that are recurrent in the loop, and
511/// substitute the exit values from the loop into any instructions outside of
512/// the loop that use the final values of the current expressions.
Dan Gohmand76d71a2009-05-12 02:17:14 +0000513///
514/// This is mostly redundant with the regular IndVarSimplify activities that
515/// happen later, except that it's more powerful in some cases, because it's
516/// able to brute-force evaluate arbitrary instructions as long as they have
517/// constant operands at the beginning of the loop.
Chris Lattnera337f5e2011-01-09 02:16:18 +0000518void IndVarSimplify::RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter) {
Dan Gohmand76d71a2009-05-12 02:17:14 +0000519 // Verify the input to the pass in already in LCSSA form.
Dan Gohman2734ebd2010-03-10 19:38:49 +0000520 assert(L->isLCSSAForm(*DT));
Dan Gohmand76d71a2009-05-12 02:17:14 +0000521
Devang Patelb5933bb2007-08-21 00:31:24 +0000522 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000523 L->getUniqueExitBlocks(ExitBlocks);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000524
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000525 // Find all values that are computed inside the loop, but used outside of it.
526 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
527 // the exit blocks of the loop to find them.
528 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
529 BasicBlock *ExitBB = ExitBlocks[i];
Dan Gohmanf84d42f2009-02-17 19:13:57 +0000530
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000531 // If there are no PHI nodes in this exit block, then no values defined
532 // inside the loop are used on this path, skip it.
533 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
534 if (!PN) continue;
Dan Gohmanf84d42f2009-02-17 19:13:57 +0000535
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000536 unsigned NumPreds = PN->getNumIncomingValues();
Dan Gohmanf84d42f2009-02-17 19:13:57 +0000537
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000538 // Iterate over all of the PHI nodes.
539 BasicBlock::iterator BBI = ExitBB->begin();
540 while ((PN = dyn_cast<PHINode>(BBI++))) {
Torok Edwin5349cf52009-05-24 19:36:09 +0000541 if (PN->use_empty())
542 continue; // dead use, don't replace it
Dan Gohmanc43d2642010-02-18 21:34:02 +0000543
544 // SCEV only supports integer expressions for now.
545 if (!PN->getType()->isIntegerTy() && !PN->getType()->isPointerTy())
546 continue;
547
Dale Johannesen1d6827a2010-02-19 07:14:22 +0000548 // It's necessary to tell ScalarEvolution about this explicitly so that
549 // it can walk the def-use list and forget all SCEVs, as it may not be
550 // watching the PHI itself. Once the new exit value is in place, there
551 // may not be a def-use connection between the loop and every instruction
552 // which got a SCEVAddRecExpr for that loop.
553 SE->forgetValue(PN);
554
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000555 // Iterate over all of the values in all the PHI nodes.
556 for (unsigned i = 0; i != NumPreds; ++i) {
557 // If the value being merged in is not integer or is not defined
558 // in the loop, skip it.
559 Value *InVal = PN->getIncomingValue(i);
Dan Gohmanc43d2642010-02-18 21:34:02 +0000560 if (!isa<Instruction>(InVal))
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000561 continue;
Chris Lattnere61b67d2004-04-02 20:24:31 +0000562
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000563 // If this pred is for a subloop, not L itself, skip it.
Dan Gohmanf84d42f2009-02-17 19:13:57 +0000564 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000565 continue; // The Block is in a subloop, skip it.
566
567 // Check that InVal is defined in the loop.
568 Instruction *Inst = cast<Instruction>(InVal);
Dan Gohman18fa5682009-12-18 01:24:09 +0000569 if (!L->contains(Inst))
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000570 continue;
Dan Gohmanf84d42f2009-02-17 19:13:57 +0000571
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000572 // Okay, this instruction has a user outside of the current loop
573 // and varies predictably *inside* the loop. Evaluate the value it
574 // contains when the loop exits, if possible.
Dan Gohmanaf752342009-07-07 17:06:11 +0000575 const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
Dan Gohmanafd6db92010-11-17 21:23:15 +0000576 if (!SE->isLoopInvariant(ExitValue, L))
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000577 continue;
Chris Lattner1f7648e2007-03-04 01:00:28 +0000578
Dan Gohmandaafbe62009-06-26 22:53:46 +0000579 Value *ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), Inst);
Dan Gohmanf84d42f2009-02-17 19:13:57 +0000580
David Greene0dd384c2010-01-05 01:27:06 +0000581 DEBUG(dbgs() << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal << '\n'
Chris Lattnerb25de3f2009-08-23 04:37:46 +0000582 << " LoopVal = " << *Inst << "\n");
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000583
Andrew Trick87716c92011-03-17 23:51:11 +0000584 if (!isValidRewrite(Inst, ExitVal)) {
585 DeadInsts.push_back(ExitVal);
586 continue;
587 }
588 Changed = true;
589 ++NumReplaced;
590
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000591 PN->setIncomingValue(i, ExitVal);
Dan Gohmanf84d42f2009-02-17 19:13:57 +0000592
Dan Gohmand76d71a2009-05-12 02:17:14 +0000593 // If this instruction is dead now, delete it.
594 RecursivelyDeleteTriviallyDeadInstructions(Inst);
Dan Gohmanf84d42f2009-02-17 19:13:57 +0000595
Dan Gohman03d5d0f2009-07-14 01:09:02 +0000596 if (NumPreds == 1) {
597 // Completely replace a single-pred PHI. This is safe, because the
598 // NewVal won't be variant in the loop, so we don't need an LCSSA phi
599 // node anymore.
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000600 PN->replaceAllUsesWith(ExitVal);
Dan Gohmand76d71a2009-05-12 02:17:14 +0000601 RecursivelyDeleteTriviallyDeadInstructions(PN);
Chris Lattnered30abf2007-03-03 22:48:48 +0000602 }
603 }
Dan Gohman03d5d0f2009-07-14 01:09:02 +0000604 if (NumPreds != 1) {
Dan Gohmandaafbe62009-06-26 22:53:46 +0000605 // Clone the PHI and delete the original one. This lets IVUsers and
606 // any other maps purge the original user from their records.
Devang Patel11cf3f42009-10-27 22:16:29 +0000607 PHINode *NewPN = cast<PHINode>(PN->clone());
Dan Gohmandaafbe62009-06-26 22:53:46 +0000608 NewPN->takeName(PN);
609 NewPN->insertBefore(PN);
610 PN->replaceAllUsesWith(NewPN);
611 PN->eraseFromParent();
612 }
Chris Lattnered30abf2007-03-03 22:48:48 +0000613 }
614 }
Dan Gohman1a2abe52010-03-20 03:53:53 +0000615
616 // The insertion point instruction may have been deleted; clear it out
617 // so that the rewriter doesn't trip over it later.
618 Rewriter.clearInsertPoint();
Chris Lattnere61b67d2004-04-02 20:24:31 +0000619}
620
Andrew Trickcdc22972011-07-12 00:08:50 +0000621//===----------------------------------------------------------------------===//
622// Rewrite IV users based on a canonical IV.
623// To be replaced by -disable-iv-rewrite.
624//===----------------------------------------------------------------------===//
Dale Johannesena71daa82009-04-15 23:31:51 +0000625
Andrew Trick69d44522011-06-21 03:22:38 +0000626/// SimplifyIVUsers - Iteratively perform simplification on IVUsers within this
627/// loop. IVUsers is treated as a worklist. Each successive simplification may
628/// push more users which may themselves be candidates for simplification.
629///
630/// This is the old approach to IV simplification to be replaced by
631/// SimplifyIVUsersNoRewrite.
632///
633void IndVarSimplify::SimplifyIVUsers(SCEVExpander &Rewriter) {
634 // Each round of simplification involves a round of eliminating operations
635 // followed by a round of widening IVs. A single IVUsers worklist is used
636 // across all rounds. The inner loop advances the user. If widening exposes
637 // more uses, then another pass through the outer loop is triggered.
638 for (IVUsers::iterator I = IU->begin(); I != IU->end(); ++I) {
639 Instruction *UseInst = I->getUser();
640 Value *IVOperand = I->getOperandValToReplace();
641
642 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
643 EliminateIVComparison(ICmp, IVOperand);
644 continue;
645 }
646 if (BinaryOperator *Rem = dyn_cast<BinaryOperator>(UseInst)) {
647 bool IsSigned = Rem->getOpcode() == Instruction::SRem;
648 if (IsSigned || Rem->getOpcode() == Instruction::URem) {
Andrew Trickfc4ccb22011-06-21 15:43:52 +0000649 EliminateIVRemainder(Rem, IVOperand, IsSigned);
Andrew Trick69d44522011-06-21 03:22:38 +0000650 continue;
651 }
652 }
653 }
654}
655
Andrew Trickcdc22972011-07-12 00:08:50 +0000656// FIXME: It is an extremely bad idea to indvar substitute anything more
657// complex than affine induction variables. Doing so will put expensive
658// polynomial evaluations inside of the loop, and the str reduction pass
659// currently can only reduce affine polynomials. For now just disable
660// indvar subst on anything more complex than an affine addrec, unless
661// it can be expanded to a trivial value.
662static bool isSafe(const SCEV *S, const Loop *L, ScalarEvolution *SE) {
663 // Loop-invariant values are safe.
664 if (SE->isLoopInvariant(S, L)) return true;
665
666 // Affine addrecs are safe. Non-affine are not, because LSR doesn't know how
667 // to transform them into efficient code.
668 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
669 return AR->isAffine();
670
671 // An add is safe it all its operands are safe.
672 if (const SCEVCommutativeExpr *Commutative = dyn_cast<SCEVCommutativeExpr>(S)) {
673 for (SCEVCommutativeExpr::op_iterator I = Commutative->op_begin(),
674 E = Commutative->op_end(); I != E; ++I)
675 if (!isSafe(*I, L, SE)) return false;
676 return true;
677 }
678
679 // A cast is safe if its operand is.
680 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
681 return isSafe(C->getOperand(), L, SE);
682
683 // A udiv is safe if its operands are.
684 if (const SCEVUDivExpr *UD = dyn_cast<SCEVUDivExpr>(S))
685 return isSafe(UD->getLHS(), L, SE) &&
686 isSafe(UD->getRHS(), L, SE);
687
688 // SCEVUnknown is always safe.
689 if (isa<SCEVUnknown>(S))
690 return true;
691
692 // Nothing else is safe.
693 return false;
694}
695
696void IndVarSimplify::RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter) {
697 // Rewrite all induction variable expressions in terms of the canonical
698 // induction variable.
699 //
700 // If there were induction variables of other sizes or offsets, manually
701 // add the offsets to the primary induction variable and cast, avoiding
702 // the need for the code evaluation methods to insert induction variables
703 // of different sizes.
704 for (IVUsers::iterator UI = IU->begin(), E = IU->end(); UI != E; ++UI) {
705 Value *Op = UI->getOperandValToReplace();
Chris Lattner229907c2011-07-18 04:54:35 +0000706 Type *UseTy = Op->getType();
Andrew Trickcdc22972011-07-12 00:08:50 +0000707 Instruction *User = UI->getUser();
708
709 // Compute the final addrec to expand into code.
710 const SCEV *AR = IU->getReplacementExpr(*UI);
711
712 // Evaluate the expression out of the loop, if possible.
713 if (!L->contains(UI->getUser())) {
714 const SCEV *ExitVal = SE->getSCEVAtScope(AR, L->getParentLoop());
715 if (SE->isLoopInvariant(ExitVal, L))
716 AR = ExitVal;
717 }
718
719 // FIXME: It is an extremely bad idea to indvar substitute anything more
720 // complex than affine induction variables. Doing so will put expensive
721 // polynomial evaluations inside of the loop, and the str reduction pass
722 // currently can only reduce affine polynomials. For now just disable
723 // indvar subst on anything more complex than an affine addrec, unless
724 // it can be expanded to a trivial value.
725 if (!isSafe(AR, L, SE))
726 continue;
727
728 // Determine the insertion point for this user. By default, insert
729 // immediately before the user. The SCEVExpander class will automatically
730 // hoist loop invariants out of the loop. For PHI nodes, there may be
731 // multiple uses, so compute the nearest common dominator for the
732 // incoming blocks.
Andrew Trick638b3552011-07-20 05:32:06 +0000733 Instruction *InsertPt = getInsertPointForUses(User, Op, DT);
Andrew Trickcdc22972011-07-12 00:08:50 +0000734
735 // Now expand it into actual Instructions and patch it into place.
736 Value *NewVal = Rewriter.expandCodeFor(AR, UseTy, InsertPt);
737
738 DEBUG(dbgs() << "INDVARS: Rewrote IV '" << *AR << "' " << *Op << '\n'
739 << " into = " << *NewVal << "\n");
740
741 if (!isValidRewrite(Op, NewVal)) {
742 DeadInsts.push_back(NewVal);
743 continue;
744 }
745 // Inform ScalarEvolution that this value is changing. The change doesn't
746 // affect its value, but it does potentially affect which use lists the
747 // value will be on after the replacement, which affects ScalarEvolution's
748 // ability to walk use lists and drop dangling pointers when a value is
749 // deleted.
750 SE->forgetValue(User);
751
752 // Patch the new value into place.
753 if (Op->hasName())
754 NewVal->takeName(Op);
755 if (Instruction *NewValI = dyn_cast<Instruction>(NewVal))
756 NewValI->setDebugLoc(User->getDebugLoc());
757 User->replaceUsesOfWith(Op, NewVal);
758 UI->setOperandValToReplace(NewVal);
759
760 ++NumRemoved;
761 Changed = true;
762
763 // The old value may be dead now.
764 DeadInsts.push_back(Op);
765 }
766}
767
768//===----------------------------------------------------------------------===//
769// IV Widening - Extend the width of an IV to cover its widest uses.
770//===----------------------------------------------------------------------===//
771
Andrew Trickf44aadf2011-05-20 18:25:42 +0000772namespace {
773 // Collect information about induction variables that are used by sign/zero
774 // extend operations. This information is recorded by CollectExtend and
775 // provides the input to WidenIV.
776 struct WideIVInfo {
Chris Lattner229907c2011-07-18 04:54:35 +0000777 Type *WidestNativeType; // Widest integer type created [sz]ext
Andrew Trickf44aadf2011-05-20 18:25:42 +0000778 bool IsSigned; // Was an sext user seen before a zext?
779
780 WideIVInfo() : WidestNativeType(0), IsSigned(false) {}
781 };
Andrew Trickf44aadf2011-05-20 18:25:42 +0000782}
783
784/// CollectExtend - Update information about the induction variable that is
785/// extended by this sign or zero extend operation. This is used to determine
786/// the final width of the IV before actually widening it.
Andrew Trick69d44522011-06-21 03:22:38 +0000787static void CollectExtend(CastInst *Cast, bool IsSigned, WideIVInfo &WI,
788 ScalarEvolution *SE, const TargetData *TD) {
Chris Lattner229907c2011-07-18 04:54:35 +0000789 Type *Ty = Cast->getType();
Andrew Trickf44aadf2011-05-20 18:25:42 +0000790 uint64_t Width = SE->getTypeSizeInBits(Ty);
791 if (TD && !TD->isLegalInteger(Width))
792 return;
793
Andrew Trick69d44522011-06-21 03:22:38 +0000794 if (!WI.WidestNativeType) {
795 WI.WidestNativeType = SE->getEffectiveSCEVType(Ty);
796 WI.IsSigned = IsSigned;
Andrew Trickf44aadf2011-05-20 18:25:42 +0000797 return;
798 }
799
800 // We extend the IV to satisfy the sign of its first user, arbitrarily.
Andrew Trick69d44522011-06-21 03:22:38 +0000801 if (WI.IsSigned != IsSigned)
Andrew Trickf44aadf2011-05-20 18:25:42 +0000802 return;
803
Andrew Trick69d44522011-06-21 03:22:38 +0000804 if (Width > SE->getTypeSizeInBits(WI.WidestNativeType))
805 WI.WidestNativeType = SE->getEffectiveSCEVType(Ty);
Andrew Trickf44aadf2011-05-20 18:25:42 +0000806}
807
808namespace {
Andrew Trick22104482011-07-20 04:39:24 +0000809
810/// NarrowIVDefUse - Record a link in the Narrow IV def-use chain along with the
811/// WideIV that computes the same value as the Narrow IV def. This avoids
812/// caching Use* pointers.
813struct NarrowIVDefUse {
814 Instruction *NarrowDef;
815 Instruction *NarrowUse;
816 Instruction *WideDef;
817
818 NarrowIVDefUse(): NarrowDef(0), NarrowUse(0), WideDef(0) {}
819
820 NarrowIVDefUse(Instruction *ND, Instruction *NU, Instruction *WD):
821 NarrowDef(ND), NarrowUse(NU), WideDef(WD) {}
822};
823
Andrew Trickf44aadf2011-05-20 18:25:42 +0000824/// WidenIV - The goal of this transform is to remove sign and zero extends
825/// without creating any new induction variables. To do this, it creates a new
826/// phi of the wider type and redirects all users, either removing extends or
827/// inserting truncs whenever we stop propagating the type.
828///
829class WidenIV {
Andrew Trick69d44522011-06-21 03:22:38 +0000830 // Parameters
Andrew Trickf44aadf2011-05-20 18:25:42 +0000831 PHINode *OrigPhi;
Chris Lattner229907c2011-07-18 04:54:35 +0000832 Type *WideType;
Andrew Trickf44aadf2011-05-20 18:25:42 +0000833 bool IsSigned;
834
Andrew Trick69d44522011-06-21 03:22:38 +0000835 // Context
836 LoopInfo *LI;
837 Loop *L;
Andrew Trickf44aadf2011-05-20 18:25:42 +0000838 ScalarEvolution *SE;
Andrew Trick69d44522011-06-21 03:22:38 +0000839 DominatorTree *DT;
Andrew Trickf44aadf2011-05-20 18:25:42 +0000840
Andrew Trick69d44522011-06-21 03:22:38 +0000841 // Result
Andrew Trickf44aadf2011-05-20 18:25:42 +0000842 PHINode *WidePhi;
843 Instruction *WideInc;
844 const SCEV *WideIncExpr;
Andrew Trick69d44522011-06-21 03:22:38 +0000845 SmallVectorImpl<WeakVH> &DeadInsts;
Andrew Trickf44aadf2011-05-20 18:25:42 +0000846
Andrew Trick69d44522011-06-21 03:22:38 +0000847 SmallPtrSet<Instruction*,16> Widened;
Andrew Trick22104482011-07-20 04:39:24 +0000848 SmallVector<NarrowIVDefUse, 8> NarrowIVUsers;
Andrew Trickf44aadf2011-05-20 18:25:42 +0000849
850public:
Andrew Trick69d44522011-06-21 03:22:38 +0000851 WidenIV(PHINode *PN, const WideIVInfo &WI, LoopInfo *LInfo,
852 ScalarEvolution *SEv, DominatorTree *DTree,
Andrew Trick7fac79e2011-05-26 00:46:11 +0000853 SmallVectorImpl<WeakVH> &DI) :
Andrew Trickf44aadf2011-05-20 18:25:42 +0000854 OrigPhi(PN),
Andrew Trick69d44522011-06-21 03:22:38 +0000855 WideType(WI.WidestNativeType),
856 IsSigned(WI.IsSigned),
Andrew Trickf44aadf2011-05-20 18:25:42 +0000857 LI(LInfo),
858 L(LI->getLoopFor(OrigPhi->getParent())),
859 SE(SEv),
Andrew Trick7fac79e2011-05-26 00:46:11 +0000860 DT(DTree),
Andrew Trickf44aadf2011-05-20 18:25:42 +0000861 WidePhi(0),
862 WideInc(0),
Andrew Trick69d44522011-06-21 03:22:38 +0000863 WideIncExpr(0),
864 DeadInsts(DI) {
Andrew Trickf44aadf2011-05-20 18:25:42 +0000865 assert(L->getHeader() == OrigPhi->getParent() && "Phi must be an IV");
866 }
867
Andrew Trick69d44522011-06-21 03:22:38 +0000868 PHINode *CreateWideIV(SCEVExpander &Rewriter);
Andrew Trickf44aadf2011-05-20 18:25:42 +0000869
870protected:
Andrew Trick22104482011-07-20 04:39:24 +0000871 Instruction *CloneIVUser(NarrowIVDefUse DU);
Andrew Trickf44aadf2011-05-20 18:25:42 +0000872
Andrew Trick92905a12011-07-05 18:19:39 +0000873 const SCEVAddRecExpr *GetWideRecurrence(Instruction *NarrowUse);
874
Andrew Trick22104482011-07-20 04:39:24 +0000875 Instruction *WidenIVUse(NarrowIVDefUse DU);
Andrew Trick6d123092011-07-02 02:34:25 +0000876
877 void pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef);
Andrew Trickf44aadf2011-05-20 18:25:42 +0000878};
879} // anonymous namespace
880
Chris Lattner229907c2011-07-18 04:54:35 +0000881static Value *getExtend( Value *NarrowOper, Type *WideType,
Andrew Trickeb3c36e2011-05-25 04:42:22 +0000882 bool IsSigned, IRBuilder<> &Builder) {
883 return IsSigned ? Builder.CreateSExt(NarrowOper, WideType) :
884 Builder.CreateZExt(NarrowOper, WideType);
Andrew Trickf44aadf2011-05-20 18:25:42 +0000885}
886
887/// CloneIVUser - Instantiate a wide operation to replace a narrow
888/// operation. This only needs to handle operations that can evaluation to
889/// SCEVAddRec. It can safely return 0 for any operation we decide not to clone.
Andrew Trick22104482011-07-20 04:39:24 +0000890Instruction *WidenIV::CloneIVUser(NarrowIVDefUse DU) {
891 unsigned Opcode = DU.NarrowUse->getOpcode();
Andrew Trickf44aadf2011-05-20 18:25:42 +0000892 switch (Opcode) {
893 default:
894 return 0;
895 case Instruction::Add:
896 case Instruction::Mul:
897 case Instruction::UDiv:
898 case Instruction::Sub:
899 case Instruction::And:
900 case Instruction::Or:
901 case Instruction::Xor:
902 case Instruction::Shl:
903 case Instruction::LShr:
904 case Instruction::AShr:
Andrew Trick22104482011-07-20 04:39:24 +0000905 DEBUG(dbgs() << "Cloning IVUser: " << *DU.NarrowUse << "\n");
Andrew Trickf44aadf2011-05-20 18:25:42 +0000906
Andrew Trick22104482011-07-20 04:39:24 +0000907 IRBuilder<> Builder(DU.NarrowUse);
Andrew Trickeb3c36e2011-05-25 04:42:22 +0000908
909 // Replace NarrowDef operands with WideDef. Otherwise, we don't know
910 // anything about the narrow operand yet so must insert a [sz]ext. It is
911 // probably loop invariant and will be folded or hoisted. If it actually
912 // comes from a widened IV, it should be removed during a future call to
913 // WidenIVUse.
Andrew Trick22104482011-07-20 04:39:24 +0000914 Value *LHS = (DU.NarrowUse->getOperand(0) == DU.NarrowDef) ? DU.WideDef :
915 getExtend(DU.NarrowUse->getOperand(0), WideType, IsSigned, Builder);
916 Value *RHS = (DU.NarrowUse->getOperand(1) == DU.NarrowDef) ? DU.WideDef :
917 getExtend(DU.NarrowUse->getOperand(1), WideType, IsSigned, Builder);
Andrew Trickeb3c36e2011-05-25 04:42:22 +0000918
Andrew Trick22104482011-07-20 04:39:24 +0000919 BinaryOperator *NarrowBO = cast<BinaryOperator>(DU.NarrowUse);
Andrew Trickf44aadf2011-05-20 18:25:42 +0000920 BinaryOperator *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(),
Andrew Trickeb3c36e2011-05-25 04:42:22 +0000921 LHS, RHS,
Andrew Trickf44aadf2011-05-20 18:25:42 +0000922 NarrowBO->getName());
Andrew Trickf44aadf2011-05-20 18:25:42 +0000923 Builder.Insert(WideBO);
Andrew Trickefe89ad2011-06-30 19:02:17 +0000924 if (const OverflowingBinaryOperator *OBO =
925 dyn_cast<OverflowingBinaryOperator>(NarrowBO)) {
926 if (OBO->hasNoUnsignedWrap()) WideBO->setHasNoUnsignedWrap();
927 if (OBO->hasNoSignedWrap()) WideBO->setHasNoSignedWrap();
928 }
Andrew Trickeb3c36e2011-05-25 04:42:22 +0000929 return WideBO;
Andrew Trickf44aadf2011-05-20 18:25:42 +0000930 }
931 llvm_unreachable(0);
932}
933
Andrew Trick7fac79e2011-05-26 00:46:11 +0000934/// HoistStep - Attempt to hoist an IV increment above a potential use.
935///
936/// To successfully hoist, two criteria must be met:
937/// - IncV operands dominate InsertPos and
938/// - InsertPos dominates IncV
939///
940/// Meeting the second condition means that we don't need to check all of IncV's
941/// existing uses (it's moving up in the domtree).
942///
943/// This does not yet recursively hoist the operands, although that would
944/// not be difficult.
945static bool HoistStep(Instruction *IncV, Instruction *InsertPos,
946 const DominatorTree *DT)
947{
948 if (DT->dominates(IncV, InsertPos))
949 return true;
950
951 if (!DT->dominates(InsertPos->getParent(), IncV->getParent()))
952 return false;
953
954 if (IncV->mayHaveSideEffects())
955 return false;
956
957 // Attempt to hoist IncV
958 for (User::op_iterator OI = IncV->op_begin(), OE = IncV->op_end();
959 OI != OE; ++OI) {
960 Instruction *OInst = dyn_cast<Instruction>(OI);
961 if (OInst && !DT->dominates(OInst, InsertPos))
962 return false;
963 }
964 IncV->moveBefore(InsertPos);
965 return true;
966}
967
Andrew Trick92905a12011-07-05 18:19:39 +0000968// GetWideRecurrence - Is this instruction potentially interesting from IVUsers'
969// perspective after widening it's type? In other words, can the extend be
970// safely hoisted out of the loop with SCEV reducing the value to a recurrence
971// on the same loop. If so, return the sign or zero extended
972// recurrence. Otherwise return NULL.
973const SCEVAddRecExpr *WidenIV::GetWideRecurrence(Instruction *NarrowUse) {
974 if (!SE->isSCEVable(NarrowUse->getType()))
975 return 0;
976
977 const SCEV *NarrowExpr = SE->getSCEV(NarrowUse);
978 if (SE->getTypeSizeInBits(NarrowExpr->getType())
979 >= SE->getTypeSizeInBits(WideType)) {
980 // NarrowUse implicitly widens its operand. e.g. a gep with a narrow
981 // index. So don't follow this use.
982 return 0;
983 }
984
985 const SCEV *WideExpr = IsSigned ?
986 SE->getSignExtendExpr(NarrowExpr, WideType) :
987 SE->getZeroExtendExpr(NarrowExpr, WideType);
988 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(WideExpr);
989 if (!AddRec || AddRec->getLoop() != L)
990 return 0;
991
992 return AddRec;
993}
994
Andrew Trickf44aadf2011-05-20 18:25:42 +0000995/// WidenIVUse - Determine whether an individual user of the narrow IV can be
996/// widened. If so, return the wide clone of the user.
Andrew Trick22104482011-07-20 04:39:24 +0000997Instruction *WidenIV::WidenIVUse(NarrowIVDefUse DU) {
Andrew Trickecdd6e42011-06-29 23:03:57 +0000998
Andrew Trick6d123092011-07-02 02:34:25 +0000999 // Stop traversing the def-use chain at inner-loop phis or post-loop phis.
Andrew Trick22104482011-07-20 04:39:24 +00001000 if (isa<PHINode>(DU.NarrowUse) &&
1001 LI->getLoopFor(DU.NarrowUse->getParent()) != L)
Andrew Trickf44aadf2011-05-20 18:25:42 +00001002 return 0;
1003
Andrew Trickf44aadf2011-05-20 18:25:42 +00001004 // Our raison d'etre! Eliminate sign and zero extension.
Andrew Trick22104482011-07-20 04:39:24 +00001005 if (IsSigned ? isa<SExtInst>(DU.NarrowUse) : isa<ZExtInst>(DU.NarrowUse)) {
1006 Value *NewDef = DU.WideDef;
1007 if (DU.NarrowUse->getType() != WideType) {
1008 unsigned CastWidth = SE->getTypeSizeInBits(DU.NarrowUse->getType());
Andrew Trickeb3c36e2011-05-25 04:42:22 +00001009 unsigned IVWidth = SE->getTypeSizeInBits(WideType);
1010 if (CastWidth < IVWidth) {
1011 // The cast isn't as wide as the IV, so insert a Trunc.
Andrew Trick22104482011-07-20 04:39:24 +00001012 IRBuilder<> Builder(DU.NarrowUse);
1013 NewDef = Builder.CreateTrunc(DU.WideDef, DU.NarrowUse->getType());
Andrew Trickeb3c36e2011-05-25 04:42:22 +00001014 }
1015 else {
1016 // A wider extend was hidden behind a narrower one. This may induce
1017 // another round of IV widening in which the intermediate IV becomes
1018 // dead. It should be very rare.
1019 DEBUG(dbgs() << "INDVARS: New IV " << *WidePhi
Andrew Trick22104482011-07-20 04:39:24 +00001020 << " not wide enough to subsume " << *DU.NarrowUse << "\n");
1021 DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef);
1022 NewDef = DU.NarrowUse;
Andrew Trickeb3c36e2011-05-25 04:42:22 +00001023 }
1024 }
Andrew Trick22104482011-07-20 04:39:24 +00001025 if (NewDef != DU.NarrowUse) {
1026 DEBUG(dbgs() << "INDVARS: eliminating " << *DU.NarrowUse
1027 << " replaced by " << *DU.WideDef << "\n");
Andrew Trickeb3c36e2011-05-25 04:42:22 +00001028 ++NumElimExt;
Andrew Trick22104482011-07-20 04:39:24 +00001029 DU.NarrowUse->replaceAllUsesWith(NewDef);
1030 DeadInsts.push_back(DU.NarrowUse);
Andrew Trickeb3c36e2011-05-25 04:42:22 +00001031 }
Andrew Trick69d44522011-06-21 03:22:38 +00001032 // Now that the extend is gone, we want to expose it's uses for potential
1033 // further simplification. We don't need to directly inform SimplifyIVUsers
1034 // of the new users, because their parent IV will be processed later as a
1035 // new loop phi. If we preserved IVUsers analysis, we would also want to
1036 // push the uses of WideDef here.
Andrew Trickf44aadf2011-05-20 18:25:42 +00001037
1038 // No further widening is needed. The deceased [sz]ext had done it for us.
1039 return 0;
1040 }
Andrew Trick6d123092011-07-02 02:34:25 +00001041
1042 // Does this user itself evaluate to a recurrence after widening?
Andrew Trick22104482011-07-20 04:39:24 +00001043 const SCEVAddRecExpr *WideAddRec = GetWideRecurrence(DU.NarrowUse);
Andrew Trickf44aadf2011-05-20 18:25:42 +00001044 if (!WideAddRec) {
1045 // This user does not evaluate to a recurence after widening, so don't
1046 // follow it. Instead insert a Trunc to kill off the original use,
1047 // eventually isolating the original narrow IV so it can be removed.
Andrew Trick638b3552011-07-20 05:32:06 +00001048 IRBuilder<> Builder(getInsertPointForUses(DU.NarrowUse, DU.NarrowDef, DT));
Andrew Trick22104482011-07-20 04:39:24 +00001049 Value *Trunc = Builder.CreateTrunc(DU.WideDef, DU.NarrowDef->getType());
1050 DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, Trunc);
Andrew Trickf44aadf2011-05-20 18:25:42 +00001051 return 0;
1052 }
Andrew Trick7da24172011-07-18 20:32:31 +00001053 // Assume block terminators cannot evaluate to a recurrence. We can't to
Andrew Trick6d123092011-07-02 02:34:25 +00001054 // insert a Trunc after a terminator if there happens to be a critical edge.
Andrew Trick22104482011-07-20 04:39:24 +00001055 assert(DU.NarrowUse != DU.NarrowUse->getParent()->getTerminator() &&
Andrew Trick6d123092011-07-02 02:34:25 +00001056 "SCEV is not expected to evaluate a block terminator");
Andrew Trickecdd6e42011-06-29 23:03:57 +00001057
Andrew Trick7fac79e2011-05-26 00:46:11 +00001058 // Reuse the IV increment that SCEVExpander created as long as it dominates
1059 // NarrowUse.
Andrew Trickf44aadf2011-05-20 18:25:42 +00001060 Instruction *WideUse = 0;
Andrew Trick22104482011-07-20 04:39:24 +00001061 if (WideAddRec == WideIncExpr && HoistStep(WideInc, DU.NarrowUse, DT)) {
Andrew Trickf44aadf2011-05-20 18:25:42 +00001062 WideUse = WideInc;
1063 }
1064 else {
Andrew Trick22104482011-07-20 04:39:24 +00001065 WideUse = CloneIVUser(DU);
Andrew Trickf44aadf2011-05-20 18:25:42 +00001066 if (!WideUse)
1067 return 0;
1068 }
Andrew Trick6d123092011-07-02 02:34:25 +00001069 // Evaluation of WideAddRec ensured that the narrow expression could be
1070 // extended outside the loop without overflow. This suggests that the wide use
Andrew Trickf44aadf2011-05-20 18:25:42 +00001071 // evaluates to the same expression as the extended narrow use, but doesn't
1072 // absolutely guarantee it. Hence the following failsafe check. In rare cases
Andrew Trick69d44522011-06-21 03:22:38 +00001073 // where it fails, we simply throw away the newly created wide use.
Andrew Trickf44aadf2011-05-20 18:25:42 +00001074 if (WideAddRec != SE->getSCEV(WideUse)) {
1075 DEBUG(dbgs() << "Wide use expression mismatch: " << *WideUse
1076 << ": " << *SE->getSCEV(WideUse) << " != " << *WideAddRec << "\n");
1077 DeadInsts.push_back(WideUse);
1078 return 0;
1079 }
1080
1081 // Returning WideUse pushes it on the worklist.
1082 return WideUse;
1083}
1084
Andrew Trick6d123092011-07-02 02:34:25 +00001085/// pushNarrowIVUsers - Add eligible users of NarrowDef to NarrowIVUsers.
1086///
1087void WidenIV::pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef) {
1088 for (Value::use_iterator UI = NarrowDef->use_begin(),
1089 UE = NarrowDef->use_end(); UI != UE; ++UI) {
Andrew Trick22104482011-07-20 04:39:24 +00001090 Instruction *NarrowUse = cast<Instruction>(*UI);
Andrew Trick6d123092011-07-02 02:34:25 +00001091
1092 // Handle data flow merges and bizarre phi cycles.
Andrew Trick22104482011-07-20 04:39:24 +00001093 if (!Widened.insert(NarrowUse))
Andrew Trick6d123092011-07-02 02:34:25 +00001094 continue;
1095
Andrew Trick22104482011-07-20 04:39:24 +00001096 NarrowIVUsers.push_back(NarrowIVDefUse(NarrowDef, NarrowUse, WideDef));
Andrew Trick6d123092011-07-02 02:34:25 +00001097 }
1098}
1099
Andrew Trickf44aadf2011-05-20 18:25:42 +00001100/// CreateWideIV - Process a single induction variable. First use the
1101/// SCEVExpander to create a wide induction variable that evaluates to the same
1102/// recurrence as the original narrow IV. Then use a worklist to forward
Andrew Trick69d44522011-06-21 03:22:38 +00001103/// traverse the narrow IV's def-use chain. After WidenIVUse has processed all
Andrew Trickf44aadf2011-05-20 18:25:42 +00001104/// interesting IV users, the narrow IV will be isolated for removal by
1105/// DeleteDeadPHIs.
1106///
1107/// It would be simpler to delete uses as they are processed, but we must avoid
1108/// invalidating SCEV expressions.
1109///
Andrew Trick69d44522011-06-21 03:22:38 +00001110PHINode *WidenIV::CreateWideIV(SCEVExpander &Rewriter) {
Andrew Trickf44aadf2011-05-20 18:25:42 +00001111 // Is this phi an induction variable?
1112 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(OrigPhi));
1113 if (!AddRec)
Andrew Trick69d44522011-06-21 03:22:38 +00001114 return NULL;
Andrew Trickf44aadf2011-05-20 18:25:42 +00001115
1116 // Widen the induction variable expression.
1117 const SCEV *WideIVExpr = IsSigned ?
1118 SE->getSignExtendExpr(AddRec, WideType) :
1119 SE->getZeroExtendExpr(AddRec, WideType);
1120
1121 assert(SE->getEffectiveSCEVType(WideIVExpr->getType()) == WideType &&
1122 "Expect the new IV expression to preserve its type");
1123
1124 // Can the IV be extended outside the loop without overflow?
1125 AddRec = dyn_cast<SCEVAddRecExpr>(WideIVExpr);
1126 if (!AddRec || AddRec->getLoop() != L)
Andrew Trick69d44522011-06-21 03:22:38 +00001127 return NULL;
Andrew Trickf44aadf2011-05-20 18:25:42 +00001128
Andrew Trick69d44522011-06-21 03:22:38 +00001129 // An AddRec must have loop-invariant operands. Since this AddRec is
Andrew Trickf44aadf2011-05-20 18:25:42 +00001130 // materialized by a loop header phi, the expression cannot have any post-loop
1131 // operands, so they must dominate the loop header.
1132 assert(SE->properlyDominates(AddRec->getStart(), L->getHeader()) &&
1133 SE->properlyDominates(AddRec->getStepRecurrence(*SE), L->getHeader())
1134 && "Loop header phi recurrence inputs do not dominate the loop");
1135
1136 // The rewriter provides a value for the desired IV expression. This may
1137 // either find an existing phi or materialize a new one. Either way, we
1138 // expect a well-formed cyclic phi-with-increments. i.e. any operand not part
1139 // of the phi-SCC dominates the loop entry.
1140 Instruction *InsertPt = L->getHeader()->begin();
1141 WidePhi = cast<PHINode>(Rewriter.expandCodeFor(AddRec, WideType, InsertPt));
1142
1143 // Remembering the WideIV increment generated by SCEVExpander allows
1144 // WidenIVUse to reuse it when widening the narrow IV's increment. We don't
1145 // employ a general reuse mechanism because the call above is the only call to
1146 // SCEVExpander. Henceforth, we produce 1-to-1 narrow to wide uses.
Andrew Trick7fac79e2011-05-26 00:46:11 +00001147 if (BasicBlock *LatchBlock = L->getLoopLatch()) {
1148 WideInc =
1149 cast<Instruction>(WidePhi->getIncomingValueForBlock(LatchBlock));
1150 WideIncExpr = SE->getSCEV(WideInc);
1151 }
Andrew Trickf44aadf2011-05-20 18:25:42 +00001152
1153 DEBUG(dbgs() << "Wide IV: " << *WidePhi << "\n");
1154 ++NumWidened;
1155
1156 // Traverse the def-use chain using a worklist starting at the original IV.
Andrew Trick6d123092011-07-02 02:34:25 +00001157 assert(Widened.empty() && NarrowIVUsers.empty() && "expect initial state" );
Andrew Trickf44aadf2011-05-20 18:25:42 +00001158
Andrew Trick6d123092011-07-02 02:34:25 +00001159 Widened.insert(OrigPhi);
1160 pushNarrowIVUsers(OrigPhi, WidePhi);
1161
Andrew Trickf44aadf2011-05-20 18:25:42 +00001162 while (!NarrowIVUsers.empty()) {
Andrew Trick22104482011-07-20 04:39:24 +00001163 NarrowIVDefUse DU = NarrowIVUsers.pop_back_val();
Andrew Trickf44aadf2011-05-20 18:25:42 +00001164
Andrew Trick7fac79e2011-05-26 00:46:11 +00001165 // Process a def-use edge. This may replace the use, so don't hold a
1166 // use_iterator across it.
Andrew Trick22104482011-07-20 04:39:24 +00001167 Instruction *WideUse = WidenIVUse(DU);
Andrew Trickf44aadf2011-05-20 18:25:42 +00001168
Andrew Trick7fac79e2011-05-26 00:46:11 +00001169 // Follow all def-use edges from the previous narrow use.
Andrew Trick6d123092011-07-02 02:34:25 +00001170 if (WideUse)
Andrew Trick22104482011-07-20 04:39:24 +00001171 pushNarrowIVUsers(DU.NarrowUse, WideUse);
Andrew Trick6d123092011-07-02 02:34:25 +00001172
Andrew Trick7fac79e2011-05-26 00:46:11 +00001173 // WidenIVUse may have removed the def-use edge.
Andrew Trick22104482011-07-20 04:39:24 +00001174 if (DU.NarrowDef->use_empty())
1175 DeadInsts.push_back(DU.NarrowDef);
Andrew Trickf44aadf2011-05-20 18:25:42 +00001176 }
Andrew Trick69d44522011-06-21 03:22:38 +00001177 return WidePhi;
Andrew Trickf44aadf2011-05-20 18:25:42 +00001178}
1179
Andrew Trickcdc22972011-07-12 00:08:50 +00001180//===----------------------------------------------------------------------===//
1181// Simplification of IV users based on SCEV evaluation.
1182//===----------------------------------------------------------------------===//
1183
Andrew Trick81683ed2011-05-12 00:04:28 +00001184void IndVarSimplify::EliminateIVComparison(ICmpInst *ICmp, Value *IVOperand) {
1185 unsigned IVOperIdx = 0;
1186 ICmpInst::Predicate Pred = ICmp->getPredicate();
1187 if (IVOperand != ICmp->getOperand(0)) {
1188 // Swapped
1189 assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
1190 IVOperIdx = 1;
1191 Pred = ICmpInst::getSwappedPredicate(Pred);
Dan Gohman5867a562010-04-13 01:46:36 +00001192 }
Andrew Trick81683ed2011-05-12 00:04:28 +00001193
1194 // Get the SCEVs for the ICmp operands.
1195 const SCEV *S = SE->getSCEV(ICmp->getOperand(IVOperIdx));
1196 const SCEV *X = SE->getSCEV(ICmp->getOperand(1 - IVOperIdx));
1197
1198 // Simplify unnecessary loops away.
1199 const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
1200 S = SE->getSCEVAtScope(S, ICmpLoop);
1201 X = SE->getSCEVAtScope(X, ICmpLoop);
1202
1203 // If the condition is always true or always false, replace it with
1204 // a constant value.
1205 if (SE->isKnownPredicate(Pred, S, X))
1206 ICmp->replaceAllUsesWith(ConstantInt::getTrue(ICmp->getContext()));
1207 else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X))
1208 ICmp->replaceAllUsesWith(ConstantInt::getFalse(ICmp->getContext()));
1209 else
1210 return;
1211
1212 DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
Andrew Trickeb3c36e2011-05-25 04:42:22 +00001213 ++NumElimCmp;
Andrew Trickb75279c2011-05-20 03:37:48 +00001214 Changed = true;
Andrew Trick81683ed2011-05-12 00:04:28 +00001215 DeadInsts.push_back(ICmp);
1216}
1217
1218void IndVarSimplify::EliminateIVRemainder(BinaryOperator *Rem,
1219 Value *IVOperand,
Andrew Trickfc4ccb22011-06-21 15:43:52 +00001220 bool IsSigned) {
Andrew Trick81683ed2011-05-12 00:04:28 +00001221 // We're only interested in the case where we know something about
1222 // the numerator.
1223 if (IVOperand != Rem->getOperand(0))
1224 return;
1225
1226 // Get the SCEVs for the ICmp operands.
1227 const SCEV *S = SE->getSCEV(Rem->getOperand(0));
1228 const SCEV *X = SE->getSCEV(Rem->getOperand(1));
1229
1230 // Simplify unnecessary loops away.
1231 const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent());
1232 S = SE->getSCEVAtScope(S, ICmpLoop);
1233 X = SE->getSCEVAtScope(X, ICmpLoop);
1234
1235 // i % n --> i if i is in [0,n).
Andrew Trickb75279c2011-05-20 03:37:48 +00001236 if ((!IsSigned || SE->isKnownNonNegative(S)) &&
1237 SE->isKnownPredicate(IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
Andrew Trick81683ed2011-05-12 00:04:28 +00001238 S, X))
1239 Rem->replaceAllUsesWith(Rem->getOperand(0));
1240 else {
1241 // (i+1) % n --> (i+1)==n?0:(i+1) if i is in [0,n).
1242 const SCEV *LessOne =
1243 SE->getMinusSCEV(S, SE->getConstant(S->getType(), 1));
Andrew Trickb75279c2011-05-20 03:37:48 +00001244 if (IsSigned && !SE->isKnownNonNegative(LessOne))
Andrew Trick81683ed2011-05-12 00:04:28 +00001245 return;
1246
Andrew Trickb75279c2011-05-20 03:37:48 +00001247 if (!SE->isKnownPredicate(IsSigned ?
Andrew Trick81683ed2011-05-12 00:04:28 +00001248 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
1249 LessOne, X))
1250 return;
1251
1252 ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ,
1253 Rem->getOperand(0), Rem->getOperand(1),
1254 "tmp");
1255 SelectInst *Sel =
1256 SelectInst::Create(ICmp,
1257 ConstantInt::get(Rem->getType(), 0),
1258 Rem->getOperand(0), "tmp", Rem);
1259 Rem->replaceAllUsesWith(Sel);
1260 }
1261
1262 // Inform IVUsers about the new users.
Andrew Trick69d44522011-06-21 03:22:38 +00001263 if (IU) {
1264 if (Instruction *I = dyn_cast<Instruction>(Rem->getOperand(0)))
Andrew Trickfc4ccb22011-06-21 15:43:52 +00001265 IU->AddUsersIfInteresting(I);
Andrew Trick69d44522011-06-21 03:22:38 +00001266 }
Andrew Trick81683ed2011-05-12 00:04:28 +00001267 DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
Andrew Trickeb3c36e2011-05-25 04:42:22 +00001268 ++NumElimRem;
Andrew Trickb75279c2011-05-20 03:37:48 +00001269 Changed = true;
Andrew Trick81683ed2011-05-12 00:04:28 +00001270 DeadInsts.push_back(Rem);
Dan Gohman5867a562010-04-13 01:46:36 +00001271}
1272
Andrew Trick69d44522011-06-21 03:22:38 +00001273/// EliminateIVUser - Eliminate an operation that consumes a simple IV and has
1274/// no observable side-effect given the range of IV values.
1275bool IndVarSimplify::EliminateIVUser(Instruction *UseInst,
1276 Instruction *IVOperand) {
1277 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
1278 EliminateIVComparison(ICmp, IVOperand);
1279 return true;
1280 }
1281 if (BinaryOperator *Rem = dyn_cast<BinaryOperator>(UseInst)) {
1282 bool IsSigned = Rem->getOpcode() == Instruction::SRem;
1283 if (IsSigned || Rem->getOpcode() == Instruction::URem) {
Andrew Trickfc4ccb22011-06-21 15:43:52 +00001284 EliminateIVRemainder(Rem, IVOperand, IsSigned);
Andrew Trick69d44522011-06-21 03:22:38 +00001285 return true;
1286 }
1287 }
1288
1289 // Eliminate any operation that SCEV can prove is an identity function.
1290 if (!SE->isSCEVable(UseInst->getType()) ||
Andrew Trickefe2b192011-06-29 03:13:40 +00001291 (UseInst->getType() != IVOperand->getType()) ||
Andrew Trick69d44522011-06-21 03:22:38 +00001292 (SE->getSCEV(UseInst) != SE->getSCEV(IVOperand)))
1293 return false;
1294
Andrew Trick69d44522011-06-21 03:22:38 +00001295 DEBUG(dbgs() << "INDVARS: Eliminated identity: " << *UseInst << '\n');
Andrew Trickcc686052011-06-30 01:27:23 +00001296
1297 UseInst->replaceAllUsesWith(IVOperand);
Andrew Trick69d44522011-06-21 03:22:38 +00001298 ++NumElimIdentity;
1299 Changed = true;
1300 DeadInsts.push_back(UseInst);
1301 return true;
1302}
1303
Andrew Trick6d45a012011-08-06 07:00:37 +00001304/// FoldIVUser - Fold an IV operand into its use. This removes increments of an
1305/// aligned IV when used by a instruction that ignores the low bits.
1306bool IndVarSimplify::FoldIVUser(Instruction *UseInst, Instruction *IVOperand) {
1307 Value *IVSrc = 0;
1308 unsigned OperIdx = 0;
1309 const SCEV *FoldedExpr = 0;
1310 switch (UseInst->getOpcode()) {
1311 default:
1312 return false;
1313 case Instruction::UDiv:
1314 case Instruction::LShr:
1315 // We're only interested in the case where we know something about
1316 // the numerator and have a constant denominator.
1317 if (IVOperand != UseInst->getOperand(OperIdx) ||
1318 !isa<ConstantInt>(UseInst->getOperand(1)))
1319 return false;
1320
1321 // Attempt to fold a binary operator with constant operand.
1322 // e.g. ((I + 1) >> 2) => I >> 2
1323 if (IVOperand->getNumOperands() != 2 ||
1324 !isa<ConstantInt>(IVOperand->getOperand(1)))
1325 return false;
1326
1327 IVSrc = IVOperand->getOperand(0);
1328 // IVSrc must be the (SCEVable) IV, since the other operand is const.
1329 assert(SE->isSCEVable(IVSrc->getType()) && "Expect SCEVable IV operand");
1330
1331 ConstantInt *D = cast<ConstantInt>(UseInst->getOperand(1));
1332 if (UseInst->getOpcode() == Instruction::LShr) {
1333 // Get a constant for the divisor. See createSCEV.
1334 uint32_t BitWidth = cast<IntegerType>(UseInst->getType())->getBitWidth();
1335 if (D->getValue().uge(BitWidth))
1336 return false;
1337
1338 D = ConstantInt::get(UseInst->getContext(),
1339 APInt(BitWidth, 1).shl(D->getZExtValue()));
1340 }
1341 FoldedExpr = SE->getUDivExpr(SE->getSCEV(IVSrc), SE->getSCEV(D));
1342 }
1343 // We have something that might fold it's operand. Compare SCEVs.
1344 if (!SE->isSCEVable(UseInst->getType()))
1345 return false;
1346
1347 // Bypass the operand if SCEV can prove it has no effect.
1348 if (SE->getSCEV(UseInst) != FoldedExpr)
1349 return false;
1350
1351 DEBUG(dbgs() << "INDVARS: Eliminated IV operand: " << *IVOperand
1352 << " -> " << *UseInst << '\n');
1353
1354 UseInst->setOperand(OperIdx, IVSrc);
1355 assert(SE->getSCEV(UseInst) == FoldedExpr && "bad SCEV with folded oper");
1356
1357 ++NumElimOperand;
1358 Changed = true;
1359 if (IVOperand->use_empty())
1360 DeadInsts.push_back(IVOperand);
1361 return true;
1362}
1363
Andrew Trick69d44522011-06-21 03:22:38 +00001364/// pushIVUsers - Add all uses of Def to the current IV's worklist.
1365///
Andrew Trick8a3c39c2011-06-28 02:49:20 +00001366static void pushIVUsers(
1367 Instruction *Def,
1368 SmallPtrSet<Instruction*,16> &Simplified,
1369 SmallVectorImpl< std::pair<Instruction*,Instruction*> > &SimpleIVUsers) {
Andrew Trick69d44522011-06-21 03:22:38 +00001370
1371 for (Value::use_iterator UI = Def->use_begin(), E = Def->use_end();
1372 UI != E; ++UI) {
1373 Instruction *User = cast<Instruction>(*UI);
1374
1375 // Avoid infinite or exponential worklist processing.
1376 // Also ensure unique worklist users.
Andrew Trickcc686052011-06-30 01:27:23 +00001377 // If Def is a LoopPhi, it may not be in the Simplified set, so check for
1378 // self edges first.
1379 if (User != Def && Simplified.insert(User))
Andrew Trick69d44522011-06-21 03:22:38 +00001380 SimpleIVUsers.push_back(std::make_pair(User, Def));
1381 }
1382}
1383
1384/// isSimpleIVUser - Return true if this instruction generates a simple SCEV
1385/// expression in terms of that IV.
1386///
1387/// This is similar to IVUsers' isInsteresting() but processes each instruction
1388/// non-recursively when the operand is already known to be a simpleIVUser.
1389///
Andrew Trickcdc22972011-07-12 00:08:50 +00001390static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE) {
Andrew Trick69d44522011-06-21 03:22:38 +00001391 if (!SE->isSCEVable(I->getType()))
1392 return false;
1393
1394 // Get the symbolic expression for this instruction.
1395 const SCEV *S = SE->getSCEV(I);
1396
1397 // Only consider affine recurrences.
1398 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S);
1399 if (AR && AR->getLoop() == L)
1400 return true;
1401
1402 return false;
1403}
1404
1405/// SimplifyIVUsersNoRewrite - Iteratively perform simplification on a worklist
1406/// of IV users. Each successive simplification may push more users which may
1407/// themselves be candidates for simplification.
1408///
1409/// The "NoRewrite" algorithm does not require IVUsers analysis. Instead, it
1410/// simplifies instructions in-place during analysis. Rather than rewriting
1411/// induction variables bottom-up from their users, it transforms a chain of
1412/// IVUsers top-down, updating the IR only when it encouters a clear
1413/// optimization opportunitiy. A SCEVExpander "Rewriter" instance is still
1414/// needed, but only used to generate a new IV (phi) of wider type for sign/zero
1415/// extend elimination.
1416///
1417/// Once DisableIVRewrite is default, LSR will be the only client of IVUsers.
1418///
1419void IndVarSimplify::SimplifyIVUsersNoRewrite(Loop *L, SCEVExpander &Rewriter) {
Andrew Trick8a3c39c2011-06-28 02:49:20 +00001420 std::map<PHINode *, WideIVInfo> WideIVMap;
1421
Andrew Trick69d44522011-06-21 03:22:38 +00001422 SmallVector<PHINode*, 8> LoopPhis;
1423 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
1424 LoopPhis.push_back(cast<PHINode>(I));
1425 }
Andrew Trick8a3c39c2011-06-28 02:49:20 +00001426 // Each round of simplification iterates through the SimplifyIVUsers worklist
1427 // for all current phis, then determines whether any IVs can be
1428 // widened. Widening adds new phis to LoopPhis, inducing another round of
1429 // simplification on the wide IVs.
Andrew Trick69d44522011-06-21 03:22:38 +00001430 while (!LoopPhis.empty()) {
Andrew Trick8a3c39c2011-06-28 02:49:20 +00001431 // Evaluate as many IV expressions as possible before widening any IVs. This
Andrew Trick4426f5b2011-06-28 16:45:04 +00001432 // forces SCEV to set no-wrap flags before evaluating sign/zero
Andrew Trick8a3c39c2011-06-28 02:49:20 +00001433 // extension. The first time SCEV attempts to normalize sign/zero extension,
1434 // the result becomes final. So for the most predictable results, we delay
1435 // evaluation of sign/zero extend evaluation until needed, and avoid running
1436 // other SCEV based analysis prior to SimplifyIVUsersNoRewrite.
1437 do {
1438 PHINode *CurrIV = LoopPhis.pop_back_val();
Andrew Trick69d44522011-06-21 03:22:38 +00001439
Andrew Trick8a3c39c2011-06-28 02:49:20 +00001440 // Information about sign/zero extensions of CurrIV.
1441 WideIVInfo WI;
Andrew Trick69d44522011-06-21 03:22:38 +00001442
Andrew Trick8a3c39c2011-06-28 02:49:20 +00001443 // Instructions processed by SimplifyIVUsers for CurrIV.
1444 SmallPtrSet<Instruction*,16> Simplified;
Andrew Trick69d44522011-06-21 03:22:38 +00001445
Andrew Trick32390552011-07-06 20:50:43 +00001446 // Use-def pairs if IV users waiting to be processed for CurrIV.
Andrew Trick8a3c39c2011-06-28 02:49:20 +00001447 SmallVector<std::pair<Instruction*, Instruction*>, 8> SimpleIVUsers;
Andrew Trick69d44522011-06-21 03:22:38 +00001448
Andrew Trickcc686052011-06-30 01:27:23 +00001449 // Push users of the current LoopPhi. In rare cases, pushIVUsers may be
1450 // called multiple times for the same LoopPhi. This is the proper thing to
1451 // do for loop header phis that use each other.
Andrew Trick8a3c39c2011-06-28 02:49:20 +00001452 pushIVUsers(CurrIV, Simplified, SimpleIVUsers);
1453
1454 while (!SimpleIVUsers.empty()) {
Andrew Trickcd3e8cb2011-07-21 17:37:39 +00001455 std::pair<Instruction*, Instruction*> UseOper =
1456 SimpleIVUsers.pop_back_val();
Andrew Trickefe89ad2011-06-30 19:02:17 +00001457 // Bypass back edges to avoid extra work.
Andrew Trickcd3e8cb2011-07-21 17:37:39 +00001458 if (UseOper.first == CurrIV) continue;
Andrew Trick8a3c39c2011-06-28 02:49:20 +00001459
Andrew Trick6d45a012011-08-06 07:00:37 +00001460 FoldIVUser(UseOper.first, UseOper.second);
1461
Andrew Trickcd3e8cb2011-07-21 17:37:39 +00001462 if (EliminateIVUser(UseOper.first, UseOper.second)) {
1463 pushIVUsers(UseOper.second, Simplified, SimpleIVUsers);
Andrew Trick8a3c39c2011-06-28 02:49:20 +00001464 continue;
Andrew Trick69d44522011-06-21 03:22:38 +00001465 }
Andrew Trickcd3e8cb2011-07-21 17:37:39 +00001466 if (CastInst *Cast = dyn_cast<CastInst>(UseOper.first)) {
Andrew Trick8a3c39c2011-06-28 02:49:20 +00001467 bool IsSigned = Cast->getOpcode() == Instruction::SExt;
1468 if (IsSigned || Cast->getOpcode() == Instruction::ZExt) {
1469 CollectExtend(Cast, IsSigned, WI, SE, TD);
1470 }
1471 continue;
1472 }
Andrew Trickcd3e8cb2011-07-21 17:37:39 +00001473 if (isSimpleIVUser(UseOper.first, L, SE)) {
1474 pushIVUsers(UseOper.first, Simplified, SimpleIVUsers);
Andrew Trick8a3c39c2011-06-28 02:49:20 +00001475 }
Andrew Trick69d44522011-06-21 03:22:38 +00001476 }
Andrew Trick8a3c39c2011-06-28 02:49:20 +00001477 if (WI.WidestNativeType) {
1478 WideIVMap[CurrIV] = WI;
Andrew Trick69d44522011-06-21 03:22:38 +00001479 }
Andrew Trick8a3c39c2011-06-28 02:49:20 +00001480 } while(!LoopPhis.empty());
1481
1482 for (std::map<PHINode *, WideIVInfo>::const_iterator I = WideIVMap.begin(),
1483 E = WideIVMap.end(); I != E; ++I) {
1484 WidenIV Widener(I->first, I->second, LI, SE, DT, DeadInsts);
Andrew Trick69d44522011-06-21 03:22:38 +00001485 if (PHINode *WidePhi = Widener.CreateWideIV(Rewriter)) {
1486 Changed = true;
1487 LoopPhis.push_back(WidePhi);
1488 }
1489 }
Andrew Trick8a3c39c2011-06-28 02:49:20 +00001490 WideIVMap.clear();
Andrew Trick69d44522011-06-21 03:22:38 +00001491 }
1492}
1493
Andrew Trick32390552011-07-06 20:50:43 +00001494/// SimplifyCongruentIVs - Check for congruent phis in this loop header and
1495/// populate ExprToIVMap for use later.
1496///
1497void IndVarSimplify::SimplifyCongruentIVs(Loop *L) {
Andrew Trick9ea55dc2011-07-16 01:06:48 +00001498 DenseMap<const SCEV *, PHINode *> ExprToIVMap;
Andrew Trick32390552011-07-06 20:50:43 +00001499 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
1500 PHINode *Phi = cast<PHINode>(I);
Andrew Trickcdc22972011-07-12 00:08:50 +00001501 if (!SE->isSCEVable(Phi->getType()))
1502 continue;
1503
Andrew Trick32390552011-07-06 20:50:43 +00001504 const SCEV *S = SE->getSCEV(Phi);
Chris Lattner5cf753c2011-07-21 06:21:31 +00001505 std::pair<DenseMap<const SCEV *, PHINode *>::const_iterator, bool> Tmp =
1506 ExprToIVMap.insert(std::make_pair(S, Phi));
1507 if (Tmp.second)
Andrew Trick32390552011-07-06 20:50:43 +00001508 continue;
Chris Lattner5cf753c2011-07-21 06:21:31 +00001509 PHINode *OrigPhi = Tmp.first->second;
Andrew Trickc5dd3e92011-07-20 02:08:58 +00001510
1511 // If one phi derives from the other via GEPs, types may differ.
1512 if (OrigPhi->getType() != Phi->getType())
1513 continue;
1514
Andrew Trick32390552011-07-06 20:50:43 +00001515 // Replacing the congruent phi is sufficient because acyclic redundancy
1516 // elimination, CSE/GVN, should handle the rest. However, once SCEV proves
1517 // that a phi is congruent, it's almost certain to be the head of an IV
1518 // user cycle that is isomorphic with the original phi. So it's worth
1519 // eagerly cleaning up the common case of a single IV increment.
1520 if (BasicBlock *LatchBlock = L->getLoopLatch()) {
1521 Instruction *OrigInc =
1522 cast<Instruction>(OrigPhi->getIncomingValueForBlock(LatchBlock));
1523 Instruction *IsomorphicInc =
1524 cast<Instruction>(Phi->getIncomingValueForBlock(LatchBlock));
1525 if (OrigInc != IsomorphicInc &&
Andrew Trickc5dd3e92011-07-20 02:08:58 +00001526 OrigInc->getType() == IsomorphicInc->getType() &&
Andrew Trick32390552011-07-06 20:50:43 +00001527 SE->getSCEV(OrigInc) == SE->getSCEV(IsomorphicInc) &&
1528 HoistStep(OrigInc, IsomorphicInc, DT)) {
1529 DEBUG(dbgs() << "INDVARS: Eliminated congruent iv.inc: "
1530 << *IsomorphicInc << '\n');
1531 IsomorphicInc->replaceAllUsesWith(OrigInc);
1532 DeadInsts.push_back(IsomorphicInc);
1533 }
1534 }
1535 DEBUG(dbgs() << "INDVARS: Eliminated congruent iv: " << *Phi << '\n');
1536 ++NumElimIV;
1537 Phi->replaceAllUsesWith(OrigPhi);
1538 DeadInsts.push_back(Phi);
1539 }
1540}
1541
Andrew Trickcdc22972011-07-12 00:08:50 +00001542//===----------------------------------------------------------------------===//
1543// LinearFunctionTestReplace and its kin. Rewrite the loop exit condition.
1544//===----------------------------------------------------------------------===//
1545
Andrew Tricka27d8b12011-07-18 18:21:35 +00001546// Check for expressions that ScalarEvolution generates to compute
1547// BackedgeTakenInfo. If these expressions have not been reduced, then expanding
1548// them may incur additional cost (albeit in the loop preheader).
1549static bool isHighCostExpansion(const SCEV *S, BranchInst *BI,
1550 ScalarEvolution *SE) {
1551 // If the backedge-taken count is a UDiv, it's very likely a UDiv that
1552 // ScalarEvolution's HowFarToZero or HowManyLessThans produced to compute a
1553 // precise expression, rather than a UDiv from the user's code. If we can't
1554 // find a UDiv in the code with some simple searching, assume the former and
1555 // forego rewriting the loop.
1556 if (isa<SCEVUDivExpr>(S)) {
1557 ICmpInst *OrigCond = dyn_cast<ICmpInst>(BI->getCondition());
1558 if (!OrigCond) return true;
1559 const SCEV *R = SE->getSCEV(OrigCond->getOperand(1));
1560 R = SE->getMinusSCEV(R, SE->getConstant(R->getType(), 1));
1561 if (R != S) {
1562 const SCEV *L = SE->getSCEV(OrigCond->getOperand(0));
1563 L = SE->getMinusSCEV(L, SE->getConstant(L->getType(), 1));
1564 if (L != S)
1565 return true;
1566 }
1567 }
1568
Andrew Trick7da24172011-07-18 20:32:31 +00001569 if (!DisableIVRewrite || ForceLFTR)
Andrew Tricka27d8b12011-07-18 18:21:35 +00001570 return false;
1571
1572 // Recurse past add expressions, which commonly occur in the
1573 // BackedgeTakenCount. They may already exist in program code, and if not,
1574 // they are not too expensive rematerialize.
1575 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
1576 for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
1577 I != E; ++I) {
1578 if (isHighCostExpansion(*I, BI, SE))
1579 return true;
1580 }
1581 return false;
1582 }
1583
1584 // HowManyLessThans uses a Max expression whenever the loop is not guarded by
1585 // the exit condition.
1586 if (isa<SCEVSMaxExpr>(S) || isa<SCEVUMaxExpr>(S))
1587 return true;
1588
1589 // If we haven't recognized an expensive SCEV patter, assume its an expression
1590 // produced by program code.
1591 return false;
1592}
1593
Andrew Trickcdc22972011-07-12 00:08:50 +00001594/// canExpandBackedgeTakenCount - Return true if this loop's backedge taken
1595/// count expression can be safely and cheaply expanded into an instruction
1596/// sequence that can be used by LinearFunctionTestReplace.
1597static bool canExpandBackedgeTakenCount(Loop *L, ScalarEvolution *SE) {
1598 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
1599 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount) ||
1600 BackedgeTakenCount->isZero())
1601 return false;
1602
1603 if (!L->getExitingBlock())
1604 return false;
1605
1606 // Can't rewrite non-branch yet.
1607 BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator());
1608 if (!BI)
1609 return false;
1610
Andrew Tricka27d8b12011-07-18 18:21:35 +00001611 if (isHighCostExpansion(BackedgeTakenCount, BI, SE))
1612 return false;
1613
Andrew Trickcdc22972011-07-12 00:08:50 +00001614 return true;
1615}
1616
1617/// getBackedgeIVType - Get the widest type used by the loop test after peeking
1618/// through Truncs.
1619///
Andrew Trick7da24172011-07-18 20:32:31 +00001620/// TODO: Unnecessary when ForceLFTR is removed.
Chris Lattner229907c2011-07-18 04:54:35 +00001621static Type *getBackedgeIVType(Loop *L) {
Andrew Trickcdc22972011-07-12 00:08:50 +00001622 if (!L->getExitingBlock())
1623 return 0;
1624
1625 // Can't rewrite non-branch yet.
1626 BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator());
1627 if (!BI)
1628 return 0;
1629
1630 ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition());
1631 if (!Cond)
1632 return 0;
1633
Chris Lattner229907c2011-07-18 04:54:35 +00001634 Type *Ty = 0;
Andrew Trickcdc22972011-07-12 00:08:50 +00001635 for(User::op_iterator OI = Cond->op_begin(), OE = Cond->op_end();
1636 OI != OE; ++OI) {
1637 assert((!Ty || Ty == (*OI)->getType()) && "bad icmp operand types");
1638 TruncInst *Trunc = dyn_cast<TruncInst>(*OI);
1639 if (!Trunc)
1640 continue;
1641
1642 return Trunc->getSrcTy();
1643 }
1644 return Ty;
1645}
1646
Andrew Trick7da24172011-07-18 20:32:31 +00001647/// isLoopInvariant - Perform a quick domtree based check for loop invariance
1648/// assuming that V is used within the loop. LoopInfo::isLoopInvariant() seems
1649/// gratuitous for this purpose.
1650static bool isLoopInvariant(Value *V, Loop *L, DominatorTree *DT) {
1651 Instruction *Inst = dyn_cast<Instruction>(V);
1652 if (!Inst)
1653 return true;
1654
1655 return DT->properlyDominates(Inst->getParent(), L->getHeader());
1656}
1657
1658/// getLoopPhiForCounter - Return the loop header phi IFF IncV adds a loop
1659/// invariant value to the phi.
1660static PHINode *getLoopPhiForCounter(Value *IncV, Loop *L, DominatorTree *DT) {
1661 Instruction *IncI = dyn_cast<Instruction>(IncV);
1662 if (!IncI)
1663 return 0;
1664
1665 switch (IncI->getOpcode()) {
1666 case Instruction::Add:
1667 case Instruction::Sub:
1668 break;
1669 case Instruction::GetElementPtr:
1670 // An IV counter must preserve its type.
1671 if (IncI->getNumOperands() == 2)
1672 break;
1673 default:
1674 return 0;
1675 }
1676
1677 PHINode *Phi = dyn_cast<PHINode>(IncI->getOperand(0));
1678 if (Phi && Phi->getParent() == L->getHeader()) {
1679 if (isLoopInvariant(IncI->getOperand(1), L, DT))
1680 return Phi;
1681 return 0;
1682 }
1683 if (IncI->getOpcode() == Instruction::GetElementPtr)
1684 return 0;
1685
1686 // Allow add/sub to be commuted.
1687 Phi = dyn_cast<PHINode>(IncI->getOperand(1));
1688 if (Phi && Phi->getParent() == L->getHeader()) {
1689 if (isLoopInvariant(IncI->getOperand(0), L, DT))
1690 return Phi;
1691 }
1692 return 0;
1693}
1694
1695/// needsLFTR - LinearFunctionTestReplace policy. Return true unless we can show
1696/// that the current exit test is already sufficiently canonical.
1697static bool needsLFTR(Loop *L, DominatorTree *DT) {
1698 assert(L->getExitingBlock() && "expected loop exit");
1699
1700 BasicBlock *LatchBlock = L->getLoopLatch();
1701 // Don't bother with LFTR if the loop is not properly simplified.
1702 if (!LatchBlock)
1703 return false;
1704
1705 BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator());
1706 assert(BI && "expected exit branch");
1707
1708 // Do LFTR to simplify the exit condition to an ICMP.
1709 ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition());
1710 if (!Cond)
1711 return true;
1712
1713 // Do LFTR to simplify the exit ICMP to EQ/NE
1714 ICmpInst::Predicate Pred = Cond->getPredicate();
1715 if (Pred != ICmpInst::ICMP_NE && Pred != ICmpInst::ICMP_EQ)
1716 return true;
1717
1718 // Look for a loop invariant RHS
1719 Value *LHS = Cond->getOperand(0);
1720 Value *RHS = Cond->getOperand(1);
1721 if (!isLoopInvariant(RHS, L, DT)) {
1722 if (!isLoopInvariant(LHS, L, DT))
1723 return true;
1724 std::swap(LHS, RHS);
1725 }
1726 // Look for a simple IV counter LHS
1727 PHINode *Phi = dyn_cast<PHINode>(LHS);
1728 if (!Phi)
1729 Phi = getLoopPhiForCounter(LHS, L, DT);
1730
1731 if (!Phi)
1732 return true;
1733
1734 // Do LFTR if the exit condition's IV is *not* a simple counter.
1735 Value *IncV = Phi->getIncomingValueForBlock(L->getLoopLatch());
1736 return Phi != getLoopPhiForCounter(IncV, L, DT);
1737}
1738
1739/// AlmostDeadIV - Return true if this IV has any uses other than the (soon to
1740/// be rewritten) loop exit test.
1741static bool AlmostDeadIV(PHINode *Phi, BasicBlock *LatchBlock, Value *Cond) {
1742 int LatchIdx = Phi->getBasicBlockIndex(LatchBlock);
1743 Value *IncV = Phi->getIncomingValue(LatchIdx);
1744
1745 for (Value::use_iterator UI = Phi->use_begin(), UE = Phi->use_end();
1746 UI != UE; ++UI) {
1747 if (*UI != Cond && *UI != IncV) return false;
1748 }
1749
1750 for (Value::use_iterator UI = IncV->use_begin(), UE = IncV->use_end();
1751 UI != UE; ++UI) {
1752 if (*UI != Cond && *UI != Phi) return false;
1753 }
1754 return true;
1755}
1756
1757/// FindLoopCounter - Find an affine IV in canonical form.
1758///
1759/// FIXME: Accept -1 stride and set IVLimit = IVInit - BECount
1760///
1761/// FIXME: Accept non-unit stride as long as SCEV can reduce BECount * Stride.
1762/// This is difficult in general for SCEV because of potential overflow. But we
1763/// could at least handle constant BECounts.
1764static PHINode *
1765FindLoopCounter(Loop *L, const SCEV *BECount,
1766 ScalarEvolution *SE, DominatorTree *DT, const TargetData *TD) {
1767 // I'm not sure how BECount could be a pointer type, but we definitely don't
1768 // want to LFTR that.
1769 if (BECount->getType()->isPointerTy())
1770 return 0;
1771
1772 uint64_t BCWidth = SE->getTypeSizeInBits(BECount->getType());
1773
1774 Value *Cond =
1775 cast<BranchInst>(L->getExitingBlock()->getTerminator())->getCondition();
1776
1777 // Loop over all of the PHI nodes, looking for a simple counter.
1778 PHINode *BestPhi = 0;
1779 const SCEV *BestInit = 0;
1780 BasicBlock *LatchBlock = L->getLoopLatch();
1781 assert(LatchBlock && "needsLFTR should guarantee a loop latch");
1782
1783 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
1784 PHINode *Phi = cast<PHINode>(I);
1785 if (!SE->isSCEVable(Phi->getType()))
1786 continue;
1787
1788 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Phi));
1789 if (!AR || AR->getLoop() != L || !AR->isAffine())
1790 continue;
1791
1792 // AR may be a pointer type, while BECount is an integer type.
1793 // AR may be wider than BECount. With eq/ne tests overflow is immaterial.
1794 // AR may not be a narrower type, or we may never exit.
1795 uint64_t PhiWidth = SE->getTypeSizeInBits(AR->getType());
1796 if (PhiWidth < BCWidth || (TD && !TD->isLegalInteger(PhiWidth)))
1797 continue;
1798
1799 const SCEV *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*SE));
1800 if (!Step || !Step->isOne())
1801 continue;
1802
1803 int LatchIdx = Phi->getBasicBlockIndex(LatchBlock);
1804 Value *IncV = Phi->getIncomingValue(LatchIdx);
1805 if (getLoopPhiForCounter(IncV, L, DT) != Phi)
1806 continue;
1807
1808 const SCEV *Init = AR->getStart();
1809
1810 if (BestPhi && !AlmostDeadIV(BestPhi, LatchBlock, Cond)) {
1811 // Don't force a live loop counter if another IV can be used.
1812 if (AlmostDeadIV(Phi, LatchBlock, Cond))
1813 continue;
1814
1815 // Prefer to count-from-zero. This is a more "canonical" counter form. It
1816 // also prefers integer to pointer IVs.
1817 if (BestInit->isZero() != Init->isZero()) {
1818 if (BestInit->isZero())
1819 continue;
1820 }
1821 // If two IVs both count from zero or both count from nonzero then the
1822 // narrower is likely a dead phi that has been widened. Use the wider phi
1823 // to allow the other to be eliminated.
1824 if (PhiWidth <= SE->getTypeSizeInBits(BestPhi->getType()))
1825 continue;
1826 }
1827 BestPhi = Phi;
1828 BestInit = Init;
1829 }
1830 return BestPhi;
1831}
1832
Andrew Trickcdc22972011-07-12 00:08:50 +00001833/// LinearFunctionTestReplace - This method rewrites the exit condition of the
1834/// loop to be a canonical != comparison against the incremented loop induction
1835/// variable. This pass is able to rewrite the exit tests of any loop where the
1836/// SCEV analysis can determine a loop-invariant trip count of the loop, which
1837/// is actually a much broader range than just linear tests.
Andrew Trick7da24172011-07-18 20:32:31 +00001838Value *IndVarSimplify::
Andrew Trickcdc22972011-07-12 00:08:50 +00001839LinearFunctionTestReplace(Loop *L,
1840 const SCEV *BackedgeTakenCount,
1841 PHINode *IndVar,
1842 SCEVExpander &Rewriter) {
1843 assert(canExpandBackedgeTakenCount(L, SE) && "precondition");
1844 BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator());
1845
Andrew Trick7da24172011-07-18 20:32:31 +00001846 // In DisableIVRewrite mode, IndVar is not necessarily a canonical IV. In this
1847 // mode, LFTR can ignore IV overflow and truncate to the width of
1848 // BECount. This avoids materializing the add(zext(add)) expression.
1849 Type *CntTy = DisableIVRewrite ?
1850 BackedgeTakenCount->getType() : IndVar->getType();
1851
1852 const SCEV *IVLimit = BackedgeTakenCount;
1853
Andrew Trickcdc22972011-07-12 00:08:50 +00001854 // If the exiting block is not the same as the backedge block, we must compare
1855 // against the preincremented value, otherwise we prefer to compare against
1856 // the post-incremented value.
1857 Value *CmpIndVar;
Andrew Trickcdc22972011-07-12 00:08:50 +00001858 if (L->getExitingBlock() == L->getLoopLatch()) {
1859 // Add one to the "backedge-taken" count to get the trip count.
1860 // If this addition may overflow, we have to be more pessimistic and
1861 // cast the induction variable before doing the add.
Andrew Trickcdc22972011-07-12 00:08:50 +00001862 const SCEV *N =
Andrew Trick7da24172011-07-18 20:32:31 +00001863 SE->getAddExpr(IVLimit, SE->getConstant(IVLimit->getType(), 1));
1864 if (CntTy == IVLimit->getType())
1865 IVLimit = N;
1866 else {
1867 const SCEV *Zero = SE->getConstant(IVLimit->getType(), 0);
1868 if ((isa<SCEVConstant>(N) && !N->isZero()) ||
1869 SE->isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) {
1870 // No overflow. Cast the sum.
1871 IVLimit = SE->getTruncateOrZeroExtend(N, CntTy);
1872 } else {
1873 // Potential overflow. Cast before doing the add.
1874 IVLimit = SE->getTruncateOrZeroExtend(IVLimit, CntTy);
1875 IVLimit = SE->getAddExpr(IVLimit, SE->getConstant(CntTy, 1));
1876 }
Andrew Trickcdc22972011-07-12 00:08:50 +00001877 }
Andrew Trickcdc22972011-07-12 00:08:50 +00001878 // The BackedgeTaken expression contains the number of times that the
1879 // backedge branches to the loop header. This is one less than the
1880 // number of times the loop executes, so use the incremented indvar.
1881 CmpIndVar = IndVar->getIncomingValueForBlock(L->getExitingBlock());
1882 } else {
1883 // We have to use the preincremented value...
Andrew Trick7da24172011-07-18 20:32:31 +00001884 IVLimit = SE->getTruncateOrZeroExtend(IVLimit, CntTy);
Andrew Trickcdc22972011-07-12 00:08:50 +00001885 CmpIndVar = IndVar;
1886 }
1887
Andrew Trick7da24172011-07-18 20:32:31 +00001888 // For unit stride, IVLimit = Start + BECount with 2's complement overflow.
1889 // So for, non-zero start compute the IVLimit here.
1890 bool isPtrIV = false;
1891 Type *CmpTy = CntTy;
1892 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(IndVar));
1893 assert(AR && AR->getLoop() == L && AR->isAffine() && "bad loop counter");
1894 if (!AR->getStart()->isZero()) {
1895 assert(AR->getStepRecurrence(*SE)->isOne() && "only handles unit stride");
1896 const SCEV *IVInit = AR->getStart();
1897
1898 // For pointer types, sign extend BECount in order to materialize a GEP.
1899 // Note that for DisableIVRewrite, we never run SCEVExpander on a
1900 // pointer type, because we must preserve the existing GEPs. Instead we
1901 // directly generate a GEP later.
1902 if (IVInit->getType()->isPointerTy()) {
1903 isPtrIV = true;
1904 CmpTy = SE->getEffectiveSCEVType(IVInit->getType());
1905 IVLimit = SE->getTruncateOrSignExtend(IVLimit, CmpTy);
1906 }
1907 // For integer types, truncate the IV before computing IVInit + BECount.
1908 else {
1909 if (SE->getTypeSizeInBits(IVInit->getType())
1910 > SE->getTypeSizeInBits(CmpTy))
1911 IVInit = SE->getTruncateExpr(IVInit, CmpTy);
1912
1913 IVLimit = SE->getAddExpr(IVInit, IVLimit);
1914 }
1915 }
Andrew Trickcdc22972011-07-12 00:08:50 +00001916 // Expand the code for the iteration count.
Andrew Trick7da24172011-07-18 20:32:31 +00001917 IRBuilder<> Builder(BI);
1918
1919 assert(SE->isLoopInvariant(IVLimit, L) &&
Andrew Trickcdc22972011-07-12 00:08:50 +00001920 "Computed iteration count is not loop invariant!");
Andrew Trick7da24172011-07-18 20:32:31 +00001921 Value *ExitCnt = Rewriter.expandCodeFor(IVLimit, CmpTy, BI);
1922
1923 // Create a gep for IVInit + IVLimit from on an existing pointer base.
1924 assert(isPtrIV == IndVar->getType()->isPointerTy() &&
1925 "IndVar type must match IVInit type");
1926 if (isPtrIV) {
1927 Value *IVStart = IndVar->getIncomingValueForBlock(L->getLoopPreheader());
1928 assert(AR->getStart() == SE->getSCEV(IVStart) && "bad loop counter");
Andrew Trickc43b6762011-07-18 21:15:03 +00001929 assert(SE->getSizeOfExpr(
1930 cast<PointerType>(IVStart->getType())->getElementType())->isOne()
1931 && "unit stride pointer IV must be i8*");
Andrew Trick7da24172011-07-18 20:32:31 +00001932
1933 Builder.SetInsertPoint(L->getLoopPreheader()->getTerminator());
1934 ExitCnt = Builder.CreateGEP(IVStart, ExitCnt, "lftr.limit");
1935 Builder.SetInsertPoint(BI);
1936 }
Andrew Trickcdc22972011-07-12 00:08:50 +00001937
1938 // Insert a new icmp_ne or icmp_eq instruction before the branch.
Andrew Trick7da24172011-07-18 20:32:31 +00001939 ICmpInst::Predicate P;
Andrew Trickcdc22972011-07-12 00:08:50 +00001940 if (L->contains(BI->getSuccessor(0)))
Andrew Trick7da24172011-07-18 20:32:31 +00001941 P = ICmpInst::ICMP_NE;
Andrew Trickcdc22972011-07-12 00:08:50 +00001942 else
Andrew Trick7da24172011-07-18 20:32:31 +00001943 P = ICmpInst::ICMP_EQ;
Andrew Trickcdc22972011-07-12 00:08:50 +00001944
1945 DEBUG(dbgs() << "INDVARS: Rewriting loop exit condition to:\n"
1946 << " LHS:" << *CmpIndVar << '\n'
1947 << " op:\t"
Andrew Trick7da24172011-07-18 20:32:31 +00001948 << (P == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
1949 << " RHS:\t" << *ExitCnt << "\n"
1950 << " Expr:\t" << *IVLimit << "\n");
Andrew Trickcdc22972011-07-12 00:08:50 +00001951
Andrew Trick7da24172011-07-18 20:32:31 +00001952 if (SE->getTypeSizeInBits(CmpIndVar->getType())
1953 > SE->getTypeSizeInBits(CmpTy)) {
1954 CmpIndVar = Builder.CreateTrunc(CmpIndVar, CmpTy, "lftr.wideiv");
1955 }
1956
1957 Value *Cond = Builder.CreateICmp(P, CmpIndVar, ExitCnt, "exitcond");
Andrew Trickcdc22972011-07-12 00:08:50 +00001958 Value *OrigCond = BI->getCondition();
1959 // It's tempting to use replaceAllUsesWith here to fully replace the old
1960 // comparison, but that's not immediately safe, since users of the old
1961 // comparison may not be dominated by the new comparison. Instead, just
1962 // update the branch to use the new comparison; in the common case this
1963 // will make old comparison dead.
1964 BI->setCondition(Cond);
1965 DeadInsts.push_back(OrigCond);
1966
1967 ++NumLFTR;
1968 Changed = true;
1969 return Cond;
1970}
1971
1972//===----------------------------------------------------------------------===//
1973// SinkUnusedInvariants. A late subpass to cleanup loop preheaders.
1974//===----------------------------------------------------------------------===//
1975
1976/// If there's a single exit block, sink any loop-invariant values that
1977/// were defined in the preheader but not used inside the loop into the
1978/// exit block to reduce register pressure in the loop.
1979void IndVarSimplify::SinkUnusedInvariants(Loop *L) {
1980 BasicBlock *ExitBlock = L->getExitBlock();
1981 if (!ExitBlock) return;
1982
1983 BasicBlock *Preheader = L->getLoopPreheader();
1984 if (!Preheader) return;
1985
1986 Instruction *InsertPt = ExitBlock->getFirstNonPHI();
1987 BasicBlock::iterator I = Preheader->getTerminator();
1988 while (I != Preheader->begin()) {
1989 --I;
1990 // New instructions were inserted at the end of the preheader.
1991 if (isa<PHINode>(I))
1992 break;
1993
1994 // Don't move instructions which might have side effects, since the side
1995 // effects need to complete before instructions inside the loop. Also don't
1996 // move instructions which might read memory, since the loop may modify
1997 // memory. Note that it's okay if the instruction might have undefined
1998 // behavior: LoopSimplify guarantees that the preheader dominates the exit
1999 // block.
2000 if (I->mayHaveSideEffects() || I->mayReadFromMemory())
2001 continue;
2002
2003 // Skip debug info intrinsics.
2004 if (isa<DbgInfoIntrinsic>(I))
2005 continue;
2006
2007 // Don't sink static AllocaInsts out of the entry block, which would
2008 // turn them into dynamic allocas!
2009 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
2010 if (AI->isStaticAlloca())
2011 continue;
2012
2013 // Determine if there is a use in or before the loop (direct or
2014 // otherwise).
2015 bool UsedInLoop = false;
2016 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2017 UI != UE; ++UI) {
2018 User *U = *UI;
2019 BasicBlock *UseBB = cast<Instruction>(U)->getParent();
2020 if (PHINode *P = dyn_cast<PHINode>(U)) {
2021 unsigned i =
2022 PHINode::getIncomingValueNumForOperand(UI.getOperandNo());
2023 UseBB = P->getIncomingBlock(i);
2024 }
2025 if (UseBB == Preheader || L->contains(UseBB)) {
2026 UsedInLoop = true;
2027 break;
2028 }
2029 }
2030
2031 // If there is, the def must remain in the preheader.
2032 if (UsedInLoop)
2033 continue;
2034
2035 // Otherwise, sink it to the exit block.
2036 Instruction *ToMove = I;
2037 bool Done = false;
2038
2039 if (I != Preheader->begin()) {
2040 // Skip debug info intrinsics.
2041 do {
2042 --I;
2043 } while (isa<DbgInfoIntrinsic>(I) && I != Preheader->begin());
2044
2045 if (isa<DbgInfoIntrinsic>(I) && I == Preheader->begin())
2046 Done = true;
2047 } else {
2048 Done = true;
2049 }
2050
2051 ToMove->moveBefore(InsertPt);
2052 if (Done) break;
2053 InsertPt = ToMove;
2054 }
2055}
2056
2057//===----------------------------------------------------------------------===//
2058// IndVarSimplify driver. Manage several subpasses of IV simplification.
2059//===----------------------------------------------------------------------===//
2060
Dan Gohmaneb6be652009-02-12 22:19:27 +00002061bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
Dan Gohmanf3aea7a2010-06-18 01:35:11 +00002062 // If LoopSimplify form is not available, stay out of trouble. Some notes:
2063 // - LSR currently only supports LoopSimplify-form loops. Indvars'
2064 // canonicalization can be a pessimization without LSR to "clean up"
2065 // afterwards.
2066 // - We depend on having a preheader; in particular,
2067 // Loop::getCanonicalInductionVariable only supports loops with preheaders,
2068 // and we're in trouble if we can't find the induction variable even when
2069 // we've manually inserted one.
2070 if (!L->isLoopSimplifyForm())
2071 return false;
2072
Andrew Trick69d44522011-06-21 03:22:38 +00002073 if (!DisableIVRewrite)
2074 IU = &getAnalysis<IVUsers>();
Devang Patel2ac57e12007-03-07 06:39:01 +00002075 LI = &getAnalysis<LoopInfo>();
2076 SE = &getAnalysis<ScalarEvolution>();
Dan Gohmanfe174b62009-06-27 05:16:57 +00002077 DT = &getAnalysis<DominatorTree>();
Andrew Trick1abe2962011-05-04 02:10:13 +00002078 TD = getAnalysisIfAvailable<TargetData>();
2079
Andrew Trick87716c92011-03-17 23:51:11 +00002080 DeadInsts.clear();
Devang Patel2ac57e12007-03-07 06:39:01 +00002081 Changed = false;
Dan Gohman43300342009-02-17 20:49:49 +00002082
Dan Gohman0a40ad92009-04-16 03:18:22 +00002083 // If there are any floating-point recurrences, attempt to
Dan Gohman43300342009-02-17 20:49:49 +00002084 // transform them to use integer recurrences.
2085 RewriteNonIntegerIVs(L);
2086
Dan Gohmanaf752342009-07-07 17:06:11 +00002087 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
Chris Lattner1f7648e2007-03-04 01:00:28 +00002088
Dan Gohmandaafbe62009-06-26 22:53:46 +00002089 // Create a rewriter object which we'll use to transform the code with.
Andrew Trick411daa52011-06-28 05:07:32 +00002090 SCEVExpander Rewriter(*SE, "indvars");
Andrew Trick163b4a72011-06-27 23:17:44 +00002091
2092 // Eliminate redundant IV users.
Andrew Trick8a3c39c2011-06-28 02:49:20 +00002093 //
2094 // Simplification works best when run before other consumers of SCEV. We
2095 // attempt to avoid evaluating SCEVs for sign/zero extend operations until
2096 // other expressions involving loop IVs have been evaluated. This helps SCEV
Andrew Trick4426f5b2011-06-28 16:45:04 +00002097 // set no-wrap flags before normalizing sign/zero extension.
Andrew Trick163b4a72011-06-27 23:17:44 +00002098 if (DisableIVRewrite) {
Andrew Trick1abe2962011-05-04 02:10:13 +00002099 Rewriter.disableCanonicalMode();
Andrew Trick163b4a72011-06-27 23:17:44 +00002100 SimplifyIVUsersNoRewrite(L, Rewriter);
2101 }
Andrew Trick1abe2962011-05-04 02:10:13 +00002102
Chris Lattnere61b67d2004-04-02 20:24:31 +00002103 // Check to see if this loop has a computable loop-invariant execution count.
2104 // If so, this means that we can compute the final value of any expressions
2105 // that are recurrent in the loop, and substitute the exit values from the
2106 // loop into any instructions outside of the loop that use the final values of
2107 // the current expressions.
Chris Lattner0b18c1d2002-05-10 15:38:35 +00002108 //
Dan Gohman0bddac12009-02-24 18:55:53 +00002109 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount))
Dan Gohman8c16b382010-02-22 04:11:59 +00002110 RewriteLoopExitValues(L, Rewriter);
Chris Lattner476e6df2001-12-03 17:28:42 +00002111
Andrew Trickf44aadf2011-05-20 18:25:42 +00002112 // Eliminate redundant IV users.
Andrew Trick163b4a72011-06-27 23:17:44 +00002113 if (!DisableIVRewrite)
Andrew Trick69d44522011-06-21 03:22:38 +00002114 SimplifyIVUsers(Rewriter);
Dan Gohman5867a562010-04-13 01:46:36 +00002115
Andrew Trick9ea55dc2011-07-16 01:06:48 +00002116 // Eliminate redundant IV cycles.
Andrew Trick32390552011-07-06 20:50:43 +00002117 if (DisableIVRewrite)
2118 SimplifyCongruentIVs(L);
2119
Dan Gohmand76d71a2009-05-12 02:17:14 +00002120 // Compute the type of the largest recurrence expression, and decide whether
2121 // a canonical induction variable should be inserted.
Chris Lattner229907c2011-07-18 04:54:35 +00002122 Type *LargestType = 0;
Dan Gohmand76d71a2009-05-12 02:17:14 +00002123 bool NeedCannIV = false;
Andrew Trick7da24172011-07-18 20:32:31 +00002124 bool ReuseIVForExit = DisableIVRewrite && !ForceLFTR;
Andrew Trickeb3c36e2011-05-25 04:42:22 +00002125 bool ExpandBECount = canExpandBackedgeTakenCount(L, SE);
Andrew Trick7da24172011-07-18 20:32:31 +00002126 if (ExpandBECount && !ReuseIVForExit) {
Dan Gohmand76d71a2009-05-12 02:17:14 +00002127 // If we have a known trip count and a single exit block, we'll be
2128 // rewriting the loop exit test condition below, which requires a
2129 // canonical induction variable.
Andrew Trick38c4e342011-05-03 22:24:10 +00002130 NeedCannIV = true;
Chris Lattner229907c2011-07-18 04:54:35 +00002131 Type *Ty = BackedgeTakenCount->getType();
Andrew Trickeb3c36e2011-05-25 04:42:22 +00002132 if (DisableIVRewrite) {
2133 // In this mode, SimplifyIVUsers may have already widened the IV used by
2134 // the backedge test and inserted a Trunc on the compare's operand. Get
2135 // the wider type to avoid creating a redundant narrow IV only used by the
2136 // loop test.
2137 LargestType = getBackedgeIVType(L);
2138 }
Andrew Trick38c4e342011-05-03 22:24:10 +00002139 if (!LargestType ||
2140 SE->getTypeSizeInBits(Ty) >
2141 SE->getTypeSizeInBits(LargestType))
2142 LargestType = SE->getEffectiveSCEVType(Ty);
Chris Lattner885a6eb2004-04-17 18:08:33 +00002143 }
Andrew Trick1abe2962011-05-04 02:10:13 +00002144 if (!DisableIVRewrite) {
2145 for (IVUsers::const_iterator I = IU->begin(), E = IU->end(); I != E; ++I) {
2146 NeedCannIV = true;
Chris Lattner229907c2011-07-18 04:54:35 +00002147 Type *Ty =
Andrew Trick1abe2962011-05-04 02:10:13 +00002148 SE->getEffectiveSCEVType(I->getOperandValToReplace()->getType());
2149 if (!LargestType ||
2150 SE->getTypeSizeInBits(Ty) >
Dan Gohmanb397e1a2009-04-21 01:07:12 +00002151 SE->getTypeSizeInBits(LargestType))
Andrew Trick1abe2962011-05-04 02:10:13 +00002152 LargestType = Ty;
2153 }
Chris Lattner476e6df2001-12-03 17:28:42 +00002154 }
2155
Dan Gohman4a618822010-02-10 16:03:48 +00002156 // Now that we know the largest of the induction variable expressions
Dan Gohmand76d71a2009-05-12 02:17:14 +00002157 // in this loop, insert a canonical induction variable of the largest size.
Dan Gohman12725c72010-07-20 17:18:52 +00002158 PHINode *IndVar = 0;
Dan Gohmand76d71a2009-05-12 02:17:14 +00002159 if (NeedCannIV) {
Dan Gohmana9c205c2010-02-25 06:57:05 +00002160 // Check to see if the loop already has any canonical-looking induction
2161 // variables. If any are present and wider than the planned canonical
2162 // induction variable, temporarily remove them, so that the Rewriter
2163 // doesn't attempt to reuse them.
2164 SmallVector<PHINode *, 2> OldCannIVs;
2165 while (PHINode *OldCannIV = L->getCanonicalInductionVariable()) {
Dan Gohman426901a2009-06-13 16:25:49 +00002166 if (SE->getTypeSizeInBits(OldCannIV->getType()) >
2167 SE->getTypeSizeInBits(LargestType))
2168 OldCannIV->removeFromParent();
2169 else
Dan Gohmana9c205c2010-02-25 06:57:05 +00002170 break;
2171 OldCannIVs.push_back(OldCannIV);
Dan Gohman426901a2009-06-13 16:25:49 +00002172 }
2173
Dan Gohmandaafbe62009-06-26 22:53:46 +00002174 IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L, LargestType);
Dan Gohman426901a2009-06-13 16:25:49 +00002175
Dan Gohmaneb6be652009-02-12 22:19:27 +00002176 ++NumInserted;
2177 Changed = true;
David Greene0dd384c2010-01-05 01:27:06 +00002178 DEBUG(dbgs() << "INDVARS: New CanIV: " << *IndVar << '\n');
Dan Gohman426901a2009-06-13 16:25:49 +00002179
2180 // Now that the official induction variable is established, reinsert
Dan Gohmana9c205c2010-02-25 06:57:05 +00002181 // any old canonical-looking variables after it so that the IR remains
2182 // consistent. They will be deleted as part of the dead-PHI deletion at
Dan Gohman426901a2009-06-13 16:25:49 +00002183 // the end of the pass.
Dan Gohmana9c205c2010-02-25 06:57:05 +00002184 while (!OldCannIVs.empty()) {
2185 PHINode *OldCannIV = OldCannIVs.pop_back_val();
2186 OldCannIV->insertBefore(L->getHeader()->getFirstNonPHI());
2187 }
Dan Gohmancb9e09a2007-06-15 14:38:12 +00002188 }
Andrew Trick7da24172011-07-18 20:32:31 +00002189 else if (ExpandBECount && ReuseIVForExit && needsLFTR(L, DT)) {
2190 IndVar = FindLoopCounter(L, BackedgeTakenCount, SE, DT, TD);
2191 }
Dan Gohmaneb6be652009-02-12 22:19:27 +00002192 // If we have a trip count expression, rewrite the loop's exit condition
2193 // using it. We can currently only handle loops with a single exit.
Andrew Trick7da24172011-07-18 20:32:31 +00002194 Value *NewICmp = 0;
2195 if (ExpandBECount && IndVar) {
Andrew Trickc591f3a2011-07-16 01:18:53 +00002196 // Check preconditions for proper SCEVExpander operation. SCEV does not
2197 // express SCEVExpander's dependencies, such as LoopSimplify. Instead any
2198 // pass that uses the SCEVExpander must do it. This does not work well for
2199 // loop passes because SCEVExpander makes assumptions about all loops, while
2200 // LoopPassManager only forces the current loop to be simplified.
2201 //
2202 // FIXME: SCEV expansion has no way to bail out, so the caller must
2203 // explicitly check any assumptions made by SCEV. Brittle.
2204 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(BackedgeTakenCount);
2205 if (!AR || AR->getLoop()->getLoopPreheader())
2206 NewICmp =
2207 LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar, Rewriter);
Chris Lattnerc1a682d2004-04-22 14:59:40 +00002208 }
Andrew Trick87716c92011-03-17 23:51:11 +00002209 // Rewrite IV-derived expressions.
Andrew Trick1abe2962011-05-04 02:10:13 +00002210 if (!DisableIVRewrite)
2211 RewriteIVExpressions(L, Rewriter);
Dan Gohmaneb6be652009-02-12 22:19:27 +00002212
Andrew Trick87716c92011-03-17 23:51:11 +00002213 // Clear the rewriter cache, because values that are in the rewriter's cache
2214 // can be deleted in the loop below, causing the AssertingVH in the cache to
2215 // trigger.
2216 Rewriter.clear();
2217
2218 // Now that we're done iterating through lists, clean up any instructions
2219 // which are now dead.
2220 while (!DeadInsts.empty())
2221 if (Instruction *Inst =
2222 dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val()))
2223 RecursivelyDeleteTriviallyDeadInstructions(Inst);
2224
Dan Gohmandaafbe62009-06-26 22:53:46 +00002225 // The Rewriter may not be used from this point on.
Torok Edwin26895b52009-05-24 20:08:21 +00002226
Dan Gohmand76d71a2009-05-12 02:17:14 +00002227 // Loop-invariant instructions in the preheader that aren't used in the
2228 // loop may be sunk below the loop to reduce register pressure.
Dan Gohmandaafbe62009-06-26 22:53:46 +00002229 SinkUnusedInvariants(L);
Dan Gohmand76d71a2009-05-12 02:17:14 +00002230
2231 // For completeness, inform IVUsers of the IV use in the newly-created
2232 // loop exit test instruction.
Andrew Trick7da24172011-07-18 20:32:31 +00002233 if (IU && NewICmp) {
2234 ICmpInst *NewICmpInst = dyn_cast<ICmpInst>(NewICmp);
2235 if (NewICmpInst)
2236 IU->AddUsersIfInteresting(cast<Instruction>(NewICmpInst->getOperand(0)));
2237 }
Dan Gohmand76d71a2009-05-12 02:17:14 +00002238 // Clean up dead instructions.
Dan Gohmanb5358002010-01-05 16:31:45 +00002239 Changed |= DeleteDeadPHIs(L->getHeader());
Dan Gohmand76d71a2009-05-12 02:17:14 +00002240 // Check a post-condition.
Andrew Trick494c5492011-07-18 18:44:20 +00002241 assert(L->isLCSSAForm(*DT) &&
2242 "Indvars did not leave the loop in lcssa form!");
2243
2244 // Verify that LFTR, and any other change have not interfered with SCEV's
2245 // ability to compute trip count.
2246#ifndef NDEBUG
2247 if (DisableIVRewrite && !isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
2248 SE->forgetLoop(L);
2249 const SCEV *NewBECount = SE->getBackedgeTakenCount(L);
2250 if (SE->getTypeSizeInBits(BackedgeTakenCount->getType()) <
2251 SE->getTypeSizeInBits(NewBECount->getType()))
2252 NewBECount = SE->getTruncateOrNoop(NewBECount,
2253 BackedgeTakenCount->getType());
2254 else
2255 BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount,
2256 NewBECount->getType());
2257 assert(BackedgeTakenCount == NewBECount && "indvars must preserve SCEV");
2258 }
2259#endif
2260
Devang Patel2ac57e12007-03-07 06:39:01 +00002261 return Changed;
Chris Lattner476e6df2001-12-03 17:28:42 +00002262}