blob: 429de9353696bb1374498712b0fe00aa427cc5eb [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"
Chris Lattner40bf8b42004-04-02 20:24:31 +000046#include "llvm/Type.h"
Dan Gohman81db61a2009-05-12 02:17:14 +000047#include "llvm/Analysis/Dominators.h"
48#include "llvm/Analysis/IVUsers.h"
Nate Begeman36f891b2005-07-30 00:12:19 +000049#include "llvm/Analysis/ScalarEvolutionExpander.h"
John Criswell47df12d2003-12-18 17:19:19 +000050#include "llvm/Analysis/LoopInfo.h"
Devang Patel5ee99972007-03-07 06:39:01 +000051#include "llvm/Analysis/LoopPass.h"
Chris Lattner455889a2002-02-12 22:39:50 +000052#include "llvm/Support/CFG.h"
Reid Spencer9133fe22007-02-05 23:32:05 +000053#include "llvm/Support/Compiler.h"
Chris Lattneree4f13a2007-01-07 01:14:12 +000054#include "llvm/Support/Debug.h"
John Criswell47df12d2003-12-18 17:19:19 +000055#include "llvm/Transforms/Utils/Local.h"
Dan Gohman81db61a2009-05-12 02:17:14 +000056#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000057#include "llvm/Support/CommandLine.h"
Reid Spencera54b7cb2007-01-12 07:05:14 +000058#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000059#include "llvm/ADT/Statistic.h"
Dan Gohman81db61a2009-05-12 02:17:14 +000060#include "llvm/ADT/STLExtras.h"
John Criswell47df12d2003-12-18 17:19:19 +000061using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000062
Chris Lattner0e5f4992006-12-19 21:40:18 +000063STATISTIC(NumRemoved , "Number of aux indvars removed");
Chris Lattner0e5f4992006-12-19 21:40:18 +000064STATISTIC(NumInserted, "Number of canonical indvars added");
65STATISTIC(NumReplaced, "Number of exit values replaced");
66STATISTIC(NumLFTR , "Number of loop exit tests replaced");
Chris Lattner3324e712003-12-22 03:58:44 +000067
Chris Lattner0e5f4992006-12-19 21:40:18 +000068namespace {
Devang Patel5ee99972007-03-07 06:39:01 +000069 class VISIBILITY_HIDDEN IndVarSimplify : public LoopPass {
Dan Gohman81db61a2009-05-12 02:17:14 +000070 IVUsers *IU;
Chris Lattner40bf8b42004-04-02 20:24:31 +000071 LoopInfo *LI;
72 ScalarEvolution *SE;
Chris Lattner15cad752003-12-23 07:47:09 +000073 bool Changed;
Chris Lattner3324e712003-12-22 03:58:44 +000074 public:
Devang Patel794fd752007-05-01 21:15:47 +000075
Nick Lewyckyecd94c82007-05-06 13:37:16 +000076 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000077 IndVarSimplify() : LoopPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000078
Dan Gohman60f8a632009-02-17 20:49:49 +000079 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
80
Devang Patel5ee99972007-03-07 06:39:01 +000081 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman81db61a2009-05-12 02:17:14 +000082 AU.addRequired<DominatorTree>();
Devang Patelbc533cd2007-09-10 18:08:23 +000083 AU.addRequired<ScalarEvolution>();
Devang Patel5ee99972007-03-07 06:39:01 +000084 AU.addRequiredID(LCSSAID);
85 AU.addRequiredID(LoopSimplifyID);
Devang Patel5ee99972007-03-07 06:39:01 +000086 AU.addRequired<LoopInfo>();
Dan Gohman81db61a2009-05-12 02:17:14 +000087 AU.addRequired<IVUsers>();
Dan Gohman474cecf2009-02-23 16:29:41 +000088 AU.addPreserved<ScalarEvolution>();
Devang Patel5ee99972007-03-07 06:39:01 +000089 AU.addPreservedID(LoopSimplifyID);
Dan Gohman81db61a2009-05-12 02:17:14 +000090 AU.addPreserved<IVUsers>();
Devang Patel5ee99972007-03-07 06:39:01 +000091 AU.addPreservedID(LCSSAID);
92 AU.setPreservesCFG();
93 }
Chris Lattner15cad752003-12-23 07:47:09 +000094
Chris Lattner40bf8b42004-04-02 20:24:31 +000095 private:
Devang Patel5ee99972007-03-07 06:39:01 +000096
Dan Gohman60f8a632009-02-17 20:49:49 +000097 void RewriteNonIntegerIVs(Loop *L);
98
Dan Gohman81db61a2009-05-12 02:17:14 +000099 ICmpInst *LinearFunctionTestReplace(Loop *L, SCEVHandle BackedgeTakenCount,
Dan Gohmana5758712009-02-17 15:57:39 +0000100 Value *IndVar,
Dan Gohmanc2390b12009-02-12 22:19:27 +0000101 BasicBlock *ExitingBlock,
102 BranchInst *BI,
Dan Gohman15cab282009-02-23 23:20:35 +0000103 SCEVExpander &Rewriter);
Dan Gohman890f92b2009-04-18 17:56:28 +0000104 void RewriteLoopExitValues(Loop *L, const SCEV *BackedgeTakenCount);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000105
Dan Gohman81db61a2009-05-12 02:17:14 +0000106 void RewriteIVExpressions(Loop *L, const Type *LargestType,
107 SCEVExpander &Rewriter);
Devang Pateld22a8492008-09-09 21:41:07 +0000108
Dan Gohman81db61a2009-05-12 02:17:14 +0000109 void SinkUnusedInvariants(Loop *L, SCEVExpander &Rewriter);
110
111 void FixUsesBeforeDefs(Loop *L, SCEVExpander &Rewriter);
112
113 void HandleFloatingPointIV(Loop *L, PHINode *PH);
Chris Lattner3324e712003-12-22 03:58:44 +0000114 };
Chris Lattner5e761402002-09-10 05:24:05 +0000115}
Chris Lattner394437f2001-12-04 04:32:29 +0000116
Dan Gohman844731a2008-05-13 00:00:25 +0000117char IndVarSimplify::ID = 0;
118static RegisterPass<IndVarSimplify>
119X("indvars", "Canonicalize Induction Variables");
120
Daniel Dunbar394f0442008-10-22 23:32:42 +0000121Pass *llvm::createIndVarSimplifyPass() {
Chris Lattner3324e712003-12-22 03:58:44 +0000122 return new IndVarSimplify();
Chris Lattner394437f2001-12-04 04:32:29 +0000123}
124
Chris Lattner40bf8b42004-04-02 20:24:31 +0000125/// LinearFunctionTestReplace - This method rewrites the exit condition of the
Chris Lattner59fdaee2004-04-15 15:21:43 +0000126/// loop to be a canonical != comparison against the incremented loop induction
127/// variable. This pass is able to rewrite the exit tests of any loop where the
128/// SCEV analysis can determine a loop-invariant trip count of the loop, which
129/// is actually a much broader range than just linear tests.
Dan Gohman81db61a2009-05-12 02:17:14 +0000130ICmpInst *IndVarSimplify::LinearFunctionTestReplace(Loop *L,
Dan Gohman46bdfb02009-02-24 18:55:53 +0000131 SCEVHandle BackedgeTakenCount,
Dan Gohmanc2390b12009-02-12 22:19:27 +0000132 Value *IndVar,
133 BasicBlock *ExitingBlock,
134 BranchInst *BI,
Dan Gohman15cab282009-02-23 23:20:35 +0000135 SCEVExpander &Rewriter) {
Chris Lattnerd2440572004-04-15 20:26:22 +0000136 // If the exiting block is not the same as the backedge block, we must compare
137 // against the preincremented value, otherwise we prefer to compare against
138 // the post-incremented value.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000139 Value *CmpIndVar;
Dan Gohman46bdfb02009-02-24 18:55:53 +0000140 SCEVHandle RHS = BackedgeTakenCount;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000141 if (ExitingBlock == L->getLoopLatch()) {
Dan Gohman46bdfb02009-02-24 18:55:53 +0000142 // Add one to the "backedge-taken" count to get the trip count.
143 // If this addition may overflow, we have to be more pessimistic and
144 // cast the induction variable before doing the add.
145 SCEVHandle Zero = SE->getIntegerSCEV(0, BackedgeTakenCount->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000146 SCEVHandle N =
Dan Gohman46bdfb02009-02-24 18:55:53 +0000147 SE->getAddExpr(BackedgeTakenCount,
148 SE->getIntegerSCEV(1, BackedgeTakenCount->getType()));
Dan Gohmanc2390b12009-02-12 22:19:27 +0000149 if ((isa<SCEVConstant>(N) && !N->isZero()) ||
150 SE->isLoopGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) {
151 // No overflow. Cast the sum.
Dan Gohman46bdfb02009-02-24 18:55:53 +0000152 RHS = SE->getTruncateOrZeroExtend(N, IndVar->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000153 } else {
154 // Potential overflow. Cast before doing the add.
Dan Gohman46bdfb02009-02-24 18:55:53 +0000155 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
156 IndVar->getType());
157 RHS = SE->getAddExpr(RHS,
158 SE->getIntegerSCEV(1, IndVar->getType()));
Dan Gohmanc2390b12009-02-12 22:19:27 +0000159 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000160
Dan Gohman46bdfb02009-02-24 18:55:53 +0000161 // The BackedgeTaken expression contains the number of times that the
162 // backedge branches to the loop header. This is one less than the
163 // number of times the loop executes, so use the incremented indvar.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000164 CmpIndVar = L->getCanonicalInductionVariableIncrement();
Chris Lattnerd2440572004-04-15 20:26:22 +0000165 } else {
166 // We have to use the preincremented value...
Dan Gohman46bdfb02009-02-24 18:55:53 +0000167 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
168 IndVar->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000169 CmpIndVar = IndVar;
Chris Lattnerd2440572004-04-15 20:26:22 +0000170 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000171
Chris Lattner40bf8b42004-04-02 20:24:31 +0000172 // Expand the code for the iteration count into the preheader of the loop.
173 BasicBlock *Preheader = L->getLoopPreheader();
Dan Gohman4d8414f2009-06-13 16:25:49 +0000174 Value *ExitCnt = Rewriter.expandCodeFor(RHS, IndVar->getType(),
Dan Gohmanc2390b12009-02-12 22:19:27 +0000175 Preheader->getTerminator());
Chris Lattner40bf8b42004-04-02 20:24:31 +0000176
Reid Spencere4d87aa2006-12-23 06:05:41 +0000177 // Insert a new icmp_ne or icmp_eq instruction before the branch.
178 ICmpInst::Predicate Opcode;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000179 if (L->contains(BI->getSuccessor(0)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000180 Opcode = ICmpInst::ICMP_NE;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000181 else
Reid Spencere4d87aa2006-12-23 06:05:41 +0000182 Opcode = ICmpInst::ICMP_EQ;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000183
Dan Gohmanc2390b12009-02-12 22:19:27 +0000184 DOUT << "INDVARS: Rewriting loop exit condition to:\n"
185 << " LHS:" << *CmpIndVar // includes a newline
186 << " op:\t"
Dan Gohmanf108e2e2009-02-14 02:26:50 +0000187 << (Opcode == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
Dan Gohman46bdfb02009-02-24 18:55:53 +0000188 << " RHS:\t" << *RHS << "\n";
Dan Gohmanc2390b12009-02-12 22:19:27 +0000189
Dan Gohman81db61a2009-05-12 02:17:14 +0000190 ICmpInst *Cond = new ICmpInst(Opcode, CmpIndVar, ExitCnt, "exitcond", BI);
191
192 Instruction *OrigCond = cast<Instruction>(BI->getCondition());
Dan Gohman95bdbfa2009-05-24 19:11:38 +0000193 // It's tempting to use replaceAllUsesWith here to fully replace the old
194 // comparison, but that's not immediately safe, since users of the old
195 // comparison may not be dominated by the new comparison. Instead, just
196 // update the branch to use the new comparison; in the common case this
197 // will make old comparison dead.
198 BI->setCondition(Cond);
Dan Gohman81db61a2009-05-12 02:17:14 +0000199 RecursivelyDeleteTriviallyDeadInstructions(OrigCond);
200
Chris Lattner40bf8b42004-04-02 20:24:31 +0000201 ++NumLFTR;
202 Changed = true;
Dan Gohman81db61a2009-05-12 02:17:14 +0000203 return Cond;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000204}
205
Chris Lattner40bf8b42004-04-02 20:24:31 +0000206/// RewriteLoopExitValues - Check to see if this loop has a computable
207/// loop-invariant execution count. If so, this means that we can compute the
208/// final value of any expressions that are recurrent in the loop, and
209/// substitute the exit values from the loop into any instructions outside of
210/// the loop that use the final values of the current expressions.
Dan Gohman81db61a2009-05-12 02:17:14 +0000211///
212/// This is mostly redundant with the regular IndVarSimplify activities that
213/// happen later, except that it's more powerful in some cases, because it's
214/// able to brute-force evaluate arbitrary instructions as long as they have
215/// constant operands at the beginning of the loop.
Dan Gohman890f92b2009-04-18 17:56:28 +0000216void IndVarSimplify::RewriteLoopExitValues(Loop *L,
217 const SCEV *BackedgeTakenCount) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000218 // Verify the input to the pass in already in LCSSA form.
219 assert(L->isLCSSAForm());
220
Chris Lattner40bf8b42004-04-02 20:24:31 +0000221 BasicBlock *Preheader = L->getLoopPreheader();
222
223 // Scan all of the instructions in the loop, looking at those that have
224 // extra-loop users and which are recurrences.
Dan Gohman5be18e82009-05-19 02:15:55 +0000225 SCEVExpander Rewriter(*SE);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000226
227 // We insert the code into the preheader of the loop if the loop contains
228 // multiple exit blocks, or in the exit block if there is exactly one.
229 BasicBlock *BlockToInsertInto;
Devang Patelb7211a22007-08-21 00:31:24 +0000230 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattner9f3d7382007-03-04 03:43:23 +0000231 L->getUniqueExitBlocks(ExitBlocks);
Chris Lattnerf1ab4b42004-04-18 22:14:10 +0000232 if (ExitBlocks.size() == 1)
233 BlockToInsertInto = ExitBlocks[0];
Chris Lattner40bf8b42004-04-02 20:24:31 +0000234 else
235 BlockToInsertInto = Preheader;
Dan Gohman02dea8b2008-05-23 21:05:58 +0000236 BasicBlock::iterator InsertPt = BlockToInsertInto->getFirstNonPHI();
Chris Lattner40bf8b42004-04-02 20:24:31 +0000237
Chris Lattner9f3d7382007-03-04 03:43:23 +0000238 std::map<Instruction*, Value*> ExitValues;
Misha Brukmanfd939082005-04-21 23:48:37 +0000239
Chris Lattner9f3d7382007-03-04 03:43:23 +0000240 // Find all values that are computed inside the loop, but used outside of it.
241 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
242 // the exit blocks of the loop to find them.
243 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
244 BasicBlock *ExitBB = ExitBlocks[i];
Dan Gohmancafb8132009-02-17 19:13:57 +0000245
Chris Lattner9f3d7382007-03-04 03:43:23 +0000246 // If there are no PHI nodes in this exit block, then no values defined
247 // inside the loop are used on this path, skip it.
248 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
249 if (!PN) continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000250
Chris Lattner9f3d7382007-03-04 03:43:23 +0000251 unsigned NumPreds = PN->getNumIncomingValues();
Dan Gohmancafb8132009-02-17 19:13:57 +0000252
Chris Lattner9f3d7382007-03-04 03:43:23 +0000253 // Iterate over all of the PHI nodes.
254 BasicBlock::iterator BBI = ExitBB->begin();
255 while ((PN = dyn_cast<PHINode>(BBI++))) {
Torok Edwin3790fb02009-05-24 19:36:09 +0000256 if (PN->use_empty())
257 continue; // dead use, don't replace it
Chris Lattner9f3d7382007-03-04 03:43:23 +0000258 // Iterate over all of the values in all the PHI nodes.
259 for (unsigned i = 0; i != NumPreds; ++i) {
260 // If the value being merged in is not integer or is not defined
261 // in the loop, skip it.
262 Value *InVal = PN->getIncomingValue(i);
263 if (!isa<Instruction>(InVal) ||
264 // SCEV only supports integer expressions for now.
Dan Gohman2d1be872009-04-16 03:18:22 +0000265 (!isa<IntegerType>(InVal->getType()) &&
266 !isa<PointerType>(InVal->getType())))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000267 continue;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000268
Chris Lattner9f3d7382007-03-04 03:43:23 +0000269 // If this pred is for a subloop, not L itself, skip it.
Dan Gohmancafb8132009-02-17 19:13:57 +0000270 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
Chris Lattner9f3d7382007-03-04 03:43:23 +0000271 continue; // The Block is in a subloop, skip it.
272
273 // Check that InVal is defined in the loop.
274 Instruction *Inst = cast<Instruction>(InVal);
275 if (!L->contains(Inst->getParent()))
276 continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000277
Chris Lattner9f3d7382007-03-04 03:43:23 +0000278 // Okay, this instruction has a user outside of the current loop
279 // and varies predictably *inside* the loop. Evaluate the value it
280 // contains when the loop exits, if possible.
Dan Gohmand594e6f2009-05-24 23:25:42 +0000281 SCEVHandle ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
282 if (!ExitValue->isLoopInvariant(L))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000283 continue;
Chris Lattner9caed542007-03-04 01:00:28 +0000284
Chris Lattner9f3d7382007-03-04 03:43:23 +0000285 Changed = true;
286 ++NumReplaced;
Dan Gohmancafb8132009-02-17 19:13:57 +0000287
Chris Lattner9f3d7382007-03-04 03:43:23 +0000288 // See if we already computed the exit value for the instruction, if so,
289 // just reuse it.
290 Value *&ExitVal = ExitValues[Inst];
291 if (!ExitVal)
Dan Gohman2d1be872009-04-16 03:18:22 +0000292 ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), InsertPt);
Dan Gohmancafb8132009-02-17 19:13:57 +0000293
Chris Lattner9f3d7382007-03-04 03:43:23 +0000294 DOUT << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal
295 << " LoopVal = " << *Inst << "\n";
296
297 PN->setIncomingValue(i, ExitVal);
Dan Gohmancafb8132009-02-17 19:13:57 +0000298
Dan Gohman81db61a2009-05-12 02:17:14 +0000299 // If this instruction is dead now, delete it.
300 RecursivelyDeleteTriviallyDeadInstructions(Inst);
Dan Gohmancafb8132009-02-17 19:13:57 +0000301
Chris Lattner9f3d7382007-03-04 03:43:23 +0000302 // See if this is a single-entry LCSSA PHI node. If so, we can (and
303 // have to) remove
Chris Lattner9caed542007-03-04 01:00:28 +0000304 // the PHI entirely. This is safe, because the NewVal won't be variant
305 // in the loop, so we don't need an LCSSA phi node anymore.
Chris Lattner9f3d7382007-03-04 03:43:23 +0000306 if (NumPreds == 1) {
307 PN->replaceAllUsesWith(ExitVal);
Dan Gohman81db61a2009-05-12 02:17:14 +0000308 RecursivelyDeleteTriviallyDeadInstructions(PN);
Chris Lattner9f3d7382007-03-04 03:43:23 +0000309 break;
Chris Lattnerc9838f22007-03-03 22:48:48 +0000310 }
311 }
Chris Lattnerc9838f22007-03-03 22:48:48 +0000312 }
313 }
Chris Lattner40bf8b42004-04-02 20:24:31 +0000314}
315
Dan Gohman60f8a632009-02-17 20:49:49 +0000316void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000317 // First step. Check to see if there are any floating-point recurrences.
Chris Lattner40bf8b42004-04-02 20:24:31 +0000318 // If there are, change them into integer recurrences, permitting analysis by
319 // the SCEV routines.
320 //
321 BasicBlock *Header = L->getHeader();
Misha Brukmanfd939082005-04-21 23:48:37 +0000322
Dan Gohman81db61a2009-05-12 02:17:14 +0000323 SmallVector<WeakVH, 8> PHIs;
324 for (BasicBlock::iterator I = Header->begin();
325 PHINode *PN = dyn_cast<PHINode>(I); ++I)
326 PHIs.push_back(PN);
327
328 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
329 if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i]))
330 HandleFloatingPointIV(L, PN);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000331
Dan Gohman2d1be872009-04-16 03:18:22 +0000332 // If the loop previously had floating-point IV, ScalarEvolution
Dan Gohman60f8a632009-02-17 20:49:49 +0000333 // may not have been able to compute a trip count. Now that we've done some
334 // re-writing, the trip count may be computable.
335 if (Changed)
Dan Gohman46bdfb02009-02-24 18:55:53 +0000336 SE->forgetLoopBackedgeTakenCount(L);
Dale Johannesenc671d892009-04-15 23:31:51 +0000337}
338
Dan Gohmanc2390b12009-02-12 22:19:27 +0000339bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000340 IU = &getAnalysis<IVUsers>();
Devang Patel5ee99972007-03-07 06:39:01 +0000341 LI = &getAnalysis<LoopInfo>();
342 SE = &getAnalysis<ScalarEvolution>();
Devang Patel5ee99972007-03-07 06:39:01 +0000343 Changed = false;
Dan Gohman60f8a632009-02-17 20:49:49 +0000344
Dan Gohman2d1be872009-04-16 03:18:22 +0000345 // If there are any floating-point recurrences, attempt to
Dan Gohman60f8a632009-02-17 20:49:49 +0000346 // transform them to use integer recurrences.
347 RewriteNonIntegerIVs(L);
348
Dan Gohmanc2390b12009-02-12 22:19:27 +0000349 BasicBlock *Header = L->getHeader();
Dan Gohman81db61a2009-05-12 02:17:14 +0000350 BasicBlock *ExitingBlock = L->getExitingBlock(); // may be null
351 SCEVHandle BackedgeTakenCount = SE->getBackedgeTakenCount(L);
Chris Lattner9caed542007-03-04 01:00:28 +0000352
Chris Lattner40bf8b42004-04-02 20:24:31 +0000353 // Check to see if this loop has a computable loop-invariant execution count.
354 // If so, this means that we can compute the final value of any expressions
355 // that are recurrent in the loop, and substitute the exit values from the
356 // loop into any instructions outside of the loop that use the final values of
357 // the current expressions.
Chris Lattner3dec1f22002-05-10 15:38:35 +0000358 //
Dan Gohman46bdfb02009-02-24 18:55:53 +0000359 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount))
360 RewriteLoopExitValues(L, BackedgeTakenCount);
Chris Lattner6148c022001-12-03 17:28:42 +0000361
Dan Gohman81db61a2009-05-12 02:17:14 +0000362 // Compute the type of the largest recurrence expression, and decide whether
363 // a canonical induction variable should be inserted.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000364 const Type *LargestType = 0;
Dan Gohman81db61a2009-05-12 02:17:14 +0000365 bool NeedCannIV = false;
Dan Gohman46bdfb02009-02-24 18:55:53 +0000366 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
367 LargestType = BackedgeTakenCount->getType();
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000368 LargestType = SE->getEffectiveSCEVType(LargestType);
Dan Gohman81db61a2009-05-12 02:17:14 +0000369 // If we have a known trip count and a single exit block, we'll be
370 // rewriting the loop exit test condition below, which requires a
371 // canonical induction variable.
372 if (ExitingBlock)
373 NeedCannIV = true;
Chris Lattnerf50af082004-04-17 18:08:33 +0000374 }
Dan Gohman81db61a2009-05-12 02:17:14 +0000375 for (unsigned i = 0, e = IU->StrideOrder.size(); i != e; ++i) {
376 SCEVHandle Stride = IU->StrideOrder[i];
377 const Type *Ty = SE->getEffectiveSCEVType(Stride->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000378 if (!LargestType ||
Dan Gohman81db61a2009-05-12 02:17:14 +0000379 SE->getTypeSizeInBits(Ty) >
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000380 SE->getTypeSizeInBits(LargestType))
Dan Gohman81db61a2009-05-12 02:17:14 +0000381 LargestType = Ty;
382
383 std::map<SCEVHandle, IVUsersOfOneStride *>::iterator SI =
384 IU->IVUsesByStride.find(IU->StrideOrder[i]);
385 assert(SI != IU->IVUsesByStride.end() && "Stride doesn't exist!");
386
387 if (!SI->second->Users.empty())
388 NeedCannIV = true;
Chris Lattner6148c022001-12-03 17:28:42 +0000389 }
390
Chris Lattner40bf8b42004-04-02 20:24:31 +0000391 // Create a rewriter object which we'll use to transform the code with.
Dan Gohman5be18e82009-05-19 02:15:55 +0000392 SCEVExpander Rewriter(*SE);
Chris Lattner15cad752003-12-23 07:47:09 +0000393
Dan Gohman81db61a2009-05-12 02:17:14 +0000394 // Now that we know the largest of of the induction variable expressions
395 // in this loop, insert a canonical induction variable of the largest size.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000396 Value *IndVar = 0;
Dan Gohman81db61a2009-05-12 02:17:14 +0000397 if (NeedCannIV) {
Dan Gohman4d8414f2009-06-13 16:25:49 +0000398 // Check to see if the loop already has a canonical-looking induction
399 // variable. If one is present and it's wider than the planned canonical
400 // induction variable, temporarily remove it, so that the Rewriter
401 // doesn't attempt to reuse it.
402 PHINode *OldCannIV = L->getCanonicalInductionVariable();
403 if (OldCannIV) {
404 if (SE->getTypeSizeInBits(OldCannIV->getType()) >
405 SE->getTypeSizeInBits(LargestType))
406 OldCannIV->removeFromParent();
407 else
408 OldCannIV = 0;
409 }
410
Dan Gohmanc2390b12009-02-12 22:19:27 +0000411 IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L,LargestType);
Dan Gohman4d8414f2009-06-13 16:25:49 +0000412
Dan Gohmanc2390b12009-02-12 22:19:27 +0000413 ++NumInserted;
414 Changed = true;
415 DOUT << "INDVARS: New CanIV: " << *IndVar;
Dan Gohman4d8414f2009-06-13 16:25:49 +0000416
417 // Now that the official induction variable is established, reinsert
418 // the old canonical-looking variable after it so that the IR remains
419 // consistent. It will be deleted as part of the dead-PHI deletion at
420 // the end of the pass.
421 if (OldCannIV)
422 OldCannIV->insertAfter(cast<Instruction>(IndVar));
Dan Gohmand19534a2007-06-15 14:38:12 +0000423 }
Chris Lattner15cad752003-12-23 07:47:09 +0000424
Dan Gohmanc2390b12009-02-12 22:19:27 +0000425 // If we have a trip count expression, rewrite the loop's exit condition
426 // using it. We can currently only handle loops with a single exit.
Dan Gohman81db61a2009-05-12 02:17:14 +0000427 ICmpInst *NewICmp = 0;
428 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) && ExitingBlock) {
429 assert(NeedCannIV &&
430 "LinearFunctionTestReplace requires a canonical induction variable");
Dan Gohmanc2390b12009-02-12 22:19:27 +0000431 // Can't rewrite non-branch yet.
Dan Gohman81db61a2009-05-12 02:17:14 +0000432 if (BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator()))
433 NewICmp = LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar,
434 ExitingBlock, BI, Rewriter);
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000435 }
436
Dan Gohman81db61a2009-05-12 02:17:14 +0000437 Rewriter.setInsertionPoint(Header->getFirstNonPHI());
Chris Lattner5d461d22004-04-21 22:22:01 +0000438
Torok Edwin3d431382009-05-24 20:08:21 +0000439 // Rewrite IV-derived expressions. Clears the rewriter cache.
Dan Gohman81db61a2009-05-12 02:17:14 +0000440 RewriteIVExpressions(L, LargestType, Rewriter);
Dan Gohmanc2390b12009-02-12 22:19:27 +0000441
Torok Edwin3d431382009-05-24 20:08:21 +0000442 // The Rewriter may only be used for isInsertedInstruction queries from this
443 // point on.
444
Dan Gohman81db61a2009-05-12 02:17:14 +0000445 // Loop-invariant instructions in the preheader that aren't used in the
446 // loop may be sunk below the loop to reduce register pressure.
447 SinkUnusedInvariants(L, Rewriter);
Chris Lattner394437f2001-12-04 04:32:29 +0000448
Dan Gohman81db61a2009-05-12 02:17:14 +0000449 // Reorder instructions to avoid use-before-def conditions.
450 FixUsesBeforeDefs(L, Rewriter);
451
452 // For completeness, inform IVUsers of the IV use in the newly-created
453 // loop exit test instruction.
454 if (NewICmp)
455 IU->AddUsersIfInteresting(cast<Instruction>(NewICmp->getOperand(0)));
456
457 // Clean up dead instructions.
458 DeleteDeadPHIs(L->getHeader());
459 // Check a post-condition.
460 assert(L->isLCSSAForm() && "Indvars did not leave the loop in lcssa form!");
Devang Patel5ee99972007-03-07 06:39:01 +0000461 return Changed;
Chris Lattner6148c022001-12-03 17:28:42 +0000462}
Devang Pateld22a8492008-09-09 21:41:07 +0000463
Dan Gohman81db61a2009-05-12 02:17:14 +0000464void IndVarSimplify::RewriteIVExpressions(Loop *L, const Type *LargestType,
465 SCEVExpander &Rewriter) {
466 SmallVector<WeakVH, 16> DeadInsts;
467
468 // Rewrite all induction variable expressions in terms of the canonical
469 // induction variable.
470 //
471 // If there were induction variables of other sizes or offsets, manually
472 // add the offsets to the primary induction variable and cast, avoiding
473 // the need for the code evaluation methods to insert induction variables
474 // of different sizes.
475 for (unsigned i = 0, e = IU->StrideOrder.size(); i != e; ++i) {
476 SCEVHandle Stride = IU->StrideOrder[i];
477
478 std::map<SCEVHandle, IVUsersOfOneStride *>::iterator SI =
479 IU->IVUsesByStride.find(IU->StrideOrder[i]);
480 assert(SI != IU->IVUsesByStride.end() && "Stride doesn't exist!");
481 ilist<IVStrideUse> &List = SI->second->Users;
482 for (ilist<IVStrideUse>::iterator UI = List.begin(),
483 E = List.end(); UI != E; ++UI) {
484 SCEVHandle Offset = UI->getOffset();
485 Value *Op = UI->getOperandValToReplace();
Dan Gohman4d8414f2009-06-13 16:25:49 +0000486 const Type *UseTy = Op->getType();
Dan Gohman81db61a2009-05-12 02:17:14 +0000487 Instruction *User = UI->getUser();
Dan Gohman81db61a2009-05-12 02:17:14 +0000488
489 // Compute the final addrec to expand into code.
490 SCEVHandle AR = IU->getReplacementExpr(*UI);
491
Dan Gohman81db61a2009-05-12 02:17:14 +0000492 Value *NewVal = 0;
493 if (AR->isLoopInvariant(L)) {
494 BasicBlock::iterator I = Rewriter.getInsertionPoint();
495 // Expand loop-invariant values in the loop preheader. They will
496 // be sunk to the exit block later, if possible.
Dan Gohman5be18e82009-05-19 02:15:55 +0000497 NewVal =
Dan Gohman4d8414f2009-06-13 16:25:49 +0000498 Rewriter.expandCodeFor(AR, UseTy,
Dan Gohman81db61a2009-05-12 02:17:14 +0000499 L->getLoopPreheader()->getTerminator());
500 Rewriter.setInsertionPoint(I);
501 ++NumReplaced;
502 } else {
Dan Gohman68c93442009-06-03 19:11:31 +0000503 // FIXME: It is an extremely bad idea to indvar substitute anything more
504 // complex than affine induction variables. Doing so will put expensive
505 // polynomial evaluations inside of the loop, and the str reduction pass
506 // currently can only reduce affine polynomials. For now just disable
507 // indvar subst on anything more complex than an affine addrec, unless
508 // it can be expanded to a trivial value.
509 if (!Stride->isLoopInvariant(L))
510 continue;
511
Dan Gohman81db61a2009-05-12 02:17:14 +0000512 // Now expand it into actual Instructions and patch it into place.
513 NewVal = Rewriter.expandCodeFor(AR, UseTy);
514 }
515
516 // Patch the new value into place.
517 if (Op->hasName())
518 NewVal->takeName(Op);
519 User->replaceUsesOfWith(Op, NewVal);
520 UI->setOperandValToReplace(NewVal);
521 DOUT << "INDVARS: Rewrote IV '" << *AR << "' " << *Op
522 << " into = " << *NewVal << "\n";
523 ++NumRemoved;
524 Changed = true;
525
526 // The old value may be dead now.
527 DeadInsts.push_back(Op);
528 }
529 }
530
Torok Edwin3d431382009-05-24 20:08:21 +0000531 // Clear the rewriter cache, because values that are in the rewriter's cache
532 // can be deleted in the loop below, causing the AssertingVH in the cache to
533 // trigger.
534 Rewriter.clear();
Dan Gohman81db61a2009-05-12 02:17:14 +0000535 // Now that we're done iterating through lists, clean up any instructions
536 // which are now dead.
537 while (!DeadInsts.empty()) {
538 Instruction *Inst = dyn_cast_or_null<Instruction>(DeadInsts.pop_back_val());
539 if (Inst)
540 RecursivelyDeleteTriviallyDeadInstructions(Inst);
541 }
542}
543
544/// If there's a single exit block, sink any loop-invariant values that
545/// were defined in the preheader but not used inside the loop into the
546/// exit block to reduce register pressure in the loop.
547void IndVarSimplify::SinkUnusedInvariants(Loop *L, SCEVExpander &Rewriter) {
548 BasicBlock *ExitBlock = L->getExitBlock();
549 if (!ExitBlock) return;
550
551 Instruction *NonPHI = ExitBlock->getFirstNonPHI();
552 BasicBlock *Preheader = L->getLoopPreheader();
553 BasicBlock::iterator I = Preheader->getTerminator();
554 while (I != Preheader->begin()) {
555 --I;
556 // New instructions were inserted at the end of the preheader. Only
557 // consider those new instructions.
558 if (!Rewriter.isInsertedInstruction(I))
559 break;
560 // Determine if there is a use in or before the loop (direct or
561 // otherwise).
562 bool UsedInLoop = false;
563 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
564 UI != UE; ++UI) {
565 BasicBlock *UseBB = cast<Instruction>(UI)->getParent();
566 if (PHINode *P = dyn_cast<PHINode>(UI)) {
567 unsigned i =
568 PHINode::getIncomingValueNumForOperand(UI.getOperandNo());
569 UseBB = P->getIncomingBlock(i);
570 }
571 if (UseBB == Preheader || L->contains(UseBB)) {
572 UsedInLoop = true;
573 break;
574 }
575 }
576 // If there is, the def must remain in the preheader.
577 if (UsedInLoop)
578 continue;
579 // Otherwise, sink it to the exit block.
580 Instruction *ToMove = I;
581 bool Done = false;
582 if (I != Preheader->begin())
583 --I;
584 else
585 Done = true;
586 ToMove->moveBefore(NonPHI);
587 if (Done)
588 break;
589 }
590}
591
592/// Re-schedule the inserted instructions to put defs before uses. This
593/// fixes problems that arrise when SCEV expressions contain loop-variant
594/// values unrelated to the induction variable which are defined inside the
595/// loop. FIXME: It would be better to insert instructions in the right
596/// place so that this step isn't needed.
597void IndVarSimplify::FixUsesBeforeDefs(Loop *L, SCEVExpander &Rewriter) {
598 // Visit all the blocks in the loop in pre-order dom-tree dfs order.
599 DominatorTree *DT = &getAnalysis<DominatorTree>();
600 std::map<Instruction *, unsigned> NumPredsLeft;
601 SmallVector<DomTreeNode *, 16> Worklist;
602 Worklist.push_back(DT->getNode(L->getHeader()));
603 do {
604 DomTreeNode *Node = Worklist.pop_back_val();
605 for (DomTreeNode::iterator I = Node->begin(), E = Node->end(); I != E; ++I)
606 if (L->contains((*I)->getBlock()))
607 Worklist.push_back(*I);
608 BasicBlock *BB = Node->getBlock();
609 // Visit all the instructions in the block top down.
610 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
611 // Count the number of operands that aren't properly dominating.
612 unsigned NumPreds = 0;
613 if (Rewriter.isInsertedInstruction(I) && !isa<PHINode>(I))
614 for (User::op_iterator OI = I->op_begin(), OE = I->op_end();
615 OI != OE; ++OI)
616 if (Instruction *Inst = dyn_cast<Instruction>(OI))
617 if (L->contains(Inst->getParent()) && !NumPredsLeft.count(Inst))
618 ++NumPreds;
619 NumPredsLeft[I] = NumPreds;
620 // Notify uses of the position of this instruction, and move the
621 // users (and their dependents, recursively) into place after this
622 // instruction if it is their last outstanding operand.
623 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
624 UI != UE; ++UI) {
625 Instruction *Inst = cast<Instruction>(UI);
626 std::map<Instruction *, unsigned>::iterator Z = NumPredsLeft.find(Inst);
627 if (Z != NumPredsLeft.end() && Z->second != 0 && --Z->second == 0) {
628 SmallVector<Instruction *, 4> UseWorkList;
629 UseWorkList.push_back(Inst);
Dan Gohmand6d02942009-05-22 16:47:11 +0000630 BasicBlock::iterator InsertPt = I;
631 if (InvokeInst *II = dyn_cast<InvokeInst>(InsertPt))
632 InsertPt = II->getNormalDest()->begin();
633 else
634 ++InsertPt;
Dan Gohman81db61a2009-05-12 02:17:14 +0000635 while (isa<PHINode>(InsertPt)) ++InsertPt;
636 do {
637 Instruction *Use = UseWorkList.pop_back_val();
638 Use->moveBefore(InsertPt);
639 NumPredsLeft.erase(Use);
640 for (Value::use_iterator IUI = Use->use_begin(),
641 IUE = Use->use_end(); IUI != IUE; ++IUI) {
642 Instruction *IUIInst = cast<Instruction>(IUI);
643 if (L->contains(IUIInst->getParent()) &&
644 Rewriter.isInsertedInstruction(IUIInst) &&
645 !isa<PHINode>(IUIInst))
646 UseWorkList.push_back(IUIInst);
647 }
648 } while (!UseWorkList.empty());
649 }
650 }
651 }
652 } while (!Worklist.empty());
653}
654
Devang Patel13877bf2008-11-18 00:40:02 +0000655/// Return true if it is OK to use SIToFPInst for an inducation variable
656/// with given inital and exit values.
657static bool useSIToFPInst(ConstantFP &InitV, ConstantFP &ExitV,
658 uint64_t intIV, uint64_t intEV) {
659
Dan Gohmancafb8132009-02-17 19:13:57 +0000660 if (InitV.getValueAPF().isNegative() || ExitV.getValueAPF().isNegative())
Devang Patel13877bf2008-11-18 00:40:02 +0000661 return true;
662
663 // If the iteration range can be handled by SIToFPInst then use it.
664 APInt Max = APInt::getSignedMaxValue(32);
Dale Johannesenbae7d6d2009-05-14 16:47:34 +0000665 if (Max.getZExtValue() > static_cast<uint64_t>(abs64(intEV - intIV)))
Devang Patel13877bf2008-11-18 00:40:02 +0000666 return true;
Dan Gohmancafb8132009-02-17 19:13:57 +0000667
Devang Patel13877bf2008-11-18 00:40:02 +0000668 return false;
669}
670
671/// convertToInt - Convert APF to an integer, if possible.
Devang Patelcd402332008-11-17 23:27:13 +0000672static bool convertToInt(const APFloat &APF, uint64_t *intVal) {
673
674 bool isExact = false;
Evan Cheng794a7db2008-11-26 01:11:57 +0000675 if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
676 return false;
Dan Gohmancafb8132009-02-17 19:13:57 +0000677 if (APF.convertToInteger(intVal, 32, APF.isNegative(),
Devang Patelcd402332008-11-17 23:27:13 +0000678 APFloat::rmTowardZero, &isExact)
679 != APFloat::opOK)
680 return false;
Dan Gohmancafb8132009-02-17 19:13:57 +0000681 if (!isExact)
Devang Patelcd402332008-11-17 23:27:13 +0000682 return false;
683 return true;
684
685}
686
Devang Patel58d43d42008-11-03 18:32:19 +0000687/// HandleFloatingPointIV - If the loop has floating induction variable
688/// then insert corresponding integer induction variable if possible.
Devang Patel84e35152008-11-17 21:32:02 +0000689/// For example,
690/// for(double i = 0; i < 10000; ++i)
691/// bar(i)
692/// is converted into
693/// for(int i = 0; i < 10000; ++i)
694/// bar((double)i);
695///
Dan Gohman81db61a2009-05-12 02:17:14 +0000696void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PH) {
Devang Patel58d43d42008-11-03 18:32:19 +0000697
Devang Patel84e35152008-11-17 21:32:02 +0000698 unsigned IncomingEdge = L->contains(PH->getIncomingBlock(0));
699 unsigned BackEdge = IncomingEdge^1;
Dan Gohmancafb8132009-02-17 19:13:57 +0000700
Devang Patel84e35152008-11-17 21:32:02 +0000701 // Check incoming value.
Devang Patelcd402332008-11-17 23:27:13 +0000702 ConstantFP *InitValue = dyn_cast<ConstantFP>(PH->getIncomingValue(IncomingEdge));
703 if (!InitValue) return;
704 uint64_t newInitValue = Type::Int32Ty->getPrimitiveSizeInBits();
705 if (!convertToInt(InitValue->getValueAPF(), &newInitValue))
706 return;
707
708 // Check IV increment. Reject this PH if increement operation is not
709 // an add or increment value can not be represented by an integer.
Dan Gohmancafb8132009-02-17 19:13:57 +0000710 BinaryOperator *Incr =
Devang Patel84e35152008-11-17 21:32:02 +0000711 dyn_cast<BinaryOperator>(PH->getIncomingValue(BackEdge));
712 if (!Incr) return;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000713 if (Incr->getOpcode() != Instruction::FAdd) return;
Devang Patel84e35152008-11-17 21:32:02 +0000714 ConstantFP *IncrValue = NULL;
715 unsigned IncrVIndex = 1;
716 if (Incr->getOperand(1) == PH)
717 IncrVIndex = 0;
718 IncrValue = dyn_cast<ConstantFP>(Incr->getOperand(IncrVIndex));
719 if (!IncrValue) return;
Devang Patelcd402332008-11-17 23:27:13 +0000720 uint64_t newIncrValue = Type::Int32Ty->getPrimitiveSizeInBits();
721 if (!convertToInt(IncrValue->getValueAPF(), &newIncrValue))
722 return;
Dan Gohmancafb8132009-02-17 19:13:57 +0000723
Devang Patelcd402332008-11-17 23:27:13 +0000724 // Check Incr uses. One user is PH and the other users is exit condition used
725 // by the conditional terminator.
Devang Patel84e35152008-11-17 21:32:02 +0000726 Value::use_iterator IncrUse = Incr->use_begin();
727 Instruction *U1 = cast<Instruction>(IncrUse++);
728 if (IncrUse == Incr->use_end()) return;
729 Instruction *U2 = cast<Instruction>(IncrUse++);
730 if (IncrUse != Incr->use_end()) return;
Dan Gohmancafb8132009-02-17 19:13:57 +0000731
Devang Patel84e35152008-11-17 21:32:02 +0000732 // Find exit condition.
733 FCmpInst *EC = dyn_cast<FCmpInst>(U1);
734 if (!EC)
735 EC = dyn_cast<FCmpInst>(U2);
736 if (!EC) return;
737
738 if (BranchInst *BI = dyn_cast<BranchInst>(EC->getParent()->getTerminator())) {
739 if (!BI->isConditional()) return;
740 if (BI->getCondition() != EC) return;
Devang Patel58d43d42008-11-03 18:32:19 +0000741 }
Devang Patel58d43d42008-11-03 18:32:19 +0000742
Devang Patelcd402332008-11-17 23:27:13 +0000743 // Find exit value. If exit value can not be represented as an interger then
744 // do not handle this floating point PH.
Devang Patel84e35152008-11-17 21:32:02 +0000745 ConstantFP *EV = NULL;
746 unsigned EVIndex = 1;
747 if (EC->getOperand(1) == Incr)
748 EVIndex = 0;
749 EV = dyn_cast<ConstantFP>(EC->getOperand(EVIndex));
750 if (!EV) return;
Devang Patel84e35152008-11-17 21:32:02 +0000751 uint64_t intEV = Type::Int32Ty->getPrimitiveSizeInBits();
Devang Patelcd402332008-11-17 23:27:13 +0000752 if (!convertToInt(EV->getValueAPF(), &intEV))
Devang Patel84e35152008-11-17 21:32:02 +0000753 return;
Dan Gohmancafb8132009-02-17 19:13:57 +0000754
Devang Patel84e35152008-11-17 21:32:02 +0000755 // Find new predicate for integer comparison.
756 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
757 switch (EC->getPredicate()) {
758 case CmpInst::FCMP_OEQ:
759 case CmpInst::FCMP_UEQ:
760 NewPred = CmpInst::ICMP_EQ;
761 break;
762 case CmpInst::FCMP_OGT:
763 case CmpInst::FCMP_UGT:
764 NewPred = CmpInst::ICMP_UGT;
765 break;
766 case CmpInst::FCMP_OGE:
767 case CmpInst::FCMP_UGE:
768 NewPred = CmpInst::ICMP_UGE;
769 break;
770 case CmpInst::FCMP_OLT:
771 case CmpInst::FCMP_ULT:
772 NewPred = CmpInst::ICMP_ULT;
773 break;
774 case CmpInst::FCMP_OLE:
775 case CmpInst::FCMP_ULE:
776 NewPred = CmpInst::ICMP_ULE;
777 break;
778 default:
779 break;
Devang Patel58d43d42008-11-03 18:32:19 +0000780 }
Devang Patel84e35152008-11-17 21:32:02 +0000781 if (NewPred == CmpInst::BAD_ICMP_PREDICATE) return;
Dan Gohmancafb8132009-02-17 19:13:57 +0000782
Devang Patel84e35152008-11-17 21:32:02 +0000783 // Insert new integer induction variable.
784 PHINode *NewPHI = PHINode::Create(Type::Int32Ty,
785 PH->getName()+".int", PH);
Devang Patelcd402332008-11-17 23:27:13 +0000786 NewPHI->addIncoming(ConstantInt::get(Type::Int32Ty, newInitValue),
Devang Patel84e35152008-11-17 21:32:02 +0000787 PH->getIncomingBlock(IncomingEdge));
788
Dan Gohmancafb8132009-02-17 19:13:57 +0000789 Value *NewAdd = BinaryOperator::CreateAdd(NewPHI,
790 ConstantInt::get(Type::Int32Ty,
Devang Patelcd402332008-11-17 23:27:13 +0000791 newIncrValue),
Devang Patel84e35152008-11-17 21:32:02 +0000792 Incr->getName()+".int", Incr);
793 NewPHI->addIncoming(NewAdd, PH->getIncomingBlock(BackEdge));
794
Dale Johannesen617d1082009-04-27 21:03:15 +0000795 // The back edge is edge 1 of newPHI, whatever it may have been in the
796 // original PHI.
Devang Patel84e35152008-11-17 21:32:02 +0000797 ConstantInt *NewEV = ConstantInt::get(Type::Int32Ty, intEV);
Dale Johannesen617d1082009-04-27 21:03:15 +0000798 Value *LHS = (EVIndex == 1 ? NewPHI->getIncomingValue(1) : NewEV);
799 Value *RHS = (EVIndex == 1 ? NewEV : NewPHI->getIncomingValue(1));
Dan Gohmancafb8132009-02-17 19:13:57 +0000800 ICmpInst *NewEC = new ICmpInst(NewPred, LHS, RHS, EC->getNameStart(),
Devang Patel84e35152008-11-17 21:32:02 +0000801 EC->getParent()->getTerminator());
Dan Gohmancafb8132009-02-17 19:13:57 +0000802
Dan Gohman81db61a2009-05-12 02:17:14 +0000803 // In the following deltions, PH may become dead and may be deleted.
804 // Use a WeakVH to observe whether this happens.
805 WeakVH WeakPH = PH;
806
Devang Patel84e35152008-11-17 21:32:02 +0000807 // Delete old, floating point, exit comparision instruction.
Dan Gohman14fba292009-05-24 18:09:01 +0000808 NewEC->takeName(EC);
Devang Patel84e35152008-11-17 21:32:02 +0000809 EC->replaceAllUsesWith(NewEC);
Dan Gohman81db61a2009-05-12 02:17:14 +0000810 RecursivelyDeleteTriviallyDeadInstructions(EC);
Dan Gohmancafb8132009-02-17 19:13:57 +0000811
Devang Patel84e35152008-11-17 21:32:02 +0000812 // Delete old, floating point, increment instruction.
813 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
Dan Gohman81db61a2009-05-12 02:17:14 +0000814 RecursivelyDeleteTriviallyDeadInstructions(Incr);
Dan Gohmancafb8132009-02-17 19:13:57 +0000815
Dan Gohman81db61a2009-05-12 02:17:14 +0000816 // Replace floating induction variable, if it isn't already deleted.
817 // Give SIToFPInst preference over UIToFPInst because it is faster on
818 // platforms that are widely used.
819 if (WeakPH && !PH->use_empty()) {
820 if (useSIToFPInst(*InitValue, *EV, newInitValue, intEV)) {
821 SIToFPInst *Conv = new SIToFPInst(NewPHI, PH->getType(), "indvar.conv",
822 PH->getParent()->getFirstNonPHI());
823 PH->replaceAllUsesWith(Conv);
824 } else {
825 UIToFPInst *Conv = new UIToFPInst(NewPHI, PH->getType(), "indvar.conv",
826 PH->getParent()->getFirstNonPHI());
827 PH->replaceAllUsesWith(Conv);
828 }
829 RecursivelyDeleteTriviallyDeadInstructions(PH);
Devang Patelcd402332008-11-17 23:27:13 +0000830 }
Devang Patel58d43d42008-11-03 18:32:19 +0000831
Dan Gohman81db61a2009-05-12 02:17:14 +0000832 // Add a new IVUsers entry for the newly-created integer PHI.
833 IU->AddUsersIfInteresting(NewPHI);
834}