blob: ceca45220e9c63b6c68f87dc4ef30f2bed4abfb6 [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"
Owen Andersond672ecb2009-07-03 00:17:18 +000046#include "llvm/LLVMContext.h"
Chris Lattner40bf8b42004-04-02 20:24:31 +000047#include "llvm/Type.h"
Dan Gohman81db61a2009-05-12 02:17:14 +000048#include "llvm/Analysis/Dominators.h"
49#include "llvm/Analysis/IVUsers.h"
Nate Begeman36f891b2005-07-30 00:12:19 +000050#include "llvm/Analysis/ScalarEvolutionExpander.h"
John Criswell47df12d2003-12-18 17:19:19 +000051#include "llvm/Analysis/LoopInfo.h"
Devang Patel5ee99972007-03-07 06:39:01 +000052#include "llvm/Analysis/LoopPass.h"
Chris Lattner455889a2002-02-12 22:39:50 +000053#include "llvm/Support/CFG.h"
Reid Spencer9133fe22007-02-05 23:32:05 +000054#include "llvm/Support/Compiler.h"
Chris Lattnerbdff5482009-08-23 04:37: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"
Reid Spencera54b7cb2007-01-12 07:05:14 +000060#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000061#include "llvm/ADT/Statistic.h"
Dan Gohman81db61a2009-05-12 02:17:14 +000062#include "llvm/ADT/STLExtras.h"
John Criswell47df12d2003-12-18 17:19:19 +000063using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000064
Chris Lattner0e5f4992006-12-19 21:40:18 +000065STATISTIC(NumRemoved , "Number of aux indvars removed");
Chris Lattner0e5f4992006-12-19 21:40:18 +000066STATISTIC(NumInserted, "Number of canonical indvars added");
67STATISTIC(NumReplaced, "Number of exit values replaced");
68STATISTIC(NumLFTR , "Number of loop exit tests replaced");
Chris Lattner3324e712003-12-22 03:58:44 +000069
Chris Lattner0e5f4992006-12-19 21:40:18 +000070namespace {
Devang Patel5ee99972007-03-07 06:39:01 +000071 class VISIBILITY_HIDDEN IndVarSimplify : public LoopPass {
Dan Gohman81db61a2009-05-12 02:17:14 +000072 IVUsers *IU;
Chris Lattner40bf8b42004-04-02 20:24:31 +000073 LoopInfo *LI;
74 ScalarEvolution *SE;
Dan Gohmande53dc02009-06-27 05:16:57 +000075 DominatorTree *DT;
Chris Lattner15cad752003-12-23 07:47:09 +000076 bool Changed;
Chris Lattner3324e712003-12-22 03:58:44 +000077 public:
Devang Patel794fd752007-05-01 21:15:47 +000078
Dan Gohman5668cf72009-07-15 01:26:32 +000079 static char ID; // Pass identification, replacement for typeid
80 IndVarSimplify() : LoopPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000081
Dan Gohman5668cf72009-07-15 01:26:32 +000082 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
Dan Gohman60f8a632009-02-17 20:49:49 +000083
Dan Gohman5668cf72009-07-15 01:26:32 +000084 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
85 AU.addRequired<DominatorTree>();
86 AU.addRequired<LoopInfo>();
87 AU.addRequired<ScalarEvolution>();
88 AU.addRequiredID(LoopSimplifyID);
89 AU.addRequiredID(LCSSAID);
90 AU.addRequired<IVUsers>();
91 AU.addPreserved<ScalarEvolution>();
92 AU.addPreservedID(LoopSimplifyID);
93 AU.addPreservedID(LCSSAID);
94 AU.addPreserved<IVUsers>();
95 AU.setPreservesCFG();
96 }
Chris Lattner15cad752003-12-23 07:47:09 +000097
Chris Lattner40bf8b42004-04-02 20:24:31 +000098 private:
Devang Patel5ee99972007-03-07 06:39:01 +000099
Dan Gohman60f8a632009-02-17 20:49:49 +0000100 void RewriteNonIntegerIVs(Loop *L);
101
Dan Gohman0bba49c2009-07-07 17:06:11 +0000102 ICmpInst *LinearFunctionTestReplace(Loop *L, const SCEV *BackedgeTakenCount,
Dan Gohmana5758712009-02-17 15:57:39 +0000103 Value *IndVar,
Dan Gohmanc2390b12009-02-12 22:19:27 +0000104 BasicBlock *ExitingBlock,
105 BranchInst *BI,
Dan Gohman15cab282009-02-23 23:20:35 +0000106 SCEVExpander &Rewriter);
Dan Gohman667d7872009-06-26 22:53:46 +0000107 void RewriteLoopExitValues(Loop *L, const SCEV *BackedgeTakenCount,
108 SCEVExpander &Rewriter);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000109
Dan Gohman81db61a2009-05-12 02:17:14 +0000110 void RewriteIVExpressions(Loop *L, const Type *LargestType,
Dan Gohman667d7872009-06-26 22:53:46 +0000111 SCEVExpander &Rewriter);
Devang Pateld22a8492008-09-09 21:41:07 +0000112
Dan Gohman667d7872009-06-26 22:53:46 +0000113 void SinkUnusedInvariants(Loop *L);
Dan Gohman81db61a2009-05-12 02:17:14 +0000114
115 void HandleFloatingPointIV(Loop *L, PHINode *PH);
Chris Lattner3324e712003-12-22 03:58:44 +0000116 };
Chris Lattner5e761402002-09-10 05:24:05 +0000117}
Chris Lattner394437f2001-12-04 04:32:29 +0000118
Dan Gohman844731a2008-05-13 00:00:25 +0000119char IndVarSimplify::ID = 0;
120static RegisterPass<IndVarSimplify>
121X("indvars", "Canonicalize Induction Variables");
122
Daniel Dunbar394f0442008-10-22 23:32:42 +0000123Pass *llvm::createIndVarSimplifyPass() {
Chris Lattner3324e712003-12-22 03:58:44 +0000124 return new IndVarSimplify();
Chris Lattner394437f2001-12-04 04:32:29 +0000125}
126
Chris Lattner40bf8b42004-04-02 20:24:31 +0000127/// LinearFunctionTestReplace - This method rewrites the exit condition of the
Chris Lattner59fdaee2004-04-15 15:21:43 +0000128/// loop to be a canonical != comparison against the incremented loop induction
129/// variable. This pass is able to rewrite the exit tests of any loop where the
130/// SCEV analysis can determine a loop-invariant trip count of the loop, which
131/// is actually a much broader range than just linear tests.
Dan Gohman81db61a2009-05-12 02:17:14 +0000132ICmpInst *IndVarSimplify::LinearFunctionTestReplace(Loop *L,
Dan Gohman0bba49c2009-07-07 17:06:11 +0000133 const SCEV *BackedgeTakenCount,
Dan Gohmanc2390b12009-02-12 22:19:27 +0000134 Value *IndVar,
135 BasicBlock *ExitingBlock,
136 BranchInst *BI,
Dan Gohman15cab282009-02-23 23:20:35 +0000137 SCEVExpander &Rewriter) {
Chris Lattnerd2440572004-04-15 20:26:22 +0000138 // If the exiting block is not the same as the backedge block, we must compare
139 // against the preincremented value, otherwise we prefer to compare against
140 // the post-incremented value.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000141 Value *CmpIndVar;
Dan Gohman0bba49c2009-07-07 17:06:11 +0000142 const SCEV *RHS = BackedgeTakenCount;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000143 if (ExitingBlock == L->getLoopLatch()) {
Dan Gohman46bdfb02009-02-24 18:55:53 +0000144 // Add one to the "backedge-taken" count to get the trip count.
145 // If this addition may overflow, we have to be more pessimistic and
146 // cast the induction variable before doing the add.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000147 const SCEV *Zero = SE->getIntegerSCEV(0, BackedgeTakenCount->getType());
148 const SCEV *N =
Dan Gohman46bdfb02009-02-24 18:55:53 +0000149 SE->getAddExpr(BackedgeTakenCount,
150 SE->getIntegerSCEV(1, BackedgeTakenCount->getType()));
Dan Gohmanc2390b12009-02-12 22:19:27 +0000151 if ((isa<SCEVConstant>(N) && !N->isZero()) ||
152 SE->isLoopGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) {
153 // No overflow. Cast the sum.
Dan Gohman46bdfb02009-02-24 18:55:53 +0000154 RHS = SE->getTruncateOrZeroExtend(N, IndVar->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000155 } else {
156 // Potential overflow. Cast before doing the add.
Dan Gohman46bdfb02009-02-24 18:55:53 +0000157 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
158 IndVar->getType());
159 RHS = SE->getAddExpr(RHS,
160 SE->getIntegerSCEV(1, IndVar->getType()));
Dan Gohmanc2390b12009-02-12 22:19:27 +0000161 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000162
Dan Gohman46bdfb02009-02-24 18:55:53 +0000163 // The BackedgeTaken expression contains the number of times that the
164 // backedge branches to the loop header. This is one less than the
165 // number of times the loop executes, so use the incremented indvar.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000166 CmpIndVar = L->getCanonicalInductionVariableIncrement();
Chris Lattnerd2440572004-04-15 20:26:22 +0000167 } else {
168 // We have to use the preincremented value...
Dan Gohman46bdfb02009-02-24 18:55:53 +0000169 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
170 IndVar->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000171 CmpIndVar = IndVar;
Chris Lattnerd2440572004-04-15 20:26:22 +0000172 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000173
Dan Gohman667d7872009-06-26 22:53:46 +0000174 // Expand the code for the iteration count.
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000175 assert(RHS->isLoopInvariant(L) &&
176 "Computed iteration count is not loop invariant!");
Dan Gohman667d7872009-06-26 22:53:46 +0000177 Value *ExitCnt = Rewriter.expandCodeFor(RHS, IndVar->getType(), BI);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000178
Reid Spencere4d87aa2006-12-23 06:05:41 +0000179 // Insert a new icmp_ne or icmp_eq instruction before the branch.
180 ICmpInst::Predicate Opcode;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000181 if (L->contains(BI->getSuccessor(0)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000182 Opcode = ICmpInst::ICMP_NE;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000183 else
Reid Spencere4d87aa2006-12-23 06:05:41 +0000184 Opcode = ICmpInst::ICMP_EQ;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000185
Chris Lattnerbdff5482009-08-23 04:37:46 +0000186 DEBUG(errs() << "INDVARS: Rewriting loop exit condition to:\n"
187 << " LHS:" << *CmpIndVar << '\n'
188 << " op:\t"
189 << (Opcode == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
190 << " RHS:\t" << *RHS << "\n");
Dan Gohmanc2390b12009-02-12 22:19:27 +0000191
Owen Anderson333c4002009-07-09 23:48:35 +0000192 ICmpInst *Cond = new ICmpInst(BI, Opcode, CmpIndVar, ExitCnt, "exitcond");
Dan Gohman81db61a2009-05-12 02:17:14 +0000193
194 Instruction *OrigCond = cast<Instruction>(BI->getCondition());
Dan Gohman95bdbfa2009-05-24 19:11:38 +0000195 // It's tempting to use replaceAllUsesWith here to fully replace the old
196 // comparison, but that's not immediately safe, since users of the old
197 // comparison may not be dominated by the new comparison. Instead, just
198 // update the branch to use the new comparison; in the common case this
199 // will make old comparison dead.
200 BI->setCondition(Cond);
Dan Gohman81db61a2009-05-12 02:17:14 +0000201 RecursivelyDeleteTriviallyDeadInstructions(OrigCond);
202
Chris Lattner40bf8b42004-04-02 20:24:31 +0000203 ++NumLFTR;
204 Changed = true;
Dan Gohman81db61a2009-05-12 02:17:14 +0000205 return Cond;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000206}
207
Chris Lattner40bf8b42004-04-02 20:24:31 +0000208/// RewriteLoopExitValues - Check to see if this loop has a computable
209/// loop-invariant execution count. If so, this means that we can compute the
210/// final value of any expressions that are recurrent in the loop, and
211/// substitute the exit values from the loop into any instructions outside of
212/// the loop that use the final values of the current expressions.
Dan Gohman81db61a2009-05-12 02:17:14 +0000213///
214/// This is mostly redundant with the regular IndVarSimplify activities that
215/// happen later, except that it's more powerful in some cases, because it's
216/// able to brute-force evaluate arbitrary instructions as long as they have
217/// constant operands at the beginning of the loop.
Dan Gohman890f92b2009-04-18 17:56:28 +0000218void IndVarSimplify::RewriteLoopExitValues(Loop *L,
Dan Gohman667d7872009-06-26 22:53:46 +0000219 const SCEV *BackedgeTakenCount,
220 SCEVExpander &Rewriter) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000221 // Verify the input to the pass in already in LCSSA form.
222 assert(L->isLCSSAForm());
223
Devang Patelb7211a22007-08-21 00:31:24 +0000224 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattner9f3d7382007-03-04 03:43:23 +0000225 L->getUniqueExitBlocks(ExitBlocks);
Misha Brukmanfd939082005-04-21 23:48:37 +0000226
Chris Lattner9f3d7382007-03-04 03:43:23 +0000227 // Find all values that are computed inside the loop, but used outside of it.
228 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
229 // the exit blocks of the loop to find them.
230 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
231 BasicBlock *ExitBB = ExitBlocks[i];
Dan Gohmancafb8132009-02-17 19:13:57 +0000232
Chris Lattner9f3d7382007-03-04 03:43:23 +0000233 // If there are no PHI nodes in this exit block, then no values defined
234 // inside the loop are used on this path, skip it.
235 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
236 if (!PN) continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000237
Chris Lattner9f3d7382007-03-04 03:43:23 +0000238 unsigned NumPreds = PN->getNumIncomingValues();
Dan Gohmancafb8132009-02-17 19:13:57 +0000239
Chris Lattner9f3d7382007-03-04 03:43:23 +0000240 // Iterate over all of the PHI nodes.
241 BasicBlock::iterator BBI = ExitBB->begin();
242 while ((PN = dyn_cast<PHINode>(BBI++))) {
Torok Edwin3790fb02009-05-24 19:36:09 +0000243 if (PN->use_empty())
244 continue; // dead use, don't replace it
Chris Lattner9f3d7382007-03-04 03:43:23 +0000245 // Iterate over all of the values in all the PHI nodes.
246 for (unsigned i = 0; i != NumPreds; ++i) {
247 // If the value being merged in is not integer or is not defined
248 // in the loop, skip it.
249 Value *InVal = PN->getIncomingValue(i);
250 if (!isa<Instruction>(InVal) ||
251 // SCEV only supports integer expressions for now.
Dan Gohman2d1be872009-04-16 03:18:22 +0000252 (!isa<IntegerType>(InVal->getType()) &&
253 !isa<PointerType>(InVal->getType())))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000254 continue;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000255
Chris Lattner9f3d7382007-03-04 03:43:23 +0000256 // If this pred is for a subloop, not L itself, skip it.
Dan Gohmancafb8132009-02-17 19:13:57 +0000257 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
Chris Lattner9f3d7382007-03-04 03:43:23 +0000258 continue; // The Block is in a subloop, skip it.
259
260 // Check that InVal is defined in the loop.
261 Instruction *Inst = cast<Instruction>(InVal);
262 if (!L->contains(Inst->getParent()))
263 continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000264
Chris Lattner9f3d7382007-03-04 03:43:23 +0000265 // Okay, this instruction has a user outside of the current loop
266 // and varies predictably *inside* the loop. Evaluate the value it
267 // contains when the loop exits, if possible.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000268 const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
Dan Gohmand594e6f2009-05-24 23:25:42 +0000269 if (!ExitValue->isLoopInvariant(L))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000270 continue;
Chris Lattner9caed542007-03-04 01:00:28 +0000271
Chris Lattner9f3d7382007-03-04 03:43:23 +0000272 Changed = true;
273 ++NumReplaced;
Dan Gohmancafb8132009-02-17 19:13:57 +0000274
Dan Gohman667d7872009-06-26 22:53:46 +0000275 Value *ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), Inst);
Dan Gohmancafb8132009-02-17 19:13:57 +0000276
Chris Lattnerbdff5482009-08-23 04:37:46 +0000277 DEBUG(errs() << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal << '\n'
278 << " LoopVal = " << *Inst << "\n");
Chris Lattner9f3d7382007-03-04 03:43:23 +0000279
280 PN->setIncomingValue(i, ExitVal);
Dan Gohmancafb8132009-02-17 19:13:57 +0000281
Dan Gohman81db61a2009-05-12 02:17:14 +0000282 // If this instruction is dead now, delete it.
283 RecursivelyDeleteTriviallyDeadInstructions(Inst);
Dan Gohmancafb8132009-02-17 19:13:57 +0000284
Dan Gohman65d1e2b2009-07-14 01:09:02 +0000285 if (NumPreds == 1) {
286 // Completely replace a single-pred PHI. This is safe, because the
287 // NewVal won't be variant in the loop, so we don't need an LCSSA phi
288 // node anymore.
Chris Lattner9f3d7382007-03-04 03:43:23 +0000289 PN->replaceAllUsesWith(ExitVal);
Dan Gohman81db61a2009-05-12 02:17:14 +0000290 RecursivelyDeleteTriviallyDeadInstructions(PN);
Chris Lattnerc9838f22007-03-03 22:48:48 +0000291 }
292 }
Dan Gohman65d1e2b2009-07-14 01:09:02 +0000293 if (NumPreds != 1) {
Dan Gohman667d7872009-06-26 22:53:46 +0000294 // Clone the PHI and delete the original one. This lets IVUsers and
295 // any other maps purge the original user from their records.
Owen Andersone922c022009-07-22 00:24:57 +0000296 PHINode *NewPN = PN->clone(PN->getContext());
Dan Gohman667d7872009-06-26 22:53:46 +0000297 NewPN->takeName(PN);
298 NewPN->insertBefore(PN);
299 PN->replaceAllUsesWith(NewPN);
300 PN->eraseFromParent();
301 }
Chris Lattnerc9838f22007-03-03 22:48:48 +0000302 }
303 }
Chris Lattner40bf8b42004-04-02 20:24:31 +0000304}
305
Dan Gohman60f8a632009-02-17 20:49:49 +0000306void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000307 // First step. Check to see if there are any floating-point recurrences.
Chris Lattner40bf8b42004-04-02 20:24:31 +0000308 // If there are, change them into integer recurrences, permitting analysis by
309 // the SCEV routines.
310 //
311 BasicBlock *Header = L->getHeader();
Misha Brukmanfd939082005-04-21 23:48:37 +0000312
Dan Gohman81db61a2009-05-12 02:17:14 +0000313 SmallVector<WeakVH, 8> PHIs;
314 for (BasicBlock::iterator I = Header->begin();
315 PHINode *PN = dyn_cast<PHINode>(I); ++I)
316 PHIs.push_back(PN);
317
318 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
319 if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i]))
320 HandleFloatingPointIV(L, PN);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000321
Dan Gohman2d1be872009-04-16 03:18:22 +0000322 // If the loop previously had floating-point IV, ScalarEvolution
Dan Gohman60f8a632009-02-17 20:49:49 +0000323 // may not have been able to compute a trip count. Now that we've done some
324 // re-writing, the trip count may be computable.
325 if (Changed)
Dan Gohman46bdfb02009-02-24 18:55:53 +0000326 SE->forgetLoopBackedgeTakenCount(L);
Dale Johannesenc671d892009-04-15 23:31:51 +0000327}
328
Dan Gohmanc2390b12009-02-12 22:19:27 +0000329bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000330 IU = &getAnalysis<IVUsers>();
Devang Patel5ee99972007-03-07 06:39:01 +0000331 LI = &getAnalysis<LoopInfo>();
332 SE = &getAnalysis<ScalarEvolution>();
Dan Gohmande53dc02009-06-27 05:16:57 +0000333 DT = &getAnalysis<DominatorTree>();
Devang Patel5ee99972007-03-07 06:39:01 +0000334 Changed = false;
Dan Gohman60f8a632009-02-17 20:49:49 +0000335
Dan Gohman2d1be872009-04-16 03:18:22 +0000336 // If there are any floating-point recurrences, attempt to
Dan Gohman60f8a632009-02-17 20:49:49 +0000337 // transform them to use integer recurrences.
338 RewriteNonIntegerIVs(L);
339
Dan Gohman81db61a2009-05-12 02:17:14 +0000340 BasicBlock *ExitingBlock = L->getExitingBlock(); // may be null
Dan Gohman0bba49c2009-07-07 17:06:11 +0000341 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
Chris Lattner9caed542007-03-04 01:00:28 +0000342
Dan Gohman667d7872009-06-26 22:53:46 +0000343 // Create a rewriter object which we'll use to transform the code with.
344 SCEVExpander Rewriter(*SE);
345
Chris Lattner40bf8b42004-04-02 20:24:31 +0000346 // Check to see if this loop has a computable loop-invariant execution count.
347 // If so, this means that we can compute the final value of any expressions
348 // that are recurrent in the loop, and substitute the exit values from the
349 // loop into any instructions outside of the loop that use the final values of
350 // the current expressions.
Chris Lattner3dec1f22002-05-10 15:38:35 +0000351 //
Dan Gohman46bdfb02009-02-24 18:55:53 +0000352 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount))
Dan Gohman667d7872009-06-26 22:53:46 +0000353 RewriteLoopExitValues(L, BackedgeTakenCount, Rewriter);
Chris Lattner6148c022001-12-03 17:28:42 +0000354
Dan Gohman81db61a2009-05-12 02:17:14 +0000355 // Compute the type of the largest recurrence expression, and decide whether
356 // a canonical induction variable should be inserted.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000357 const Type *LargestType = 0;
Dan Gohman81db61a2009-05-12 02:17:14 +0000358 bool NeedCannIV = false;
Dan Gohman46bdfb02009-02-24 18:55:53 +0000359 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
360 LargestType = BackedgeTakenCount->getType();
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000361 LargestType = SE->getEffectiveSCEVType(LargestType);
Dan Gohman81db61a2009-05-12 02:17:14 +0000362 // If we have a known trip count and a single exit block, we'll be
363 // rewriting the loop exit test condition below, which requires a
364 // canonical induction variable.
365 if (ExitingBlock)
366 NeedCannIV = true;
Chris Lattnerf50af082004-04-17 18:08:33 +0000367 }
Dan Gohman81db61a2009-05-12 02:17:14 +0000368 for (unsigned i = 0, e = IU->StrideOrder.size(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000369 const SCEV *Stride = IU->StrideOrder[i];
Dan Gohman81db61a2009-05-12 02:17:14 +0000370 const Type *Ty = SE->getEffectiveSCEVType(Stride->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000371 if (!LargestType ||
Dan Gohman81db61a2009-05-12 02:17:14 +0000372 SE->getTypeSizeInBits(Ty) >
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000373 SE->getTypeSizeInBits(LargestType))
Dan Gohman81db61a2009-05-12 02:17:14 +0000374 LargestType = Ty;
375
Dan Gohman0bba49c2009-07-07 17:06:11 +0000376 std::map<const SCEV *, IVUsersOfOneStride *>::iterator SI =
Dan Gohman81db61a2009-05-12 02:17:14 +0000377 IU->IVUsesByStride.find(IU->StrideOrder[i]);
378 assert(SI != IU->IVUsesByStride.end() && "Stride doesn't exist!");
379
380 if (!SI->second->Users.empty())
381 NeedCannIV = true;
Chris Lattner6148c022001-12-03 17:28:42 +0000382 }
383
Dan Gohman81db61a2009-05-12 02:17:14 +0000384 // Now that we know the largest of of the induction variable expressions
385 // in this loop, insert a canonical induction variable of the largest size.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000386 Value *IndVar = 0;
Dan Gohman81db61a2009-05-12 02:17:14 +0000387 if (NeedCannIV) {
Dan Gohman4d8414f2009-06-13 16:25:49 +0000388 // Check to see if the loop already has a canonical-looking induction
389 // variable. If one is present and it's wider than the planned canonical
390 // induction variable, temporarily remove it, so that the Rewriter
391 // doesn't attempt to reuse it.
392 PHINode *OldCannIV = L->getCanonicalInductionVariable();
393 if (OldCannIV) {
394 if (SE->getTypeSizeInBits(OldCannIV->getType()) >
395 SE->getTypeSizeInBits(LargestType))
396 OldCannIV->removeFromParent();
397 else
398 OldCannIV = 0;
399 }
400
Dan Gohman667d7872009-06-26 22:53:46 +0000401 IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L, LargestType);
Dan Gohman4d8414f2009-06-13 16:25:49 +0000402
Dan Gohmanc2390b12009-02-12 22:19:27 +0000403 ++NumInserted;
404 Changed = true;
Chris Lattnerbdff5482009-08-23 04:37:46 +0000405 DEBUG(errs() << "INDVARS: New CanIV: " << *IndVar << '\n');
Dan Gohman4d8414f2009-06-13 16:25:49 +0000406
407 // Now that the official induction variable is established, reinsert
408 // the old canonical-looking variable after it so that the IR remains
409 // consistent. It will be deleted as part of the dead-PHI deletion at
410 // the end of the pass.
411 if (OldCannIV)
412 OldCannIV->insertAfter(cast<Instruction>(IndVar));
Dan Gohmand19534a2007-06-15 14:38:12 +0000413 }
Chris Lattner15cad752003-12-23 07:47:09 +0000414
Dan Gohmanc2390b12009-02-12 22:19:27 +0000415 // If we have a trip count expression, rewrite the loop's exit condition
416 // using it. We can currently only handle loops with a single exit.
Dan Gohman81db61a2009-05-12 02:17:14 +0000417 ICmpInst *NewICmp = 0;
418 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) && ExitingBlock) {
419 assert(NeedCannIV &&
420 "LinearFunctionTestReplace requires a canonical induction variable");
Dan Gohmanc2390b12009-02-12 22:19:27 +0000421 // Can't rewrite non-branch yet.
Dan Gohman81db61a2009-05-12 02:17:14 +0000422 if (BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator()))
423 NewICmp = LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar,
424 ExitingBlock, BI, Rewriter);
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000425 }
426
Torok Edwin3d431382009-05-24 20:08:21 +0000427 // Rewrite IV-derived expressions. Clears the rewriter cache.
Dan Gohman667d7872009-06-26 22:53:46 +0000428 RewriteIVExpressions(L, LargestType, Rewriter);
Dan Gohmanc2390b12009-02-12 22:19:27 +0000429
Dan Gohman667d7872009-06-26 22:53:46 +0000430 // The Rewriter may not be used from this point on.
Torok Edwin3d431382009-05-24 20:08:21 +0000431
Dan Gohman81db61a2009-05-12 02:17:14 +0000432 // Loop-invariant instructions in the preheader that aren't used in the
433 // loop may be sunk below the loop to reduce register pressure.
Dan Gohman667d7872009-06-26 22:53:46 +0000434 SinkUnusedInvariants(L);
Dan Gohman81db61a2009-05-12 02:17:14 +0000435
436 // For completeness, inform IVUsers of the IV use in the newly-created
437 // loop exit test instruction.
438 if (NewICmp)
439 IU->AddUsersIfInteresting(cast<Instruction>(NewICmp->getOperand(0)));
440
441 // Clean up dead instructions.
442 DeleteDeadPHIs(L->getHeader());
443 // Check a post-condition.
444 assert(L->isLCSSAForm() && "Indvars did not leave the loop in lcssa form!");
Devang Patel5ee99972007-03-07 06:39:01 +0000445 return Changed;
Chris Lattner6148c022001-12-03 17:28:42 +0000446}
Devang Pateld22a8492008-09-09 21:41:07 +0000447
Dan Gohman81db61a2009-05-12 02:17:14 +0000448void IndVarSimplify::RewriteIVExpressions(Loop *L, const Type *LargestType,
Dan Gohman667d7872009-06-26 22:53:46 +0000449 SCEVExpander &Rewriter) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000450 SmallVector<WeakVH, 16> DeadInsts;
451
452 // Rewrite all induction variable expressions in terms of the canonical
453 // induction variable.
454 //
455 // If there were induction variables of other sizes or offsets, manually
456 // add the offsets to the primary induction variable and cast, avoiding
457 // the need for the code evaluation methods to insert induction variables
458 // of different sizes.
459 for (unsigned i = 0, e = IU->StrideOrder.size(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000460 const SCEV *Stride = IU->StrideOrder[i];
Dan Gohman81db61a2009-05-12 02:17:14 +0000461
Dan Gohman0bba49c2009-07-07 17:06:11 +0000462 std::map<const SCEV *, IVUsersOfOneStride *>::iterator SI =
Dan Gohman81db61a2009-05-12 02:17:14 +0000463 IU->IVUsesByStride.find(IU->StrideOrder[i]);
464 assert(SI != IU->IVUsesByStride.end() && "Stride doesn't exist!");
465 ilist<IVStrideUse> &List = SI->second->Users;
466 for (ilist<IVStrideUse>::iterator UI = List.begin(),
467 E = List.end(); UI != E; ++UI) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000468 Value *Op = UI->getOperandValToReplace();
Dan Gohman4d8414f2009-06-13 16:25:49 +0000469 const Type *UseTy = Op->getType();
Dan Gohman81db61a2009-05-12 02:17:14 +0000470 Instruction *User = UI->getUser();
Dan Gohman81db61a2009-05-12 02:17:14 +0000471
472 // Compute the final addrec to expand into code.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000473 const SCEV *AR = IU->getReplacementExpr(*UI);
Dan Gohman81db61a2009-05-12 02:17:14 +0000474
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000475 // FIXME: It is an extremely bad idea to indvar substitute anything more
476 // complex than affine induction variables. Doing so will put expensive
477 // polynomial evaluations inside of the loop, and the str reduction pass
478 // currently can only reduce affine polynomials. For now just disable
479 // indvar subst on anything more complex than an affine addrec, unless
480 // it can be expanded to a trivial value.
481 if (!AR->isLoopInvariant(L) && !Stride->isLoopInvariant(L))
482 continue;
Dan Gohman68c93442009-06-03 19:11:31 +0000483
Dan Gohmande53dc02009-06-27 05:16:57 +0000484 // Determine the insertion point for this user. By default, insert
485 // immediately before the user. The SCEVExpander class will automatically
486 // hoist loop invariants out of the loop. For PHI nodes, there may be
487 // multiple uses, so compute the nearest common dominator for the
488 // incoming blocks.
Dan Gohman667d7872009-06-26 22:53:46 +0000489 Instruction *InsertPt = User;
490 if (PHINode *PHI = dyn_cast<PHINode>(InsertPt))
Dan Gohmande53dc02009-06-27 05:16:57 +0000491 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
Dan Gohman667d7872009-06-26 22:53:46 +0000492 if (PHI->getIncomingValue(i) == Op) {
Dan Gohmande53dc02009-06-27 05:16:57 +0000493 if (InsertPt == User)
494 InsertPt = PHI->getIncomingBlock(i)->getTerminator();
495 else
496 InsertPt =
497 DT->findNearestCommonDominator(InsertPt->getParent(),
498 PHI->getIncomingBlock(i))
499 ->getTerminator();
Dan Gohman667d7872009-06-26 22:53:46 +0000500 }
501
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000502 // Now expand it into actual Instructions and patch it into place.
503 Value *NewVal = Rewriter.expandCodeFor(AR, UseTy, InsertPt);
Dan Gohman81db61a2009-05-12 02:17:14 +0000504
505 // Patch the new value into place.
506 if (Op->hasName())
507 NewVal->takeName(Op);
508 User->replaceUsesOfWith(Op, NewVal);
509 UI->setOperandValToReplace(NewVal);
Chris Lattnerbdff5482009-08-23 04:37:46 +0000510 DEBUG(errs() << "INDVARS: Rewrote IV '" << *AR << "' " << *Op << '\n'
511 << " into = " << *NewVal << "\n");
Dan Gohman81db61a2009-05-12 02:17:14 +0000512 ++NumRemoved;
513 Changed = true;
514
515 // The old value may be dead now.
516 DeadInsts.push_back(Op);
517 }
518 }
519
Torok Edwin3d431382009-05-24 20:08:21 +0000520 // Clear the rewriter cache, because values that are in the rewriter's cache
521 // can be deleted in the loop below, causing the AssertingVH in the cache to
522 // trigger.
523 Rewriter.clear();
Dan Gohman81db61a2009-05-12 02:17:14 +0000524 // Now that we're done iterating through lists, clean up any instructions
525 // which are now dead.
526 while (!DeadInsts.empty()) {
527 Instruction *Inst = dyn_cast_or_null<Instruction>(DeadInsts.pop_back_val());
528 if (Inst)
529 RecursivelyDeleteTriviallyDeadInstructions(Inst);
530 }
531}
532
533/// If there's a single exit block, sink any loop-invariant values that
534/// were defined in the preheader but not used inside the loop into the
535/// exit block to reduce register pressure in the loop.
Dan Gohman667d7872009-06-26 22:53:46 +0000536void IndVarSimplify::SinkUnusedInvariants(Loop *L) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000537 BasicBlock *ExitBlock = L->getExitBlock();
538 if (!ExitBlock) return;
539
Dan Gohman667d7872009-06-26 22:53:46 +0000540 Instruction *InsertPt = ExitBlock->getFirstNonPHI();
Dan Gohman81db61a2009-05-12 02:17:14 +0000541 BasicBlock *Preheader = L->getLoopPreheader();
542 BasicBlock::iterator I = Preheader->getTerminator();
543 while (I != Preheader->begin()) {
544 --I;
Dan Gohman667d7872009-06-26 22:53:46 +0000545 // New instructions were inserted at the end of the preheader.
546 if (isa<PHINode>(I))
Dan Gohman81db61a2009-05-12 02:17:14 +0000547 break;
Eli Friedman0c77db32009-07-15 22:48:29 +0000548 // Don't move instructions which might have side effects, since the side
549 // effects need to complete before instructions inside the loop. Also
550 // don't move instructions which might read memory, since the loop may
551 // modify memory. Note that it's okay if the instruction might have
552 // undefined behavior: LoopSimplify guarantees that the preheader
553 // dominates the exit block.
554 if (I->mayHaveSideEffects() || I->mayReadFromMemory())
Dan Gohman667d7872009-06-26 22:53:46 +0000555 continue;
Dan Gohman76f497a2009-08-25 17:42:10 +0000556 // Don't sink static AllocaInsts out of the entry block, which would
557 // turn them into dynamic allocas!
558 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
559 if (AI->isStaticAlloca())
560 continue;
Dan Gohman81db61a2009-05-12 02:17:14 +0000561 // Determine if there is a use in or before the loop (direct or
562 // otherwise).
563 bool UsedInLoop = false;
564 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
565 UI != UE; ++UI) {
566 BasicBlock *UseBB = cast<Instruction>(UI)->getParent();
567 if (PHINode *P = dyn_cast<PHINode>(UI)) {
568 unsigned i =
569 PHINode::getIncomingValueNumForOperand(UI.getOperandNo());
570 UseBB = P->getIncomingBlock(i);
571 }
572 if (UseBB == Preheader || L->contains(UseBB)) {
573 UsedInLoop = true;
574 break;
575 }
576 }
577 // If there is, the def must remain in the preheader.
578 if (UsedInLoop)
579 continue;
580 // Otherwise, sink it to the exit block.
581 Instruction *ToMove = I;
582 bool Done = false;
583 if (I != Preheader->begin())
584 --I;
585 else
586 Done = true;
Dan Gohman667d7872009-06-26 22:53:46 +0000587 ToMove->moveBefore(InsertPt);
Dan Gohman81db61a2009-05-12 02:17:14 +0000588 if (Done)
589 break;
Dan Gohman667d7872009-06-26 22:53:46 +0000590 InsertPt = ToMove;
Dan Gohman81db61a2009-05-12 02:17:14 +0000591 }
592}
593
Devang Patel13877bf2008-11-18 00:40:02 +0000594/// Return true if it is OK to use SIToFPInst for an inducation variable
595/// with given inital and exit values.
596static bool useSIToFPInst(ConstantFP &InitV, ConstantFP &ExitV,
597 uint64_t intIV, uint64_t intEV) {
598
Dan Gohmancafb8132009-02-17 19:13:57 +0000599 if (InitV.getValueAPF().isNegative() || ExitV.getValueAPF().isNegative())
Devang Patel13877bf2008-11-18 00:40:02 +0000600 return true;
601
602 // If the iteration range can be handled by SIToFPInst then use it.
603 APInt Max = APInt::getSignedMaxValue(32);
Dale Johannesenbae7d6d2009-05-14 16:47:34 +0000604 if (Max.getZExtValue() > static_cast<uint64_t>(abs64(intEV - intIV)))
Devang Patel13877bf2008-11-18 00:40:02 +0000605 return true;
Dan Gohmancafb8132009-02-17 19:13:57 +0000606
Devang Patel13877bf2008-11-18 00:40:02 +0000607 return false;
608}
609
610/// convertToInt - Convert APF to an integer, if possible.
Devang Patelcd402332008-11-17 23:27:13 +0000611static bool convertToInt(const APFloat &APF, uint64_t *intVal) {
612
613 bool isExact = false;
Evan Cheng794a7db2008-11-26 01:11:57 +0000614 if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
615 return false;
Dan Gohmancafb8132009-02-17 19:13:57 +0000616 if (APF.convertToInteger(intVal, 32, APF.isNegative(),
Devang Patelcd402332008-11-17 23:27:13 +0000617 APFloat::rmTowardZero, &isExact)
618 != APFloat::opOK)
619 return false;
Dan Gohmancafb8132009-02-17 19:13:57 +0000620 if (!isExact)
Devang Patelcd402332008-11-17 23:27:13 +0000621 return false;
622 return true;
623
624}
625
Devang Patel58d43d42008-11-03 18:32:19 +0000626/// HandleFloatingPointIV - If the loop has floating induction variable
627/// then insert corresponding integer induction variable if possible.
Devang Patel84e35152008-11-17 21:32:02 +0000628/// For example,
629/// for(double i = 0; i < 10000; ++i)
630/// bar(i)
631/// is converted into
632/// for(int i = 0; i < 10000; ++i)
633/// bar((double)i);
634///
Dan Gohman81db61a2009-05-12 02:17:14 +0000635void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PH) {
Devang Patel58d43d42008-11-03 18:32:19 +0000636
Devang Patel84e35152008-11-17 21:32:02 +0000637 unsigned IncomingEdge = L->contains(PH->getIncomingBlock(0));
638 unsigned BackEdge = IncomingEdge^1;
Dan Gohmancafb8132009-02-17 19:13:57 +0000639
Devang Patel84e35152008-11-17 21:32:02 +0000640 // Check incoming value.
Devang Patelcd402332008-11-17 23:27:13 +0000641 ConstantFP *InitValue = dyn_cast<ConstantFP>(PH->getIncomingValue(IncomingEdge));
642 if (!InitValue) return;
Owen Anderson1d0be152009-08-13 21:58:54 +0000643 uint64_t newInitValue =
644 Type::getInt32Ty(PH->getContext())->getPrimitiveSizeInBits();
Devang Patelcd402332008-11-17 23:27:13 +0000645 if (!convertToInt(InitValue->getValueAPF(), &newInitValue))
646 return;
647
648 // Check IV increment. Reject this PH if increement operation is not
649 // an add or increment value can not be represented by an integer.
Dan Gohmancafb8132009-02-17 19:13:57 +0000650 BinaryOperator *Incr =
Devang Patel84e35152008-11-17 21:32:02 +0000651 dyn_cast<BinaryOperator>(PH->getIncomingValue(BackEdge));
652 if (!Incr) return;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000653 if (Incr->getOpcode() != Instruction::FAdd) return;
Devang Patel84e35152008-11-17 21:32:02 +0000654 ConstantFP *IncrValue = NULL;
655 unsigned IncrVIndex = 1;
656 if (Incr->getOperand(1) == PH)
657 IncrVIndex = 0;
658 IncrValue = dyn_cast<ConstantFP>(Incr->getOperand(IncrVIndex));
659 if (!IncrValue) return;
Owen Anderson1d0be152009-08-13 21:58:54 +0000660 uint64_t newIncrValue =
661 Type::getInt32Ty(PH->getContext())->getPrimitiveSizeInBits();
Devang Patelcd402332008-11-17 23:27:13 +0000662 if (!convertToInt(IncrValue->getValueAPF(), &newIncrValue))
663 return;
Dan Gohmancafb8132009-02-17 19:13:57 +0000664
Devang Patelcd402332008-11-17 23:27:13 +0000665 // Check Incr uses. One user is PH and the other users is exit condition used
666 // by the conditional terminator.
Devang Patel84e35152008-11-17 21:32:02 +0000667 Value::use_iterator IncrUse = Incr->use_begin();
668 Instruction *U1 = cast<Instruction>(IncrUse++);
669 if (IncrUse == Incr->use_end()) return;
670 Instruction *U2 = cast<Instruction>(IncrUse++);
671 if (IncrUse != Incr->use_end()) return;
Dan Gohmancafb8132009-02-17 19:13:57 +0000672
Devang Patel84e35152008-11-17 21:32:02 +0000673 // Find exit condition.
674 FCmpInst *EC = dyn_cast<FCmpInst>(U1);
675 if (!EC)
676 EC = dyn_cast<FCmpInst>(U2);
677 if (!EC) return;
678
679 if (BranchInst *BI = dyn_cast<BranchInst>(EC->getParent()->getTerminator())) {
680 if (!BI->isConditional()) return;
681 if (BI->getCondition() != EC) return;
Devang Patel58d43d42008-11-03 18:32:19 +0000682 }
Devang Patel58d43d42008-11-03 18:32:19 +0000683
Devang Patelcd402332008-11-17 23:27:13 +0000684 // Find exit value. If exit value can not be represented as an interger then
685 // do not handle this floating point PH.
Devang Patel84e35152008-11-17 21:32:02 +0000686 ConstantFP *EV = NULL;
687 unsigned EVIndex = 1;
688 if (EC->getOperand(1) == Incr)
689 EVIndex = 0;
690 EV = dyn_cast<ConstantFP>(EC->getOperand(EVIndex));
691 if (!EV) return;
Owen Anderson1d0be152009-08-13 21:58:54 +0000692 uint64_t intEV = Type::getInt32Ty(PH->getContext())->getPrimitiveSizeInBits();
Devang Patelcd402332008-11-17 23:27:13 +0000693 if (!convertToInt(EV->getValueAPF(), &intEV))
Devang Patel84e35152008-11-17 21:32:02 +0000694 return;
Dan Gohmancafb8132009-02-17 19:13:57 +0000695
Devang Patel84e35152008-11-17 21:32:02 +0000696 // Find new predicate for integer comparison.
697 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
698 switch (EC->getPredicate()) {
699 case CmpInst::FCMP_OEQ:
700 case CmpInst::FCMP_UEQ:
701 NewPred = CmpInst::ICMP_EQ;
702 break;
703 case CmpInst::FCMP_OGT:
704 case CmpInst::FCMP_UGT:
705 NewPred = CmpInst::ICMP_UGT;
706 break;
707 case CmpInst::FCMP_OGE:
708 case CmpInst::FCMP_UGE:
709 NewPred = CmpInst::ICMP_UGE;
710 break;
711 case CmpInst::FCMP_OLT:
712 case CmpInst::FCMP_ULT:
713 NewPred = CmpInst::ICMP_ULT;
714 break;
715 case CmpInst::FCMP_OLE:
716 case CmpInst::FCMP_ULE:
717 NewPred = CmpInst::ICMP_ULE;
718 break;
719 default:
720 break;
Devang Patel58d43d42008-11-03 18:32:19 +0000721 }
Devang Patel84e35152008-11-17 21:32:02 +0000722 if (NewPred == CmpInst::BAD_ICMP_PREDICATE) return;
Dan Gohmancafb8132009-02-17 19:13:57 +0000723
Devang Patel84e35152008-11-17 21:32:02 +0000724 // Insert new integer induction variable.
Owen Anderson1d0be152009-08-13 21:58:54 +0000725 PHINode *NewPHI = PHINode::Create(Type::getInt32Ty(PH->getContext()),
Devang Patel84e35152008-11-17 21:32:02 +0000726 PH->getName()+".int", PH);
Owen Anderson1d0be152009-08-13 21:58:54 +0000727 NewPHI->addIncoming(ConstantInt::get(Type::getInt32Ty(PH->getContext()),
728 newInitValue),
Devang Patel84e35152008-11-17 21:32:02 +0000729 PH->getIncomingBlock(IncomingEdge));
730
Dan Gohmancafb8132009-02-17 19:13:57 +0000731 Value *NewAdd = BinaryOperator::CreateAdd(NewPHI,
Owen Anderson1d0be152009-08-13 21:58:54 +0000732 ConstantInt::get(Type::getInt32Ty(PH->getContext()),
Devang Patelcd402332008-11-17 23:27:13 +0000733 newIncrValue),
Devang Patel84e35152008-11-17 21:32:02 +0000734 Incr->getName()+".int", Incr);
735 NewPHI->addIncoming(NewAdd, PH->getIncomingBlock(BackEdge));
736
Dale Johannesen617d1082009-04-27 21:03:15 +0000737 // The back edge is edge 1 of newPHI, whatever it may have been in the
738 // original PHI.
Owen Anderson1d0be152009-08-13 21:58:54 +0000739 ConstantInt *NewEV = ConstantInt::get(Type::getInt32Ty(PH->getContext()),
740 intEV);
Dale Johannesen617d1082009-04-27 21:03:15 +0000741 Value *LHS = (EVIndex == 1 ? NewPHI->getIncomingValue(1) : NewEV);
742 Value *RHS = (EVIndex == 1 ? NewEV : NewPHI->getIncomingValue(1));
Owen Anderson333c4002009-07-09 23:48:35 +0000743 ICmpInst *NewEC = new ICmpInst(EC->getParent()->getTerminator(),
Daniel Dunbar460f6562009-07-26 09:48:23 +0000744 NewPred, LHS, RHS, EC->getName());
Dan Gohmancafb8132009-02-17 19:13:57 +0000745
Dan Gohman81db61a2009-05-12 02:17:14 +0000746 // In the following deltions, PH may become dead and may be deleted.
747 // Use a WeakVH to observe whether this happens.
748 WeakVH WeakPH = PH;
749
Devang Patel84e35152008-11-17 21:32:02 +0000750 // Delete old, floating point, exit comparision instruction.
Dan Gohman14fba292009-05-24 18:09:01 +0000751 NewEC->takeName(EC);
Devang Patel84e35152008-11-17 21:32:02 +0000752 EC->replaceAllUsesWith(NewEC);
Dan Gohman81db61a2009-05-12 02:17:14 +0000753 RecursivelyDeleteTriviallyDeadInstructions(EC);
Dan Gohmancafb8132009-02-17 19:13:57 +0000754
Devang Patel84e35152008-11-17 21:32:02 +0000755 // Delete old, floating point, increment instruction.
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000756 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
Dan Gohman81db61a2009-05-12 02:17:14 +0000757 RecursivelyDeleteTriviallyDeadInstructions(Incr);
Dan Gohmancafb8132009-02-17 19:13:57 +0000758
Dan Gohman81db61a2009-05-12 02:17:14 +0000759 // Replace floating induction variable, if it isn't already deleted.
760 // Give SIToFPInst preference over UIToFPInst because it is faster on
761 // platforms that are widely used.
762 if (WeakPH && !PH->use_empty()) {
763 if (useSIToFPInst(*InitValue, *EV, newInitValue, intEV)) {
764 SIToFPInst *Conv = new SIToFPInst(NewPHI, PH->getType(), "indvar.conv",
765 PH->getParent()->getFirstNonPHI());
766 PH->replaceAllUsesWith(Conv);
767 } else {
768 UIToFPInst *Conv = new UIToFPInst(NewPHI, PH->getType(), "indvar.conv",
769 PH->getParent()->getFirstNonPHI());
770 PH->replaceAllUsesWith(Conv);
771 }
772 RecursivelyDeleteTriviallyDeadInstructions(PH);
Devang Patelcd402332008-11-17 23:27:13 +0000773 }
Devang Patel58d43d42008-11-03 18:32:19 +0000774
Dan Gohman81db61a2009-05-12 02:17:14 +0000775 // Add a new IVUsers entry for the newly-created integer PHI.
776 IU->AddUsersIfInteresting(NewPHI);
777}