blob: 04ee7c8ccb3bd8381c51e72a084a0abf52364f11 [file] [log] [blame]
Chris Lattner6148c022001-12-03 17:28:42 +00001//===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner6148c022001-12-03 17:28:42 +00009//
Chris Lattner40bf8b42004-04-02 20:24:31 +000010// This transformation analyzes and transforms the induction variables (and
11// computations derived from them) into simpler forms suitable for subsequent
12// analysis and transformation.
13//
Reid Spencer47a53ac2006-08-18 09:01:07 +000014// This transformation makes the following changes to each loop with an
Chris Lattner40bf8b42004-04-02 20:24:31 +000015// identifiable induction variable:
16// 1. All loops are transformed to have a SINGLE canonical induction variable
17// which starts at zero and steps by one.
18// 2. The canonical induction variable is guaranteed to be the first PHI node
19// in the loop header block.
Dan Gohmanea73f3c2009-06-14 22:38:41 +000020// 3. The canonical induction variable is guaranteed to be in a wide enough
21// type so that IV expressions need not be (directly) zero-extended or
22// sign-extended.
23// 4. Any pointer arithmetic recurrences are raised to use array subscripts.
Chris Lattner40bf8b42004-04-02 20:24:31 +000024//
25// If the trip count of a loop is computable, this pass also makes the following
26// changes:
27// 1. The exit condition for the loop is canonicalized to compare the
28// induction value against the exit value. This turns loops like:
29// 'for (i = 7; i*i < 1000; ++i)' into 'for (i = 0; i != 25; ++i)'
30// 2. Any use outside of the loop of an expression derived from the indvar
31// is changed to compute the derived value outside of the loop, eliminating
32// the dependence on the exit value of the induction variable. If the only
33// purpose of the loop is to compute the exit value of some derived
34// expression, this transformation will make the loop dead.
35//
36// This transformation should be followed by strength reduction after all of the
Dan Gohmanc2c4cbf2009-05-19 20:38:47 +000037// desired loop transformations have been performed.
Chris Lattner6148c022001-12-03 17:28:42 +000038//
39//===----------------------------------------------------------------------===//
40
Chris Lattner0e5f4992006-12-19 21:40:18 +000041#define DEBUG_TYPE "indvars"
Chris Lattner022103b2002-05-07 20:03:00 +000042#include "llvm/Transforms/Scalar.h"
Chris Lattner40bf8b42004-04-02 20:24:31 +000043#include "llvm/BasicBlock.h"
Chris Lattner59fdaee2004-04-15 15:21:43 +000044#include "llvm/Constants.h"
Chris Lattner18b3c972003-12-22 05:02:01 +000045#include "llvm/Instructions.h"
Devang Patel7b9f6b12010-03-15 22:23:03 +000046#include "llvm/IntrinsicInst.h"
Owen Andersond672ecb2009-07-03 00:17:18 +000047#include "llvm/LLVMContext.h"
Chris Lattner40bf8b42004-04-02 20:24:31 +000048#include "llvm/Type.h"
Dan Gohman81db61a2009-05-12 02:17:14 +000049#include "llvm/Analysis/Dominators.h"
50#include "llvm/Analysis/IVUsers.h"
Nate Begeman36f891b2005-07-30 00:12:19 +000051#include "llvm/Analysis/ScalarEvolutionExpander.h"
John Criswell47df12d2003-12-18 17:19:19 +000052#include "llvm/Analysis/LoopInfo.h"
Devang Patel5ee99972007-03-07 06:39:01 +000053#include "llvm/Analysis/LoopPass.h"
Chris Lattner455889a2002-02-12 22:39:50 +000054#include "llvm/Support/CFG.h"
Chris Lattneree4f13a2007-01-07 01:14:12 +000055#include "llvm/Support/Debug.h"
Chris Lattnerbdff5482009-08-23 04:37:46 +000056#include "llvm/Support/raw_ostream.h"
John Criswell47df12d2003-12-18 17:19:19 +000057#include "llvm/Transforms/Utils/Local.h"
Dan Gohman81db61a2009-05-12 02:17:14 +000058#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Andrew Trick37da4082011-05-04 02:10:13 +000059#include "llvm/Target/TargetData.h"
Reid Spencera54b7cb2007-01-12 07:05:14 +000060#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000061#include "llvm/ADT/Statistic.h"
Dan Gohman81db61a2009-05-12 02:17:14 +000062#include "llvm/ADT/STLExtras.h"
John Criswell47df12d2003-12-18 17:19:19 +000063using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000064
Chris Lattner0e5f4992006-12-19 21:40:18 +000065STATISTIC(NumRemoved , "Number of aux indvars removed");
Andrew Trick37da4082011-05-04 02:10:13 +000066STATISTIC(NumWidened , "Number of indvars widened");
Chris Lattner0e5f4992006-12-19 21:40:18 +000067STATISTIC(NumInserted, "Number of canonical indvars added");
68STATISTIC(NumReplaced, "Number of exit values replaced");
69STATISTIC(NumLFTR , "Number of loop exit tests replaced");
Andrew Trick03d3d3b2011-05-25 04:42:22 +000070STATISTIC(NumElimExt , "Number of IV sign/zero extends eliminated");
71STATISTIC(NumElimRem , "Number of IV remainder operations eliminated");
72STATISTIC(NumElimCmp , "Number of IV comparisons eliminated");
Chris Lattner3324e712003-12-22 03:58:44 +000073
Andrew Trick37da4082011-05-04 02:10:13 +000074// DisableIVRewrite mode currently affects IVUsers, so is defined in libAnalysis
75// and referenced here.
76namespace llvm {
77 extern bool DisableIVRewrite;
78}
79
Chris Lattner0e5f4992006-12-19 21:40:18 +000080namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000081 class IndVarSimplify : public LoopPass {
Dan Gohman81db61a2009-05-12 02:17:14 +000082 IVUsers *IU;
Chris Lattner40bf8b42004-04-02 20:24:31 +000083 LoopInfo *LI;
84 ScalarEvolution *SE;
Dan Gohmande53dc02009-06-27 05:16:57 +000085 DominatorTree *DT;
Andrew Trick37da4082011-05-04 02:10:13 +000086 TargetData *TD;
Andrew Trickb12a7542011-03-17 23:51:11 +000087 SmallVector<WeakVH, 16> DeadInsts;
Chris Lattner15cad752003-12-23 07:47:09 +000088 bool Changed;
Chris Lattner3324e712003-12-22 03:58:44 +000089 public:
Devang Patel794fd752007-05-01 21:15:47 +000090
Dan Gohman5668cf72009-07-15 01:26:32 +000091 static char ID; // Pass identification, replacement for typeid
Andrew Trick37da4082011-05-04 02:10:13 +000092 IndVarSimplify() : LoopPass(ID), IU(0), LI(0), SE(0), DT(0), TD(0) {
Owen Anderson081c34b2010-10-19 17:21:58 +000093 initializeIndVarSimplifyPass(*PassRegistry::getPassRegistry());
94 }
Devang Patel794fd752007-05-01 21:15:47 +000095
Dan Gohman5668cf72009-07-15 01:26:32 +000096 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
Dan Gohman60f8a632009-02-17 20:49:49 +000097
Dan Gohman5668cf72009-07-15 01:26:32 +000098 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
99 AU.addRequired<DominatorTree>();
100 AU.addRequired<LoopInfo>();
101 AU.addRequired<ScalarEvolution>();
102 AU.addRequiredID(LoopSimplifyID);
103 AU.addRequiredID(LCSSAID);
104 AU.addRequired<IVUsers>();
105 AU.addPreserved<ScalarEvolution>();
106 AU.addPreservedID(LoopSimplifyID);
107 AU.addPreservedID(LCSSAID);
108 AU.addPreserved<IVUsers>();
109 AU.setPreservesCFG();
110 }
Chris Lattner15cad752003-12-23 07:47:09 +0000111
Chris Lattner40bf8b42004-04-02 20:24:31 +0000112 private:
Andrew Trickb12a7542011-03-17 23:51:11 +0000113 bool isValidRewrite(Value *FromVal, Value *ToVal);
Devang Patel5ee99972007-03-07 06:39:01 +0000114
Andrew Trickf85092c2011-05-20 18:25:42 +0000115 void SimplifyIVUsers(SCEVExpander &Rewriter);
Andrew Trickaeee4612011-05-12 00:04:28 +0000116 void EliminateIVComparison(ICmpInst *ICmp, Value *IVOperand);
117 void EliminateIVRemainder(BinaryOperator *Rem,
118 Value *IVOperand,
Andrew Trickf85092c2011-05-20 18:25:42 +0000119 bool IsSigned,
120 PHINode *IVPhi);
Dan Gohman60f8a632009-02-17 20:49:49 +0000121 void RewriteNonIntegerIVs(Loop *L);
122
Dan Gohman0bba49c2009-07-07 17:06:11 +0000123 ICmpInst *LinearFunctionTestReplace(Loop *L, const SCEV *BackedgeTakenCount,
Andrew Trick4dfdf242011-05-03 22:24:10 +0000124 PHINode *IndVar,
125 SCEVExpander &Rewriter);
Andrew Trick37da4082011-05-04 02:10:13 +0000126
Dan Gohman454d26d2010-02-22 04:11:59 +0000127 void RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000128
Dan Gohman454d26d2010-02-22 04:11:59 +0000129 void RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter);
Devang Pateld22a8492008-09-09 21:41:07 +0000130
Dan Gohman667d7872009-06-26 22:53:46 +0000131 void SinkUnusedInvariants(Loop *L);
Dan Gohman81db61a2009-05-12 02:17:14 +0000132
133 void HandleFloatingPointIV(Loop *L, PHINode *PH);
Chris Lattner3324e712003-12-22 03:58:44 +0000134 };
Chris Lattner5e761402002-09-10 05:24:05 +0000135}
Chris Lattner394437f2001-12-04 04:32:29 +0000136
Dan Gohman844731a2008-05-13 00:00:25 +0000137char IndVarSimplify::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000138INITIALIZE_PASS_BEGIN(IndVarSimplify, "indvars",
Andrew Trick37da4082011-05-04 02:10:13 +0000139 "Induction Variable Simplification", false, false)
Owen Anderson2ab36d32010-10-12 19:48:12 +0000140INITIALIZE_PASS_DEPENDENCY(DominatorTree)
141INITIALIZE_PASS_DEPENDENCY(LoopInfo)
142INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
143INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
144INITIALIZE_PASS_DEPENDENCY(LCSSA)
145INITIALIZE_PASS_DEPENDENCY(IVUsers)
146INITIALIZE_PASS_END(IndVarSimplify, "indvars",
Andrew Trick37da4082011-05-04 02:10:13 +0000147 "Induction Variable Simplification", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000148
Daniel Dunbar394f0442008-10-22 23:32:42 +0000149Pass *llvm::createIndVarSimplifyPass() {
Chris Lattner3324e712003-12-22 03:58:44 +0000150 return new IndVarSimplify();
Chris Lattner394437f2001-12-04 04:32:29 +0000151}
152
Andrew Trickb12a7542011-03-17 23:51:11 +0000153/// isValidRewrite - Return true if the SCEV expansion generated by the
154/// rewriter can replace the original value. SCEV guarantees that it
155/// produces the same value, but the way it is produced may be illegal IR.
156/// Ideally, this function will only be called for verification.
157bool IndVarSimplify::isValidRewrite(Value *FromVal, Value *ToVal) {
158 // If an SCEV expression subsumed multiple pointers, its expansion could
159 // reassociate the GEP changing the base pointer. This is illegal because the
160 // final address produced by a GEP chain must be inbounds relative to its
161 // underlying object. Otherwise basic alias analysis, among other things,
162 // could fail in a dangerous way. Ultimately, SCEV will be improved to avoid
163 // producing an expression involving multiple pointers. Until then, we must
164 // bail out here.
165 //
166 // Retrieve the pointer operand of the GEP. Don't use GetUnderlyingObject
167 // because it understands lcssa phis while SCEV does not.
168 Value *FromPtr = FromVal;
169 Value *ToPtr = ToVal;
170 if (GEPOperator *GEP = dyn_cast<GEPOperator>(FromVal)) {
171 FromPtr = GEP->getPointerOperand();
172 }
173 if (GEPOperator *GEP = dyn_cast<GEPOperator>(ToVal)) {
174 ToPtr = GEP->getPointerOperand();
175 }
176 if (FromPtr != FromVal || ToPtr != ToVal) {
177 // Quickly check the common case
178 if (FromPtr == ToPtr)
179 return true;
180
181 // SCEV may have rewritten an expression that produces the GEP's pointer
182 // operand. That's ok as long as the pointer operand has the same base
183 // pointer. Unlike GetUnderlyingObject(), getPointerBase() will find the
184 // base of a recurrence. This handles the case in which SCEV expansion
185 // converts a pointer type recurrence into a nonrecurrent pointer base
186 // indexed by an integer recurrence.
187 const SCEV *FromBase = SE->getPointerBase(SE->getSCEV(FromPtr));
188 const SCEV *ToBase = SE->getPointerBase(SE->getSCEV(ToPtr));
189 if (FromBase == ToBase)
190 return true;
191
192 DEBUG(dbgs() << "INDVARS: GEP rewrite bail out "
193 << *FromBase << " != " << *ToBase << "\n");
194
195 return false;
196 }
197 return true;
198}
199
Andrew Trick4dfdf242011-05-03 22:24:10 +0000200/// canExpandBackedgeTakenCount - Return true if this loop's backedge taken
201/// count expression can be safely and cheaply expanded into an instruction
202/// sequence that can be used by LinearFunctionTestReplace.
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000203static bool canExpandBackedgeTakenCount(Loop *L, ScalarEvolution *SE) {
204 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
Andrew Trick4dfdf242011-05-03 22:24:10 +0000205 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount) ||
206 BackedgeTakenCount->isZero())
207 return false;
208
209 if (!L->getExitingBlock())
210 return false;
211
212 // Can't rewrite non-branch yet.
213 BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator());
214 if (!BI)
215 return false;
216
Dan Gohmanca9b7032010-04-12 21:13:43 +0000217 // Special case: If the backedge-taken count is a UDiv, it's very likely a
218 // UDiv that ScalarEvolution produced in order to compute a precise
219 // expression, rather than a UDiv from the user's code. If we can't find a
220 // UDiv in the code with some simple searching, assume the former and forego
221 // rewriting the loop.
222 if (isa<SCEVUDivExpr>(BackedgeTakenCount)) {
223 ICmpInst *OrigCond = dyn_cast<ICmpInst>(BI->getCondition());
Andrew Trick37da4082011-05-04 02:10:13 +0000224 if (!OrigCond) return false;
Dan Gohmanca9b7032010-04-12 21:13:43 +0000225 const SCEV *R = SE->getSCEV(OrigCond->getOperand(1));
Dan Gohmandeff6212010-05-03 22:09:21 +0000226 R = SE->getMinusSCEV(R, SE->getConstant(R->getType(), 1));
Dan Gohmanca9b7032010-04-12 21:13:43 +0000227 if (R != BackedgeTakenCount) {
228 const SCEV *L = SE->getSCEV(OrigCond->getOperand(0));
Dan Gohmandeff6212010-05-03 22:09:21 +0000229 L = SE->getMinusSCEV(L, SE->getConstant(L->getType(), 1));
Dan Gohmanca9b7032010-04-12 21:13:43 +0000230 if (L != BackedgeTakenCount)
Andrew Trick4dfdf242011-05-03 22:24:10 +0000231 return false;
Dan Gohmanca9b7032010-04-12 21:13:43 +0000232 }
233 }
Andrew Trick4dfdf242011-05-03 22:24:10 +0000234 return true;
235}
236
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000237/// getBackedgeIVType - Get the widest type used by the loop test after peeking
238/// through Truncs.
239///
240/// TODO: Unnecessary once LinearFunctionTestReplace is removed.
241static const Type *getBackedgeIVType(Loop *L) {
242 if (!L->getExitingBlock())
243 return 0;
244
245 // Can't rewrite non-branch yet.
246 BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator());
247 if (!BI)
248 return 0;
249
250 ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition());
251 if (!Cond)
252 return 0;
253
254 const Type *Ty = 0;
255 for(User::op_iterator OI = Cond->op_begin(), OE = Cond->op_end();
256 OI != OE; ++OI) {
257 assert((!Ty || Ty == (*OI)->getType()) && "bad icmp operand types");
258 TruncInst *Trunc = dyn_cast<TruncInst>(*OI);
259 if (!Trunc)
260 continue;
261
262 return Trunc->getSrcTy();
263 }
264 return Ty;
265}
266
Andrew Trick4dfdf242011-05-03 22:24:10 +0000267/// LinearFunctionTestReplace - This method rewrites the exit condition of the
268/// loop to be a canonical != comparison against the incremented loop induction
269/// variable. This pass is able to rewrite the exit tests of any loop where the
270/// SCEV analysis can determine a loop-invariant trip count of the loop, which
271/// is actually a much broader range than just linear tests.
272ICmpInst *IndVarSimplify::
273LinearFunctionTestReplace(Loop *L,
274 const SCEV *BackedgeTakenCount,
275 PHINode *IndVar,
276 SCEVExpander &Rewriter) {
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000277 assert(canExpandBackedgeTakenCount(L, SE) && "precondition");
Andrew Trick4dfdf242011-05-03 22:24:10 +0000278 BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator());
Dan Gohmanca9b7032010-04-12 21:13:43 +0000279
Chris Lattnerd2440572004-04-15 20:26:22 +0000280 // If the exiting block is not the same as the backedge block, we must compare
281 // against the preincremented value, otherwise we prefer to compare against
282 // the post-incremented value.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000283 Value *CmpIndVar;
Dan Gohman0bba49c2009-07-07 17:06:11 +0000284 const SCEV *RHS = BackedgeTakenCount;
Andrew Trick4dfdf242011-05-03 22:24:10 +0000285 if (L->getExitingBlock() == L->getLoopLatch()) {
Dan Gohman46bdfb02009-02-24 18:55:53 +0000286 // Add one to the "backedge-taken" count to get the trip count.
287 // If this addition may overflow, we have to be more pessimistic and
288 // cast the induction variable before doing the add.
Dan Gohmandeff6212010-05-03 22:09:21 +0000289 const SCEV *Zero = SE->getConstant(BackedgeTakenCount->getType(), 0);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000290 const SCEV *N =
Dan Gohman46bdfb02009-02-24 18:55:53 +0000291 SE->getAddExpr(BackedgeTakenCount,
Dan Gohmandeff6212010-05-03 22:09:21 +0000292 SE->getConstant(BackedgeTakenCount->getType(), 1));
Dan Gohmanc2390b12009-02-12 22:19:27 +0000293 if ((isa<SCEVConstant>(N) && !N->isZero()) ||
Dan Gohman3948d0b2010-04-11 19:27:13 +0000294 SE->isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) {
Dan Gohmanc2390b12009-02-12 22:19:27 +0000295 // No overflow. Cast the sum.
Dan Gohman46bdfb02009-02-24 18:55:53 +0000296 RHS = SE->getTruncateOrZeroExtend(N, IndVar->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000297 } else {
298 // Potential overflow. Cast before doing the add.
Dan Gohman46bdfb02009-02-24 18:55:53 +0000299 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
300 IndVar->getType());
301 RHS = SE->getAddExpr(RHS,
Dan Gohmandeff6212010-05-03 22:09:21 +0000302 SE->getConstant(IndVar->getType(), 1));
Dan Gohmanc2390b12009-02-12 22:19:27 +0000303 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000304
Dan Gohman46bdfb02009-02-24 18:55:53 +0000305 // The BackedgeTaken expression contains the number of times that the
306 // backedge branches to the loop header. This is one less than the
307 // number of times the loop executes, so use the incremented indvar.
Andrew Trick4dfdf242011-05-03 22:24:10 +0000308 CmpIndVar = IndVar->getIncomingValueForBlock(L->getExitingBlock());
Chris Lattnerd2440572004-04-15 20:26:22 +0000309 } else {
310 // We have to use the preincremented value...
Dan Gohman46bdfb02009-02-24 18:55:53 +0000311 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
312 IndVar->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000313 CmpIndVar = IndVar;
Chris Lattnerd2440572004-04-15 20:26:22 +0000314 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000315
Dan Gohman667d7872009-06-26 22:53:46 +0000316 // Expand the code for the iteration count.
Dan Gohman17ead4f2010-11-17 21:23:15 +0000317 assert(SE->isLoopInvariant(RHS, L) &&
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000318 "Computed iteration count is not loop invariant!");
Dan Gohman667d7872009-06-26 22:53:46 +0000319 Value *ExitCnt = Rewriter.expandCodeFor(RHS, IndVar->getType(), BI);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000320
Reid Spencere4d87aa2006-12-23 06:05:41 +0000321 // Insert a new icmp_ne or icmp_eq instruction before the branch.
322 ICmpInst::Predicate Opcode;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000323 if (L->contains(BI->getSuccessor(0)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000324 Opcode = ICmpInst::ICMP_NE;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000325 else
Reid Spencere4d87aa2006-12-23 06:05:41 +0000326 Opcode = ICmpInst::ICMP_EQ;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000327
David Greenef67ef312010-01-05 01:27:06 +0000328 DEBUG(dbgs() << "INDVARS: Rewriting loop exit condition to:\n"
Chris Lattnerbdff5482009-08-23 04:37:46 +0000329 << " LHS:" << *CmpIndVar << '\n'
330 << " op:\t"
331 << (Opcode == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
332 << " RHS:\t" << *RHS << "\n");
Dan Gohmanc2390b12009-02-12 22:19:27 +0000333
Owen Anderson333c4002009-07-09 23:48:35 +0000334 ICmpInst *Cond = new ICmpInst(BI, Opcode, CmpIndVar, ExitCnt, "exitcond");
Dan Gohman81db61a2009-05-12 02:17:14 +0000335
Dan Gohman24440802010-02-22 02:07:36 +0000336 Value *OrigCond = BI->getCondition();
Dan Gohman95bdbfa2009-05-24 19:11:38 +0000337 // It's tempting to use replaceAllUsesWith here to fully replace the old
338 // comparison, but that's not immediately safe, since users of the old
339 // comparison may not be dominated by the new comparison. Instead, just
340 // update the branch to use the new comparison; in the common case this
341 // will make old comparison dead.
342 BI->setCondition(Cond);
Andrew Trick88e92cf2011-04-28 17:30:04 +0000343 DeadInsts.push_back(OrigCond);
Dan Gohman81db61a2009-05-12 02:17:14 +0000344
Chris Lattner40bf8b42004-04-02 20:24:31 +0000345 ++NumLFTR;
346 Changed = true;
Dan Gohman81db61a2009-05-12 02:17:14 +0000347 return Cond;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000348}
349
Chris Lattner40bf8b42004-04-02 20:24:31 +0000350/// RewriteLoopExitValues - Check to see if this loop has a computable
351/// loop-invariant execution count. If so, this means that we can compute the
352/// final value of any expressions that are recurrent in the loop, and
353/// substitute the exit values from the loop into any instructions outside of
354/// the loop that use the final values of the current expressions.
Dan Gohman81db61a2009-05-12 02:17:14 +0000355///
356/// This is mostly redundant with the regular IndVarSimplify activities that
357/// happen later, except that it's more powerful in some cases, because it's
358/// able to brute-force evaluate arbitrary instructions as long as they have
359/// constant operands at the beginning of the loop.
Chris Lattnerf1859892011-01-09 02:16:18 +0000360void IndVarSimplify::RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000361 // Verify the input to the pass in already in LCSSA form.
Dan Gohmanbbf81d82010-03-10 19:38:49 +0000362 assert(L->isLCSSAForm(*DT));
Dan Gohman81db61a2009-05-12 02:17:14 +0000363
Devang Patelb7211a22007-08-21 00:31:24 +0000364 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattner9f3d7382007-03-04 03:43:23 +0000365 L->getUniqueExitBlocks(ExitBlocks);
Misha Brukmanfd939082005-04-21 23:48:37 +0000366
Chris Lattner9f3d7382007-03-04 03:43:23 +0000367 // Find all values that are computed inside the loop, but used outside of it.
368 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
369 // the exit blocks of the loop to find them.
370 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
371 BasicBlock *ExitBB = ExitBlocks[i];
Dan Gohmancafb8132009-02-17 19:13:57 +0000372
Chris Lattner9f3d7382007-03-04 03:43:23 +0000373 // If there are no PHI nodes in this exit block, then no values defined
374 // inside the loop are used on this path, skip it.
375 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
376 if (!PN) continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000377
Chris Lattner9f3d7382007-03-04 03:43:23 +0000378 unsigned NumPreds = PN->getNumIncomingValues();
Dan Gohmancafb8132009-02-17 19:13:57 +0000379
Chris Lattner9f3d7382007-03-04 03:43:23 +0000380 // Iterate over all of the PHI nodes.
381 BasicBlock::iterator BBI = ExitBB->begin();
382 while ((PN = dyn_cast<PHINode>(BBI++))) {
Torok Edwin3790fb02009-05-24 19:36:09 +0000383 if (PN->use_empty())
384 continue; // dead use, don't replace it
Dan Gohman814f2b22010-02-18 21:34:02 +0000385
386 // SCEV only supports integer expressions for now.
387 if (!PN->getType()->isIntegerTy() && !PN->getType()->isPointerTy())
388 continue;
389
Dale Johannesen45a2d7d2010-02-19 07:14:22 +0000390 // It's necessary to tell ScalarEvolution about this explicitly so that
391 // it can walk the def-use list and forget all SCEVs, as it may not be
392 // watching the PHI itself. Once the new exit value is in place, there
393 // may not be a def-use connection between the loop and every instruction
394 // which got a SCEVAddRecExpr for that loop.
395 SE->forgetValue(PN);
396
Chris Lattner9f3d7382007-03-04 03:43:23 +0000397 // Iterate over all of the values in all the PHI nodes.
398 for (unsigned i = 0; i != NumPreds; ++i) {
399 // If the value being merged in is not integer or is not defined
400 // in the loop, skip it.
401 Value *InVal = PN->getIncomingValue(i);
Dan Gohman814f2b22010-02-18 21:34:02 +0000402 if (!isa<Instruction>(InVal))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000403 continue;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000404
Chris Lattner9f3d7382007-03-04 03:43:23 +0000405 // If this pred is for a subloop, not L itself, skip it.
Dan Gohmancafb8132009-02-17 19:13:57 +0000406 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
Chris Lattner9f3d7382007-03-04 03:43:23 +0000407 continue; // The Block is in a subloop, skip it.
408
409 // Check that InVal is defined in the loop.
410 Instruction *Inst = cast<Instruction>(InVal);
Dan Gohman92329c72009-12-18 01:24:09 +0000411 if (!L->contains(Inst))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000412 continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000413
Chris Lattner9f3d7382007-03-04 03:43:23 +0000414 // Okay, this instruction has a user outside of the current loop
415 // and varies predictably *inside* the loop. Evaluate the value it
416 // contains when the loop exits, if possible.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000417 const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
Dan Gohman17ead4f2010-11-17 21:23:15 +0000418 if (!SE->isLoopInvariant(ExitValue, L))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000419 continue;
Chris Lattner9caed542007-03-04 01:00:28 +0000420
Dan Gohman667d7872009-06-26 22:53:46 +0000421 Value *ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), Inst);
Dan Gohmancafb8132009-02-17 19:13:57 +0000422
David Greenef67ef312010-01-05 01:27:06 +0000423 DEBUG(dbgs() << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal << '\n'
Chris Lattnerbdff5482009-08-23 04:37:46 +0000424 << " LoopVal = " << *Inst << "\n");
Chris Lattner9f3d7382007-03-04 03:43:23 +0000425
Andrew Trickb12a7542011-03-17 23:51:11 +0000426 if (!isValidRewrite(Inst, ExitVal)) {
427 DeadInsts.push_back(ExitVal);
428 continue;
429 }
430 Changed = true;
431 ++NumReplaced;
432
Chris Lattner9f3d7382007-03-04 03:43:23 +0000433 PN->setIncomingValue(i, ExitVal);
Dan Gohmancafb8132009-02-17 19:13:57 +0000434
Dan Gohman81db61a2009-05-12 02:17:14 +0000435 // If this instruction is dead now, delete it.
436 RecursivelyDeleteTriviallyDeadInstructions(Inst);
Dan Gohmancafb8132009-02-17 19:13:57 +0000437
Dan Gohman65d1e2b2009-07-14 01:09:02 +0000438 if (NumPreds == 1) {
439 // Completely replace a single-pred PHI. This is safe, because the
440 // NewVal won't be variant in the loop, so we don't need an LCSSA phi
441 // node anymore.
Chris Lattner9f3d7382007-03-04 03:43:23 +0000442 PN->replaceAllUsesWith(ExitVal);
Dan Gohman81db61a2009-05-12 02:17:14 +0000443 RecursivelyDeleteTriviallyDeadInstructions(PN);
Chris Lattnerc9838f22007-03-03 22:48:48 +0000444 }
445 }
Dan Gohman65d1e2b2009-07-14 01:09:02 +0000446 if (NumPreds != 1) {
Dan Gohman667d7872009-06-26 22:53:46 +0000447 // Clone the PHI and delete the original one. This lets IVUsers and
448 // any other maps purge the original user from their records.
Devang Patel50b6e332009-10-27 22:16:29 +0000449 PHINode *NewPN = cast<PHINode>(PN->clone());
Dan Gohman667d7872009-06-26 22:53:46 +0000450 NewPN->takeName(PN);
451 NewPN->insertBefore(PN);
452 PN->replaceAllUsesWith(NewPN);
453 PN->eraseFromParent();
454 }
Chris Lattnerc9838f22007-03-03 22:48:48 +0000455 }
456 }
Dan Gohman472fdf72010-03-20 03:53:53 +0000457
458 // The insertion point instruction may have been deleted; clear it out
459 // so that the rewriter doesn't trip over it later.
460 Rewriter.clearInsertPoint();
Chris Lattner40bf8b42004-04-02 20:24:31 +0000461}
462
Dan Gohman60f8a632009-02-17 20:49:49 +0000463void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000464 // First step. Check to see if there are any floating-point recurrences.
Chris Lattner40bf8b42004-04-02 20:24:31 +0000465 // If there are, change them into integer recurrences, permitting analysis by
466 // the SCEV routines.
467 //
Chris Lattnerf1859892011-01-09 02:16:18 +0000468 BasicBlock *Header = L->getHeader();
Misha Brukmanfd939082005-04-21 23:48:37 +0000469
Dan Gohman81db61a2009-05-12 02:17:14 +0000470 SmallVector<WeakVH, 8> PHIs;
471 for (BasicBlock::iterator I = Header->begin();
472 PHINode *PN = dyn_cast<PHINode>(I); ++I)
473 PHIs.push_back(PN);
474
475 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
Gabor Greifea4894a2010-09-18 11:53:39 +0000476 if (PHINode *PN = dyn_cast_or_null<PHINode>(&*PHIs[i]))
Dan Gohman81db61a2009-05-12 02:17:14 +0000477 HandleFloatingPointIV(L, PN);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000478
Dan Gohman2d1be872009-04-16 03:18:22 +0000479 // If the loop previously had floating-point IV, ScalarEvolution
Dan Gohman60f8a632009-02-17 20:49:49 +0000480 // may not have been able to compute a trip count. Now that we've done some
481 // re-writing, the trip count may be computable.
482 if (Changed)
Dan Gohman4c7279a2009-10-31 15:04:55 +0000483 SE->forgetLoop(L);
Dale Johannesenc671d892009-04-15 23:31:51 +0000484}
485
Andrew Trickf85092c2011-05-20 18:25:42 +0000486namespace {
487 // Collect information about induction variables that are used by sign/zero
488 // extend operations. This information is recorded by CollectExtend and
489 // provides the input to WidenIV.
490 struct WideIVInfo {
491 const Type *WidestNativeType; // Widest integer type created [sz]ext
492 bool IsSigned; // Was an sext user seen before a zext?
493
494 WideIVInfo() : WidestNativeType(0), IsSigned(false) {}
495 };
496 typedef std::map<PHINode *, WideIVInfo> WideIVMap;
497}
498
499/// CollectExtend - Update information about the induction variable that is
500/// extended by this sign or zero extend operation. This is used to determine
501/// the final width of the IV before actually widening it.
502static void CollectExtend(CastInst *Cast, PHINode *Phi, bool IsSigned,
503 WideIVMap &IVMap, ScalarEvolution *SE,
504 const TargetData *TD) {
505 const Type *Ty = Cast->getType();
506 uint64_t Width = SE->getTypeSizeInBits(Ty);
507 if (TD && !TD->isLegalInteger(Width))
508 return;
509
510 WideIVInfo &IVInfo = IVMap[Phi];
511 if (!IVInfo.WidestNativeType) {
512 IVInfo.WidestNativeType = SE->getEffectiveSCEVType(Ty);
513 IVInfo.IsSigned = IsSigned;
514 return;
515 }
516
517 // We extend the IV to satisfy the sign of its first user, arbitrarily.
518 if (IVInfo.IsSigned != IsSigned)
519 return;
520
521 if (Width > SE->getTypeSizeInBits(IVInfo.WidestNativeType))
522 IVInfo.WidestNativeType = SE->getEffectiveSCEVType(Ty);
523}
524
525namespace {
526/// WidenIV - The goal of this transform is to remove sign and zero extends
527/// without creating any new induction variables. To do this, it creates a new
528/// phi of the wider type and redirects all users, either removing extends or
529/// inserting truncs whenever we stop propagating the type.
530///
531class WidenIV {
532 PHINode *OrigPhi;
533 const Type *WideType;
534 bool IsSigned;
535
536 IVUsers *IU;
537 LoopInfo *LI;
538 Loop *L;
539 ScalarEvolution *SE;
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000540 DominatorTree *DT;
Andrew Trickf85092c2011-05-20 18:25:42 +0000541 SmallVectorImpl<WeakVH> &DeadInsts;
542
543 PHINode *WidePhi;
544 Instruction *WideInc;
545 const SCEV *WideIncExpr;
546
547 SmallPtrSet<Instruction*,16> Processed;
548
549public:
550 WidenIV(PHINode *PN, const WideIVInfo &IVInfo, IVUsers *IUsers,
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000551 LoopInfo *LInfo, ScalarEvolution *SEv, DominatorTree *DTree,
552 SmallVectorImpl<WeakVH> &DI) :
Andrew Trickf85092c2011-05-20 18:25:42 +0000553 OrigPhi(PN),
554 WideType(IVInfo.WidestNativeType),
555 IsSigned(IVInfo.IsSigned),
556 IU(IUsers),
557 LI(LInfo),
558 L(LI->getLoopFor(OrigPhi->getParent())),
559 SE(SEv),
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000560 DT(DTree),
Andrew Trickf85092c2011-05-20 18:25:42 +0000561 DeadInsts(DI),
562 WidePhi(0),
563 WideInc(0),
564 WideIncExpr(0) {
565 assert(L->getHeader() == OrigPhi->getParent() && "Phi must be an IV");
566 }
567
568 bool CreateWideIV(SCEVExpander &Rewriter);
569
570protected:
Andrew Trickf85092c2011-05-20 18:25:42 +0000571 Instruction *CloneIVUser(Instruction *NarrowUse,
572 Instruction *NarrowDef,
573 Instruction *WideDef);
574
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000575 const SCEVAddRecExpr *GetWideRecurrence(Instruction *NarrowUse);
576
Andrew Trickf85092c2011-05-20 18:25:42 +0000577 Instruction *WidenIVUse(Instruction *NarrowUse,
578 Instruction *NarrowDef,
579 Instruction *WideDef);
580};
581} // anonymous namespace
582
Andrew Trickaeee4612011-05-12 00:04:28 +0000583/// SimplifyIVUsers - Iteratively perform simplification on IVUsers within this
584/// loop. IVUsers is treated as a worklist. Each successive simplification may
585/// push more users which may themselves be candidates for simplification.
Andrew Trickf85092c2011-05-20 18:25:42 +0000586///
587void IndVarSimplify::SimplifyIVUsers(SCEVExpander &Rewriter) {
588 WideIVMap IVMap;
Dan Gohman931e3452010-04-12 02:21:50 +0000589
Andrew Trickf85092c2011-05-20 18:25:42 +0000590 // Each round of simplification involves a round of eliminating operations
591 // followed by a round of widening IVs. A single IVUsers worklist is used
592 // across all rounds. The inner loop advances the user. If widening exposes
593 // more uses, then another pass through the outer loop is triggered.
594 for (IVUsers::iterator I = IU->begin(), E = IU->end(); I != E;) {
595 for(; I != E; ++I) {
596 Instruction *UseInst = I->getUser();
597 Value *IVOperand = I->getOperandValToReplace();
Dan Gohman931e3452010-04-12 02:21:50 +0000598
Andrew Trickf85092c2011-05-20 18:25:42 +0000599 if (DisableIVRewrite) {
600 if (CastInst *Cast = dyn_cast<CastInst>(UseInst)) {
601 bool IsSigned = Cast->getOpcode() == Instruction::SExt;
602 if (IsSigned || Cast->getOpcode() == Instruction::ZExt) {
603 CollectExtend(Cast, I->getPhi(), IsSigned, IVMap, SE, TD);
604 continue;
605 }
606 }
607 }
608 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
609 EliminateIVComparison(ICmp, IVOperand);
Andrew Trickaeee4612011-05-12 00:04:28 +0000610 continue;
611 }
Andrew Trickf85092c2011-05-20 18:25:42 +0000612 if (BinaryOperator *Rem = dyn_cast<BinaryOperator>(UseInst)) {
613 bool IsSigned = Rem->getOpcode() == Instruction::SRem;
614 if (IsSigned || Rem->getOpcode() == Instruction::URem) {
615 EliminateIVRemainder(Rem, IVOperand, IsSigned, I->getPhi());
616 continue;
617 }
618 }
619 }
620 for (WideIVMap::const_iterator I = IVMap.begin(), E = IVMap.end();
621 I != E; ++I) {
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000622 WidenIV Widener(I->first, I->second, IU, LI, SE, DT, DeadInsts);
Andrew Trickf85092c2011-05-20 18:25:42 +0000623 if (Widener.CreateWideIV(Rewriter))
624 Changed = true;
Andrew Trickaeee4612011-05-12 00:04:28 +0000625 }
Dan Gohman931e3452010-04-12 02:21:50 +0000626 }
627}
628
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000629static Value *getExtend( Value *NarrowOper, const Type *WideType,
630 bool IsSigned, IRBuilder<> &Builder) {
631 return IsSigned ? Builder.CreateSExt(NarrowOper, WideType) :
632 Builder.CreateZExt(NarrowOper, WideType);
Andrew Trickf85092c2011-05-20 18:25:42 +0000633}
634
635/// CloneIVUser - Instantiate a wide operation to replace a narrow
636/// operation. This only needs to handle operations that can evaluation to
637/// SCEVAddRec. It can safely return 0 for any operation we decide not to clone.
638Instruction *WidenIV::CloneIVUser(Instruction *NarrowUse,
639 Instruction *NarrowDef,
640 Instruction *WideDef) {
641 unsigned Opcode = NarrowUse->getOpcode();
642 switch (Opcode) {
643 default:
644 return 0;
645 case Instruction::Add:
646 case Instruction::Mul:
647 case Instruction::UDiv:
648 case Instruction::Sub:
649 case Instruction::And:
650 case Instruction::Or:
651 case Instruction::Xor:
652 case Instruction::Shl:
653 case Instruction::LShr:
654 case Instruction::AShr:
655 DEBUG(dbgs() << "Cloning IVUser: " << *NarrowUse << "\n");
656
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000657 IRBuilder<> Builder(NarrowUse);
658
659 // Replace NarrowDef operands with WideDef. Otherwise, we don't know
660 // anything about the narrow operand yet so must insert a [sz]ext. It is
661 // probably loop invariant and will be folded or hoisted. If it actually
662 // comes from a widened IV, it should be removed during a future call to
663 // WidenIVUse.
664 Value *LHS = (NarrowUse->getOperand(0) == NarrowDef) ? WideDef :
665 getExtend(NarrowUse->getOperand(0), WideType, IsSigned, Builder);
666 Value *RHS = (NarrowUse->getOperand(1) == NarrowDef) ? WideDef :
667 getExtend(NarrowUse->getOperand(1), WideType, IsSigned, Builder);
668
Andrew Trickf85092c2011-05-20 18:25:42 +0000669 BinaryOperator *NarrowBO = cast<BinaryOperator>(NarrowUse);
670 BinaryOperator *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(),
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000671 LHS, RHS,
Andrew Trickf85092c2011-05-20 18:25:42 +0000672 NarrowBO->getName());
Andrew Trickf85092c2011-05-20 18:25:42 +0000673 Builder.Insert(WideBO);
674 if (NarrowBO->hasNoUnsignedWrap()) WideBO->setHasNoUnsignedWrap();
675 if (NarrowBO->hasNoSignedWrap()) WideBO->setHasNoSignedWrap();
676
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000677 return WideBO;
Andrew Trickf85092c2011-05-20 18:25:42 +0000678 }
679 llvm_unreachable(0);
680}
681
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000682// GetWideRecurrence - Is this instruction potentially interesting from IVUsers'
683// perspective after widening it's type? In other words, can the extend be
684// safely hoisted out of the loop with SCEV reducing the value to a recurrence
685// on the same loop. If so, return the sign or zero extended
686// recurrence. Otherwise return NULL.
687const SCEVAddRecExpr *WidenIV::GetWideRecurrence(Instruction *NarrowUse) {
688 if (!SE->isSCEVable(NarrowUse->getType()))
689 return 0;
690
691 const SCEV *NarrowExpr = SE->getSCEV(NarrowUse);
692 const SCEV *WideExpr = IsSigned ?
693 SE->getSignExtendExpr(NarrowExpr, WideType) :
694 SE->getZeroExtendExpr(NarrowExpr, WideType);
695 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(WideExpr);
696 if (!AddRec || AddRec->getLoop() != L)
697 return 0;
698
699 return AddRec;
700}
701
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000702/// HoistStep - Attempt to hoist an IV increment above a potential use.
703///
704/// To successfully hoist, two criteria must be met:
705/// - IncV operands dominate InsertPos and
706/// - InsertPos dominates IncV
707///
708/// Meeting the second condition means that we don't need to check all of IncV's
709/// existing uses (it's moving up in the domtree).
710///
711/// This does not yet recursively hoist the operands, although that would
712/// not be difficult.
713static bool HoistStep(Instruction *IncV, Instruction *InsertPos,
714 const DominatorTree *DT)
715{
716 if (DT->dominates(IncV, InsertPos))
717 return true;
718
719 if (!DT->dominates(InsertPos->getParent(), IncV->getParent()))
720 return false;
721
722 if (IncV->mayHaveSideEffects())
723 return false;
724
725 // Attempt to hoist IncV
726 for (User::op_iterator OI = IncV->op_begin(), OE = IncV->op_end();
727 OI != OE; ++OI) {
728 Instruction *OInst = dyn_cast<Instruction>(OI);
729 if (OInst && !DT->dominates(OInst, InsertPos))
730 return false;
731 }
732 IncV->moveBefore(InsertPos);
733 return true;
734}
735
Andrew Trickf85092c2011-05-20 18:25:42 +0000736/// WidenIVUse - Determine whether an individual user of the narrow IV can be
737/// widened. If so, return the wide clone of the user.
738Instruction *WidenIV::WidenIVUse(Instruction *NarrowUse,
739 Instruction *NarrowDef,
740 Instruction *WideDef) {
741 // To be consistent with IVUsers, stop traversing the def-use chain at
742 // inner-loop phis or post-loop phis.
743 if (isa<PHINode>(NarrowUse) && LI->getLoopFor(NarrowUse->getParent()) != L)
744 return 0;
745
746 // Handle data flow merges and bizarre phi cycles.
747 if (!Processed.insert(NarrowUse))
748 return 0;
749
750 // Our raison d'etre! Eliminate sign and zero extension.
751 if (IsSigned ? isa<SExtInst>(NarrowUse) : isa<ZExtInst>(NarrowUse)) {
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000752 Value *NewDef = WideDef;
753 if (NarrowUse->getType() != WideType) {
754 unsigned CastWidth = SE->getTypeSizeInBits(NarrowUse->getType());
755 unsigned IVWidth = SE->getTypeSizeInBits(WideType);
756 if (CastWidth < IVWidth) {
757 // The cast isn't as wide as the IV, so insert a Trunc.
758 IRBuilder<> Builder(NarrowUse);
759 NewDef = Builder.CreateTrunc(WideDef, NarrowUse->getType());
760 }
761 else {
762 // A wider extend was hidden behind a narrower one. This may induce
763 // another round of IV widening in which the intermediate IV becomes
764 // dead. It should be very rare.
765 DEBUG(dbgs() << "INDVARS: New IV " << *WidePhi
766 << " not wide enough to subsume " << *NarrowUse << "\n");
767 NarrowUse->replaceUsesOfWith(NarrowDef, WideDef);
768 NewDef = NarrowUse;
769 }
770 }
771 if (NewDef != NarrowUse) {
772 DEBUG(dbgs() << "INDVARS: eliminating " << *NarrowUse
773 << " replaced by " << *WideDef << "\n");
774 ++NumElimExt;
775 NarrowUse->replaceAllUsesWith(NewDef);
776 DeadInsts.push_back(NarrowUse);
777 }
Andrew Trickf85092c2011-05-20 18:25:42 +0000778 // Now that the extend is gone, expose it's uses to IVUsers for potential
779 // further simplification within SimplifyIVUsers.
780 IU->AddUsersIfInteresting(WideDef, WidePhi);
781
782 // No further widening is needed. The deceased [sz]ext had done it for us.
783 return 0;
784 }
785 const SCEVAddRecExpr *WideAddRec = GetWideRecurrence(NarrowUse);
786 if (!WideAddRec) {
787 // This user does not evaluate to a recurence after widening, so don't
788 // follow it. Instead insert a Trunc to kill off the original use,
789 // eventually isolating the original narrow IV so it can be removed.
790 IRBuilder<> Builder(NarrowUse);
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000791 Value *Trunc = Builder.CreateTrunc(WideDef, NarrowDef->getType());
Andrew Trickf85092c2011-05-20 18:25:42 +0000792 NarrowUse->replaceUsesOfWith(NarrowDef, Trunc);
793 return 0;
794 }
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000795 // Reuse the IV increment that SCEVExpander created as long as it dominates
796 // NarrowUse.
Andrew Trickf85092c2011-05-20 18:25:42 +0000797 Instruction *WideUse = 0;
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000798 if (WideAddRec == WideIncExpr && HoistStep(WideInc, NarrowUse, DT)) {
Andrew Trickf85092c2011-05-20 18:25:42 +0000799 WideUse = WideInc;
800 }
801 else {
802 WideUse = CloneIVUser(NarrowUse, NarrowDef, WideDef);
803 if (!WideUse)
804 return 0;
805 }
806 // GetWideRecurrence ensured that the narrow expression could be extended
807 // outside the loop without overflow. This suggests that the wide use
808 // evaluates to the same expression as the extended narrow use, but doesn't
809 // absolutely guarantee it. Hence the following failsafe check. In rare cases
810 // where it fails, we simple throw away the newly created wide use.
811 if (WideAddRec != SE->getSCEV(WideUse)) {
812 DEBUG(dbgs() << "Wide use expression mismatch: " << *WideUse
813 << ": " << *SE->getSCEV(WideUse) << " != " << *WideAddRec << "\n");
814 DeadInsts.push_back(WideUse);
815 return 0;
816 }
817
818 // Returning WideUse pushes it on the worklist.
819 return WideUse;
820}
821
822/// CreateWideIV - Process a single induction variable. First use the
823/// SCEVExpander to create a wide induction variable that evaluates to the same
824/// recurrence as the original narrow IV. Then use a worklist to forward
825/// traverse the narrow IV's def-use chain. After WidenIVUse as processed all
826/// interesting IV users, the narrow IV will be isolated for removal by
827/// DeleteDeadPHIs.
828///
829/// It would be simpler to delete uses as they are processed, but we must avoid
830/// invalidating SCEV expressions.
831///
832bool WidenIV::CreateWideIV(SCEVExpander &Rewriter) {
833 // Is this phi an induction variable?
834 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(OrigPhi));
835 if (!AddRec)
836 return false;
837
838 // Widen the induction variable expression.
839 const SCEV *WideIVExpr = IsSigned ?
840 SE->getSignExtendExpr(AddRec, WideType) :
841 SE->getZeroExtendExpr(AddRec, WideType);
842
843 assert(SE->getEffectiveSCEVType(WideIVExpr->getType()) == WideType &&
844 "Expect the new IV expression to preserve its type");
845
846 // Can the IV be extended outside the loop without overflow?
847 AddRec = dyn_cast<SCEVAddRecExpr>(WideIVExpr);
848 if (!AddRec || AddRec->getLoop() != L)
849 return false;
850
851 // An AddRec must have loop-invariant operands. Since this AddRec it
852 // materialized by a loop header phi, the expression cannot have any post-loop
853 // operands, so they must dominate the loop header.
854 assert(SE->properlyDominates(AddRec->getStart(), L->getHeader()) &&
855 SE->properlyDominates(AddRec->getStepRecurrence(*SE), L->getHeader())
856 && "Loop header phi recurrence inputs do not dominate the loop");
857
858 // The rewriter provides a value for the desired IV expression. This may
859 // either find an existing phi or materialize a new one. Either way, we
860 // expect a well-formed cyclic phi-with-increments. i.e. any operand not part
861 // of the phi-SCC dominates the loop entry.
862 Instruction *InsertPt = L->getHeader()->begin();
863 WidePhi = cast<PHINode>(Rewriter.expandCodeFor(AddRec, WideType, InsertPt));
864
865 // Remembering the WideIV increment generated by SCEVExpander allows
866 // WidenIVUse to reuse it when widening the narrow IV's increment. We don't
867 // employ a general reuse mechanism because the call above is the only call to
868 // SCEVExpander. Henceforth, we produce 1-to-1 narrow to wide uses.
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000869 if (BasicBlock *LatchBlock = L->getLoopLatch()) {
870 WideInc =
871 cast<Instruction>(WidePhi->getIncomingValueForBlock(LatchBlock));
872 WideIncExpr = SE->getSCEV(WideInc);
873 }
Andrew Trickf85092c2011-05-20 18:25:42 +0000874
875 DEBUG(dbgs() << "Wide IV: " << *WidePhi << "\n");
876 ++NumWidened;
877
878 // Traverse the def-use chain using a worklist starting at the original IV.
879 assert(Processed.empty() && "expect initial state" );
Andrew Trickf85092c2011-05-20 18:25:42 +0000880
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000881 // Each worklist entry has a Narrow def-use link and Wide def.
882 SmallVector<std::pair<Use *, Instruction *>, 8> NarrowIVUsers;
883 for (Value::use_iterator UI = OrigPhi->use_begin(),
884 UE = OrigPhi->use_end(); UI != UE; ++UI) {
885 NarrowIVUsers.push_back(std::make_pair(&UI.getUse(), WidePhi));
886 }
Andrew Trickf85092c2011-05-20 18:25:42 +0000887 while (!NarrowIVUsers.empty()) {
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000888 Use *NarrowDefUse;
889 Instruction *WideDef;
890 tie(NarrowDefUse, WideDef) = NarrowIVUsers.pop_back_val();
Andrew Trickf85092c2011-05-20 18:25:42 +0000891
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000892 // Process a def-use edge. This may replace the use, so don't hold a
893 // use_iterator across it.
894 Instruction *NarrowDef = cast<Instruction>(NarrowDefUse->get());
895 Instruction *NarrowUse = cast<Instruction>(NarrowDefUse->getUser());
896 Instruction *WideUse = WidenIVUse(NarrowUse, NarrowDef, WideDef);
Andrew Trickf85092c2011-05-20 18:25:42 +0000897
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000898 // Follow all def-use edges from the previous narrow use.
899 if (WideUse) {
900 for (Value::use_iterator UI = NarrowUse->use_begin(),
901 UE = NarrowUse->use_end(); UI != UE; ++UI) {
902 NarrowIVUsers.push_back(std::make_pair(&UI.getUse(), WideUse));
903 }
Andrew Trickf85092c2011-05-20 18:25:42 +0000904 }
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000905 // WidenIVUse may have removed the def-use edge.
906 if (NarrowDef->use_empty())
907 DeadInsts.push_back(NarrowDef);
Andrew Trickf85092c2011-05-20 18:25:42 +0000908 }
909 return true;
910}
911
Andrew Trickaeee4612011-05-12 00:04:28 +0000912void IndVarSimplify::EliminateIVComparison(ICmpInst *ICmp, Value *IVOperand) {
913 unsigned IVOperIdx = 0;
914 ICmpInst::Predicate Pred = ICmp->getPredicate();
915 if (IVOperand != ICmp->getOperand(0)) {
916 // Swapped
917 assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
918 IVOperIdx = 1;
919 Pred = ICmpInst::getSwappedPredicate(Pred);
Dan Gohmana590b792010-04-13 01:46:36 +0000920 }
Andrew Trickaeee4612011-05-12 00:04:28 +0000921
922 // Get the SCEVs for the ICmp operands.
923 const SCEV *S = SE->getSCEV(ICmp->getOperand(IVOperIdx));
924 const SCEV *X = SE->getSCEV(ICmp->getOperand(1 - IVOperIdx));
925
926 // Simplify unnecessary loops away.
927 const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
928 S = SE->getSCEVAtScope(S, ICmpLoop);
929 X = SE->getSCEVAtScope(X, ICmpLoop);
930
931 // If the condition is always true or always false, replace it with
932 // a constant value.
933 if (SE->isKnownPredicate(Pred, S, X))
934 ICmp->replaceAllUsesWith(ConstantInt::getTrue(ICmp->getContext()));
935 else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X))
936 ICmp->replaceAllUsesWith(ConstantInt::getFalse(ICmp->getContext()));
937 else
938 return;
939
940 DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000941 ++NumElimCmp;
Andrew Trick074397d2011-05-20 03:37:48 +0000942 Changed = true;
Andrew Trickaeee4612011-05-12 00:04:28 +0000943 DeadInsts.push_back(ICmp);
944}
945
946void IndVarSimplify::EliminateIVRemainder(BinaryOperator *Rem,
947 Value *IVOperand,
Andrew Trickf85092c2011-05-20 18:25:42 +0000948 bool IsSigned,
949 PHINode *IVPhi) {
Andrew Trickaeee4612011-05-12 00:04:28 +0000950 // We're only interested in the case where we know something about
951 // the numerator.
952 if (IVOperand != Rem->getOperand(0))
953 return;
954
955 // Get the SCEVs for the ICmp operands.
956 const SCEV *S = SE->getSCEV(Rem->getOperand(0));
957 const SCEV *X = SE->getSCEV(Rem->getOperand(1));
958
959 // Simplify unnecessary loops away.
960 const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent());
961 S = SE->getSCEVAtScope(S, ICmpLoop);
962 X = SE->getSCEVAtScope(X, ICmpLoop);
963
964 // i % n --> i if i is in [0,n).
Andrew Trick074397d2011-05-20 03:37:48 +0000965 if ((!IsSigned || SE->isKnownNonNegative(S)) &&
966 SE->isKnownPredicate(IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
Andrew Trickaeee4612011-05-12 00:04:28 +0000967 S, X))
968 Rem->replaceAllUsesWith(Rem->getOperand(0));
969 else {
970 // (i+1) % n --> (i+1)==n?0:(i+1) if i is in [0,n).
971 const SCEV *LessOne =
972 SE->getMinusSCEV(S, SE->getConstant(S->getType(), 1));
Andrew Trick074397d2011-05-20 03:37:48 +0000973 if (IsSigned && !SE->isKnownNonNegative(LessOne))
Andrew Trickaeee4612011-05-12 00:04:28 +0000974 return;
975
Andrew Trick074397d2011-05-20 03:37:48 +0000976 if (!SE->isKnownPredicate(IsSigned ?
Andrew Trickaeee4612011-05-12 00:04:28 +0000977 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
978 LessOne, X))
979 return;
980
981 ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ,
982 Rem->getOperand(0), Rem->getOperand(1),
983 "tmp");
984 SelectInst *Sel =
985 SelectInst::Create(ICmp,
986 ConstantInt::get(Rem->getType(), 0),
987 Rem->getOperand(0), "tmp", Rem);
988 Rem->replaceAllUsesWith(Sel);
989 }
990
991 // Inform IVUsers about the new users.
992 if (Instruction *I = dyn_cast<Instruction>(Rem->getOperand(0)))
Andrew Trickf85092c2011-05-20 18:25:42 +0000993 IU->AddUsersIfInteresting(I, IVPhi);
Andrew Trickaeee4612011-05-12 00:04:28 +0000994
995 DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000996 ++NumElimRem;
Andrew Trick074397d2011-05-20 03:37:48 +0000997 Changed = true;
Andrew Trickaeee4612011-05-12 00:04:28 +0000998 DeadInsts.push_back(Rem);
Dan Gohmana590b792010-04-13 01:46:36 +0000999}
1000
Dan Gohmanc2390b12009-02-12 22:19:27 +00001001bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
Dan Gohmana5283822010-06-18 01:35:11 +00001002 // If LoopSimplify form is not available, stay out of trouble. Some notes:
1003 // - LSR currently only supports LoopSimplify-form loops. Indvars'
1004 // canonicalization can be a pessimization without LSR to "clean up"
1005 // afterwards.
1006 // - We depend on having a preheader; in particular,
1007 // Loop::getCanonicalInductionVariable only supports loops with preheaders,
1008 // and we're in trouble if we can't find the induction variable even when
1009 // we've manually inserted one.
1010 if (!L->isLoopSimplifyForm())
1011 return false;
1012
Dan Gohman81db61a2009-05-12 02:17:14 +00001013 IU = &getAnalysis<IVUsers>();
Devang Patel5ee99972007-03-07 06:39:01 +00001014 LI = &getAnalysis<LoopInfo>();
1015 SE = &getAnalysis<ScalarEvolution>();
Dan Gohmande53dc02009-06-27 05:16:57 +00001016 DT = &getAnalysis<DominatorTree>();
Andrew Trick37da4082011-05-04 02:10:13 +00001017 TD = getAnalysisIfAvailable<TargetData>();
1018
Andrew Trickb12a7542011-03-17 23:51:11 +00001019 DeadInsts.clear();
Devang Patel5ee99972007-03-07 06:39:01 +00001020 Changed = false;
Dan Gohman60f8a632009-02-17 20:49:49 +00001021
Dan Gohman2d1be872009-04-16 03:18:22 +00001022 // If there are any floating-point recurrences, attempt to
Dan Gohman60f8a632009-02-17 20:49:49 +00001023 // transform them to use integer recurrences.
1024 RewriteNonIntegerIVs(L);
1025
Dan Gohman0bba49c2009-07-07 17:06:11 +00001026 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
Chris Lattner9caed542007-03-04 01:00:28 +00001027
Dan Gohman667d7872009-06-26 22:53:46 +00001028 // Create a rewriter object which we'll use to transform the code with.
1029 SCEVExpander Rewriter(*SE);
Andrew Trick37da4082011-05-04 02:10:13 +00001030 if (DisableIVRewrite)
1031 Rewriter.disableCanonicalMode();
1032
Chris Lattner40bf8b42004-04-02 20:24:31 +00001033 // Check to see if this loop has a computable loop-invariant execution count.
1034 // If so, this means that we can compute the final value of any expressions
1035 // that are recurrent in the loop, and substitute the exit values from the
1036 // loop into any instructions outside of the loop that use the final values of
1037 // the current expressions.
Chris Lattner3dec1f22002-05-10 15:38:35 +00001038 //
Dan Gohman46bdfb02009-02-24 18:55:53 +00001039 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount))
Dan Gohman454d26d2010-02-22 04:11:59 +00001040 RewriteLoopExitValues(L, Rewriter);
Chris Lattner6148c022001-12-03 17:28:42 +00001041
Andrew Trickf85092c2011-05-20 18:25:42 +00001042 // Eliminate redundant IV users.
1043 SimplifyIVUsers(Rewriter);
Dan Gohmana590b792010-04-13 01:46:36 +00001044
Dan Gohman81db61a2009-05-12 02:17:14 +00001045 // Compute the type of the largest recurrence expression, and decide whether
1046 // a canonical induction variable should be inserted.
Andrew Trickf85092c2011-05-20 18:25:42 +00001047 const Type *LargestType = 0;
Dan Gohman81db61a2009-05-12 02:17:14 +00001048 bool NeedCannIV = false;
Andrew Trick03d3d3b2011-05-25 04:42:22 +00001049 bool ExpandBECount = canExpandBackedgeTakenCount(L, SE);
Andrew Trick4dfdf242011-05-03 22:24:10 +00001050 if (ExpandBECount) {
Dan Gohman81db61a2009-05-12 02:17:14 +00001051 // If we have a known trip count and a single exit block, we'll be
1052 // rewriting the loop exit test condition below, which requires a
1053 // canonical induction variable.
Andrew Trick4dfdf242011-05-03 22:24:10 +00001054 NeedCannIV = true;
1055 const Type *Ty = BackedgeTakenCount->getType();
Andrew Trick03d3d3b2011-05-25 04:42:22 +00001056 if (DisableIVRewrite) {
1057 // In this mode, SimplifyIVUsers may have already widened the IV used by
1058 // the backedge test and inserted a Trunc on the compare's operand. Get
1059 // the wider type to avoid creating a redundant narrow IV only used by the
1060 // loop test.
1061 LargestType = getBackedgeIVType(L);
1062 }
Andrew Trick4dfdf242011-05-03 22:24:10 +00001063 if (!LargestType ||
1064 SE->getTypeSizeInBits(Ty) >
1065 SE->getTypeSizeInBits(LargestType))
1066 LargestType = SE->getEffectiveSCEVType(Ty);
Chris Lattnerf50af082004-04-17 18:08:33 +00001067 }
Andrew Trick37da4082011-05-04 02:10:13 +00001068 if (!DisableIVRewrite) {
1069 for (IVUsers::const_iterator I = IU->begin(), E = IU->end(); I != E; ++I) {
1070 NeedCannIV = true;
1071 const Type *Ty =
1072 SE->getEffectiveSCEVType(I->getOperandValToReplace()->getType());
1073 if (!LargestType ||
1074 SE->getTypeSizeInBits(Ty) >
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001075 SE->getTypeSizeInBits(LargestType))
Andrew Trick37da4082011-05-04 02:10:13 +00001076 LargestType = Ty;
1077 }
Chris Lattner6148c022001-12-03 17:28:42 +00001078 }
1079
Dan Gohmanf451cb82010-02-10 16:03:48 +00001080 // Now that we know the largest of the induction variable expressions
Dan Gohman81db61a2009-05-12 02:17:14 +00001081 // in this loop, insert a canonical induction variable of the largest size.
Dan Gohman43ef3fb2010-07-20 17:18:52 +00001082 PHINode *IndVar = 0;
Dan Gohman81db61a2009-05-12 02:17:14 +00001083 if (NeedCannIV) {
Dan Gohman85669632010-02-25 06:57:05 +00001084 // Check to see if the loop already has any canonical-looking induction
1085 // variables. If any are present and wider than the planned canonical
1086 // induction variable, temporarily remove them, so that the Rewriter
1087 // doesn't attempt to reuse them.
1088 SmallVector<PHINode *, 2> OldCannIVs;
1089 while (PHINode *OldCannIV = L->getCanonicalInductionVariable()) {
Dan Gohman4d8414f2009-06-13 16:25:49 +00001090 if (SE->getTypeSizeInBits(OldCannIV->getType()) >
1091 SE->getTypeSizeInBits(LargestType))
1092 OldCannIV->removeFromParent();
1093 else
Dan Gohman85669632010-02-25 06:57:05 +00001094 break;
1095 OldCannIVs.push_back(OldCannIV);
Dan Gohman4d8414f2009-06-13 16:25:49 +00001096 }
1097
Dan Gohman667d7872009-06-26 22:53:46 +00001098 IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L, LargestType);
Dan Gohman4d8414f2009-06-13 16:25:49 +00001099
Dan Gohmanc2390b12009-02-12 22:19:27 +00001100 ++NumInserted;
1101 Changed = true;
David Greenef67ef312010-01-05 01:27:06 +00001102 DEBUG(dbgs() << "INDVARS: New CanIV: " << *IndVar << '\n');
Dan Gohman4d8414f2009-06-13 16:25:49 +00001103
1104 // Now that the official induction variable is established, reinsert
Dan Gohman85669632010-02-25 06:57:05 +00001105 // any old canonical-looking variables after it so that the IR remains
1106 // consistent. They will be deleted as part of the dead-PHI deletion at
Dan Gohman4d8414f2009-06-13 16:25:49 +00001107 // the end of the pass.
Dan Gohman85669632010-02-25 06:57:05 +00001108 while (!OldCannIVs.empty()) {
1109 PHINode *OldCannIV = OldCannIVs.pop_back_val();
1110 OldCannIV->insertBefore(L->getHeader()->getFirstNonPHI());
1111 }
Dan Gohmand19534a2007-06-15 14:38:12 +00001112 }
Chris Lattner15cad752003-12-23 07:47:09 +00001113
Dan Gohmanc2390b12009-02-12 22:19:27 +00001114 // If we have a trip count expression, rewrite the loop's exit condition
1115 // using it. We can currently only handle loops with a single exit.
Dan Gohman81db61a2009-05-12 02:17:14 +00001116 ICmpInst *NewICmp = 0;
Andrew Trick4dfdf242011-05-03 22:24:10 +00001117 if (ExpandBECount) {
Andrew Trick03d3d3b2011-05-25 04:42:22 +00001118 assert(canExpandBackedgeTakenCount(L, SE) &&
Andrew Trick4dfdf242011-05-03 22:24:10 +00001119 "canonical IV disrupted BackedgeTaken expansion");
Dan Gohman81db61a2009-05-12 02:17:14 +00001120 assert(NeedCannIV &&
1121 "LinearFunctionTestReplace requires a canonical induction variable");
Andrew Trick4dfdf242011-05-03 22:24:10 +00001122 NewICmp = LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar,
1123 Rewriter);
Chris Lattnerfcb81f52004-04-22 14:59:40 +00001124 }
Andrew Trickb12a7542011-03-17 23:51:11 +00001125 // Rewrite IV-derived expressions.
Andrew Trick37da4082011-05-04 02:10:13 +00001126 if (!DisableIVRewrite)
1127 RewriteIVExpressions(L, Rewriter);
Dan Gohmanc2390b12009-02-12 22:19:27 +00001128
Andrew Trickb12a7542011-03-17 23:51:11 +00001129 // Clear the rewriter cache, because values that are in the rewriter's cache
1130 // can be deleted in the loop below, causing the AssertingVH in the cache to
1131 // trigger.
1132 Rewriter.clear();
1133
1134 // Now that we're done iterating through lists, clean up any instructions
1135 // which are now dead.
1136 while (!DeadInsts.empty())
1137 if (Instruction *Inst =
1138 dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val()))
1139 RecursivelyDeleteTriviallyDeadInstructions(Inst);
1140
Dan Gohman667d7872009-06-26 22:53:46 +00001141 // The Rewriter may not be used from this point on.
Torok Edwin3d431382009-05-24 20:08:21 +00001142
Dan Gohman81db61a2009-05-12 02:17:14 +00001143 // Loop-invariant instructions in the preheader that aren't used in the
1144 // loop may be sunk below the loop to reduce register pressure.
Dan Gohman667d7872009-06-26 22:53:46 +00001145 SinkUnusedInvariants(L);
Dan Gohman81db61a2009-05-12 02:17:14 +00001146
1147 // For completeness, inform IVUsers of the IV use in the newly-created
1148 // loop exit test instruction.
1149 if (NewICmp)
Andrew Trickf85092c2011-05-20 18:25:42 +00001150 IU->AddUsersIfInteresting(cast<Instruction>(NewICmp->getOperand(0)),
1151 IndVar);
Dan Gohman81db61a2009-05-12 02:17:14 +00001152
1153 // Clean up dead instructions.
Dan Gohman9fff2182010-01-05 16:31:45 +00001154 Changed |= DeleteDeadPHIs(L->getHeader());
Dan Gohman81db61a2009-05-12 02:17:14 +00001155 // Check a post-condition.
Dan Gohmanbbf81d82010-03-10 19:38:49 +00001156 assert(L->isLCSSAForm(*DT) && "Indvars did not leave the loop in lcssa form!");
Devang Patel5ee99972007-03-07 06:39:01 +00001157 return Changed;
Chris Lattner6148c022001-12-03 17:28:42 +00001158}
Devang Pateld22a8492008-09-09 21:41:07 +00001159
Dan Gohman448db1c2010-04-07 22:27:08 +00001160// FIXME: It is an extremely bad idea to indvar substitute anything more
1161// complex than affine induction variables. Doing so will put expensive
1162// polynomial evaluations inside of the loop, and the str reduction pass
1163// currently can only reduce affine polynomials. For now just disable
1164// indvar subst on anything more complex than an affine addrec, unless
1165// it can be expanded to a trivial value.
Dan Gohman17ead4f2010-11-17 21:23:15 +00001166static bool isSafe(const SCEV *S, const Loop *L, ScalarEvolution *SE) {
Dan Gohman448db1c2010-04-07 22:27:08 +00001167 // Loop-invariant values are safe.
Dan Gohman17ead4f2010-11-17 21:23:15 +00001168 if (SE->isLoopInvariant(S, L)) return true;
Dan Gohman448db1c2010-04-07 22:27:08 +00001169
1170 // Affine addrecs are safe. Non-affine are not, because LSR doesn't know how
1171 // to transform them into efficient code.
1172 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
1173 return AR->isAffine();
1174
1175 // An add is safe it all its operands are safe.
1176 if (const SCEVCommutativeExpr *Commutative = dyn_cast<SCEVCommutativeExpr>(S)) {
1177 for (SCEVCommutativeExpr::op_iterator I = Commutative->op_begin(),
1178 E = Commutative->op_end(); I != E; ++I)
Dan Gohman17ead4f2010-11-17 21:23:15 +00001179 if (!isSafe(*I, L, SE)) return false;
Dan Gohman448db1c2010-04-07 22:27:08 +00001180 return true;
1181 }
Andrew Trickead71d52011-03-17 23:46:48 +00001182
Dan Gohman448db1c2010-04-07 22:27:08 +00001183 // A cast is safe if its operand is.
1184 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
Dan Gohman17ead4f2010-11-17 21:23:15 +00001185 return isSafe(C->getOperand(), L, SE);
Dan Gohman448db1c2010-04-07 22:27:08 +00001186
1187 // A udiv is safe if its operands are.
1188 if (const SCEVUDivExpr *UD = dyn_cast<SCEVUDivExpr>(S))
Dan Gohman17ead4f2010-11-17 21:23:15 +00001189 return isSafe(UD->getLHS(), L, SE) &&
1190 isSafe(UD->getRHS(), L, SE);
Dan Gohman448db1c2010-04-07 22:27:08 +00001191
1192 // SCEVUnknown is always safe.
1193 if (isa<SCEVUnknown>(S))
1194 return true;
1195
1196 // Nothing else is safe.
1197 return false;
1198}
1199
Dan Gohman454d26d2010-02-22 04:11:59 +00001200void IndVarSimplify::RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter) {
Dan Gohman81db61a2009-05-12 02:17:14 +00001201 // Rewrite all induction variable expressions in terms of the canonical
1202 // induction variable.
1203 //
1204 // If there were induction variables of other sizes or offsets, manually
1205 // add the offsets to the primary induction variable and cast, avoiding
1206 // the need for the code evaluation methods to insert induction variables
1207 // of different sizes.
Dan Gohman572645c2010-02-12 10:34:29 +00001208 for (IVUsers::iterator UI = IU->begin(), E = IU->end(); UI != E; ++UI) {
Dan Gohman572645c2010-02-12 10:34:29 +00001209 Value *Op = UI->getOperandValToReplace();
1210 const Type *UseTy = Op->getType();
1211 Instruction *User = UI->getUser();
Dan Gohman81db61a2009-05-12 02:17:14 +00001212
Dan Gohman572645c2010-02-12 10:34:29 +00001213 // Compute the final addrec to expand into code.
1214 const SCEV *AR = IU->getReplacementExpr(*UI);
Dan Gohman81db61a2009-05-12 02:17:14 +00001215
Dan Gohman572645c2010-02-12 10:34:29 +00001216 // Evaluate the expression out of the loop, if possible.
1217 if (!L->contains(UI->getUser())) {
1218 const SCEV *ExitVal = SE->getSCEVAtScope(AR, L->getParentLoop());
Dan Gohman17ead4f2010-11-17 21:23:15 +00001219 if (SE->isLoopInvariant(ExitVal, L))
Dan Gohman572645c2010-02-12 10:34:29 +00001220 AR = ExitVal;
Dan Gohman81db61a2009-05-12 02:17:14 +00001221 }
Dan Gohman572645c2010-02-12 10:34:29 +00001222
1223 // FIXME: It is an extremely bad idea to indvar substitute anything more
1224 // complex than affine induction variables. Doing so will put expensive
1225 // polynomial evaluations inside of the loop, and the str reduction pass
1226 // currently can only reduce affine polynomials. For now just disable
1227 // indvar subst on anything more complex than an affine addrec, unless
1228 // it can be expanded to a trivial value.
Dan Gohman17ead4f2010-11-17 21:23:15 +00001229 if (!isSafe(AR, L, SE))
Dan Gohman572645c2010-02-12 10:34:29 +00001230 continue;
1231
1232 // Determine the insertion point for this user. By default, insert
1233 // immediately before the user. The SCEVExpander class will automatically
1234 // hoist loop invariants out of the loop. For PHI nodes, there may be
1235 // multiple uses, so compute the nearest common dominator for the
1236 // incoming blocks.
1237 Instruction *InsertPt = User;
1238 if (PHINode *PHI = dyn_cast<PHINode>(InsertPt))
1239 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
1240 if (PHI->getIncomingValue(i) == Op) {
1241 if (InsertPt == User)
1242 InsertPt = PHI->getIncomingBlock(i)->getTerminator();
1243 else
1244 InsertPt =
1245 DT->findNearestCommonDominator(InsertPt->getParent(),
1246 PHI->getIncomingBlock(i))
1247 ->getTerminator();
1248 }
1249
1250 // Now expand it into actual Instructions and patch it into place.
1251 Value *NewVal = Rewriter.expandCodeFor(AR, UseTy, InsertPt);
1252
Andrew Trickb12a7542011-03-17 23:51:11 +00001253 DEBUG(dbgs() << "INDVARS: Rewrote IV '" << *AR << "' " << *Op << '\n'
1254 << " into = " << *NewVal << "\n");
1255
1256 if (!isValidRewrite(Op, NewVal)) {
1257 DeadInsts.push_back(NewVal);
1258 continue;
1259 }
Dan Gohmand7bfd002010-04-02 14:48:31 +00001260 // Inform ScalarEvolution that this value is changing. The change doesn't
1261 // affect its value, but it does potentially affect which use lists the
1262 // value will be on after the replacement, which affects ScalarEvolution's
1263 // ability to walk use lists and drop dangling pointers when a value is
1264 // deleted.
1265 SE->forgetValue(User);
1266
Dan Gohman572645c2010-02-12 10:34:29 +00001267 // Patch the new value into place.
1268 if (Op->hasName())
1269 NewVal->takeName(Op);
1270 User->replaceUsesOfWith(Op, NewVal);
1271 UI->setOperandValToReplace(NewVal);
Andrew Trickb12a7542011-03-17 23:51:11 +00001272
Dan Gohman572645c2010-02-12 10:34:29 +00001273 ++NumRemoved;
1274 Changed = true;
1275
1276 // The old value may be dead now.
1277 DeadInsts.push_back(Op);
Dan Gohman81db61a2009-05-12 02:17:14 +00001278 }
Dan Gohman81db61a2009-05-12 02:17:14 +00001279}
1280
1281/// If there's a single exit block, sink any loop-invariant values that
1282/// were defined in the preheader but not used inside the loop into the
1283/// exit block to reduce register pressure in the loop.
Dan Gohman667d7872009-06-26 22:53:46 +00001284void IndVarSimplify::SinkUnusedInvariants(Loop *L) {
Dan Gohman81db61a2009-05-12 02:17:14 +00001285 BasicBlock *ExitBlock = L->getExitBlock();
1286 if (!ExitBlock) return;
1287
Dan Gohman81db61a2009-05-12 02:17:14 +00001288 BasicBlock *Preheader = L->getLoopPreheader();
Dan Gohman03e896b2009-11-05 21:11:53 +00001289 if (!Preheader) return;
1290
1291 Instruction *InsertPt = ExitBlock->getFirstNonPHI();
Dan Gohman81db61a2009-05-12 02:17:14 +00001292 BasicBlock::iterator I = Preheader->getTerminator();
1293 while (I != Preheader->begin()) {
1294 --I;
Dan Gohman667d7872009-06-26 22:53:46 +00001295 // New instructions were inserted at the end of the preheader.
1296 if (isa<PHINode>(I))
Dan Gohman81db61a2009-05-12 02:17:14 +00001297 break;
Bill Wendling87a10f52010-03-23 21:15:59 +00001298
Eli Friedman0c77db32009-07-15 22:48:29 +00001299 // Don't move instructions which might have side effects, since the side
Bill Wendling87a10f52010-03-23 21:15:59 +00001300 // effects need to complete before instructions inside the loop. Also don't
1301 // move instructions which might read memory, since the loop may modify
1302 // memory. Note that it's okay if the instruction might have undefined
1303 // behavior: LoopSimplify guarantees that the preheader dominates the exit
1304 // block.
Eli Friedman0c77db32009-07-15 22:48:29 +00001305 if (I->mayHaveSideEffects() || I->mayReadFromMemory())
Dan Gohman667d7872009-06-26 22:53:46 +00001306 continue;
Bill Wendling87a10f52010-03-23 21:15:59 +00001307
Devang Patel7b9f6b12010-03-15 22:23:03 +00001308 // Skip debug info intrinsics.
1309 if (isa<DbgInfoIntrinsic>(I))
1310 continue;
Bill Wendling87a10f52010-03-23 21:15:59 +00001311
Dan Gohman76f497a2009-08-25 17:42:10 +00001312 // Don't sink static AllocaInsts out of the entry block, which would
1313 // turn them into dynamic allocas!
1314 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
1315 if (AI->isStaticAlloca())
1316 continue;
Bill Wendling87a10f52010-03-23 21:15:59 +00001317
Dan Gohman81db61a2009-05-12 02:17:14 +00001318 // Determine if there is a use in or before the loop (direct or
1319 // otherwise).
1320 bool UsedInLoop = false;
1321 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
1322 UI != UE; ++UI) {
Gabor Greif76560182010-07-09 15:40:10 +00001323 User *U = *UI;
1324 BasicBlock *UseBB = cast<Instruction>(U)->getParent();
1325 if (PHINode *P = dyn_cast<PHINode>(U)) {
Dan Gohman81db61a2009-05-12 02:17:14 +00001326 unsigned i =
1327 PHINode::getIncomingValueNumForOperand(UI.getOperandNo());
1328 UseBB = P->getIncomingBlock(i);
1329 }
1330 if (UseBB == Preheader || L->contains(UseBB)) {
1331 UsedInLoop = true;
1332 break;
1333 }
1334 }
Bill Wendling87a10f52010-03-23 21:15:59 +00001335
Dan Gohman81db61a2009-05-12 02:17:14 +00001336 // If there is, the def must remain in the preheader.
1337 if (UsedInLoop)
1338 continue;
Bill Wendling87a10f52010-03-23 21:15:59 +00001339
Dan Gohman81db61a2009-05-12 02:17:14 +00001340 // Otherwise, sink it to the exit block.
1341 Instruction *ToMove = I;
1342 bool Done = false;
Bill Wendling87a10f52010-03-23 21:15:59 +00001343
1344 if (I != Preheader->begin()) {
1345 // Skip debug info intrinsics.
1346 do {
1347 --I;
1348 } while (isa<DbgInfoIntrinsic>(I) && I != Preheader->begin());
1349
1350 if (isa<DbgInfoIntrinsic>(I) && I == Preheader->begin())
1351 Done = true;
1352 } else {
Dan Gohman81db61a2009-05-12 02:17:14 +00001353 Done = true;
Bill Wendling87a10f52010-03-23 21:15:59 +00001354 }
1355
Dan Gohman667d7872009-06-26 22:53:46 +00001356 ToMove->moveBefore(InsertPt);
Bill Wendling87a10f52010-03-23 21:15:59 +00001357 if (Done) break;
Dan Gohman667d7872009-06-26 22:53:46 +00001358 InsertPt = ToMove;
Dan Gohman81db61a2009-05-12 02:17:14 +00001359 }
1360}
1361
Chris Lattnerbbb91492010-04-03 06:41:49 +00001362/// ConvertToSInt - Convert APF to an integer, if possible.
1363static bool ConvertToSInt(const APFloat &APF, int64_t &IntVal) {
Devang Patelcd402332008-11-17 23:27:13 +00001364 bool isExact = false;
Evan Cheng794a7db2008-11-26 01:11:57 +00001365 if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
1366 return false;
Chris Lattnerbbb91492010-04-03 06:41:49 +00001367 // See if we can convert this to an int64_t
1368 uint64_t UIntVal;
1369 if (APF.convertToInteger(&UIntVal, 64, true, APFloat::rmTowardZero,
1370 &isExact) != APFloat::opOK || !isExact)
Devang Patelcd402332008-11-17 23:27:13 +00001371 return false;
Chris Lattnerbbb91492010-04-03 06:41:49 +00001372 IntVal = UIntVal;
Devang Patelcd402332008-11-17 23:27:13 +00001373 return true;
Devang Patelcd402332008-11-17 23:27:13 +00001374}
1375
Devang Patel58d43d42008-11-03 18:32:19 +00001376/// HandleFloatingPointIV - If the loop has floating induction variable
1377/// then insert corresponding integer induction variable if possible.
Devang Patel84e35152008-11-17 21:32:02 +00001378/// For example,
1379/// for(double i = 0; i < 10000; ++i)
1380/// bar(i)
1381/// is converted into
1382/// for(int i = 0; i < 10000; ++i)
1383/// bar((double)i);
1384///
Chris Lattnerc91961e2010-04-03 06:17:08 +00001385void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PN) {
1386 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
Devang Patel84e35152008-11-17 21:32:02 +00001387 unsigned BackEdge = IncomingEdge^1;
Dan Gohmancafb8132009-02-17 19:13:57 +00001388
Devang Patel84e35152008-11-17 21:32:02 +00001389 // Check incoming value.
Chris Lattnerc4f7e802010-04-03 06:05:10 +00001390 ConstantFP *InitValueVal =
Chris Lattnerc91961e2010-04-03 06:17:08 +00001391 dyn_cast<ConstantFP>(PN->getIncomingValue(IncomingEdge));
Chris Lattner96fd7662010-04-03 07:18:48 +00001392
Chris Lattnerbbb91492010-04-03 06:41:49 +00001393 int64_t InitValue;
Chris Lattner96fd7662010-04-03 07:18:48 +00001394 if (!InitValueVal || !ConvertToSInt(InitValueVal->getValueAPF(), InitValue))
Devang Patelcd402332008-11-17 23:27:13 +00001395 return;
1396
Chris Lattnerc91961e2010-04-03 06:17:08 +00001397 // Check IV increment. Reject this PN if increment operation is not
Devang Patelcd402332008-11-17 23:27:13 +00001398 // an add or increment value can not be represented by an integer.
Dan Gohmancafb8132009-02-17 19:13:57 +00001399 BinaryOperator *Incr =
Chris Lattnerc91961e2010-04-03 06:17:08 +00001400 dyn_cast<BinaryOperator>(PN->getIncomingValue(BackEdge));
Chris Lattner07aa76a2010-04-03 05:54:59 +00001401 if (Incr == 0 || Incr->getOpcode() != Instruction::FAdd) return;
Andrew Trickead71d52011-03-17 23:46:48 +00001402
Chris Lattner07aa76a2010-04-03 05:54:59 +00001403 // If this is not an add of the PHI with a constantfp, or if the constant fp
1404 // is not an integer, bail out.
Chris Lattnerc4f7e802010-04-03 06:05:10 +00001405 ConstantFP *IncValueVal = dyn_cast<ConstantFP>(Incr->getOperand(1));
Chris Lattner96fd7662010-04-03 07:18:48 +00001406 int64_t IncValue;
Chris Lattnerc91961e2010-04-03 06:17:08 +00001407 if (IncValueVal == 0 || Incr->getOperand(0) != PN ||
Chris Lattner96fd7662010-04-03 07:18:48 +00001408 !ConvertToSInt(IncValueVal->getValueAPF(), IncValue))
Devang Patelcd402332008-11-17 23:27:13 +00001409 return;
Dan Gohmancafb8132009-02-17 19:13:57 +00001410
Chris Lattnerc91961e2010-04-03 06:17:08 +00001411 // Check Incr uses. One user is PN and the other user is an exit condition
Chris Lattner07aa76a2010-04-03 05:54:59 +00001412 // used by the conditional terminator.
Devang Patel84e35152008-11-17 21:32:02 +00001413 Value::use_iterator IncrUse = Incr->use_begin();
Gabor Greif96f1d8e2010-07-22 13:36:47 +00001414 Instruction *U1 = cast<Instruction>(*IncrUse++);
Devang Patel84e35152008-11-17 21:32:02 +00001415 if (IncrUse == Incr->use_end()) return;
Gabor Greif96f1d8e2010-07-22 13:36:47 +00001416 Instruction *U2 = cast<Instruction>(*IncrUse++);
Devang Patel84e35152008-11-17 21:32:02 +00001417 if (IncrUse != Incr->use_end()) return;
Dan Gohmancafb8132009-02-17 19:13:57 +00001418
Chris Lattner07aa76a2010-04-03 05:54:59 +00001419 // Find exit condition, which is an fcmp. If it doesn't exist, or if it isn't
1420 // only used by a branch, we can't transform it.
Chris Lattnerca703bd2010-04-03 06:11:07 +00001421 FCmpInst *Compare = dyn_cast<FCmpInst>(U1);
1422 if (!Compare)
1423 Compare = dyn_cast<FCmpInst>(U2);
1424 if (Compare == 0 || !Compare->hasOneUse() ||
1425 !isa<BranchInst>(Compare->use_back()))
Chris Lattner07aa76a2010-04-03 05:54:59 +00001426 return;
Andrew Trickead71d52011-03-17 23:46:48 +00001427
Chris Lattnerca703bd2010-04-03 06:11:07 +00001428 BranchInst *TheBr = cast<BranchInst>(Compare->use_back());
Devang Patel84e35152008-11-17 21:32:02 +00001429
Chris Lattnerd52c0722010-04-03 07:21:39 +00001430 // We need to verify that the branch actually controls the iteration count
1431 // of the loop. If not, the new IV can overflow and no one will notice.
1432 // The branch block must be in the loop and one of the successors must be out
1433 // of the loop.
1434 assert(TheBr->isConditional() && "Can't use fcmp if not conditional");
1435 if (!L->contains(TheBr->getParent()) ||
1436 (L->contains(TheBr->getSuccessor(0)) &&
1437 L->contains(TheBr->getSuccessor(1))))
1438 return;
Andrew Trickead71d52011-03-17 23:46:48 +00001439
1440
Chris Lattner07aa76a2010-04-03 05:54:59 +00001441 // If it isn't a comparison with an integer-as-fp (the exit value), we can't
1442 // transform it.
Chris Lattnerca703bd2010-04-03 06:11:07 +00001443 ConstantFP *ExitValueVal = dyn_cast<ConstantFP>(Compare->getOperand(1));
Chris Lattnerbbb91492010-04-03 06:41:49 +00001444 int64_t ExitValue;
1445 if (ExitValueVal == 0 ||
1446 !ConvertToSInt(ExitValueVal->getValueAPF(), ExitValue))
Devang Patel84e35152008-11-17 21:32:02 +00001447 return;
Andrew Trickead71d52011-03-17 23:46:48 +00001448
Devang Patel84e35152008-11-17 21:32:02 +00001449 // Find new predicate for integer comparison.
1450 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
Chris Lattnerca703bd2010-04-03 06:11:07 +00001451 switch (Compare->getPredicate()) {
Chris Lattnerc4f7e802010-04-03 06:05:10 +00001452 default: return; // Unknown comparison.
Devang Patel84e35152008-11-17 21:32:02 +00001453 case CmpInst::FCMP_OEQ:
Chris Lattnerc4f7e802010-04-03 06:05:10 +00001454 case CmpInst::FCMP_UEQ: NewPred = CmpInst::ICMP_EQ; break;
Chris Lattner96fd7662010-04-03 07:18:48 +00001455 case CmpInst::FCMP_ONE:
1456 case CmpInst::FCMP_UNE: NewPred = CmpInst::ICMP_NE; break;
Devang Patel84e35152008-11-17 21:32:02 +00001457 case CmpInst::FCMP_OGT:
Chris Lattnera40e4a02010-04-03 06:25:21 +00001458 case CmpInst::FCMP_UGT: NewPred = CmpInst::ICMP_SGT; break;
Devang Patel84e35152008-11-17 21:32:02 +00001459 case CmpInst::FCMP_OGE:
Chris Lattnera40e4a02010-04-03 06:25:21 +00001460 case CmpInst::FCMP_UGE: NewPred = CmpInst::ICMP_SGE; break;
Devang Patel84e35152008-11-17 21:32:02 +00001461 case CmpInst::FCMP_OLT:
Chris Lattner43b85272010-04-03 06:30:03 +00001462 case CmpInst::FCMP_ULT: NewPred = CmpInst::ICMP_SLT; break;
Devang Patel84e35152008-11-17 21:32:02 +00001463 case CmpInst::FCMP_OLE:
Chris Lattner43b85272010-04-03 06:30:03 +00001464 case CmpInst::FCMP_ULE: NewPred = CmpInst::ICMP_SLE; break;
Devang Patel58d43d42008-11-03 18:32:19 +00001465 }
Andrew Trickead71d52011-03-17 23:46:48 +00001466
Chris Lattner96fd7662010-04-03 07:18:48 +00001467 // We convert the floating point induction variable to a signed i32 value if
1468 // we can. This is only safe if the comparison will not overflow in a way
1469 // that won't be trapped by the integer equivalent operations. Check for this
1470 // now.
1471 // TODO: We could use i64 if it is native and the range requires it.
Andrew Trickead71d52011-03-17 23:46:48 +00001472
Chris Lattner96fd7662010-04-03 07:18:48 +00001473 // The start/stride/exit values must all fit in signed i32.
1474 if (!isInt<32>(InitValue) || !isInt<32>(IncValue) || !isInt<32>(ExitValue))
1475 return;
1476
1477 // If not actually striding (add x, 0.0), avoid touching the code.
1478 if (IncValue == 0)
1479 return;
1480
1481 // Positive and negative strides have different safety conditions.
1482 if (IncValue > 0) {
1483 // If we have a positive stride, we require the init to be less than the
1484 // exit value and an equality or less than comparison.
1485 if (InitValue >= ExitValue ||
1486 NewPred == CmpInst::ICMP_SGT || NewPred == CmpInst::ICMP_SGE)
1487 return;
Andrew Trickead71d52011-03-17 23:46:48 +00001488
Chris Lattner96fd7662010-04-03 07:18:48 +00001489 uint32_t Range = uint32_t(ExitValue-InitValue);
1490 if (NewPred == CmpInst::ICMP_SLE) {
1491 // Normalize SLE -> SLT, check for infinite loop.
1492 if (++Range == 0) return; // Range overflows.
1493 }
Andrew Trickead71d52011-03-17 23:46:48 +00001494
Chris Lattner96fd7662010-04-03 07:18:48 +00001495 unsigned Leftover = Range % uint32_t(IncValue);
Andrew Trickead71d52011-03-17 23:46:48 +00001496
Chris Lattner96fd7662010-04-03 07:18:48 +00001497 // If this is an equality comparison, we require that the strided value
1498 // exactly land on the exit value, otherwise the IV condition will wrap
1499 // around and do things the fp IV wouldn't.
1500 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
1501 Leftover != 0)
1502 return;
Andrew Trickead71d52011-03-17 23:46:48 +00001503
Chris Lattner96fd7662010-04-03 07:18:48 +00001504 // If the stride would wrap around the i32 before exiting, we can't
1505 // transform the IV.
1506 if (Leftover != 0 && int32_t(ExitValue+IncValue) < ExitValue)
1507 return;
Andrew Trickead71d52011-03-17 23:46:48 +00001508
Chris Lattner96fd7662010-04-03 07:18:48 +00001509 } else {
1510 // If we have a negative stride, we require the init to be greater than the
1511 // exit value and an equality or greater than comparison.
1512 if (InitValue >= ExitValue ||
1513 NewPred == CmpInst::ICMP_SLT || NewPred == CmpInst::ICMP_SLE)
1514 return;
Andrew Trickead71d52011-03-17 23:46:48 +00001515
Chris Lattner96fd7662010-04-03 07:18:48 +00001516 uint32_t Range = uint32_t(InitValue-ExitValue);
1517 if (NewPred == CmpInst::ICMP_SGE) {
1518 // Normalize SGE -> SGT, check for infinite loop.
1519 if (++Range == 0) return; // Range overflows.
1520 }
Andrew Trickead71d52011-03-17 23:46:48 +00001521
Chris Lattner96fd7662010-04-03 07:18:48 +00001522 unsigned Leftover = Range % uint32_t(-IncValue);
Andrew Trickead71d52011-03-17 23:46:48 +00001523
Chris Lattner96fd7662010-04-03 07:18:48 +00001524 // If this is an equality comparison, we require that the strided value
1525 // exactly land on the exit value, otherwise the IV condition will wrap
1526 // around and do things the fp IV wouldn't.
1527 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
1528 Leftover != 0)
1529 return;
Andrew Trickead71d52011-03-17 23:46:48 +00001530
Chris Lattner96fd7662010-04-03 07:18:48 +00001531 // If the stride would wrap around the i32 before exiting, we can't
1532 // transform the IV.
1533 if (Leftover != 0 && int32_t(ExitValue+IncValue) > ExitValue)
1534 return;
1535 }
Andrew Trickead71d52011-03-17 23:46:48 +00001536
Chris Lattner96fd7662010-04-03 07:18:48 +00001537 const IntegerType *Int32Ty = Type::getInt32Ty(PN->getContext());
Dan Gohmancafb8132009-02-17 19:13:57 +00001538
Chris Lattnerbbb91492010-04-03 06:41:49 +00001539 // Insert new integer induction variable.
Jay Foad3ecfc862011-03-30 11:28:46 +00001540 PHINode *NewPHI = PHINode::Create(Int32Ty, 2, PN->getName()+".int", PN);
Chris Lattnerc4f7e802010-04-03 06:05:10 +00001541 NewPHI->addIncoming(ConstantInt::get(Int32Ty, InitValue),
Chris Lattnerc91961e2010-04-03 06:17:08 +00001542 PN->getIncomingBlock(IncomingEdge));
Devang Patel84e35152008-11-17 21:32:02 +00001543
Chris Lattnerc4f7e802010-04-03 06:05:10 +00001544 Value *NewAdd =
Chris Lattner96fd7662010-04-03 07:18:48 +00001545 BinaryOperator::CreateAdd(NewPHI, ConstantInt::get(Int32Ty, IncValue),
Chris Lattnerc4f7e802010-04-03 06:05:10 +00001546 Incr->getName()+".int", Incr);
Chris Lattnerc91961e2010-04-03 06:17:08 +00001547 NewPHI->addIncoming(NewAdd, PN->getIncomingBlock(BackEdge));
Devang Patel84e35152008-11-17 21:32:02 +00001548
Chris Lattnerca703bd2010-04-03 06:11:07 +00001549 ICmpInst *NewCompare = new ICmpInst(TheBr, NewPred, NewAdd,
1550 ConstantInt::get(Int32Ty, ExitValue),
1551 Compare->getName());
Dan Gohmancafb8132009-02-17 19:13:57 +00001552
Chris Lattnerc91961e2010-04-03 06:17:08 +00001553 // In the following deletions, PN may become dead and may be deleted.
Dan Gohman81db61a2009-05-12 02:17:14 +00001554 // Use a WeakVH to observe whether this happens.
Chris Lattnerc91961e2010-04-03 06:17:08 +00001555 WeakVH WeakPH = PN;
Dan Gohman81db61a2009-05-12 02:17:14 +00001556
Chris Lattnerca703bd2010-04-03 06:11:07 +00001557 // Delete the old floating point exit comparison. The branch starts using the
1558 // new comparison.
1559 NewCompare->takeName(Compare);
1560 Compare->replaceAllUsesWith(NewCompare);
1561 RecursivelyDeleteTriviallyDeadInstructions(Compare);
Dan Gohmancafb8132009-02-17 19:13:57 +00001562
Chris Lattnerca703bd2010-04-03 06:11:07 +00001563 // Delete the old floating point increment.
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001564 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
Dan Gohman81db61a2009-05-12 02:17:14 +00001565 RecursivelyDeleteTriviallyDeadInstructions(Incr);
Dan Gohmancafb8132009-02-17 19:13:57 +00001566
Chris Lattner70c0d4f2010-04-03 06:16:22 +00001567 // If the FP induction variable still has uses, this is because something else
1568 // in the loop uses its value. In order to canonicalize the induction
1569 // variable, we chose to eliminate the IV and rewrite it in terms of an
1570 // int->fp cast.
1571 //
1572 // We give preference to sitofp over uitofp because it is faster on most
1573 // platforms.
1574 if (WeakPH) {
Chris Lattnera40e4a02010-04-03 06:25:21 +00001575 Value *Conv = new SIToFPInst(NewPHI, PN->getType(), "indvar.conv",
1576 PN->getParent()->getFirstNonPHI());
1577 PN->replaceAllUsesWith(Conv);
Chris Lattnerc91961e2010-04-03 06:17:08 +00001578 RecursivelyDeleteTriviallyDeadInstructions(PN);
Devang Patelcd402332008-11-17 23:27:13 +00001579 }
Devang Patel58d43d42008-11-03 18:32:19 +00001580
Dan Gohman81db61a2009-05-12 02:17:14 +00001581 // Add a new IVUsers entry for the newly-created integer PHI.
Andrew Trickf85092c2011-05-20 18:25:42 +00001582 IU->AddUsersIfInteresting(NewPHI, NewPHI);
Dan Gohman81db61a2009-05-12 02:17:14 +00001583}