blob: b7c97e5071ac6c987c596f67be5bbb563e8b2fd0 [file] [log] [blame]
Chris Lattner6148c022001-12-03 17:28:42 +00001//===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner6148c022001-12-03 17:28:42 +00009//
Chris Lattner40bf8b42004-04-02 20:24:31 +000010// This transformation analyzes and transforms the induction variables (and
11// computations derived from them) into simpler forms suitable for subsequent
12// analysis and transformation.
13//
Reid Spencer47a53ac2006-08-18 09:01:07 +000014// This transformation makes the following changes to each loop with an
Chris Lattner40bf8b42004-04-02 20:24:31 +000015// identifiable induction variable:
16// 1. All loops are transformed to have a SINGLE canonical induction variable
17// which starts at zero and steps by one.
18// 2. The canonical induction variable is guaranteed to be the first PHI node
19// in the loop header block.
Dan Gohmanea73f3c2009-06-14 22:38:41 +000020// 3. The canonical induction variable is guaranteed to be in a wide enough
21// type so that IV expressions need not be (directly) zero-extended or
22// sign-extended.
23// 4. Any pointer arithmetic recurrences are raised to use array subscripts.
Chris Lattner40bf8b42004-04-02 20:24:31 +000024//
25// If the trip count of a loop is computable, this pass also makes the following
26// changes:
27// 1. The exit condition for the loop is canonicalized to compare the
28// induction value against the exit value. This turns loops like:
29// 'for (i = 7; i*i < 1000; ++i)' into 'for (i = 0; i != 25; ++i)'
30// 2. Any use outside of the loop of an expression derived from the indvar
31// is changed to compute the derived value outside of the loop, eliminating
32// the dependence on the exit value of the induction variable. If the only
33// purpose of the loop is to compute the exit value of some derived
34// expression, this transformation will make the loop dead.
35//
36// This transformation should be followed by strength reduction after all of the
Dan Gohmanc2c4cbf2009-05-19 20:38:47 +000037// desired loop transformations have been performed.
Chris Lattner6148c022001-12-03 17:28:42 +000038//
39//===----------------------------------------------------------------------===//
40
Chris Lattner0e5f4992006-12-19 21:40:18 +000041#define DEBUG_TYPE "indvars"
Chris Lattner022103b2002-05-07 20:03:00 +000042#include "llvm/Transforms/Scalar.h"
Chris Lattner40bf8b42004-04-02 20:24:31 +000043#include "llvm/BasicBlock.h"
Chris Lattner59fdaee2004-04-15 15:21:43 +000044#include "llvm/Constants.h"
Chris Lattner18b3c972003-12-22 05:02:01 +000045#include "llvm/Instructions.h"
Devang Patel7b9f6b12010-03-15 22:23:03 +000046#include "llvm/IntrinsicInst.h"
Owen Andersond672ecb2009-07-03 00:17:18 +000047#include "llvm/LLVMContext.h"
Chris Lattner40bf8b42004-04-02 20:24:31 +000048#include "llvm/Type.h"
Dan Gohman81db61a2009-05-12 02:17:14 +000049#include "llvm/Analysis/Dominators.h"
50#include "llvm/Analysis/IVUsers.h"
Nate Begeman36f891b2005-07-30 00:12:19 +000051#include "llvm/Analysis/ScalarEvolutionExpander.h"
John Criswell47df12d2003-12-18 17:19:19 +000052#include "llvm/Analysis/LoopInfo.h"
Devang Patel5ee99972007-03-07 06:39:01 +000053#include "llvm/Analysis/LoopPass.h"
Chris Lattner455889a2002-02-12 22:39:50 +000054#include "llvm/Support/CFG.h"
Andrew Trick56caa092011-06-28 03:01:46 +000055#include "llvm/Support/CommandLine.h"
Chris Lattneree4f13a2007-01-07 01:14:12 +000056#include "llvm/Support/Debug.h"
Chris Lattnerbdff5482009-08-23 04:37:46 +000057#include "llvm/Support/raw_ostream.h"
John Criswell47df12d2003-12-18 17:19:19 +000058#include "llvm/Transforms/Utils/Local.h"
Dan Gohman81db61a2009-05-12 02:17:14 +000059#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Andrew Trick37da4082011-05-04 02:10:13 +000060#include "llvm/Target/TargetData.h"
Reid Spencera54b7cb2007-01-12 07:05:14 +000061#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000062#include "llvm/ADT/Statistic.h"
Dan Gohman81db61a2009-05-12 02:17:14 +000063#include "llvm/ADT/STLExtras.h"
John Criswell47df12d2003-12-18 17:19:19 +000064using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000065
Andrew Trick2fabd462011-06-21 03:22:38 +000066STATISTIC(NumRemoved , "Number of aux indvars removed");
67STATISTIC(NumWidened , "Number of indvars widened");
68STATISTIC(NumInserted , "Number of canonical indvars added");
69STATISTIC(NumReplaced , "Number of exit values replaced");
70STATISTIC(NumLFTR , "Number of loop exit tests replaced");
71STATISTIC(NumElimIdentity, "Number of IV identities eliminated");
72STATISTIC(NumElimExt , "Number of IV sign/zero extends eliminated");
73STATISTIC(NumElimRem , "Number of IV remainder operations eliminated");
74STATISTIC(NumElimCmp , "Number of IV comparisons eliminated");
Chris Lattner3324e712003-12-22 03:58:44 +000075
Andrew Trick56caa092011-06-28 03:01:46 +000076static cl::opt<bool> DisableIVRewrite(
77 "disable-iv-rewrite", cl::Hidden,
78 cl::desc("Disable canonical induction variable rewriting"));
Andrew Trick37da4082011-05-04 02:10:13 +000079
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 Trick2fabd462011-06-21 03:22:38 +000087
Andrew Trickb12a7542011-03-17 23:51:11 +000088 SmallVector<WeakVH, 16> DeadInsts;
Chris Lattner15cad752003-12-23 07:47:09 +000089 bool Changed;
Chris Lattner3324e712003-12-22 03:58:44 +000090 public:
Devang Patel794fd752007-05-01 21:15:47 +000091
Dan Gohman5668cf72009-07-15 01:26:32 +000092 static char ID; // Pass identification, replacement for typeid
Andrew Trick2fabd462011-06-21 03:22:38 +000093 IndVarSimplify() : LoopPass(ID), IU(0), LI(0), SE(0), DT(0), TD(0),
Andrew Trick15832f62011-06-28 02:49:20 +000094 Changed(false) {
Owen Anderson081c34b2010-10-19 17:21:58 +000095 initializeIndVarSimplifyPass(*PassRegistry::getPassRegistry());
96 }
Devang Patel794fd752007-05-01 21:15:47 +000097
Dan Gohman5668cf72009-07-15 01:26:32 +000098 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
Dan Gohman60f8a632009-02-17 20:49:49 +000099
Dan Gohman5668cf72009-07-15 01:26:32 +0000100 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
101 AU.addRequired<DominatorTree>();
102 AU.addRequired<LoopInfo>();
103 AU.addRequired<ScalarEvolution>();
104 AU.addRequiredID(LoopSimplifyID);
105 AU.addRequiredID(LCSSAID);
Andrew Trick56caa092011-06-28 03:01:46 +0000106 if (!DisableIVRewrite)
107 AU.addRequired<IVUsers>();
Dan Gohman5668cf72009-07-15 01:26:32 +0000108 AU.addPreserved<ScalarEvolution>();
109 AU.addPreservedID(LoopSimplifyID);
110 AU.addPreservedID(LCSSAID);
Andrew Trick2fabd462011-06-21 03:22:38 +0000111 if (!DisableIVRewrite)
112 AU.addPreserved<IVUsers>();
Dan Gohman5668cf72009-07-15 01:26:32 +0000113 AU.setPreservesCFG();
114 }
Chris Lattner15cad752003-12-23 07:47:09 +0000115
Chris Lattner40bf8b42004-04-02 20:24:31 +0000116 private:
Andrew Trickb12a7542011-03-17 23:51:11 +0000117 bool isValidRewrite(Value *FromVal, Value *ToVal);
Devang Patel5ee99972007-03-07 06:39:01 +0000118
Andrew Trickf85092c2011-05-20 18:25:42 +0000119 void SimplifyIVUsers(SCEVExpander &Rewriter);
Andrew Trick2fabd462011-06-21 03:22:38 +0000120 void SimplifyIVUsersNoRewrite(Loop *L, SCEVExpander &Rewriter);
121
122 bool EliminateIVUser(Instruction *UseInst, Instruction *IVOperand);
Andrew Trickaeee4612011-05-12 00:04:28 +0000123 void EliminateIVComparison(ICmpInst *ICmp, Value *IVOperand);
124 void EliminateIVRemainder(BinaryOperator *Rem,
125 Value *IVOperand,
Andrew Trick4417e532011-06-21 15:43:52 +0000126 bool IsSigned);
Andrew Trick2fabd462011-06-21 03:22:38 +0000127 bool isSimpleIVUser(Instruction *I, const Loop *L);
Dan Gohman60f8a632009-02-17 20:49:49 +0000128 void RewriteNonIntegerIVs(Loop *L);
129
Dan Gohman0bba49c2009-07-07 17:06:11 +0000130 ICmpInst *LinearFunctionTestReplace(Loop *L, const SCEV *BackedgeTakenCount,
Andrew Trick4dfdf242011-05-03 22:24:10 +0000131 PHINode *IndVar,
132 SCEVExpander &Rewriter);
Andrew Trick37da4082011-05-04 02:10:13 +0000133
Dan Gohman454d26d2010-02-22 04:11:59 +0000134 void RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000135
Dan Gohman454d26d2010-02-22 04:11:59 +0000136 void RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter);
Devang Pateld22a8492008-09-09 21:41:07 +0000137
Dan Gohman667d7872009-06-26 22:53:46 +0000138 void SinkUnusedInvariants(Loop *L);
Dan Gohman81db61a2009-05-12 02:17:14 +0000139
140 void HandleFloatingPointIV(Loop *L, PHINode *PH);
Chris Lattner3324e712003-12-22 03:58:44 +0000141 };
Chris Lattner5e761402002-09-10 05:24:05 +0000142}
Chris Lattner394437f2001-12-04 04:32:29 +0000143
Dan Gohman844731a2008-05-13 00:00:25 +0000144char IndVarSimplify::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000145INITIALIZE_PASS_BEGIN(IndVarSimplify, "indvars",
Andrew Trick37da4082011-05-04 02:10:13 +0000146 "Induction Variable Simplification", false, false)
Owen Anderson2ab36d32010-10-12 19:48:12 +0000147INITIALIZE_PASS_DEPENDENCY(DominatorTree)
148INITIALIZE_PASS_DEPENDENCY(LoopInfo)
149INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
150INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
151INITIALIZE_PASS_DEPENDENCY(LCSSA)
152INITIALIZE_PASS_DEPENDENCY(IVUsers)
153INITIALIZE_PASS_END(IndVarSimplify, "indvars",
Andrew Trick37da4082011-05-04 02:10:13 +0000154 "Induction Variable Simplification", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000155
Daniel Dunbar394f0442008-10-22 23:32:42 +0000156Pass *llvm::createIndVarSimplifyPass() {
Chris Lattner3324e712003-12-22 03:58:44 +0000157 return new IndVarSimplify();
Chris Lattner394437f2001-12-04 04:32:29 +0000158}
159
Andrew Trickb12a7542011-03-17 23:51:11 +0000160/// isValidRewrite - Return true if the SCEV expansion generated by the
161/// rewriter can replace the original value. SCEV guarantees that it
162/// produces the same value, but the way it is produced may be illegal IR.
163/// Ideally, this function will only be called for verification.
164bool IndVarSimplify::isValidRewrite(Value *FromVal, Value *ToVal) {
165 // If an SCEV expression subsumed multiple pointers, its expansion could
166 // reassociate the GEP changing the base pointer. This is illegal because the
167 // final address produced by a GEP chain must be inbounds relative to its
168 // underlying object. Otherwise basic alias analysis, among other things,
169 // could fail in a dangerous way. Ultimately, SCEV will be improved to avoid
170 // producing an expression involving multiple pointers. Until then, we must
171 // bail out here.
172 //
173 // Retrieve the pointer operand of the GEP. Don't use GetUnderlyingObject
174 // because it understands lcssa phis while SCEV does not.
175 Value *FromPtr = FromVal;
176 Value *ToPtr = ToVal;
177 if (GEPOperator *GEP = dyn_cast<GEPOperator>(FromVal)) {
178 FromPtr = GEP->getPointerOperand();
179 }
180 if (GEPOperator *GEP = dyn_cast<GEPOperator>(ToVal)) {
181 ToPtr = GEP->getPointerOperand();
182 }
183 if (FromPtr != FromVal || ToPtr != ToVal) {
184 // Quickly check the common case
185 if (FromPtr == ToPtr)
186 return true;
187
188 // SCEV may have rewritten an expression that produces the GEP's pointer
189 // operand. That's ok as long as the pointer operand has the same base
190 // pointer. Unlike GetUnderlyingObject(), getPointerBase() will find the
191 // base of a recurrence. This handles the case in which SCEV expansion
192 // converts a pointer type recurrence into a nonrecurrent pointer base
193 // indexed by an integer recurrence.
194 const SCEV *FromBase = SE->getPointerBase(SE->getSCEV(FromPtr));
195 const SCEV *ToBase = SE->getPointerBase(SE->getSCEV(ToPtr));
196 if (FromBase == ToBase)
197 return true;
198
199 DEBUG(dbgs() << "INDVARS: GEP rewrite bail out "
200 << *FromBase << " != " << *ToBase << "\n");
201
202 return false;
203 }
204 return true;
205}
206
Andrew Trick4dfdf242011-05-03 22:24:10 +0000207/// canExpandBackedgeTakenCount - Return true if this loop's backedge taken
208/// count expression can be safely and cheaply expanded into an instruction
209/// sequence that can be used by LinearFunctionTestReplace.
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000210static bool canExpandBackedgeTakenCount(Loop *L, ScalarEvolution *SE) {
211 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
Andrew Trick4dfdf242011-05-03 22:24:10 +0000212 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount) ||
213 BackedgeTakenCount->isZero())
214 return false;
215
216 if (!L->getExitingBlock())
217 return false;
218
219 // Can't rewrite non-branch yet.
220 BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator());
221 if (!BI)
222 return false;
223
Dan Gohmanca9b7032010-04-12 21:13:43 +0000224 // Special case: If the backedge-taken count is a UDiv, it's very likely a
225 // UDiv that ScalarEvolution produced in order to compute a precise
226 // expression, rather than a UDiv from the user's code. If we can't find a
227 // UDiv in the code with some simple searching, assume the former and forego
228 // rewriting the loop.
229 if (isa<SCEVUDivExpr>(BackedgeTakenCount)) {
230 ICmpInst *OrigCond = dyn_cast<ICmpInst>(BI->getCondition());
Andrew Trick37da4082011-05-04 02:10:13 +0000231 if (!OrigCond) return false;
Dan Gohmanca9b7032010-04-12 21:13:43 +0000232 const SCEV *R = SE->getSCEV(OrigCond->getOperand(1));
Dan Gohmandeff6212010-05-03 22:09:21 +0000233 R = SE->getMinusSCEV(R, SE->getConstant(R->getType(), 1));
Dan Gohmanca9b7032010-04-12 21:13:43 +0000234 if (R != BackedgeTakenCount) {
235 const SCEV *L = SE->getSCEV(OrigCond->getOperand(0));
Dan Gohmandeff6212010-05-03 22:09:21 +0000236 L = SE->getMinusSCEV(L, SE->getConstant(L->getType(), 1));
Dan Gohmanca9b7032010-04-12 21:13:43 +0000237 if (L != BackedgeTakenCount)
Andrew Trick4dfdf242011-05-03 22:24:10 +0000238 return false;
Dan Gohmanca9b7032010-04-12 21:13:43 +0000239 }
240 }
Andrew Trick4dfdf242011-05-03 22:24:10 +0000241 return true;
242}
243
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000244/// getBackedgeIVType - Get the widest type used by the loop test after peeking
245/// through Truncs.
246///
247/// TODO: Unnecessary once LinearFunctionTestReplace is removed.
248static const Type *getBackedgeIVType(Loop *L) {
249 if (!L->getExitingBlock())
250 return 0;
251
252 // Can't rewrite non-branch yet.
253 BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator());
254 if (!BI)
255 return 0;
256
257 ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition());
258 if (!Cond)
259 return 0;
260
261 const Type *Ty = 0;
262 for(User::op_iterator OI = Cond->op_begin(), OE = Cond->op_end();
263 OI != OE; ++OI) {
264 assert((!Ty || Ty == (*OI)->getType()) && "bad icmp operand types");
265 TruncInst *Trunc = dyn_cast<TruncInst>(*OI);
266 if (!Trunc)
267 continue;
268
269 return Trunc->getSrcTy();
270 }
271 return Ty;
272}
273
Andrew Trick4dfdf242011-05-03 22:24:10 +0000274/// LinearFunctionTestReplace - This method rewrites the exit condition of the
275/// loop to be a canonical != comparison against the incremented loop induction
276/// variable. This pass is able to rewrite the exit tests of any loop where the
277/// SCEV analysis can determine a loop-invariant trip count of the loop, which
278/// is actually a much broader range than just linear tests.
279ICmpInst *IndVarSimplify::
280LinearFunctionTestReplace(Loop *L,
281 const SCEV *BackedgeTakenCount,
282 PHINode *IndVar,
283 SCEVExpander &Rewriter) {
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000284 assert(canExpandBackedgeTakenCount(L, SE) && "precondition");
Andrew Trick4dfdf242011-05-03 22:24:10 +0000285 BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator());
Dan Gohmanca9b7032010-04-12 21:13:43 +0000286
Chris Lattnerd2440572004-04-15 20:26:22 +0000287 // If the exiting block is not the same as the backedge block, we must compare
288 // against the preincremented value, otherwise we prefer to compare against
289 // the post-incremented value.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000290 Value *CmpIndVar;
Dan Gohman0bba49c2009-07-07 17:06:11 +0000291 const SCEV *RHS = BackedgeTakenCount;
Andrew Trick4dfdf242011-05-03 22:24:10 +0000292 if (L->getExitingBlock() == L->getLoopLatch()) {
Dan Gohman46bdfb02009-02-24 18:55:53 +0000293 // Add one to the "backedge-taken" count to get the trip count.
294 // If this addition may overflow, we have to be more pessimistic and
295 // cast the induction variable before doing the add.
Dan Gohmandeff6212010-05-03 22:09:21 +0000296 const SCEV *Zero = SE->getConstant(BackedgeTakenCount->getType(), 0);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000297 const SCEV *N =
Dan Gohman46bdfb02009-02-24 18:55:53 +0000298 SE->getAddExpr(BackedgeTakenCount,
Dan Gohmandeff6212010-05-03 22:09:21 +0000299 SE->getConstant(BackedgeTakenCount->getType(), 1));
Dan Gohmanc2390b12009-02-12 22:19:27 +0000300 if ((isa<SCEVConstant>(N) && !N->isZero()) ||
Dan Gohman3948d0b2010-04-11 19:27:13 +0000301 SE->isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) {
Dan Gohmanc2390b12009-02-12 22:19:27 +0000302 // No overflow. Cast the sum.
Dan Gohman46bdfb02009-02-24 18:55:53 +0000303 RHS = SE->getTruncateOrZeroExtend(N, IndVar->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000304 } else {
305 // Potential overflow. Cast before doing the add.
Dan Gohman46bdfb02009-02-24 18:55:53 +0000306 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
307 IndVar->getType());
308 RHS = SE->getAddExpr(RHS,
Dan Gohmandeff6212010-05-03 22:09:21 +0000309 SE->getConstant(IndVar->getType(), 1));
Dan Gohmanc2390b12009-02-12 22:19:27 +0000310 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000311
Dan Gohman46bdfb02009-02-24 18:55:53 +0000312 // The BackedgeTaken expression contains the number of times that the
313 // backedge branches to the loop header. This is one less than the
314 // number of times the loop executes, so use the incremented indvar.
Andrew Trick4dfdf242011-05-03 22:24:10 +0000315 CmpIndVar = IndVar->getIncomingValueForBlock(L->getExitingBlock());
Chris Lattnerd2440572004-04-15 20:26:22 +0000316 } else {
317 // We have to use the preincremented value...
Dan Gohman46bdfb02009-02-24 18:55:53 +0000318 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
319 IndVar->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000320 CmpIndVar = IndVar;
Chris Lattnerd2440572004-04-15 20:26:22 +0000321 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000322
Dan Gohman667d7872009-06-26 22:53:46 +0000323 // Expand the code for the iteration count.
Dan Gohman17ead4f2010-11-17 21:23:15 +0000324 assert(SE->isLoopInvariant(RHS, L) &&
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000325 "Computed iteration count is not loop invariant!");
Dan Gohman667d7872009-06-26 22:53:46 +0000326 Value *ExitCnt = Rewriter.expandCodeFor(RHS, IndVar->getType(), BI);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000327
Reid Spencere4d87aa2006-12-23 06:05:41 +0000328 // Insert a new icmp_ne or icmp_eq instruction before the branch.
329 ICmpInst::Predicate Opcode;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000330 if (L->contains(BI->getSuccessor(0)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000331 Opcode = ICmpInst::ICMP_NE;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000332 else
Reid Spencere4d87aa2006-12-23 06:05:41 +0000333 Opcode = ICmpInst::ICMP_EQ;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000334
David Greenef67ef312010-01-05 01:27:06 +0000335 DEBUG(dbgs() << "INDVARS: Rewriting loop exit condition to:\n"
Chris Lattnerbdff5482009-08-23 04:37:46 +0000336 << " LHS:" << *CmpIndVar << '\n'
337 << " op:\t"
338 << (Opcode == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
339 << " RHS:\t" << *RHS << "\n");
Dan Gohmanc2390b12009-02-12 22:19:27 +0000340
Owen Anderson333c4002009-07-09 23:48:35 +0000341 ICmpInst *Cond = new ICmpInst(BI, Opcode, CmpIndVar, ExitCnt, "exitcond");
Dan Gohman81db61a2009-05-12 02:17:14 +0000342
Dan Gohman24440802010-02-22 02:07:36 +0000343 Value *OrigCond = BI->getCondition();
Dan Gohman95bdbfa2009-05-24 19:11:38 +0000344 // It's tempting to use replaceAllUsesWith here to fully replace the old
345 // comparison, but that's not immediately safe, since users of the old
346 // comparison may not be dominated by the new comparison. Instead, just
347 // update the branch to use the new comparison; in the common case this
348 // will make old comparison dead.
349 BI->setCondition(Cond);
Andrew Trick88e92cf2011-04-28 17:30:04 +0000350 DeadInsts.push_back(OrigCond);
Dan Gohman81db61a2009-05-12 02:17:14 +0000351
Chris Lattner40bf8b42004-04-02 20:24:31 +0000352 ++NumLFTR;
353 Changed = true;
Dan Gohman81db61a2009-05-12 02:17:14 +0000354 return Cond;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000355}
356
Chris Lattner40bf8b42004-04-02 20:24:31 +0000357/// RewriteLoopExitValues - Check to see if this loop has a computable
358/// loop-invariant execution count. If so, this means that we can compute the
359/// final value of any expressions that are recurrent in the loop, and
360/// substitute the exit values from the loop into any instructions outside of
361/// the loop that use the final values of the current expressions.
Dan Gohman81db61a2009-05-12 02:17:14 +0000362///
363/// This is mostly redundant with the regular IndVarSimplify activities that
364/// happen later, except that it's more powerful in some cases, because it's
365/// able to brute-force evaluate arbitrary instructions as long as they have
366/// constant operands at the beginning of the loop.
Chris Lattnerf1859892011-01-09 02:16:18 +0000367void IndVarSimplify::RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000368 // Verify the input to the pass in already in LCSSA form.
Dan Gohmanbbf81d82010-03-10 19:38:49 +0000369 assert(L->isLCSSAForm(*DT));
Dan Gohman81db61a2009-05-12 02:17:14 +0000370
Devang Patelb7211a22007-08-21 00:31:24 +0000371 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattner9f3d7382007-03-04 03:43:23 +0000372 L->getUniqueExitBlocks(ExitBlocks);
Misha Brukmanfd939082005-04-21 23:48:37 +0000373
Chris Lattner9f3d7382007-03-04 03:43:23 +0000374 // Find all values that are computed inside the loop, but used outside of it.
375 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
376 // the exit blocks of the loop to find them.
377 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
378 BasicBlock *ExitBB = ExitBlocks[i];
Dan Gohmancafb8132009-02-17 19:13:57 +0000379
Chris Lattner9f3d7382007-03-04 03:43:23 +0000380 // If there are no PHI nodes in this exit block, then no values defined
381 // inside the loop are used on this path, skip it.
382 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
383 if (!PN) continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000384
Chris Lattner9f3d7382007-03-04 03:43:23 +0000385 unsigned NumPreds = PN->getNumIncomingValues();
Dan Gohmancafb8132009-02-17 19:13:57 +0000386
Chris Lattner9f3d7382007-03-04 03:43:23 +0000387 // Iterate over all of the PHI nodes.
388 BasicBlock::iterator BBI = ExitBB->begin();
389 while ((PN = dyn_cast<PHINode>(BBI++))) {
Torok Edwin3790fb02009-05-24 19:36:09 +0000390 if (PN->use_empty())
391 continue; // dead use, don't replace it
Dan Gohman814f2b22010-02-18 21:34:02 +0000392
393 // SCEV only supports integer expressions for now.
394 if (!PN->getType()->isIntegerTy() && !PN->getType()->isPointerTy())
395 continue;
396
Dale Johannesen45a2d7d2010-02-19 07:14:22 +0000397 // It's necessary to tell ScalarEvolution about this explicitly so that
398 // it can walk the def-use list and forget all SCEVs, as it may not be
399 // watching the PHI itself. Once the new exit value is in place, there
400 // may not be a def-use connection between the loop and every instruction
401 // which got a SCEVAddRecExpr for that loop.
402 SE->forgetValue(PN);
403
Chris Lattner9f3d7382007-03-04 03:43:23 +0000404 // Iterate over all of the values in all the PHI nodes.
405 for (unsigned i = 0; i != NumPreds; ++i) {
406 // If the value being merged in is not integer or is not defined
407 // in the loop, skip it.
408 Value *InVal = PN->getIncomingValue(i);
Dan Gohman814f2b22010-02-18 21:34:02 +0000409 if (!isa<Instruction>(InVal))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000410 continue;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000411
Chris Lattner9f3d7382007-03-04 03:43:23 +0000412 // If this pred is for a subloop, not L itself, skip it.
Dan Gohmancafb8132009-02-17 19:13:57 +0000413 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
Chris Lattner9f3d7382007-03-04 03:43:23 +0000414 continue; // The Block is in a subloop, skip it.
415
416 // Check that InVal is defined in the loop.
417 Instruction *Inst = cast<Instruction>(InVal);
Dan Gohman92329c72009-12-18 01:24:09 +0000418 if (!L->contains(Inst))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000419 continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000420
Chris Lattner9f3d7382007-03-04 03:43:23 +0000421 // Okay, this instruction has a user outside of the current loop
422 // and varies predictably *inside* the loop. Evaluate the value it
423 // contains when the loop exits, if possible.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000424 const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
Dan Gohman17ead4f2010-11-17 21:23:15 +0000425 if (!SE->isLoopInvariant(ExitValue, L))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000426 continue;
Chris Lattner9caed542007-03-04 01:00:28 +0000427
Dan Gohman667d7872009-06-26 22:53:46 +0000428 Value *ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), Inst);
Dan Gohmancafb8132009-02-17 19:13:57 +0000429
David Greenef67ef312010-01-05 01:27:06 +0000430 DEBUG(dbgs() << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal << '\n'
Chris Lattnerbdff5482009-08-23 04:37:46 +0000431 << " LoopVal = " << *Inst << "\n");
Chris Lattner9f3d7382007-03-04 03:43:23 +0000432
Andrew Trickb12a7542011-03-17 23:51:11 +0000433 if (!isValidRewrite(Inst, ExitVal)) {
434 DeadInsts.push_back(ExitVal);
435 continue;
436 }
437 Changed = true;
438 ++NumReplaced;
439
Chris Lattner9f3d7382007-03-04 03:43:23 +0000440 PN->setIncomingValue(i, ExitVal);
Dan Gohmancafb8132009-02-17 19:13:57 +0000441
Dan Gohman81db61a2009-05-12 02:17:14 +0000442 // If this instruction is dead now, delete it.
443 RecursivelyDeleteTriviallyDeadInstructions(Inst);
Dan Gohmancafb8132009-02-17 19:13:57 +0000444
Dan Gohman65d1e2b2009-07-14 01:09:02 +0000445 if (NumPreds == 1) {
446 // Completely replace a single-pred PHI. This is safe, because the
447 // NewVal won't be variant in the loop, so we don't need an LCSSA phi
448 // node anymore.
Chris Lattner9f3d7382007-03-04 03:43:23 +0000449 PN->replaceAllUsesWith(ExitVal);
Dan Gohman81db61a2009-05-12 02:17:14 +0000450 RecursivelyDeleteTriviallyDeadInstructions(PN);
Chris Lattnerc9838f22007-03-03 22:48:48 +0000451 }
452 }
Dan Gohman65d1e2b2009-07-14 01:09:02 +0000453 if (NumPreds != 1) {
Dan Gohman667d7872009-06-26 22:53:46 +0000454 // Clone the PHI and delete the original one. This lets IVUsers and
455 // any other maps purge the original user from their records.
Devang Patel50b6e332009-10-27 22:16:29 +0000456 PHINode *NewPN = cast<PHINode>(PN->clone());
Dan Gohman667d7872009-06-26 22:53:46 +0000457 NewPN->takeName(PN);
458 NewPN->insertBefore(PN);
459 PN->replaceAllUsesWith(NewPN);
460 PN->eraseFromParent();
461 }
Chris Lattnerc9838f22007-03-03 22:48:48 +0000462 }
463 }
Dan Gohman472fdf72010-03-20 03:53:53 +0000464
465 // The insertion point instruction may have been deleted; clear it out
466 // so that the rewriter doesn't trip over it later.
467 Rewriter.clearInsertPoint();
Chris Lattner40bf8b42004-04-02 20:24:31 +0000468}
469
Dan Gohman60f8a632009-02-17 20:49:49 +0000470void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000471 // First step. Check to see if there are any floating-point recurrences.
Chris Lattner40bf8b42004-04-02 20:24:31 +0000472 // If there are, change them into integer recurrences, permitting analysis by
473 // the SCEV routines.
474 //
Chris Lattnerf1859892011-01-09 02:16:18 +0000475 BasicBlock *Header = L->getHeader();
Misha Brukmanfd939082005-04-21 23:48:37 +0000476
Dan Gohman81db61a2009-05-12 02:17:14 +0000477 SmallVector<WeakVH, 8> PHIs;
478 for (BasicBlock::iterator I = Header->begin();
479 PHINode *PN = dyn_cast<PHINode>(I); ++I)
480 PHIs.push_back(PN);
481
482 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
Gabor Greifea4894a2010-09-18 11:53:39 +0000483 if (PHINode *PN = dyn_cast_or_null<PHINode>(&*PHIs[i]))
Dan Gohman81db61a2009-05-12 02:17:14 +0000484 HandleFloatingPointIV(L, PN);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000485
Dan Gohman2d1be872009-04-16 03:18:22 +0000486 // If the loop previously had floating-point IV, ScalarEvolution
Dan Gohman60f8a632009-02-17 20:49:49 +0000487 // may not have been able to compute a trip count. Now that we've done some
488 // re-writing, the trip count may be computable.
489 if (Changed)
Dan Gohman4c7279a2009-10-31 15:04:55 +0000490 SE->forgetLoop(L);
Dale Johannesenc671d892009-04-15 23:31:51 +0000491}
492
Andrew Trick2fabd462011-06-21 03:22:38 +0000493/// SimplifyIVUsers - Iteratively perform simplification on IVUsers within this
494/// loop. IVUsers is treated as a worklist. Each successive simplification may
495/// push more users which may themselves be candidates for simplification.
496///
497/// This is the old approach to IV simplification to be replaced by
498/// SimplifyIVUsersNoRewrite.
499///
500void IndVarSimplify::SimplifyIVUsers(SCEVExpander &Rewriter) {
501 // Each round of simplification involves a round of eliminating operations
502 // followed by a round of widening IVs. A single IVUsers worklist is used
503 // across all rounds. The inner loop advances the user. If widening exposes
504 // more uses, then another pass through the outer loop is triggered.
505 for (IVUsers::iterator I = IU->begin(); I != IU->end(); ++I) {
506 Instruction *UseInst = I->getUser();
507 Value *IVOperand = I->getOperandValToReplace();
508
509 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
510 EliminateIVComparison(ICmp, IVOperand);
511 continue;
512 }
513 if (BinaryOperator *Rem = dyn_cast<BinaryOperator>(UseInst)) {
514 bool IsSigned = Rem->getOpcode() == Instruction::SRem;
515 if (IsSigned || Rem->getOpcode() == Instruction::URem) {
Andrew Trick4417e532011-06-21 15:43:52 +0000516 EliminateIVRemainder(Rem, IVOperand, IsSigned);
Andrew Trick2fabd462011-06-21 03:22:38 +0000517 continue;
518 }
519 }
520 }
521}
522
Andrew Trickf85092c2011-05-20 18:25:42 +0000523namespace {
524 // Collect information about induction variables that are used by sign/zero
525 // extend operations. This information is recorded by CollectExtend and
526 // provides the input to WidenIV.
527 struct WideIVInfo {
528 const Type *WidestNativeType; // Widest integer type created [sz]ext
529 bool IsSigned; // Was an sext user seen before a zext?
530
531 WideIVInfo() : WidestNativeType(0), IsSigned(false) {}
532 };
Andrew Trickf85092c2011-05-20 18:25:42 +0000533}
534
535/// CollectExtend - Update information about the induction variable that is
536/// extended by this sign or zero extend operation. This is used to determine
537/// the final width of the IV before actually widening it.
Andrew Trick2fabd462011-06-21 03:22:38 +0000538static void CollectExtend(CastInst *Cast, bool IsSigned, WideIVInfo &WI,
539 ScalarEvolution *SE, const TargetData *TD) {
Andrew Trickf85092c2011-05-20 18:25:42 +0000540 const Type *Ty = Cast->getType();
541 uint64_t Width = SE->getTypeSizeInBits(Ty);
542 if (TD && !TD->isLegalInteger(Width))
543 return;
544
Andrew Trick2fabd462011-06-21 03:22:38 +0000545 if (!WI.WidestNativeType) {
546 WI.WidestNativeType = SE->getEffectiveSCEVType(Ty);
547 WI.IsSigned = IsSigned;
Andrew Trickf85092c2011-05-20 18:25:42 +0000548 return;
549 }
550
551 // We extend the IV to satisfy the sign of its first user, arbitrarily.
Andrew Trick2fabd462011-06-21 03:22:38 +0000552 if (WI.IsSigned != IsSigned)
Andrew Trickf85092c2011-05-20 18:25:42 +0000553 return;
554
Andrew Trick2fabd462011-06-21 03:22:38 +0000555 if (Width > SE->getTypeSizeInBits(WI.WidestNativeType))
556 WI.WidestNativeType = SE->getEffectiveSCEVType(Ty);
Andrew Trickf85092c2011-05-20 18:25:42 +0000557}
558
559namespace {
560/// WidenIV - The goal of this transform is to remove sign and zero extends
561/// without creating any new induction variables. To do this, it creates a new
562/// phi of the wider type and redirects all users, either removing extends or
563/// inserting truncs whenever we stop propagating the type.
564///
565class WidenIV {
Andrew Trick2fabd462011-06-21 03:22:38 +0000566 // Parameters
Andrew Trickf85092c2011-05-20 18:25:42 +0000567 PHINode *OrigPhi;
568 const Type *WideType;
569 bool IsSigned;
570
Andrew Trick2fabd462011-06-21 03:22:38 +0000571 // Context
572 LoopInfo *LI;
573 Loop *L;
Andrew Trickf85092c2011-05-20 18:25:42 +0000574 ScalarEvolution *SE;
Andrew Trick2fabd462011-06-21 03:22:38 +0000575 DominatorTree *DT;
Andrew Trickf85092c2011-05-20 18:25:42 +0000576
Andrew Trick2fabd462011-06-21 03:22:38 +0000577 // Result
Andrew Trickf85092c2011-05-20 18:25:42 +0000578 PHINode *WidePhi;
579 Instruction *WideInc;
580 const SCEV *WideIncExpr;
Andrew Trick2fabd462011-06-21 03:22:38 +0000581 SmallVectorImpl<WeakVH> &DeadInsts;
Andrew Trickf85092c2011-05-20 18:25:42 +0000582
Andrew Trick2fabd462011-06-21 03:22:38 +0000583 SmallPtrSet<Instruction*,16> Widened;
Andrew Trick4b029152011-07-02 02:34:25 +0000584 SmallVector<std::pair<Use *, Instruction *>, 8> NarrowIVUsers;
Andrew Trickf85092c2011-05-20 18:25:42 +0000585
586public:
Andrew Trick2fabd462011-06-21 03:22:38 +0000587 WidenIV(PHINode *PN, const WideIVInfo &WI, LoopInfo *LInfo,
588 ScalarEvolution *SEv, DominatorTree *DTree,
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000589 SmallVectorImpl<WeakVH> &DI) :
Andrew Trickf85092c2011-05-20 18:25:42 +0000590 OrigPhi(PN),
Andrew Trick2fabd462011-06-21 03:22:38 +0000591 WideType(WI.WidestNativeType),
592 IsSigned(WI.IsSigned),
Andrew Trickf85092c2011-05-20 18:25:42 +0000593 LI(LInfo),
594 L(LI->getLoopFor(OrigPhi->getParent())),
595 SE(SEv),
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000596 DT(DTree),
Andrew Trickf85092c2011-05-20 18:25:42 +0000597 WidePhi(0),
598 WideInc(0),
Andrew Trick2fabd462011-06-21 03:22:38 +0000599 WideIncExpr(0),
600 DeadInsts(DI) {
Andrew Trickf85092c2011-05-20 18:25:42 +0000601 assert(L->getHeader() == OrigPhi->getParent() && "Phi must be an IV");
602 }
603
Andrew Trick2fabd462011-06-21 03:22:38 +0000604 PHINode *CreateWideIV(SCEVExpander &Rewriter);
Andrew Trickf85092c2011-05-20 18:25:42 +0000605
606protected:
Andrew Trickf85092c2011-05-20 18:25:42 +0000607 Instruction *CloneIVUser(Instruction *NarrowUse,
608 Instruction *NarrowDef,
609 Instruction *WideDef);
610
Andrew Trickcc359d92011-06-29 23:03:57 +0000611 Instruction *WidenIVUse(Use &NarrowDefUse, Instruction *NarrowDef,
Andrew Trickf85092c2011-05-20 18:25:42 +0000612 Instruction *WideDef);
Andrew Trick4b029152011-07-02 02:34:25 +0000613
614 void pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef);
Andrew Trickf85092c2011-05-20 18:25:42 +0000615};
616} // anonymous namespace
617
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000618static Value *getExtend( Value *NarrowOper, const Type *WideType,
619 bool IsSigned, IRBuilder<> &Builder) {
620 return IsSigned ? Builder.CreateSExt(NarrowOper, WideType) :
621 Builder.CreateZExt(NarrowOper, WideType);
Andrew Trickf85092c2011-05-20 18:25:42 +0000622}
623
624/// CloneIVUser - Instantiate a wide operation to replace a narrow
625/// operation. This only needs to handle operations that can evaluation to
626/// SCEVAddRec. It can safely return 0 for any operation we decide not to clone.
627Instruction *WidenIV::CloneIVUser(Instruction *NarrowUse,
628 Instruction *NarrowDef,
629 Instruction *WideDef) {
630 unsigned Opcode = NarrowUse->getOpcode();
631 switch (Opcode) {
632 default:
633 return 0;
634 case Instruction::Add:
635 case Instruction::Mul:
636 case Instruction::UDiv:
637 case Instruction::Sub:
638 case Instruction::And:
639 case Instruction::Or:
640 case Instruction::Xor:
641 case Instruction::Shl:
642 case Instruction::LShr:
643 case Instruction::AShr:
644 DEBUG(dbgs() << "Cloning IVUser: " << *NarrowUse << "\n");
645
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000646 IRBuilder<> Builder(NarrowUse);
647
648 // Replace NarrowDef operands with WideDef. Otherwise, we don't know
649 // anything about the narrow operand yet so must insert a [sz]ext. It is
650 // probably loop invariant and will be folded or hoisted. If it actually
651 // comes from a widened IV, it should be removed during a future call to
652 // WidenIVUse.
653 Value *LHS = (NarrowUse->getOperand(0) == NarrowDef) ? WideDef :
654 getExtend(NarrowUse->getOperand(0), WideType, IsSigned, Builder);
655 Value *RHS = (NarrowUse->getOperand(1) == NarrowDef) ? WideDef :
656 getExtend(NarrowUse->getOperand(1), WideType, IsSigned, Builder);
657
Andrew Trickf85092c2011-05-20 18:25:42 +0000658 BinaryOperator *NarrowBO = cast<BinaryOperator>(NarrowUse);
659 BinaryOperator *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(),
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000660 LHS, RHS,
Andrew Trickf85092c2011-05-20 18:25:42 +0000661 NarrowBO->getName());
Andrew Trickf85092c2011-05-20 18:25:42 +0000662 Builder.Insert(WideBO);
Andrew Trick6e0ce242011-06-30 19:02:17 +0000663 if (const OverflowingBinaryOperator *OBO =
664 dyn_cast<OverflowingBinaryOperator>(NarrowBO)) {
665 if (OBO->hasNoUnsignedWrap()) WideBO->setHasNoUnsignedWrap();
666 if (OBO->hasNoSignedWrap()) WideBO->setHasNoSignedWrap();
667 }
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000668 return WideBO;
Andrew Trickf85092c2011-05-20 18:25:42 +0000669 }
670 llvm_unreachable(0);
671}
672
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000673/// HoistStep - Attempt to hoist an IV increment above a potential use.
674///
675/// To successfully hoist, two criteria must be met:
676/// - IncV operands dominate InsertPos and
677/// - InsertPos dominates IncV
678///
679/// Meeting the second condition means that we don't need to check all of IncV's
680/// existing uses (it's moving up in the domtree).
681///
682/// This does not yet recursively hoist the operands, although that would
683/// not be difficult.
684static bool HoistStep(Instruction *IncV, Instruction *InsertPos,
685 const DominatorTree *DT)
686{
687 if (DT->dominates(IncV, InsertPos))
688 return true;
689
690 if (!DT->dominates(InsertPos->getParent(), IncV->getParent()))
691 return false;
692
693 if (IncV->mayHaveSideEffects())
694 return false;
695
696 // Attempt to hoist IncV
697 for (User::op_iterator OI = IncV->op_begin(), OE = IncV->op_end();
698 OI != OE; ++OI) {
699 Instruction *OInst = dyn_cast<Instruction>(OI);
700 if (OInst && !DT->dominates(OInst, InsertPos))
701 return false;
702 }
703 IncV->moveBefore(InsertPos);
704 return true;
705}
706
Andrew Trickf85092c2011-05-20 18:25:42 +0000707/// WidenIVUse - Determine whether an individual user of the narrow IV can be
708/// widened. If so, return the wide clone of the user.
Andrew Trickcc359d92011-06-29 23:03:57 +0000709Instruction *WidenIV::WidenIVUse(Use &NarrowDefUse, Instruction *NarrowDef,
Andrew Trickf85092c2011-05-20 18:25:42 +0000710 Instruction *WideDef) {
Andrew Trickcc359d92011-06-29 23:03:57 +0000711 Instruction *NarrowUse = cast<Instruction>(NarrowDefUse.getUser());
712
Andrew Trick4b029152011-07-02 02:34:25 +0000713 // Stop traversing the def-use chain at inner-loop phis or post-loop phis.
Andrew Trickf85092c2011-05-20 18:25:42 +0000714 if (isa<PHINode>(NarrowUse) && LI->getLoopFor(NarrowUse->getParent()) != L)
715 return 0;
716
Andrew Trickf85092c2011-05-20 18:25:42 +0000717 // Our raison d'etre! Eliminate sign and zero extension.
718 if (IsSigned ? isa<SExtInst>(NarrowUse) : isa<ZExtInst>(NarrowUse)) {
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000719 Value *NewDef = WideDef;
720 if (NarrowUse->getType() != WideType) {
721 unsigned CastWidth = SE->getTypeSizeInBits(NarrowUse->getType());
722 unsigned IVWidth = SE->getTypeSizeInBits(WideType);
723 if (CastWidth < IVWidth) {
724 // The cast isn't as wide as the IV, so insert a Trunc.
Andrew Trickcc359d92011-06-29 23:03:57 +0000725 IRBuilder<> Builder(NarrowDefUse);
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000726 NewDef = Builder.CreateTrunc(WideDef, NarrowUse->getType());
727 }
728 else {
729 // A wider extend was hidden behind a narrower one. This may induce
730 // another round of IV widening in which the intermediate IV becomes
731 // dead. It should be very rare.
732 DEBUG(dbgs() << "INDVARS: New IV " << *WidePhi
733 << " not wide enough to subsume " << *NarrowUse << "\n");
734 NarrowUse->replaceUsesOfWith(NarrowDef, WideDef);
735 NewDef = NarrowUse;
736 }
737 }
738 if (NewDef != NarrowUse) {
739 DEBUG(dbgs() << "INDVARS: eliminating " << *NarrowUse
740 << " replaced by " << *WideDef << "\n");
741 ++NumElimExt;
742 NarrowUse->replaceAllUsesWith(NewDef);
743 DeadInsts.push_back(NarrowUse);
744 }
Andrew Trick2fabd462011-06-21 03:22:38 +0000745 // Now that the extend is gone, we want to expose it's uses for potential
746 // further simplification. We don't need to directly inform SimplifyIVUsers
747 // of the new users, because their parent IV will be processed later as a
748 // new loop phi. If we preserved IVUsers analysis, we would also want to
749 // push the uses of WideDef here.
Andrew Trickf85092c2011-05-20 18:25:42 +0000750
751 // No further widening is needed. The deceased [sz]ext had done it for us.
752 return 0;
753 }
Andrew Trick4b029152011-07-02 02:34:25 +0000754
755 // Does this user itself evaluate to a recurrence after widening?
756 const SCEVAddRecExpr *WideAddRec = 0;
757 if (SE->isSCEVable(NarrowUse->getType())) {
758 const SCEV *NarrowExpr = SE->getSCEV(NarrowUse);
759 if (SE->getTypeSizeInBits(NarrowExpr->getType())
760 >= SE->getTypeSizeInBits(WideType)) {
761 // NarrowUse implicitly widens its operand. e.g. a gep with a narrow
762 // index. We have already extended the operand, so we're done.
763 return 0;
764 }
765 const SCEV *WideExpr = IsSigned ?
766 SE->getSignExtendExpr(NarrowExpr, WideType) :
767 SE->getZeroExtendExpr(NarrowExpr, WideType);
768
769 // Only widen past values that evaluate to a recurrence in the same loop.
770 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(WideExpr);
771 if (AddRec && AddRec->getLoop() == L)
772 WideAddRec = AddRec;
773 }
Andrew Trickf85092c2011-05-20 18:25:42 +0000774 if (!WideAddRec) {
775 // This user does not evaluate to a recurence after widening, so don't
776 // follow it. Instead insert a Trunc to kill off the original use,
777 // eventually isolating the original narrow IV so it can be removed.
Andrew Trickcc359d92011-06-29 23:03:57 +0000778 IRBuilder<> Builder(NarrowDefUse);
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000779 Value *Trunc = Builder.CreateTrunc(WideDef, NarrowDef->getType());
Andrew Trickf85092c2011-05-20 18:25:42 +0000780 NarrowUse->replaceUsesOfWith(NarrowDef, Trunc);
781 return 0;
782 }
Andrew Trick4b029152011-07-02 02:34:25 +0000783 // We assume that block terminators are not SCEVable. We wouldn't want to
784 // insert a Trunc after a terminator if there happens to be a critical edge.
Andrew Trickcc359d92011-06-29 23:03:57 +0000785 assert(NarrowUse != NarrowUse->getParent()->getTerminator() &&
Andrew Trick4b029152011-07-02 02:34:25 +0000786 "SCEV is not expected to evaluate a block terminator");
Andrew Trickcc359d92011-06-29 23:03:57 +0000787
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000788 // Reuse the IV increment that SCEVExpander created as long as it dominates
789 // NarrowUse.
Andrew Trickf85092c2011-05-20 18:25:42 +0000790 Instruction *WideUse = 0;
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000791 if (WideAddRec == WideIncExpr && HoistStep(WideInc, NarrowUse, DT)) {
Andrew Trickf85092c2011-05-20 18:25:42 +0000792 WideUse = WideInc;
793 }
794 else {
795 WideUse = CloneIVUser(NarrowUse, NarrowDef, WideDef);
796 if (!WideUse)
797 return 0;
798 }
Andrew Trick4b029152011-07-02 02:34:25 +0000799 // Evaluation of WideAddRec ensured that the narrow expression could be
800 // extended outside the loop without overflow. This suggests that the wide use
Andrew Trickf85092c2011-05-20 18:25:42 +0000801 // evaluates to the same expression as the extended narrow use, but doesn't
802 // absolutely guarantee it. Hence the following failsafe check. In rare cases
Andrew Trick2fabd462011-06-21 03:22:38 +0000803 // where it fails, we simply throw away the newly created wide use.
Andrew Trickf85092c2011-05-20 18:25:42 +0000804 if (WideAddRec != SE->getSCEV(WideUse)) {
805 DEBUG(dbgs() << "Wide use expression mismatch: " << *WideUse
806 << ": " << *SE->getSCEV(WideUse) << " != " << *WideAddRec << "\n");
807 DeadInsts.push_back(WideUse);
808 return 0;
809 }
810
811 // Returning WideUse pushes it on the worklist.
812 return WideUse;
813}
814
Andrew Trick4b029152011-07-02 02:34:25 +0000815/// pushNarrowIVUsers - Add eligible users of NarrowDef to NarrowIVUsers.
816///
817void WidenIV::pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef) {
818 for (Value::use_iterator UI = NarrowDef->use_begin(),
819 UE = NarrowDef->use_end(); UI != UE; ++UI) {
820 Use &U = UI.getUse();
821
822 // Handle data flow merges and bizarre phi cycles.
823 if (!Widened.insert(cast<Instruction>(U.getUser())))
824 continue;
825
826 NarrowIVUsers.push_back(std::make_pair(&UI.getUse(), WideDef));
827 }
828}
829
Andrew Trickf85092c2011-05-20 18:25:42 +0000830/// CreateWideIV - Process a single induction variable. First use the
831/// SCEVExpander to create a wide induction variable that evaluates to the same
832/// recurrence as the original narrow IV. Then use a worklist to forward
Andrew Trick2fabd462011-06-21 03:22:38 +0000833/// traverse the narrow IV's def-use chain. After WidenIVUse has processed all
Andrew Trickf85092c2011-05-20 18:25:42 +0000834/// interesting IV users, the narrow IV will be isolated for removal by
835/// DeleteDeadPHIs.
836///
837/// It would be simpler to delete uses as they are processed, but we must avoid
838/// invalidating SCEV expressions.
839///
Andrew Trick2fabd462011-06-21 03:22:38 +0000840PHINode *WidenIV::CreateWideIV(SCEVExpander &Rewriter) {
Andrew Trickf85092c2011-05-20 18:25:42 +0000841 // Is this phi an induction variable?
842 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(OrigPhi));
843 if (!AddRec)
Andrew Trick2fabd462011-06-21 03:22:38 +0000844 return NULL;
Andrew Trickf85092c2011-05-20 18:25:42 +0000845
846 // Widen the induction variable expression.
847 const SCEV *WideIVExpr = IsSigned ?
848 SE->getSignExtendExpr(AddRec, WideType) :
849 SE->getZeroExtendExpr(AddRec, WideType);
850
851 assert(SE->getEffectiveSCEVType(WideIVExpr->getType()) == WideType &&
852 "Expect the new IV expression to preserve its type");
853
854 // Can the IV be extended outside the loop without overflow?
855 AddRec = dyn_cast<SCEVAddRecExpr>(WideIVExpr);
856 if (!AddRec || AddRec->getLoop() != L)
Andrew Trick2fabd462011-06-21 03:22:38 +0000857 return NULL;
Andrew Trickf85092c2011-05-20 18:25:42 +0000858
Andrew Trick2fabd462011-06-21 03:22:38 +0000859 // An AddRec must have loop-invariant operands. Since this AddRec is
Andrew Trickf85092c2011-05-20 18:25:42 +0000860 // materialized by a loop header phi, the expression cannot have any post-loop
861 // operands, so they must dominate the loop header.
862 assert(SE->properlyDominates(AddRec->getStart(), L->getHeader()) &&
863 SE->properlyDominates(AddRec->getStepRecurrence(*SE), L->getHeader())
864 && "Loop header phi recurrence inputs do not dominate the loop");
865
866 // The rewriter provides a value for the desired IV expression. This may
867 // either find an existing phi or materialize a new one. Either way, we
868 // expect a well-formed cyclic phi-with-increments. i.e. any operand not part
869 // of the phi-SCC dominates the loop entry.
870 Instruction *InsertPt = L->getHeader()->begin();
871 WidePhi = cast<PHINode>(Rewriter.expandCodeFor(AddRec, WideType, InsertPt));
872
873 // Remembering the WideIV increment generated by SCEVExpander allows
874 // WidenIVUse to reuse it when widening the narrow IV's increment. We don't
875 // employ a general reuse mechanism because the call above is the only call to
876 // SCEVExpander. Henceforth, we produce 1-to-1 narrow to wide uses.
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000877 if (BasicBlock *LatchBlock = L->getLoopLatch()) {
878 WideInc =
879 cast<Instruction>(WidePhi->getIncomingValueForBlock(LatchBlock));
880 WideIncExpr = SE->getSCEV(WideInc);
881 }
Andrew Trickf85092c2011-05-20 18:25:42 +0000882
883 DEBUG(dbgs() << "Wide IV: " << *WidePhi << "\n");
884 ++NumWidened;
885
886 // Traverse the def-use chain using a worklist starting at the original IV.
Andrew Trick4b029152011-07-02 02:34:25 +0000887 assert(Widened.empty() && NarrowIVUsers.empty() && "expect initial state" );
Andrew Trickf85092c2011-05-20 18:25:42 +0000888
Andrew Trick4b029152011-07-02 02:34:25 +0000889 Widened.insert(OrigPhi);
890 pushNarrowIVUsers(OrigPhi, WidePhi);
891
Andrew Trickf85092c2011-05-20 18:25:42 +0000892 while (!NarrowIVUsers.empty()) {
Andrew Trickcc359d92011-06-29 23:03:57 +0000893 Use *UsePtr;
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000894 Instruction *WideDef;
Andrew Trickcc359d92011-06-29 23:03:57 +0000895 tie(UsePtr, WideDef) = NarrowIVUsers.pop_back_val();
896 Use &NarrowDefUse = *UsePtr;
Andrew Trickf85092c2011-05-20 18:25:42 +0000897
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000898 // Process a def-use edge. This may replace the use, so don't hold a
899 // use_iterator across it.
Andrew Trickcc359d92011-06-29 23:03:57 +0000900 Instruction *NarrowDef = cast<Instruction>(NarrowDefUse.get());
901 Instruction *WideUse = WidenIVUse(NarrowDefUse, NarrowDef, WideDef);
Andrew Trickf85092c2011-05-20 18:25:42 +0000902
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000903 // Follow all def-use edges from the previous narrow use.
Andrew Trick4b029152011-07-02 02:34:25 +0000904 if (WideUse)
905 pushNarrowIVUsers(cast<Instruction>(NarrowDefUse.getUser()), WideUse);
906
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000907 // WidenIVUse may have removed the def-use edge.
908 if (NarrowDef->use_empty())
909 DeadInsts.push_back(NarrowDef);
Andrew Trickf85092c2011-05-20 18:25:42 +0000910 }
Andrew Trick2fabd462011-06-21 03:22:38 +0000911 return WidePhi;
Andrew Trickf85092c2011-05-20 18:25:42 +0000912}
913
Andrew Trickaeee4612011-05-12 00:04:28 +0000914void IndVarSimplify::EliminateIVComparison(ICmpInst *ICmp, Value *IVOperand) {
915 unsigned IVOperIdx = 0;
916 ICmpInst::Predicate Pred = ICmp->getPredicate();
917 if (IVOperand != ICmp->getOperand(0)) {
918 // Swapped
919 assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
920 IVOperIdx = 1;
921 Pred = ICmpInst::getSwappedPredicate(Pred);
Dan Gohmana590b792010-04-13 01:46:36 +0000922 }
Andrew Trickaeee4612011-05-12 00:04:28 +0000923
924 // Get the SCEVs for the ICmp operands.
925 const SCEV *S = SE->getSCEV(ICmp->getOperand(IVOperIdx));
926 const SCEV *X = SE->getSCEV(ICmp->getOperand(1 - IVOperIdx));
927
928 // Simplify unnecessary loops away.
929 const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
930 S = SE->getSCEVAtScope(S, ICmpLoop);
931 X = SE->getSCEVAtScope(X, ICmpLoop);
932
933 // If the condition is always true or always false, replace it with
934 // a constant value.
935 if (SE->isKnownPredicate(Pred, S, X))
936 ICmp->replaceAllUsesWith(ConstantInt::getTrue(ICmp->getContext()));
937 else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X))
938 ICmp->replaceAllUsesWith(ConstantInt::getFalse(ICmp->getContext()));
939 else
940 return;
941
942 DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000943 ++NumElimCmp;
Andrew Trick074397d2011-05-20 03:37:48 +0000944 Changed = true;
Andrew Trickaeee4612011-05-12 00:04:28 +0000945 DeadInsts.push_back(ICmp);
946}
947
948void IndVarSimplify::EliminateIVRemainder(BinaryOperator *Rem,
949 Value *IVOperand,
Andrew Trick4417e532011-06-21 15:43:52 +0000950 bool IsSigned) {
Andrew Trickaeee4612011-05-12 00:04:28 +0000951 // We're only interested in the case where we know something about
952 // the numerator.
953 if (IVOperand != Rem->getOperand(0))
954 return;
955
956 // Get the SCEVs for the ICmp operands.
957 const SCEV *S = SE->getSCEV(Rem->getOperand(0));
958 const SCEV *X = SE->getSCEV(Rem->getOperand(1));
959
960 // Simplify unnecessary loops away.
961 const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent());
962 S = SE->getSCEVAtScope(S, ICmpLoop);
963 X = SE->getSCEVAtScope(X, ICmpLoop);
964
965 // i % n --> i if i is in [0,n).
Andrew Trick074397d2011-05-20 03:37:48 +0000966 if ((!IsSigned || SE->isKnownNonNegative(S)) &&
967 SE->isKnownPredicate(IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
Andrew Trickaeee4612011-05-12 00:04:28 +0000968 S, X))
969 Rem->replaceAllUsesWith(Rem->getOperand(0));
970 else {
971 // (i+1) % n --> (i+1)==n?0:(i+1) if i is in [0,n).
972 const SCEV *LessOne =
973 SE->getMinusSCEV(S, SE->getConstant(S->getType(), 1));
Andrew Trick074397d2011-05-20 03:37:48 +0000974 if (IsSigned && !SE->isKnownNonNegative(LessOne))
Andrew Trickaeee4612011-05-12 00:04:28 +0000975 return;
976
Andrew Trick074397d2011-05-20 03:37:48 +0000977 if (!SE->isKnownPredicate(IsSigned ?
Andrew Trickaeee4612011-05-12 00:04:28 +0000978 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
979 LessOne, X))
980 return;
981
982 ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ,
983 Rem->getOperand(0), Rem->getOperand(1),
984 "tmp");
985 SelectInst *Sel =
986 SelectInst::Create(ICmp,
987 ConstantInt::get(Rem->getType(), 0),
988 Rem->getOperand(0), "tmp", Rem);
989 Rem->replaceAllUsesWith(Sel);
990 }
991
992 // Inform IVUsers about the new users.
Andrew Trick2fabd462011-06-21 03:22:38 +0000993 if (IU) {
994 if (Instruction *I = dyn_cast<Instruction>(Rem->getOperand(0)))
Andrew Trick4417e532011-06-21 15:43:52 +0000995 IU->AddUsersIfInteresting(I);
Andrew Trick2fabd462011-06-21 03:22:38 +0000996 }
Andrew Trickaeee4612011-05-12 00:04:28 +0000997 DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000998 ++NumElimRem;
Andrew Trick074397d2011-05-20 03:37:48 +0000999 Changed = true;
Andrew Trickaeee4612011-05-12 00:04:28 +00001000 DeadInsts.push_back(Rem);
Dan Gohmana590b792010-04-13 01:46:36 +00001001}
1002
Andrew Trick2fabd462011-06-21 03:22:38 +00001003/// EliminateIVUser - Eliminate an operation that consumes a simple IV and has
1004/// no observable side-effect given the range of IV values.
1005bool IndVarSimplify::EliminateIVUser(Instruction *UseInst,
1006 Instruction *IVOperand) {
1007 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
1008 EliminateIVComparison(ICmp, IVOperand);
1009 return true;
1010 }
1011 if (BinaryOperator *Rem = dyn_cast<BinaryOperator>(UseInst)) {
1012 bool IsSigned = Rem->getOpcode() == Instruction::SRem;
1013 if (IsSigned || Rem->getOpcode() == Instruction::URem) {
Andrew Trick4417e532011-06-21 15:43:52 +00001014 EliminateIVRemainder(Rem, IVOperand, IsSigned);
Andrew Trick2fabd462011-06-21 03:22:38 +00001015 return true;
1016 }
1017 }
1018
1019 // Eliminate any operation that SCEV can prove is an identity function.
1020 if (!SE->isSCEVable(UseInst->getType()) ||
Andrew Trick11745d42011-06-29 03:13:40 +00001021 (UseInst->getType() != IVOperand->getType()) ||
Andrew Trick2fabd462011-06-21 03:22:38 +00001022 (SE->getSCEV(UseInst) != SE->getSCEV(IVOperand)))
1023 return false;
1024
Andrew Trick2fabd462011-06-21 03:22:38 +00001025 DEBUG(dbgs() << "INDVARS: Eliminated identity: " << *UseInst << '\n');
Andrew Trick60ac7192011-06-30 01:27:23 +00001026
1027 UseInst->replaceAllUsesWith(IVOperand);
Andrew Trick2fabd462011-06-21 03:22:38 +00001028 ++NumElimIdentity;
1029 Changed = true;
1030 DeadInsts.push_back(UseInst);
1031 return true;
1032}
1033
1034/// pushIVUsers - Add all uses of Def to the current IV's worklist.
1035///
Andrew Trick15832f62011-06-28 02:49:20 +00001036static void pushIVUsers(
1037 Instruction *Def,
1038 SmallPtrSet<Instruction*,16> &Simplified,
1039 SmallVectorImpl< std::pair<Instruction*,Instruction*> > &SimpleIVUsers) {
Andrew Trick2fabd462011-06-21 03:22:38 +00001040
1041 for (Value::use_iterator UI = Def->use_begin(), E = Def->use_end();
1042 UI != E; ++UI) {
1043 Instruction *User = cast<Instruction>(*UI);
1044
1045 // Avoid infinite or exponential worklist processing.
1046 // Also ensure unique worklist users.
Andrew Trick60ac7192011-06-30 01:27:23 +00001047 // If Def is a LoopPhi, it may not be in the Simplified set, so check for
1048 // self edges first.
1049 if (User != Def && Simplified.insert(User))
Andrew Trick2fabd462011-06-21 03:22:38 +00001050 SimpleIVUsers.push_back(std::make_pair(User, Def));
1051 }
1052}
1053
1054/// isSimpleIVUser - Return true if this instruction generates a simple SCEV
1055/// expression in terms of that IV.
1056///
1057/// This is similar to IVUsers' isInsteresting() but processes each instruction
1058/// non-recursively when the operand is already known to be a simpleIVUser.
1059///
1060bool IndVarSimplify::isSimpleIVUser(Instruction *I, const Loop *L) {
1061 if (!SE->isSCEVable(I->getType()))
1062 return false;
1063
1064 // Get the symbolic expression for this instruction.
1065 const SCEV *S = SE->getSCEV(I);
1066
Andrew Trickcc359d92011-06-29 23:03:57 +00001067 // We assume that terminators are not SCEVable.
1068 assert((!S || I != I->getParent()->getTerminator()) &&
1069 "can't fold terminators");
1070
Andrew Trick2fabd462011-06-21 03:22:38 +00001071 // Only consider affine recurrences.
1072 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S);
1073 if (AR && AR->getLoop() == L)
1074 return true;
1075
1076 return false;
1077}
1078
1079/// SimplifyIVUsersNoRewrite - Iteratively perform simplification on a worklist
1080/// of IV users. Each successive simplification may push more users which may
1081/// themselves be candidates for simplification.
1082///
1083/// The "NoRewrite" algorithm does not require IVUsers analysis. Instead, it
1084/// simplifies instructions in-place during analysis. Rather than rewriting
1085/// induction variables bottom-up from their users, it transforms a chain of
1086/// IVUsers top-down, updating the IR only when it encouters a clear
1087/// optimization opportunitiy. A SCEVExpander "Rewriter" instance is still
1088/// needed, but only used to generate a new IV (phi) of wider type for sign/zero
1089/// extend elimination.
1090///
1091/// Once DisableIVRewrite is default, LSR will be the only client of IVUsers.
1092///
1093void IndVarSimplify::SimplifyIVUsersNoRewrite(Loop *L, SCEVExpander &Rewriter) {
Andrew Trick15832f62011-06-28 02:49:20 +00001094 std::map<PHINode *, WideIVInfo> WideIVMap;
1095
Andrew Trick2fabd462011-06-21 03:22:38 +00001096 SmallVector<PHINode*, 8> LoopPhis;
1097 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
1098 LoopPhis.push_back(cast<PHINode>(I));
1099 }
Andrew Trick15832f62011-06-28 02:49:20 +00001100 // Each round of simplification iterates through the SimplifyIVUsers worklist
1101 // for all current phis, then determines whether any IVs can be
1102 // widened. Widening adds new phis to LoopPhis, inducing another round of
1103 // simplification on the wide IVs.
Andrew Trick2fabd462011-06-21 03:22:38 +00001104 while (!LoopPhis.empty()) {
Andrew Trick15832f62011-06-28 02:49:20 +00001105 // Evaluate as many IV expressions as possible before widening any IVs. This
Andrew Trick99a92f62011-06-28 16:45:04 +00001106 // forces SCEV to set no-wrap flags before evaluating sign/zero
Andrew Trick15832f62011-06-28 02:49:20 +00001107 // extension. The first time SCEV attempts to normalize sign/zero extension,
1108 // the result becomes final. So for the most predictable results, we delay
1109 // evaluation of sign/zero extend evaluation until needed, and avoid running
1110 // other SCEV based analysis prior to SimplifyIVUsersNoRewrite.
1111 do {
1112 PHINode *CurrIV = LoopPhis.pop_back_val();
Andrew Trick2fabd462011-06-21 03:22:38 +00001113
Andrew Trick15832f62011-06-28 02:49:20 +00001114 // Information about sign/zero extensions of CurrIV.
1115 WideIVInfo WI;
Andrew Trick2fabd462011-06-21 03:22:38 +00001116
Andrew Trick15832f62011-06-28 02:49:20 +00001117 // Instructions processed by SimplifyIVUsers for CurrIV.
1118 SmallPtrSet<Instruction*,16> Simplified;
Andrew Trick2fabd462011-06-21 03:22:38 +00001119
Andrew Trick15832f62011-06-28 02:49:20 +00001120 // Use-def pairs if IVUsers waiting to be processed for CurrIV.
1121 SmallVector<std::pair<Instruction*, Instruction*>, 8> SimpleIVUsers;
Andrew Trick2fabd462011-06-21 03:22:38 +00001122
Andrew Trick60ac7192011-06-30 01:27:23 +00001123 // Push users of the current LoopPhi. In rare cases, pushIVUsers may be
1124 // called multiple times for the same LoopPhi. This is the proper thing to
1125 // do for loop header phis that use each other.
Andrew Trick15832f62011-06-28 02:49:20 +00001126 pushIVUsers(CurrIV, Simplified, SimpleIVUsers);
1127
1128 while (!SimpleIVUsers.empty()) {
1129 Instruction *UseInst, *Operand;
1130 tie(UseInst, Operand) = SimpleIVUsers.pop_back_val();
Andrew Trick6e0ce242011-06-30 19:02:17 +00001131 // Bypass back edges to avoid extra work.
1132 if (UseInst == CurrIV) continue;
Andrew Trick15832f62011-06-28 02:49:20 +00001133
1134 if (EliminateIVUser(UseInst, Operand)) {
1135 pushIVUsers(Operand, Simplified, SimpleIVUsers);
1136 continue;
Andrew Trick2fabd462011-06-21 03:22:38 +00001137 }
Andrew Trick15832f62011-06-28 02:49:20 +00001138 if (CastInst *Cast = dyn_cast<CastInst>(UseInst)) {
1139 bool IsSigned = Cast->getOpcode() == Instruction::SExt;
1140 if (IsSigned || Cast->getOpcode() == Instruction::ZExt) {
1141 CollectExtend(Cast, IsSigned, WI, SE, TD);
1142 }
1143 continue;
1144 }
1145 if (isSimpleIVUser(UseInst, L)) {
1146 pushIVUsers(UseInst, Simplified, SimpleIVUsers);
1147 }
Andrew Trick2fabd462011-06-21 03:22:38 +00001148 }
Andrew Trick15832f62011-06-28 02:49:20 +00001149 if (WI.WidestNativeType) {
1150 WideIVMap[CurrIV] = WI;
Andrew Trick2fabd462011-06-21 03:22:38 +00001151 }
Andrew Trick15832f62011-06-28 02:49:20 +00001152 } while(!LoopPhis.empty());
1153
1154 for (std::map<PHINode *, WideIVInfo>::const_iterator I = WideIVMap.begin(),
1155 E = WideIVMap.end(); I != E; ++I) {
1156 WidenIV Widener(I->first, I->second, LI, SE, DT, DeadInsts);
Andrew Trick2fabd462011-06-21 03:22:38 +00001157 if (PHINode *WidePhi = Widener.CreateWideIV(Rewriter)) {
1158 Changed = true;
1159 LoopPhis.push_back(WidePhi);
1160 }
1161 }
Andrew Trick15832f62011-06-28 02:49:20 +00001162 WideIVMap.clear();
Andrew Trick2fabd462011-06-21 03:22:38 +00001163 }
1164}
1165
Dan Gohmanc2390b12009-02-12 22:19:27 +00001166bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
Dan Gohmana5283822010-06-18 01:35:11 +00001167 // If LoopSimplify form is not available, stay out of trouble. Some notes:
1168 // - LSR currently only supports LoopSimplify-form loops. Indvars'
1169 // canonicalization can be a pessimization without LSR to "clean up"
1170 // afterwards.
1171 // - We depend on having a preheader; in particular,
1172 // Loop::getCanonicalInductionVariable only supports loops with preheaders,
1173 // and we're in trouble if we can't find the induction variable even when
1174 // we've manually inserted one.
1175 if (!L->isLoopSimplifyForm())
1176 return false;
1177
Andrew Trick2fabd462011-06-21 03:22:38 +00001178 if (!DisableIVRewrite)
1179 IU = &getAnalysis<IVUsers>();
Devang Patel5ee99972007-03-07 06:39:01 +00001180 LI = &getAnalysis<LoopInfo>();
1181 SE = &getAnalysis<ScalarEvolution>();
Dan Gohmande53dc02009-06-27 05:16:57 +00001182 DT = &getAnalysis<DominatorTree>();
Andrew Trick37da4082011-05-04 02:10:13 +00001183 TD = getAnalysisIfAvailable<TargetData>();
1184
Andrew Trickb12a7542011-03-17 23:51:11 +00001185 DeadInsts.clear();
Devang Patel5ee99972007-03-07 06:39:01 +00001186 Changed = false;
Dan Gohman60f8a632009-02-17 20:49:49 +00001187
Dan Gohman2d1be872009-04-16 03:18:22 +00001188 // If there are any floating-point recurrences, attempt to
Dan Gohman60f8a632009-02-17 20:49:49 +00001189 // transform them to use integer recurrences.
1190 RewriteNonIntegerIVs(L);
1191
Dan Gohman0bba49c2009-07-07 17:06:11 +00001192 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
Chris Lattner9caed542007-03-04 01:00:28 +00001193
Dan Gohman667d7872009-06-26 22:53:46 +00001194 // Create a rewriter object which we'll use to transform the code with.
Andrew Trick5e7645b2011-06-28 05:07:32 +00001195 SCEVExpander Rewriter(*SE, "indvars");
Andrew Trick156d4602011-06-27 23:17:44 +00001196
1197 // Eliminate redundant IV users.
Andrew Trick15832f62011-06-28 02:49:20 +00001198 //
1199 // Simplification works best when run before other consumers of SCEV. We
1200 // attempt to avoid evaluating SCEVs for sign/zero extend operations until
1201 // other expressions involving loop IVs have been evaluated. This helps SCEV
Andrew Trick99a92f62011-06-28 16:45:04 +00001202 // set no-wrap flags before normalizing sign/zero extension.
Andrew Trick156d4602011-06-27 23:17:44 +00001203 if (DisableIVRewrite) {
Andrew Trick37da4082011-05-04 02:10:13 +00001204 Rewriter.disableCanonicalMode();
Andrew Trick156d4602011-06-27 23:17:44 +00001205 SimplifyIVUsersNoRewrite(L, Rewriter);
1206 }
Andrew Trick37da4082011-05-04 02:10:13 +00001207
Chris Lattner40bf8b42004-04-02 20:24:31 +00001208 // Check to see if this loop has a computable loop-invariant execution count.
1209 // If so, this means that we can compute the final value of any expressions
1210 // that are recurrent in the loop, and substitute the exit values from the
1211 // loop into any instructions outside of the loop that use the final values of
1212 // the current expressions.
Chris Lattner3dec1f22002-05-10 15:38:35 +00001213 //
Dan Gohman46bdfb02009-02-24 18:55:53 +00001214 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount))
Dan Gohman454d26d2010-02-22 04:11:59 +00001215 RewriteLoopExitValues(L, Rewriter);
Chris Lattner6148c022001-12-03 17:28:42 +00001216
Andrew Trickf85092c2011-05-20 18:25:42 +00001217 // Eliminate redundant IV users.
Andrew Trick156d4602011-06-27 23:17:44 +00001218 if (!DisableIVRewrite)
Andrew Trick2fabd462011-06-21 03:22:38 +00001219 SimplifyIVUsers(Rewriter);
Dan Gohmana590b792010-04-13 01:46:36 +00001220
Dan Gohman81db61a2009-05-12 02:17:14 +00001221 // Compute the type of the largest recurrence expression, and decide whether
1222 // a canonical induction variable should be inserted.
Andrew Trickf85092c2011-05-20 18:25:42 +00001223 const Type *LargestType = 0;
Dan Gohman81db61a2009-05-12 02:17:14 +00001224 bool NeedCannIV = false;
Andrew Trick03d3d3b2011-05-25 04:42:22 +00001225 bool ExpandBECount = canExpandBackedgeTakenCount(L, SE);
Andrew Trick4dfdf242011-05-03 22:24:10 +00001226 if (ExpandBECount) {
Dan Gohman81db61a2009-05-12 02:17:14 +00001227 // If we have a known trip count and a single exit block, we'll be
1228 // rewriting the loop exit test condition below, which requires a
1229 // canonical induction variable.
Andrew Trick4dfdf242011-05-03 22:24:10 +00001230 NeedCannIV = true;
1231 const Type *Ty = BackedgeTakenCount->getType();
Andrew Trick03d3d3b2011-05-25 04:42:22 +00001232 if (DisableIVRewrite) {
1233 // In this mode, SimplifyIVUsers may have already widened the IV used by
1234 // the backedge test and inserted a Trunc on the compare's operand. Get
1235 // the wider type to avoid creating a redundant narrow IV only used by the
1236 // loop test.
1237 LargestType = getBackedgeIVType(L);
1238 }
Andrew Trick4dfdf242011-05-03 22:24:10 +00001239 if (!LargestType ||
1240 SE->getTypeSizeInBits(Ty) >
1241 SE->getTypeSizeInBits(LargestType))
1242 LargestType = SE->getEffectiveSCEVType(Ty);
Chris Lattnerf50af082004-04-17 18:08:33 +00001243 }
Andrew Trick37da4082011-05-04 02:10:13 +00001244 if (!DisableIVRewrite) {
1245 for (IVUsers::const_iterator I = IU->begin(), E = IU->end(); I != E; ++I) {
1246 NeedCannIV = true;
1247 const Type *Ty =
1248 SE->getEffectiveSCEVType(I->getOperandValToReplace()->getType());
1249 if (!LargestType ||
1250 SE->getTypeSizeInBits(Ty) >
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001251 SE->getTypeSizeInBits(LargestType))
Andrew Trick37da4082011-05-04 02:10:13 +00001252 LargestType = Ty;
1253 }
Chris Lattner6148c022001-12-03 17:28:42 +00001254 }
1255
Dan Gohmanf451cb82010-02-10 16:03:48 +00001256 // Now that we know the largest of the induction variable expressions
Dan Gohman81db61a2009-05-12 02:17:14 +00001257 // in this loop, insert a canonical induction variable of the largest size.
Dan Gohman43ef3fb2010-07-20 17:18:52 +00001258 PHINode *IndVar = 0;
Dan Gohman81db61a2009-05-12 02:17:14 +00001259 if (NeedCannIV) {
Dan Gohman85669632010-02-25 06:57:05 +00001260 // Check to see if the loop already has any canonical-looking induction
1261 // variables. If any are present and wider than the planned canonical
1262 // induction variable, temporarily remove them, so that the Rewriter
1263 // doesn't attempt to reuse them.
1264 SmallVector<PHINode *, 2> OldCannIVs;
1265 while (PHINode *OldCannIV = L->getCanonicalInductionVariable()) {
Dan Gohman4d8414f2009-06-13 16:25:49 +00001266 if (SE->getTypeSizeInBits(OldCannIV->getType()) >
1267 SE->getTypeSizeInBits(LargestType))
1268 OldCannIV->removeFromParent();
1269 else
Dan Gohman85669632010-02-25 06:57:05 +00001270 break;
1271 OldCannIVs.push_back(OldCannIV);
Dan Gohman4d8414f2009-06-13 16:25:49 +00001272 }
1273
Dan Gohman667d7872009-06-26 22:53:46 +00001274 IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L, LargestType);
Dan Gohman4d8414f2009-06-13 16:25:49 +00001275
Dan Gohmanc2390b12009-02-12 22:19:27 +00001276 ++NumInserted;
1277 Changed = true;
David Greenef67ef312010-01-05 01:27:06 +00001278 DEBUG(dbgs() << "INDVARS: New CanIV: " << *IndVar << '\n');
Dan Gohman4d8414f2009-06-13 16:25:49 +00001279
1280 // Now that the official induction variable is established, reinsert
Dan Gohman85669632010-02-25 06:57:05 +00001281 // any old canonical-looking variables after it so that the IR remains
1282 // consistent. They will be deleted as part of the dead-PHI deletion at
Dan Gohman4d8414f2009-06-13 16:25:49 +00001283 // the end of the pass.
Dan Gohman85669632010-02-25 06:57:05 +00001284 while (!OldCannIVs.empty()) {
1285 PHINode *OldCannIV = OldCannIVs.pop_back_val();
1286 OldCannIV->insertBefore(L->getHeader()->getFirstNonPHI());
1287 }
Dan Gohmand19534a2007-06-15 14:38:12 +00001288 }
Chris Lattner15cad752003-12-23 07:47:09 +00001289
Dan Gohmanc2390b12009-02-12 22:19:27 +00001290 // If we have a trip count expression, rewrite the loop's exit condition
1291 // using it. We can currently only handle loops with a single exit.
Dan Gohman81db61a2009-05-12 02:17:14 +00001292 ICmpInst *NewICmp = 0;
Andrew Trick4dfdf242011-05-03 22:24:10 +00001293 if (ExpandBECount) {
Andrew Trick03d3d3b2011-05-25 04:42:22 +00001294 assert(canExpandBackedgeTakenCount(L, SE) &&
Andrew Trick4dfdf242011-05-03 22:24:10 +00001295 "canonical IV disrupted BackedgeTaken expansion");
Dan Gohman81db61a2009-05-12 02:17:14 +00001296 assert(NeedCannIV &&
1297 "LinearFunctionTestReplace requires a canonical induction variable");
Andrew Trick4dfdf242011-05-03 22:24:10 +00001298 NewICmp = LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar,
1299 Rewriter);
Chris Lattnerfcb81f52004-04-22 14:59:40 +00001300 }
Andrew Trickb12a7542011-03-17 23:51:11 +00001301 // Rewrite IV-derived expressions.
Andrew Trick37da4082011-05-04 02:10:13 +00001302 if (!DisableIVRewrite)
1303 RewriteIVExpressions(L, Rewriter);
Dan Gohmanc2390b12009-02-12 22:19:27 +00001304
Andrew Trickb12a7542011-03-17 23:51:11 +00001305 // Clear the rewriter cache, because values that are in the rewriter's cache
1306 // can be deleted in the loop below, causing the AssertingVH in the cache to
1307 // trigger.
1308 Rewriter.clear();
1309
1310 // Now that we're done iterating through lists, clean up any instructions
1311 // which are now dead.
1312 while (!DeadInsts.empty())
1313 if (Instruction *Inst =
1314 dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val()))
1315 RecursivelyDeleteTriviallyDeadInstructions(Inst);
1316
Dan Gohman667d7872009-06-26 22:53:46 +00001317 // The Rewriter may not be used from this point on.
Torok Edwin3d431382009-05-24 20:08:21 +00001318
Dan Gohman81db61a2009-05-12 02:17:14 +00001319 // Loop-invariant instructions in the preheader that aren't used in the
1320 // loop may be sunk below the loop to reduce register pressure.
Dan Gohman667d7872009-06-26 22:53:46 +00001321 SinkUnusedInvariants(L);
Dan Gohman81db61a2009-05-12 02:17:14 +00001322
1323 // For completeness, inform IVUsers of the IV use in the newly-created
1324 // loop exit test instruction.
Andrew Trick2fabd462011-06-21 03:22:38 +00001325 if (NewICmp && IU)
Andrew Trick4417e532011-06-21 15:43:52 +00001326 IU->AddUsersIfInteresting(cast<Instruction>(NewICmp->getOperand(0)));
Dan Gohman81db61a2009-05-12 02:17:14 +00001327
1328 // Clean up dead instructions.
Dan Gohman9fff2182010-01-05 16:31:45 +00001329 Changed |= DeleteDeadPHIs(L->getHeader());
Dan Gohman81db61a2009-05-12 02:17:14 +00001330 // Check a post-condition.
Dan Gohmanbbf81d82010-03-10 19:38:49 +00001331 assert(L->isLCSSAForm(*DT) && "Indvars did not leave the loop in lcssa form!");
Devang Patel5ee99972007-03-07 06:39:01 +00001332 return Changed;
Chris Lattner6148c022001-12-03 17:28:42 +00001333}
Devang Pateld22a8492008-09-09 21:41:07 +00001334
Dan Gohman448db1c2010-04-07 22:27:08 +00001335// FIXME: It is an extremely bad idea to indvar substitute anything more
1336// complex than affine induction variables. Doing so will put expensive
1337// polynomial evaluations inside of the loop, and the str reduction pass
1338// currently can only reduce affine polynomials. For now just disable
1339// indvar subst on anything more complex than an affine addrec, unless
1340// it can be expanded to a trivial value.
Dan Gohman17ead4f2010-11-17 21:23:15 +00001341static bool isSafe(const SCEV *S, const Loop *L, ScalarEvolution *SE) {
Dan Gohman448db1c2010-04-07 22:27:08 +00001342 // Loop-invariant values are safe.
Dan Gohman17ead4f2010-11-17 21:23:15 +00001343 if (SE->isLoopInvariant(S, L)) return true;
Dan Gohman448db1c2010-04-07 22:27:08 +00001344
1345 // Affine addrecs are safe. Non-affine are not, because LSR doesn't know how
1346 // to transform them into efficient code.
1347 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
1348 return AR->isAffine();
1349
1350 // An add is safe it all its operands are safe.
1351 if (const SCEVCommutativeExpr *Commutative = dyn_cast<SCEVCommutativeExpr>(S)) {
1352 for (SCEVCommutativeExpr::op_iterator I = Commutative->op_begin(),
1353 E = Commutative->op_end(); I != E; ++I)
Dan Gohman17ead4f2010-11-17 21:23:15 +00001354 if (!isSafe(*I, L, SE)) return false;
Dan Gohman448db1c2010-04-07 22:27:08 +00001355 return true;
1356 }
Andrew Trickead71d52011-03-17 23:46:48 +00001357
Dan Gohman448db1c2010-04-07 22:27:08 +00001358 // A cast is safe if its operand is.
1359 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
Dan Gohman17ead4f2010-11-17 21:23:15 +00001360 return isSafe(C->getOperand(), L, SE);
Dan Gohman448db1c2010-04-07 22:27:08 +00001361
1362 // A udiv is safe if its operands are.
1363 if (const SCEVUDivExpr *UD = dyn_cast<SCEVUDivExpr>(S))
Dan Gohman17ead4f2010-11-17 21:23:15 +00001364 return isSafe(UD->getLHS(), L, SE) &&
1365 isSafe(UD->getRHS(), L, SE);
Dan Gohman448db1c2010-04-07 22:27:08 +00001366
1367 // SCEVUnknown is always safe.
1368 if (isa<SCEVUnknown>(S))
1369 return true;
1370
1371 // Nothing else is safe.
1372 return false;
1373}
1374
Dan Gohman454d26d2010-02-22 04:11:59 +00001375void IndVarSimplify::RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter) {
Dan Gohman81db61a2009-05-12 02:17:14 +00001376 // Rewrite all induction variable expressions in terms of the canonical
1377 // induction variable.
1378 //
1379 // If there were induction variables of other sizes or offsets, manually
1380 // add the offsets to the primary induction variable and cast, avoiding
1381 // the need for the code evaluation methods to insert induction variables
1382 // of different sizes.
Dan Gohman572645c2010-02-12 10:34:29 +00001383 for (IVUsers::iterator UI = IU->begin(), E = IU->end(); UI != E; ++UI) {
Dan Gohman572645c2010-02-12 10:34:29 +00001384 Value *Op = UI->getOperandValToReplace();
1385 const Type *UseTy = Op->getType();
1386 Instruction *User = UI->getUser();
Dan Gohman81db61a2009-05-12 02:17:14 +00001387
Dan Gohman572645c2010-02-12 10:34:29 +00001388 // Compute the final addrec to expand into code.
1389 const SCEV *AR = IU->getReplacementExpr(*UI);
Dan Gohman81db61a2009-05-12 02:17:14 +00001390
Dan Gohman572645c2010-02-12 10:34:29 +00001391 // Evaluate the expression out of the loop, if possible.
1392 if (!L->contains(UI->getUser())) {
1393 const SCEV *ExitVal = SE->getSCEVAtScope(AR, L->getParentLoop());
Dan Gohman17ead4f2010-11-17 21:23:15 +00001394 if (SE->isLoopInvariant(ExitVal, L))
Dan Gohman572645c2010-02-12 10:34:29 +00001395 AR = ExitVal;
Dan Gohman81db61a2009-05-12 02:17:14 +00001396 }
Dan Gohman572645c2010-02-12 10:34:29 +00001397
1398 // FIXME: It is an extremely bad idea to indvar substitute anything more
1399 // complex than affine induction variables. Doing so will put expensive
1400 // polynomial evaluations inside of the loop, and the str reduction pass
1401 // currently can only reduce affine polynomials. For now just disable
1402 // indvar subst on anything more complex than an affine addrec, unless
1403 // it can be expanded to a trivial value.
Dan Gohman17ead4f2010-11-17 21:23:15 +00001404 if (!isSafe(AR, L, SE))
Dan Gohman572645c2010-02-12 10:34:29 +00001405 continue;
1406
1407 // Determine the insertion point for this user. By default, insert
1408 // immediately before the user. The SCEVExpander class will automatically
1409 // hoist loop invariants out of the loop. For PHI nodes, there may be
1410 // multiple uses, so compute the nearest common dominator for the
1411 // incoming blocks.
1412 Instruction *InsertPt = User;
1413 if (PHINode *PHI = dyn_cast<PHINode>(InsertPt))
1414 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
1415 if (PHI->getIncomingValue(i) == Op) {
1416 if (InsertPt == User)
1417 InsertPt = PHI->getIncomingBlock(i)->getTerminator();
1418 else
1419 InsertPt =
1420 DT->findNearestCommonDominator(InsertPt->getParent(),
1421 PHI->getIncomingBlock(i))
1422 ->getTerminator();
1423 }
1424
1425 // Now expand it into actual Instructions and patch it into place.
1426 Value *NewVal = Rewriter.expandCodeFor(AR, UseTy, InsertPt);
1427
Andrew Trickb12a7542011-03-17 23:51:11 +00001428 DEBUG(dbgs() << "INDVARS: Rewrote IV '" << *AR << "' " << *Op << '\n'
1429 << " into = " << *NewVal << "\n");
1430
1431 if (!isValidRewrite(Op, NewVal)) {
1432 DeadInsts.push_back(NewVal);
1433 continue;
1434 }
Dan Gohmand7bfd002010-04-02 14:48:31 +00001435 // Inform ScalarEvolution that this value is changing. The change doesn't
1436 // affect its value, but it does potentially affect which use lists the
1437 // value will be on after the replacement, which affects ScalarEvolution's
1438 // ability to walk use lists and drop dangling pointers when a value is
1439 // deleted.
1440 SE->forgetValue(User);
1441
Dan Gohman572645c2010-02-12 10:34:29 +00001442 // Patch the new value into place.
1443 if (Op->hasName())
1444 NewVal->takeName(Op);
Devang Patela098bf12011-06-22 19:52:36 +00001445 if (Instruction *NewValI = dyn_cast<Instruction>(NewVal))
1446 NewValI->setDebugLoc(User->getDebugLoc());
Dan Gohman572645c2010-02-12 10:34:29 +00001447 User->replaceUsesOfWith(Op, NewVal);
1448 UI->setOperandValToReplace(NewVal);
Andrew Trickb12a7542011-03-17 23:51:11 +00001449
Dan Gohman572645c2010-02-12 10:34:29 +00001450 ++NumRemoved;
1451 Changed = true;
1452
1453 // The old value may be dead now.
1454 DeadInsts.push_back(Op);
Dan Gohman81db61a2009-05-12 02:17:14 +00001455 }
Dan Gohman81db61a2009-05-12 02:17:14 +00001456}
1457
1458/// If there's a single exit block, sink any loop-invariant values that
1459/// were defined in the preheader but not used inside the loop into the
1460/// exit block to reduce register pressure in the loop.
Dan Gohman667d7872009-06-26 22:53:46 +00001461void IndVarSimplify::SinkUnusedInvariants(Loop *L) {
Dan Gohman81db61a2009-05-12 02:17:14 +00001462 BasicBlock *ExitBlock = L->getExitBlock();
1463 if (!ExitBlock) return;
1464
Dan Gohman81db61a2009-05-12 02:17:14 +00001465 BasicBlock *Preheader = L->getLoopPreheader();
Dan Gohman03e896b2009-11-05 21:11:53 +00001466 if (!Preheader) return;
1467
1468 Instruction *InsertPt = ExitBlock->getFirstNonPHI();
Dan Gohman81db61a2009-05-12 02:17:14 +00001469 BasicBlock::iterator I = Preheader->getTerminator();
1470 while (I != Preheader->begin()) {
1471 --I;
Dan Gohman667d7872009-06-26 22:53:46 +00001472 // New instructions were inserted at the end of the preheader.
1473 if (isa<PHINode>(I))
Dan Gohman81db61a2009-05-12 02:17:14 +00001474 break;
Bill Wendling87a10f52010-03-23 21:15:59 +00001475
Eli Friedman0c77db32009-07-15 22:48:29 +00001476 // Don't move instructions which might have side effects, since the side
Bill Wendling87a10f52010-03-23 21:15:59 +00001477 // effects need to complete before instructions inside the loop. Also don't
1478 // move instructions which might read memory, since the loop may modify
1479 // memory. Note that it's okay if the instruction might have undefined
1480 // behavior: LoopSimplify guarantees that the preheader dominates the exit
1481 // block.
Eli Friedman0c77db32009-07-15 22:48:29 +00001482 if (I->mayHaveSideEffects() || I->mayReadFromMemory())
Dan Gohman667d7872009-06-26 22:53:46 +00001483 continue;
Bill Wendling87a10f52010-03-23 21:15:59 +00001484
Devang Patel7b9f6b12010-03-15 22:23:03 +00001485 // Skip debug info intrinsics.
1486 if (isa<DbgInfoIntrinsic>(I))
1487 continue;
Bill Wendling87a10f52010-03-23 21:15:59 +00001488
Dan Gohman76f497a2009-08-25 17:42:10 +00001489 // Don't sink static AllocaInsts out of the entry block, which would
1490 // turn them into dynamic allocas!
1491 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
1492 if (AI->isStaticAlloca())
1493 continue;
Bill Wendling87a10f52010-03-23 21:15:59 +00001494
Dan Gohman81db61a2009-05-12 02:17:14 +00001495 // Determine if there is a use in or before the loop (direct or
1496 // otherwise).
1497 bool UsedInLoop = false;
1498 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
1499 UI != UE; ++UI) {
Gabor Greif76560182010-07-09 15:40:10 +00001500 User *U = *UI;
1501 BasicBlock *UseBB = cast<Instruction>(U)->getParent();
1502 if (PHINode *P = dyn_cast<PHINode>(U)) {
Dan Gohman81db61a2009-05-12 02:17:14 +00001503 unsigned i =
1504 PHINode::getIncomingValueNumForOperand(UI.getOperandNo());
1505 UseBB = P->getIncomingBlock(i);
1506 }
1507 if (UseBB == Preheader || L->contains(UseBB)) {
1508 UsedInLoop = true;
1509 break;
1510 }
1511 }
Bill Wendling87a10f52010-03-23 21:15:59 +00001512
Dan Gohman81db61a2009-05-12 02:17:14 +00001513 // If there is, the def must remain in the preheader.
1514 if (UsedInLoop)
1515 continue;
Bill Wendling87a10f52010-03-23 21:15:59 +00001516
Dan Gohman81db61a2009-05-12 02:17:14 +00001517 // Otherwise, sink it to the exit block.
1518 Instruction *ToMove = I;
1519 bool Done = false;
Bill Wendling87a10f52010-03-23 21:15:59 +00001520
1521 if (I != Preheader->begin()) {
1522 // Skip debug info intrinsics.
1523 do {
1524 --I;
1525 } while (isa<DbgInfoIntrinsic>(I) && I != Preheader->begin());
1526
1527 if (isa<DbgInfoIntrinsic>(I) && I == Preheader->begin())
1528 Done = true;
1529 } else {
Dan Gohman81db61a2009-05-12 02:17:14 +00001530 Done = true;
Bill Wendling87a10f52010-03-23 21:15:59 +00001531 }
1532
Dan Gohman667d7872009-06-26 22:53:46 +00001533 ToMove->moveBefore(InsertPt);
Bill Wendling87a10f52010-03-23 21:15:59 +00001534 if (Done) break;
Dan Gohman667d7872009-06-26 22:53:46 +00001535 InsertPt = ToMove;
Dan Gohman81db61a2009-05-12 02:17:14 +00001536 }
1537}
1538
Chris Lattnerbbb91492010-04-03 06:41:49 +00001539/// ConvertToSInt - Convert APF to an integer, if possible.
1540static bool ConvertToSInt(const APFloat &APF, int64_t &IntVal) {
Devang Patelcd402332008-11-17 23:27:13 +00001541 bool isExact = false;
Evan Cheng794a7db2008-11-26 01:11:57 +00001542 if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
1543 return false;
Chris Lattnerbbb91492010-04-03 06:41:49 +00001544 // See if we can convert this to an int64_t
1545 uint64_t UIntVal;
1546 if (APF.convertToInteger(&UIntVal, 64, true, APFloat::rmTowardZero,
1547 &isExact) != APFloat::opOK || !isExact)
Devang Patelcd402332008-11-17 23:27:13 +00001548 return false;
Chris Lattnerbbb91492010-04-03 06:41:49 +00001549 IntVal = UIntVal;
Devang Patelcd402332008-11-17 23:27:13 +00001550 return true;
Devang Patelcd402332008-11-17 23:27:13 +00001551}
1552
Devang Patel58d43d42008-11-03 18:32:19 +00001553/// HandleFloatingPointIV - If the loop has floating induction variable
1554/// then insert corresponding integer induction variable if possible.
Devang Patel84e35152008-11-17 21:32:02 +00001555/// For example,
1556/// for(double i = 0; i < 10000; ++i)
1557/// bar(i)
1558/// is converted into
1559/// for(int i = 0; i < 10000; ++i)
1560/// bar((double)i);
1561///
Chris Lattnerc91961e2010-04-03 06:17:08 +00001562void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PN) {
1563 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
Devang Patel84e35152008-11-17 21:32:02 +00001564 unsigned BackEdge = IncomingEdge^1;
Dan Gohmancafb8132009-02-17 19:13:57 +00001565
Devang Patel84e35152008-11-17 21:32:02 +00001566 // Check incoming value.
Chris Lattnerc4f7e802010-04-03 06:05:10 +00001567 ConstantFP *InitValueVal =
Chris Lattnerc91961e2010-04-03 06:17:08 +00001568 dyn_cast<ConstantFP>(PN->getIncomingValue(IncomingEdge));
Chris Lattner96fd7662010-04-03 07:18:48 +00001569
Chris Lattnerbbb91492010-04-03 06:41:49 +00001570 int64_t InitValue;
Chris Lattner96fd7662010-04-03 07:18:48 +00001571 if (!InitValueVal || !ConvertToSInt(InitValueVal->getValueAPF(), InitValue))
Devang Patelcd402332008-11-17 23:27:13 +00001572 return;
1573
Chris Lattnerc91961e2010-04-03 06:17:08 +00001574 // Check IV increment. Reject this PN if increment operation is not
Devang Patelcd402332008-11-17 23:27:13 +00001575 // an add or increment value can not be represented by an integer.
Dan Gohmancafb8132009-02-17 19:13:57 +00001576 BinaryOperator *Incr =
Chris Lattnerc91961e2010-04-03 06:17:08 +00001577 dyn_cast<BinaryOperator>(PN->getIncomingValue(BackEdge));
Chris Lattner07aa76a2010-04-03 05:54:59 +00001578 if (Incr == 0 || Incr->getOpcode() != Instruction::FAdd) return;
Andrew Trickead71d52011-03-17 23:46:48 +00001579
Chris Lattner07aa76a2010-04-03 05:54:59 +00001580 // If this is not an add of the PHI with a constantfp, or if the constant fp
1581 // is not an integer, bail out.
Chris Lattnerc4f7e802010-04-03 06:05:10 +00001582 ConstantFP *IncValueVal = dyn_cast<ConstantFP>(Incr->getOperand(1));
Chris Lattner96fd7662010-04-03 07:18:48 +00001583 int64_t IncValue;
Chris Lattnerc91961e2010-04-03 06:17:08 +00001584 if (IncValueVal == 0 || Incr->getOperand(0) != PN ||
Chris Lattner96fd7662010-04-03 07:18:48 +00001585 !ConvertToSInt(IncValueVal->getValueAPF(), IncValue))
Devang Patelcd402332008-11-17 23:27:13 +00001586 return;
Dan Gohmancafb8132009-02-17 19:13:57 +00001587
Chris Lattnerc91961e2010-04-03 06:17:08 +00001588 // Check Incr uses. One user is PN and the other user is an exit condition
Chris Lattner07aa76a2010-04-03 05:54:59 +00001589 // used by the conditional terminator.
Devang Patel84e35152008-11-17 21:32:02 +00001590 Value::use_iterator IncrUse = Incr->use_begin();
Gabor Greif96f1d8e2010-07-22 13:36:47 +00001591 Instruction *U1 = cast<Instruction>(*IncrUse++);
Devang Patel84e35152008-11-17 21:32:02 +00001592 if (IncrUse == Incr->use_end()) return;
Gabor Greif96f1d8e2010-07-22 13:36:47 +00001593 Instruction *U2 = cast<Instruction>(*IncrUse++);
Devang Patel84e35152008-11-17 21:32:02 +00001594 if (IncrUse != Incr->use_end()) return;
Dan Gohmancafb8132009-02-17 19:13:57 +00001595
Chris Lattner07aa76a2010-04-03 05:54:59 +00001596 // Find exit condition, which is an fcmp. If it doesn't exist, or if it isn't
1597 // only used by a branch, we can't transform it.
Chris Lattnerca703bd2010-04-03 06:11:07 +00001598 FCmpInst *Compare = dyn_cast<FCmpInst>(U1);
1599 if (!Compare)
1600 Compare = dyn_cast<FCmpInst>(U2);
1601 if (Compare == 0 || !Compare->hasOneUse() ||
1602 !isa<BranchInst>(Compare->use_back()))
Chris Lattner07aa76a2010-04-03 05:54:59 +00001603 return;
Andrew Trickead71d52011-03-17 23:46:48 +00001604
Chris Lattnerca703bd2010-04-03 06:11:07 +00001605 BranchInst *TheBr = cast<BranchInst>(Compare->use_back());
Devang Patel84e35152008-11-17 21:32:02 +00001606
Chris Lattnerd52c0722010-04-03 07:21:39 +00001607 // We need to verify that the branch actually controls the iteration count
1608 // of the loop. If not, the new IV can overflow and no one will notice.
1609 // The branch block must be in the loop and one of the successors must be out
1610 // of the loop.
1611 assert(TheBr->isConditional() && "Can't use fcmp if not conditional");
1612 if (!L->contains(TheBr->getParent()) ||
1613 (L->contains(TheBr->getSuccessor(0)) &&
1614 L->contains(TheBr->getSuccessor(1))))
1615 return;
Andrew Trickead71d52011-03-17 23:46:48 +00001616
1617
Chris Lattner07aa76a2010-04-03 05:54:59 +00001618 // If it isn't a comparison with an integer-as-fp (the exit value), we can't
1619 // transform it.
Chris Lattnerca703bd2010-04-03 06:11:07 +00001620 ConstantFP *ExitValueVal = dyn_cast<ConstantFP>(Compare->getOperand(1));
Chris Lattnerbbb91492010-04-03 06:41:49 +00001621 int64_t ExitValue;
1622 if (ExitValueVal == 0 ||
1623 !ConvertToSInt(ExitValueVal->getValueAPF(), ExitValue))
Devang Patel84e35152008-11-17 21:32:02 +00001624 return;
Andrew Trickead71d52011-03-17 23:46:48 +00001625
Devang Patel84e35152008-11-17 21:32:02 +00001626 // Find new predicate for integer comparison.
1627 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
Chris Lattnerca703bd2010-04-03 06:11:07 +00001628 switch (Compare->getPredicate()) {
Chris Lattnerc4f7e802010-04-03 06:05:10 +00001629 default: return; // Unknown comparison.
Devang Patel84e35152008-11-17 21:32:02 +00001630 case CmpInst::FCMP_OEQ:
Chris Lattnerc4f7e802010-04-03 06:05:10 +00001631 case CmpInst::FCMP_UEQ: NewPred = CmpInst::ICMP_EQ; break;
Chris Lattner96fd7662010-04-03 07:18:48 +00001632 case CmpInst::FCMP_ONE:
1633 case CmpInst::FCMP_UNE: NewPred = CmpInst::ICMP_NE; break;
Devang Patel84e35152008-11-17 21:32:02 +00001634 case CmpInst::FCMP_OGT:
Chris Lattnera40e4a02010-04-03 06:25:21 +00001635 case CmpInst::FCMP_UGT: NewPred = CmpInst::ICMP_SGT; break;
Devang Patel84e35152008-11-17 21:32:02 +00001636 case CmpInst::FCMP_OGE:
Chris Lattnera40e4a02010-04-03 06:25:21 +00001637 case CmpInst::FCMP_UGE: NewPred = CmpInst::ICMP_SGE; break;
Devang Patel84e35152008-11-17 21:32:02 +00001638 case CmpInst::FCMP_OLT:
Chris Lattner43b85272010-04-03 06:30:03 +00001639 case CmpInst::FCMP_ULT: NewPred = CmpInst::ICMP_SLT; break;
Devang Patel84e35152008-11-17 21:32:02 +00001640 case CmpInst::FCMP_OLE:
Chris Lattner43b85272010-04-03 06:30:03 +00001641 case CmpInst::FCMP_ULE: NewPred = CmpInst::ICMP_SLE; break;
Devang Patel58d43d42008-11-03 18:32:19 +00001642 }
Andrew Trickead71d52011-03-17 23:46:48 +00001643
Chris Lattner96fd7662010-04-03 07:18:48 +00001644 // We convert the floating point induction variable to a signed i32 value if
1645 // we can. This is only safe if the comparison will not overflow in a way
1646 // that won't be trapped by the integer equivalent operations. Check for this
1647 // now.
1648 // TODO: We could use i64 if it is native and the range requires it.
Andrew Trickead71d52011-03-17 23:46:48 +00001649
Chris Lattner96fd7662010-04-03 07:18:48 +00001650 // The start/stride/exit values must all fit in signed i32.
1651 if (!isInt<32>(InitValue) || !isInt<32>(IncValue) || !isInt<32>(ExitValue))
1652 return;
1653
1654 // If not actually striding (add x, 0.0), avoid touching the code.
1655 if (IncValue == 0)
1656 return;
1657
1658 // Positive and negative strides have different safety conditions.
1659 if (IncValue > 0) {
1660 // If we have a positive stride, we require the init to be less than the
1661 // exit value and an equality or less than comparison.
1662 if (InitValue >= ExitValue ||
1663 NewPred == CmpInst::ICMP_SGT || NewPred == CmpInst::ICMP_SGE)
1664 return;
Andrew Trickead71d52011-03-17 23:46:48 +00001665
Chris Lattner96fd7662010-04-03 07:18:48 +00001666 uint32_t Range = uint32_t(ExitValue-InitValue);
1667 if (NewPred == CmpInst::ICMP_SLE) {
1668 // Normalize SLE -> SLT, check for infinite loop.
1669 if (++Range == 0) return; // Range overflows.
1670 }
Andrew Trickead71d52011-03-17 23:46:48 +00001671
Chris Lattner96fd7662010-04-03 07:18:48 +00001672 unsigned Leftover = Range % uint32_t(IncValue);
Andrew Trickead71d52011-03-17 23:46:48 +00001673
Chris Lattner96fd7662010-04-03 07:18:48 +00001674 // If this is an equality comparison, we require that the strided value
1675 // exactly land on the exit value, otherwise the IV condition will wrap
1676 // around and do things the fp IV wouldn't.
1677 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
1678 Leftover != 0)
1679 return;
Andrew Trickead71d52011-03-17 23:46:48 +00001680
Chris Lattner96fd7662010-04-03 07:18:48 +00001681 // If the stride would wrap around the i32 before exiting, we can't
1682 // transform the IV.
1683 if (Leftover != 0 && int32_t(ExitValue+IncValue) < ExitValue)
1684 return;
Andrew Trickead71d52011-03-17 23:46:48 +00001685
Chris Lattner96fd7662010-04-03 07:18:48 +00001686 } else {
1687 // If we have a negative stride, we require the init to be greater than the
1688 // exit value and an equality or greater than comparison.
1689 if (InitValue >= ExitValue ||
1690 NewPred == CmpInst::ICMP_SLT || NewPred == CmpInst::ICMP_SLE)
1691 return;
Andrew Trickead71d52011-03-17 23:46:48 +00001692
Chris Lattner96fd7662010-04-03 07:18:48 +00001693 uint32_t Range = uint32_t(InitValue-ExitValue);
1694 if (NewPred == CmpInst::ICMP_SGE) {
1695 // Normalize SGE -> SGT, check for infinite loop.
1696 if (++Range == 0) return; // Range overflows.
1697 }
Andrew Trickead71d52011-03-17 23:46:48 +00001698
Chris Lattner96fd7662010-04-03 07:18:48 +00001699 unsigned Leftover = Range % uint32_t(-IncValue);
Andrew Trickead71d52011-03-17 23:46:48 +00001700
Chris Lattner96fd7662010-04-03 07:18:48 +00001701 // If this is an equality comparison, we require that the strided value
1702 // exactly land on the exit value, otherwise the IV condition will wrap
1703 // around and do things the fp IV wouldn't.
1704 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
1705 Leftover != 0)
1706 return;
Andrew Trickead71d52011-03-17 23:46:48 +00001707
Chris Lattner96fd7662010-04-03 07:18:48 +00001708 // If the stride would wrap around the i32 before exiting, we can't
1709 // transform the IV.
1710 if (Leftover != 0 && int32_t(ExitValue+IncValue) > ExitValue)
1711 return;
1712 }
Andrew Trickead71d52011-03-17 23:46:48 +00001713
Chris Lattner96fd7662010-04-03 07:18:48 +00001714 const IntegerType *Int32Ty = Type::getInt32Ty(PN->getContext());
Dan Gohmancafb8132009-02-17 19:13:57 +00001715
Chris Lattnerbbb91492010-04-03 06:41:49 +00001716 // Insert new integer induction variable.
Jay Foad3ecfc862011-03-30 11:28:46 +00001717 PHINode *NewPHI = PHINode::Create(Int32Ty, 2, PN->getName()+".int", PN);
Chris Lattnerc4f7e802010-04-03 06:05:10 +00001718 NewPHI->addIncoming(ConstantInt::get(Int32Ty, InitValue),
Chris Lattnerc91961e2010-04-03 06:17:08 +00001719 PN->getIncomingBlock(IncomingEdge));
Devang Patel84e35152008-11-17 21:32:02 +00001720
Chris Lattnerc4f7e802010-04-03 06:05:10 +00001721 Value *NewAdd =
Chris Lattner96fd7662010-04-03 07:18:48 +00001722 BinaryOperator::CreateAdd(NewPHI, ConstantInt::get(Int32Ty, IncValue),
Chris Lattnerc4f7e802010-04-03 06:05:10 +00001723 Incr->getName()+".int", Incr);
Chris Lattnerc91961e2010-04-03 06:17:08 +00001724 NewPHI->addIncoming(NewAdd, PN->getIncomingBlock(BackEdge));
Devang Patel84e35152008-11-17 21:32:02 +00001725
Chris Lattnerca703bd2010-04-03 06:11:07 +00001726 ICmpInst *NewCompare = new ICmpInst(TheBr, NewPred, NewAdd,
1727 ConstantInt::get(Int32Ty, ExitValue),
1728 Compare->getName());
Dan Gohmancafb8132009-02-17 19:13:57 +00001729
Chris Lattnerc91961e2010-04-03 06:17:08 +00001730 // In the following deletions, PN may become dead and may be deleted.
Dan Gohman81db61a2009-05-12 02:17:14 +00001731 // Use a WeakVH to observe whether this happens.
Chris Lattnerc91961e2010-04-03 06:17:08 +00001732 WeakVH WeakPH = PN;
Dan Gohman81db61a2009-05-12 02:17:14 +00001733
Chris Lattnerca703bd2010-04-03 06:11:07 +00001734 // Delete the old floating point exit comparison. The branch starts using the
1735 // new comparison.
1736 NewCompare->takeName(Compare);
1737 Compare->replaceAllUsesWith(NewCompare);
1738 RecursivelyDeleteTriviallyDeadInstructions(Compare);
Dan Gohmancafb8132009-02-17 19:13:57 +00001739
Chris Lattnerca703bd2010-04-03 06:11:07 +00001740 // Delete the old floating point increment.
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001741 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
Dan Gohman81db61a2009-05-12 02:17:14 +00001742 RecursivelyDeleteTriviallyDeadInstructions(Incr);
Dan Gohmancafb8132009-02-17 19:13:57 +00001743
Chris Lattner70c0d4f2010-04-03 06:16:22 +00001744 // If the FP induction variable still has uses, this is because something else
1745 // in the loop uses its value. In order to canonicalize the induction
1746 // variable, we chose to eliminate the IV and rewrite it in terms of an
1747 // int->fp cast.
1748 //
1749 // We give preference to sitofp over uitofp because it is faster on most
1750 // platforms.
1751 if (WeakPH) {
Chris Lattnera40e4a02010-04-03 06:25:21 +00001752 Value *Conv = new SIToFPInst(NewPHI, PN->getType(), "indvar.conv",
1753 PN->getParent()->getFirstNonPHI());
1754 PN->replaceAllUsesWith(Conv);
Chris Lattnerc91961e2010-04-03 06:17:08 +00001755 RecursivelyDeleteTriviallyDeadInstructions(PN);
Devang Patelcd402332008-11-17 23:27:13 +00001756 }
Devang Patel58d43d42008-11-03 18:32:19 +00001757
Dan Gohman81db61a2009-05-12 02:17:14 +00001758 // Add a new IVUsers entry for the newly-created integer PHI.
Andrew Trick2fabd462011-06-21 03:22:38 +00001759 if (IU)
Andrew Trick4417e532011-06-21 15:43:52 +00001760 IU->AddUsersIfInteresting(NewPHI);
Dan Gohman81db61a2009-05-12 02:17:14 +00001761}