blob: ec4be9b905d73c872cfcd4210ca97cceb33f1877 [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
Owen Anderson372b46c2009-06-22 21:39:50 +000099 ICmpInst *LinearFunctionTestReplace(Loop *L, const SCEV* 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,
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000107 SCEVExpander &Rewriter,
108 BasicBlock::iterator InsertPt);
Devang Pateld22a8492008-09-09 21:41:07 +0000109
Dan Gohman81db61a2009-05-12 02:17:14 +0000110 void SinkUnusedInvariants(Loop *L, SCEVExpander &Rewriter);
111
112 void FixUsesBeforeDefs(Loop *L, SCEVExpander &Rewriter);
113
114 void HandleFloatingPointIV(Loop *L, PHINode *PH);
Chris Lattner3324e712003-12-22 03:58:44 +0000115 };
Chris Lattner5e761402002-09-10 05:24:05 +0000116}
Chris Lattner394437f2001-12-04 04:32:29 +0000117
Dan Gohman844731a2008-05-13 00:00:25 +0000118char IndVarSimplify::ID = 0;
119static RegisterPass<IndVarSimplify>
120X("indvars", "Canonicalize Induction Variables");
121
Daniel Dunbar394f0442008-10-22 23:32:42 +0000122Pass *llvm::createIndVarSimplifyPass() {
Chris Lattner3324e712003-12-22 03:58:44 +0000123 return new IndVarSimplify();
Chris Lattner394437f2001-12-04 04:32:29 +0000124}
125
Chris Lattner40bf8b42004-04-02 20:24:31 +0000126/// LinearFunctionTestReplace - This method rewrites the exit condition of the
Chris Lattner59fdaee2004-04-15 15:21:43 +0000127/// loop to be a canonical != comparison against the incremented loop induction
128/// variable. This pass is able to rewrite the exit tests of any loop where the
129/// SCEV analysis can determine a loop-invariant trip count of the loop, which
130/// is actually a much broader range than just linear tests.
Dan Gohman81db61a2009-05-12 02:17:14 +0000131ICmpInst *IndVarSimplify::LinearFunctionTestReplace(Loop *L,
Owen Anderson372b46c2009-06-22 21:39:50 +0000132 const SCEV* BackedgeTakenCount,
Dan Gohmanc2390b12009-02-12 22:19:27 +0000133 Value *IndVar,
134 BasicBlock *ExitingBlock,
135 BranchInst *BI,
Dan Gohman15cab282009-02-23 23:20:35 +0000136 SCEVExpander &Rewriter) {
Chris Lattnerd2440572004-04-15 20:26:22 +0000137 // If the exiting block is not the same as the backedge block, we must compare
138 // against the preincremented value, otherwise we prefer to compare against
139 // the post-incremented value.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000140 Value *CmpIndVar;
Owen Anderson372b46c2009-06-22 21:39:50 +0000141 const SCEV* RHS = BackedgeTakenCount;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000142 if (ExitingBlock == L->getLoopLatch()) {
Dan Gohman46bdfb02009-02-24 18:55:53 +0000143 // Add one to the "backedge-taken" count to get the trip count.
144 // If this addition may overflow, we have to be more pessimistic and
145 // cast the induction variable before doing the add.
Owen Anderson372b46c2009-06-22 21:39:50 +0000146 const SCEV* Zero = SE->getIntegerSCEV(0, BackedgeTakenCount->getType());
147 const SCEV* N =
Dan Gohman46bdfb02009-02-24 18:55:53 +0000148 SE->getAddExpr(BackedgeTakenCount,
149 SE->getIntegerSCEV(1, BackedgeTakenCount->getType()));
Dan Gohmanc2390b12009-02-12 22:19:27 +0000150 if ((isa<SCEVConstant>(N) && !N->isZero()) ||
151 SE->isLoopGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) {
152 // No overflow. Cast the sum.
Dan Gohman46bdfb02009-02-24 18:55:53 +0000153 RHS = SE->getTruncateOrZeroExtend(N, IndVar->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000154 } else {
155 // Potential overflow. Cast before doing the add.
Dan Gohman46bdfb02009-02-24 18:55:53 +0000156 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
157 IndVar->getType());
158 RHS = SE->getAddExpr(RHS,
159 SE->getIntegerSCEV(1, IndVar->getType()));
Dan Gohmanc2390b12009-02-12 22:19:27 +0000160 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000161
Dan Gohman46bdfb02009-02-24 18:55:53 +0000162 // The BackedgeTaken expression contains the number of times that the
163 // backedge branches to the loop header. This is one less than the
164 // number of times the loop executes, so use the incremented indvar.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000165 CmpIndVar = L->getCanonicalInductionVariableIncrement();
Chris Lattnerd2440572004-04-15 20:26:22 +0000166 } else {
167 // We have to use the preincremented value...
Dan Gohman46bdfb02009-02-24 18:55:53 +0000168 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
169 IndVar->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000170 CmpIndVar = IndVar;
Chris Lattnerd2440572004-04-15 20:26:22 +0000171 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000172
Chris Lattner40bf8b42004-04-02 20:24:31 +0000173 // Expand the code for the iteration count into the preheader of the loop.
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000174 assert(RHS->isLoopInvariant(L) &&
175 "Computed iteration count is not loop invariant!");
Chris Lattner40bf8b42004-04-02 20:24:31 +0000176 BasicBlock *Preheader = L->getLoopPreheader();
Dan Gohman4d8414f2009-06-13 16:25:49 +0000177 Value *ExitCnt = Rewriter.expandCodeFor(RHS, IndVar->getType(),
Dan Gohmanc2390b12009-02-12 22:19:27 +0000178 Preheader->getTerminator());
Chris Lattner40bf8b42004-04-02 20:24:31 +0000179
Reid Spencere4d87aa2006-12-23 06:05:41 +0000180 // Insert a new icmp_ne or icmp_eq instruction before the branch.
181 ICmpInst::Predicate Opcode;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000182 if (L->contains(BI->getSuccessor(0)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000183 Opcode = ICmpInst::ICMP_NE;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000184 else
Reid Spencere4d87aa2006-12-23 06:05:41 +0000185 Opcode = ICmpInst::ICMP_EQ;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000186
Dan Gohmanc2390b12009-02-12 22:19:27 +0000187 DOUT << "INDVARS: Rewriting loop exit condition to:\n"
188 << " LHS:" << *CmpIndVar // includes a newline
189 << " op:\t"
Dan Gohmanf108e2e2009-02-14 02:26:50 +0000190 << (Opcode == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
Dan Gohman46bdfb02009-02-24 18:55:53 +0000191 << " RHS:\t" << *RHS << "\n";
Dan Gohmanc2390b12009-02-12 22:19:27 +0000192
Dan Gohman81db61a2009-05-12 02:17:14 +0000193 ICmpInst *Cond = new ICmpInst(Opcode, CmpIndVar, ExitCnt, "exitcond", BI);
194
195 Instruction *OrigCond = cast<Instruction>(BI->getCondition());
Dan Gohman95bdbfa2009-05-24 19:11:38 +0000196 // It's tempting to use replaceAllUsesWith here to fully replace the old
197 // comparison, but that's not immediately safe, since users of the old
198 // comparison may not be dominated by the new comparison. Instead, just
199 // update the branch to use the new comparison; in the common case this
200 // will make old comparison dead.
201 BI->setCondition(Cond);
Dan Gohman81db61a2009-05-12 02:17:14 +0000202 RecursivelyDeleteTriviallyDeadInstructions(OrigCond);
203
Chris Lattner40bf8b42004-04-02 20:24:31 +0000204 ++NumLFTR;
205 Changed = true;
Dan Gohman81db61a2009-05-12 02:17:14 +0000206 return Cond;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000207}
208
Chris Lattner40bf8b42004-04-02 20:24:31 +0000209/// RewriteLoopExitValues - Check to see if this loop has a computable
210/// loop-invariant execution count. If so, this means that we can compute the
211/// final value of any expressions that are recurrent in the loop, and
212/// substitute the exit values from the loop into any instructions outside of
213/// the loop that use the final values of the current expressions.
Dan Gohman81db61a2009-05-12 02:17:14 +0000214///
215/// This is mostly redundant with the regular IndVarSimplify activities that
216/// happen later, except that it's more powerful in some cases, because it's
217/// able to brute-force evaluate arbitrary instructions as long as they have
218/// constant operands at the beginning of the loop.
Dan Gohman890f92b2009-04-18 17:56:28 +0000219void IndVarSimplify::RewriteLoopExitValues(Loop *L,
220 const SCEV *BackedgeTakenCount) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000221 // Verify the input to the pass in already in LCSSA form.
222 assert(L->isLCSSAForm());
223
Chris Lattner40bf8b42004-04-02 20:24:31 +0000224 BasicBlock *Preheader = L->getLoopPreheader();
225
226 // Scan all of the instructions in the loop, looking at those that have
227 // extra-loop users and which are recurrences.
Dan Gohman5be18e82009-05-19 02:15:55 +0000228 SCEVExpander Rewriter(*SE);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000229
230 // We insert the code into the preheader of the loop if the loop contains
231 // multiple exit blocks, or in the exit block if there is exactly one.
232 BasicBlock *BlockToInsertInto;
Dan Gohman32a81a32009-06-24 14:31:06 +0000233 BasicBlock::iterator InsertPt;
Devang Patelb7211a22007-08-21 00:31:24 +0000234 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattner9f3d7382007-03-04 03:43:23 +0000235 L->getUniqueExitBlocks(ExitBlocks);
Dan Gohman32a81a32009-06-24 14:31:06 +0000236 if (ExitBlocks.size() == 1) {
Chris Lattnerf1ab4b42004-04-18 22:14:10 +0000237 BlockToInsertInto = ExitBlocks[0];
Dan Gohman32a81a32009-06-24 14:31:06 +0000238 InsertPt = BlockToInsertInto->getFirstNonPHI();
239 } else {
Chris Lattner40bf8b42004-04-02 20:24:31 +0000240 BlockToInsertInto = Preheader;
Dan Gohman32a81a32009-06-24 14:31:06 +0000241 InsertPt = BlockToInsertInto->getTerminator();
242 }
Chris Lattner40bf8b42004-04-02 20:24:31 +0000243
Chris Lattner9f3d7382007-03-04 03:43:23 +0000244 std::map<Instruction*, Value*> ExitValues;
Misha Brukmanfd939082005-04-21 23:48:37 +0000245
Chris Lattner9f3d7382007-03-04 03:43:23 +0000246 // Find all values that are computed inside the loop, but used outside of it.
247 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
248 // the exit blocks of the loop to find them.
249 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
250 BasicBlock *ExitBB = ExitBlocks[i];
Dan Gohmancafb8132009-02-17 19:13:57 +0000251
Chris Lattner9f3d7382007-03-04 03:43:23 +0000252 // If there are no PHI nodes in this exit block, then no values defined
253 // inside the loop are used on this path, skip it.
254 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
255 if (!PN) continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000256
Chris Lattner9f3d7382007-03-04 03:43:23 +0000257 unsigned NumPreds = PN->getNumIncomingValues();
Dan Gohmancafb8132009-02-17 19:13:57 +0000258
Chris Lattner9f3d7382007-03-04 03:43:23 +0000259 // Iterate over all of the PHI nodes.
260 BasicBlock::iterator BBI = ExitBB->begin();
261 while ((PN = dyn_cast<PHINode>(BBI++))) {
Torok Edwin3790fb02009-05-24 19:36:09 +0000262 if (PN->use_empty())
263 continue; // dead use, don't replace it
Chris Lattner9f3d7382007-03-04 03:43:23 +0000264 // Iterate over all of the values in all the PHI nodes.
265 for (unsigned i = 0; i != NumPreds; ++i) {
266 // If the value being merged in is not integer or is not defined
267 // in the loop, skip it.
268 Value *InVal = PN->getIncomingValue(i);
269 if (!isa<Instruction>(InVal) ||
270 // SCEV only supports integer expressions for now.
Dan Gohman2d1be872009-04-16 03:18:22 +0000271 (!isa<IntegerType>(InVal->getType()) &&
272 !isa<PointerType>(InVal->getType())))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000273 continue;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000274
Chris Lattner9f3d7382007-03-04 03:43:23 +0000275 // If this pred is for a subloop, not L itself, skip it.
Dan Gohmancafb8132009-02-17 19:13:57 +0000276 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
Chris Lattner9f3d7382007-03-04 03:43:23 +0000277 continue; // The Block is in a subloop, skip it.
278
279 // Check that InVal is defined in the loop.
280 Instruction *Inst = cast<Instruction>(InVal);
281 if (!L->contains(Inst->getParent()))
282 continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000283
Chris Lattner9f3d7382007-03-04 03:43:23 +0000284 // Okay, this instruction has a user outside of the current loop
285 // and varies predictably *inside* the loop. Evaluate the value it
286 // contains when the loop exits, if possible.
Owen Anderson372b46c2009-06-22 21:39:50 +0000287 const SCEV* ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
Dan Gohmand594e6f2009-05-24 23:25:42 +0000288 if (!ExitValue->isLoopInvariant(L))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000289 continue;
Chris Lattner9caed542007-03-04 01:00:28 +0000290
Chris Lattner9f3d7382007-03-04 03:43:23 +0000291 Changed = true;
292 ++NumReplaced;
Dan Gohmancafb8132009-02-17 19:13:57 +0000293
Chris Lattner9f3d7382007-03-04 03:43:23 +0000294 // See if we already computed the exit value for the instruction, if so,
295 // just reuse it.
296 Value *&ExitVal = ExitValues[Inst];
297 if (!ExitVal)
Dan Gohman2d1be872009-04-16 03:18:22 +0000298 ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), InsertPt);
Dan Gohmancafb8132009-02-17 19:13:57 +0000299
Chris Lattner9f3d7382007-03-04 03:43:23 +0000300 DOUT << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal
301 << " LoopVal = " << *Inst << "\n";
302
303 PN->setIncomingValue(i, ExitVal);
Dan Gohmancafb8132009-02-17 19:13:57 +0000304
Dan Gohman81db61a2009-05-12 02:17:14 +0000305 // If this instruction is dead now, delete it.
306 RecursivelyDeleteTriviallyDeadInstructions(Inst);
Dan Gohmancafb8132009-02-17 19:13:57 +0000307
Dan Gohman03ad6982009-06-22 00:15:15 +0000308 // If we're inserting code into the exit block rather than the
309 // preheader, we can (and have to) remove the PHI entirely.
310 // This is safe, because the NewVal won't be variant
Chris Lattner9caed542007-03-04 01:00:28 +0000311 // in the loop, so we don't need an LCSSA phi node anymore.
Dan Gohman03ad6982009-06-22 00:15:15 +0000312 if (ExitBlocks.size() == 1) {
Chris Lattner9f3d7382007-03-04 03:43:23 +0000313 PN->replaceAllUsesWith(ExitVal);
Dan Gohman81db61a2009-05-12 02:17:14 +0000314 RecursivelyDeleteTriviallyDeadInstructions(PN);
Chris Lattner9f3d7382007-03-04 03:43:23 +0000315 break;
Chris Lattnerc9838f22007-03-03 22:48:48 +0000316 }
317 }
Chris Lattnerc9838f22007-03-03 22:48:48 +0000318 }
319 }
Chris Lattner40bf8b42004-04-02 20:24:31 +0000320}
321
Dan Gohman60f8a632009-02-17 20:49:49 +0000322void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000323 // First step. Check to see if there are any floating-point recurrences.
Chris Lattner40bf8b42004-04-02 20:24:31 +0000324 // If there are, change them into integer recurrences, permitting analysis by
325 // the SCEV routines.
326 //
327 BasicBlock *Header = L->getHeader();
Misha Brukmanfd939082005-04-21 23:48:37 +0000328
Dan Gohman81db61a2009-05-12 02:17:14 +0000329 SmallVector<WeakVH, 8> PHIs;
330 for (BasicBlock::iterator I = Header->begin();
331 PHINode *PN = dyn_cast<PHINode>(I); ++I)
332 PHIs.push_back(PN);
333
334 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
335 if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i]))
336 HandleFloatingPointIV(L, PN);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000337
Dan Gohman2d1be872009-04-16 03:18:22 +0000338 // If the loop previously had floating-point IV, ScalarEvolution
Dan Gohman60f8a632009-02-17 20:49:49 +0000339 // may not have been able to compute a trip count. Now that we've done some
340 // re-writing, the trip count may be computable.
341 if (Changed)
Dan Gohman46bdfb02009-02-24 18:55:53 +0000342 SE->forgetLoopBackedgeTakenCount(L);
Dale Johannesenc671d892009-04-15 23:31:51 +0000343}
344
Dan Gohmanc2390b12009-02-12 22:19:27 +0000345bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000346 IU = &getAnalysis<IVUsers>();
Devang Patel5ee99972007-03-07 06:39:01 +0000347 LI = &getAnalysis<LoopInfo>();
348 SE = &getAnalysis<ScalarEvolution>();
Devang Patel5ee99972007-03-07 06:39:01 +0000349 Changed = false;
Dan Gohman60f8a632009-02-17 20:49:49 +0000350
Dan Gohman2d1be872009-04-16 03:18:22 +0000351 // If there are any floating-point recurrences, attempt to
Dan Gohman60f8a632009-02-17 20:49:49 +0000352 // transform them to use integer recurrences.
353 RewriteNonIntegerIVs(L);
354
Dan Gohmanc2390b12009-02-12 22:19:27 +0000355 BasicBlock *Header = L->getHeader();
Dan Gohman81db61a2009-05-12 02:17:14 +0000356 BasicBlock *ExitingBlock = L->getExitingBlock(); // may be null
Owen Anderson372b46c2009-06-22 21:39:50 +0000357 const SCEV* BackedgeTakenCount = SE->getBackedgeTakenCount(L);
Chris Lattner9caed542007-03-04 01:00:28 +0000358
Chris Lattner40bf8b42004-04-02 20:24:31 +0000359 // Check to see if this loop has a computable loop-invariant execution count.
360 // If so, this means that we can compute the final value of any expressions
361 // that are recurrent in the loop, and substitute the exit values from the
362 // loop into any instructions outside of the loop that use the final values of
363 // the current expressions.
Chris Lattner3dec1f22002-05-10 15:38:35 +0000364 //
Dan Gohman46bdfb02009-02-24 18:55:53 +0000365 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount))
366 RewriteLoopExitValues(L, BackedgeTakenCount);
Chris Lattner6148c022001-12-03 17:28:42 +0000367
Dan Gohman81db61a2009-05-12 02:17:14 +0000368 // Compute the type of the largest recurrence expression, and decide whether
369 // a canonical induction variable should be inserted.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000370 const Type *LargestType = 0;
Dan Gohman81db61a2009-05-12 02:17:14 +0000371 bool NeedCannIV = false;
Dan Gohman46bdfb02009-02-24 18:55:53 +0000372 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
373 LargestType = BackedgeTakenCount->getType();
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000374 LargestType = SE->getEffectiveSCEVType(LargestType);
Dan Gohman81db61a2009-05-12 02:17:14 +0000375 // If we have a known trip count and a single exit block, we'll be
376 // rewriting the loop exit test condition below, which requires a
377 // canonical induction variable.
378 if (ExitingBlock)
379 NeedCannIV = true;
Chris Lattnerf50af082004-04-17 18:08:33 +0000380 }
Dan Gohman81db61a2009-05-12 02:17:14 +0000381 for (unsigned i = 0, e = IU->StrideOrder.size(); i != e; ++i) {
Owen Anderson372b46c2009-06-22 21:39:50 +0000382 const SCEV* Stride = IU->StrideOrder[i];
Dan Gohman81db61a2009-05-12 02:17:14 +0000383 const Type *Ty = SE->getEffectiveSCEVType(Stride->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000384 if (!LargestType ||
Dan Gohman81db61a2009-05-12 02:17:14 +0000385 SE->getTypeSizeInBits(Ty) >
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000386 SE->getTypeSizeInBits(LargestType))
Dan Gohman81db61a2009-05-12 02:17:14 +0000387 LargestType = Ty;
388
Owen Anderson372b46c2009-06-22 21:39:50 +0000389 std::map<const SCEV*, IVUsersOfOneStride *>::iterator SI =
Dan Gohman81db61a2009-05-12 02:17:14 +0000390 IU->IVUsesByStride.find(IU->StrideOrder[i]);
391 assert(SI != IU->IVUsesByStride.end() && "Stride doesn't exist!");
392
393 if (!SI->second->Users.empty())
394 NeedCannIV = true;
Chris Lattner6148c022001-12-03 17:28:42 +0000395 }
396
Chris Lattner40bf8b42004-04-02 20:24:31 +0000397 // Create a rewriter object which we'll use to transform the code with.
Dan Gohman5be18e82009-05-19 02:15:55 +0000398 SCEVExpander Rewriter(*SE);
Chris Lattner15cad752003-12-23 07:47:09 +0000399
Dan Gohman81db61a2009-05-12 02:17:14 +0000400 // Now that we know the largest of of the induction variable expressions
401 // in this loop, insert a canonical induction variable of the largest size.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000402 Value *IndVar = 0;
Dan Gohman81db61a2009-05-12 02:17:14 +0000403 if (NeedCannIV) {
Dan Gohman4d8414f2009-06-13 16:25:49 +0000404 // Check to see if the loop already has a canonical-looking induction
405 // variable. If one is present and it's wider than the planned canonical
406 // induction variable, temporarily remove it, so that the Rewriter
407 // doesn't attempt to reuse it.
408 PHINode *OldCannIV = L->getCanonicalInductionVariable();
409 if (OldCannIV) {
410 if (SE->getTypeSizeInBits(OldCannIV->getType()) >
411 SE->getTypeSizeInBits(LargestType))
412 OldCannIV->removeFromParent();
413 else
414 OldCannIV = 0;
415 }
416
Dan Gohmanc2390b12009-02-12 22:19:27 +0000417 IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L,LargestType);
Dan Gohman4d8414f2009-06-13 16:25:49 +0000418
Dan Gohmanc2390b12009-02-12 22:19:27 +0000419 ++NumInserted;
420 Changed = true;
421 DOUT << "INDVARS: New CanIV: " << *IndVar;
Dan Gohman4d8414f2009-06-13 16:25:49 +0000422
423 // Now that the official induction variable is established, reinsert
424 // the old canonical-looking variable after it so that the IR remains
425 // consistent. It will be deleted as part of the dead-PHI deletion at
426 // the end of the pass.
427 if (OldCannIV)
428 OldCannIV->insertAfter(cast<Instruction>(IndVar));
Dan Gohmand19534a2007-06-15 14:38:12 +0000429 }
Chris Lattner15cad752003-12-23 07:47:09 +0000430
Dan Gohmanc2390b12009-02-12 22:19:27 +0000431 // If we have a trip count expression, rewrite the loop's exit condition
432 // using it. We can currently only handle loops with a single exit.
Dan Gohman81db61a2009-05-12 02:17:14 +0000433 ICmpInst *NewICmp = 0;
434 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) && ExitingBlock) {
435 assert(NeedCannIV &&
436 "LinearFunctionTestReplace requires a canonical induction variable");
Dan Gohmanc2390b12009-02-12 22:19:27 +0000437 // Can't rewrite non-branch yet.
Dan Gohman81db61a2009-05-12 02:17:14 +0000438 if (BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator()))
439 NewICmp = LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar,
440 ExitingBlock, BI, Rewriter);
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000441 }
442
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000443 BasicBlock::iterator InsertPt = Header->getFirstNonPHI();
Chris Lattner5d461d22004-04-21 22:22:01 +0000444
Torok Edwin3d431382009-05-24 20:08:21 +0000445 // Rewrite IV-derived expressions. Clears the rewriter cache.
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000446 RewriteIVExpressions(L, LargestType, Rewriter, InsertPt);
Dan Gohmanc2390b12009-02-12 22:19:27 +0000447
Torok Edwin3d431382009-05-24 20:08:21 +0000448 // The Rewriter may only be used for isInsertedInstruction queries from this
449 // point on.
450
Dan Gohman81db61a2009-05-12 02:17:14 +0000451 // Loop-invariant instructions in the preheader that aren't used in the
452 // loop may be sunk below the loop to reduce register pressure.
453 SinkUnusedInvariants(L, Rewriter);
Chris Lattner394437f2001-12-04 04:32:29 +0000454
Dan Gohman81db61a2009-05-12 02:17:14 +0000455 // Reorder instructions to avoid use-before-def conditions.
456 FixUsesBeforeDefs(L, Rewriter);
457
458 // For completeness, inform IVUsers of the IV use in the newly-created
459 // loop exit test instruction.
460 if (NewICmp)
461 IU->AddUsersIfInteresting(cast<Instruction>(NewICmp->getOperand(0)));
462
463 // Clean up dead instructions.
464 DeleteDeadPHIs(L->getHeader());
465 // Check a post-condition.
466 assert(L->isLCSSAForm() && "Indvars did not leave the loop in lcssa form!");
Devang Patel5ee99972007-03-07 06:39:01 +0000467 return Changed;
Chris Lattner6148c022001-12-03 17:28:42 +0000468}
Devang Pateld22a8492008-09-09 21:41:07 +0000469
Dan Gohman81db61a2009-05-12 02:17:14 +0000470void IndVarSimplify::RewriteIVExpressions(Loop *L, const Type *LargestType,
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000471 SCEVExpander &Rewriter,
472 BasicBlock::iterator InsertPt) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000473 SmallVector<WeakVH, 16> DeadInsts;
474
475 // Rewrite all induction variable expressions in terms of the canonical
476 // induction variable.
477 //
478 // If there were induction variables of other sizes or offsets, manually
479 // add the offsets to the primary induction variable and cast, avoiding
480 // the need for the code evaluation methods to insert induction variables
481 // of different sizes.
482 for (unsigned i = 0, e = IU->StrideOrder.size(); i != e; ++i) {
Owen Anderson372b46c2009-06-22 21:39:50 +0000483 const SCEV* Stride = IU->StrideOrder[i];
Dan Gohman81db61a2009-05-12 02:17:14 +0000484
Owen Anderson372b46c2009-06-22 21:39:50 +0000485 std::map<const SCEV*, IVUsersOfOneStride *>::iterator SI =
Dan Gohman81db61a2009-05-12 02:17:14 +0000486 IU->IVUsesByStride.find(IU->StrideOrder[i]);
487 assert(SI != IU->IVUsesByStride.end() && "Stride doesn't exist!");
488 ilist<IVStrideUse> &List = SI->second->Users;
489 for (ilist<IVStrideUse>::iterator UI = List.begin(),
490 E = List.end(); UI != E; ++UI) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000491 Value *Op = UI->getOperandValToReplace();
Dan Gohman4d8414f2009-06-13 16:25:49 +0000492 const Type *UseTy = Op->getType();
Dan Gohman81db61a2009-05-12 02:17:14 +0000493 Instruction *User = UI->getUser();
Dan Gohman81db61a2009-05-12 02:17:14 +0000494
495 // Compute the final addrec to expand into code.
Owen Anderson372b46c2009-06-22 21:39:50 +0000496 const SCEV* AR = IU->getReplacementExpr(*UI);
Dan Gohman81db61a2009-05-12 02:17:14 +0000497
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000498 // FIXME: It is an extremely bad idea to indvar substitute anything more
499 // complex than affine induction variables. Doing so will put expensive
500 // polynomial evaluations inside of the loop, and the str reduction pass
501 // currently can only reduce affine polynomials. For now just disable
502 // indvar subst on anything more complex than an affine addrec, unless
503 // it can be expanded to a trivial value.
504 if (!AR->isLoopInvariant(L) && !Stride->isLoopInvariant(L))
505 continue;
Dan Gohman68c93442009-06-03 19:11:31 +0000506
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000507 // Now expand it into actual Instructions and patch it into place.
508 Value *NewVal = Rewriter.expandCodeFor(AR, UseTy, InsertPt);
Dan Gohman81db61a2009-05-12 02:17:14 +0000509
510 // Patch the new value into place.
511 if (Op->hasName())
512 NewVal->takeName(Op);
513 User->replaceUsesOfWith(Op, NewVal);
514 UI->setOperandValToReplace(NewVal);
515 DOUT << "INDVARS: Rewrote IV '" << *AR << "' " << *Op
516 << " into = " << *NewVal << "\n";
517 ++NumRemoved;
518 Changed = true;
519
520 // The old value may be dead now.
521 DeadInsts.push_back(Op);
522 }
523 }
524
Torok Edwin3d431382009-05-24 20:08:21 +0000525 // Clear the rewriter cache, because values that are in the rewriter's cache
526 // can be deleted in the loop below, causing the AssertingVH in the cache to
527 // trigger.
528 Rewriter.clear();
Dan Gohman81db61a2009-05-12 02:17:14 +0000529 // Now that we're done iterating through lists, clean up any instructions
530 // which are now dead.
531 while (!DeadInsts.empty()) {
532 Instruction *Inst = dyn_cast_or_null<Instruction>(DeadInsts.pop_back_val());
533 if (Inst)
534 RecursivelyDeleteTriviallyDeadInstructions(Inst);
535 }
536}
537
538/// If there's a single exit block, sink any loop-invariant values that
539/// were defined in the preheader but not used inside the loop into the
540/// exit block to reduce register pressure in the loop.
541void IndVarSimplify::SinkUnusedInvariants(Loop *L, SCEVExpander &Rewriter) {
542 BasicBlock *ExitBlock = L->getExitBlock();
543 if (!ExitBlock) return;
544
545 Instruction *NonPHI = ExitBlock->getFirstNonPHI();
546 BasicBlock *Preheader = L->getLoopPreheader();
547 BasicBlock::iterator I = Preheader->getTerminator();
548 while (I != Preheader->begin()) {
549 --I;
550 // New instructions were inserted at the end of the preheader. Only
551 // consider those new instructions.
552 if (!Rewriter.isInsertedInstruction(I))
553 break;
554 // Determine if there is a use in or before the loop (direct or
555 // otherwise).
556 bool UsedInLoop = false;
557 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
558 UI != UE; ++UI) {
559 BasicBlock *UseBB = cast<Instruction>(UI)->getParent();
560 if (PHINode *P = dyn_cast<PHINode>(UI)) {
561 unsigned i =
562 PHINode::getIncomingValueNumForOperand(UI.getOperandNo());
563 UseBB = P->getIncomingBlock(i);
564 }
565 if (UseBB == Preheader || L->contains(UseBB)) {
566 UsedInLoop = true;
567 break;
568 }
569 }
570 // If there is, the def must remain in the preheader.
571 if (UsedInLoop)
572 continue;
573 // Otherwise, sink it to the exit block.
574 Instruction *ToMove = I;
575 bool Done = false;
576 if (I != Preheader->begin())
577 --I;
578 else
579 Done = true;
580 ToMove->moveBefore(NonPHI);
581 if (Done)
582 break;
583 }
584}
585
586/// Re-schedule the inserted instructions to put defs before uses. This
587/// fixes problems that arrise when SCEV expressions contain loop-variant
588/// values unrelated to the induction variable which are defined inside the
589/// loop. FIXME: It would be better to insert instructions in the right
590/// place so that this step isn't needed.
591void IndVarSimplify::FixUsesBeforeDefs(Loop *L, SCEVExpander &Rewriter) {
592 // Visit all the blocks in the loop in pre-order dom-tree dfs order.
593 DominatorTree *DT = &getAnalysis<DominatorTree>();
594 std::map<Instruction *, unsigned> NumPredsLeft;
595 SmallVector<DomTreeNode *, 16> Worklist;
596 Worklist.push_back(DT->getNode(L->getHeader()));
597 do {
598 DomTreeNode *Node = Worklist.pop_back_val();
599 for (DomTreeNode::iterator I = Node->begin(), E = Node->end(); I != E; ++I)
600 if (L->contains((*I)->getBlock()))
601 Worklist.push_back(*I);
602 BasicBlock *BB = Node->getBlock();
603 // Visit all the instructions in the block top down.
604 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
605 // Count the number of operands that aren't properly dominating.
606 unsigned NumPreds = 0;
607 if (Rewriter.isInsertedInstruction(I) && !isa<PHINode>(I))
608 for (User::op_iterator OI = I->op_begin(), OE = I->op_end();
609 OI != OE; ++OI)
610 if (Instruction *Inst = dyn_cast<Instruction>(OI))
611 if (L->contains(Inst->getParent()) && !NumPredsLeft.count(Inst))
612 ++NumPreds;
613 NumPredsLeft[I] = NumPreds;
614 // Notify uses of the position of this instruction, and move the
615 // users (and their dependents, recursively) into place after this
616 // instruction if it is their last outstanding operand.
617 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
618 UI != UE; ++UI) {
619 Instruction *Inst = cast<Instruction>(UI);
620 std::map<Instruction *, unsigned>::iterator Z = NumPredsLeft.find(Inst);
621 if (Z != NumPredsLeft.end() && Z->second != 0 && --Z->second == 0) {
622 SmallVector<Instruction *, 4> UseWorkList;
623 UseWorkList.push_back(Inst);
Dan Gohmand6d02942009-05-22 16:47:11 +0000624 BasicBlock::iterator InsertPt = I;
625 if (InvokeInst *II = dyn_cast<InvokeInst>(InsertPt))
626 InsertPt = II->getNormalDest()->begin();
627 else
628 ++InsertPt;
Dan Gohman81db61a2009-05-12 02:17:14 +0000629 while (isa<PHINode>(InsertPt)) ++InsertPt;
630 do {
631 Instruction *Use = UseWorkList.pop_back_val();
632 Use->moveBefore(InsertPt);
633 NumPredsLeft.erase(Use);
634 for (Value::use_iterator IUI = Use->use_begin(),
635 IUE = Use->use_end(); IUI != IUE; ++IUI) {
636 Instruction *IUIInst = cast<Instruction>(IUI);
637 if (L->contains(IUIInst->getParent()) &&
638 Rewriter.isInsertedInstruction(IUIInst) &&
639 !isa<PHINode>(IUIInst))
640 UseWorkList.push_back(IUIInst);
641 }
642 } while (!UseWorkList.empty());
643 }
644 }
645 }
646 } while (!Worklist.empty());
647}
648
Devang Patel13877bf2008-11-18 00:40:02 +0000649/// Return true if it is OK to use SIToFPInst for an inducation variable
650/// with given inital and exit values.
651static bool useSIToFPInst(ConstantFP &InitV, ConstantFP &ExitV,
652 uint64_t intIV, uint64_t intEV) {
653
Dan Gohmancafb8132009-02-17 19:13:57 +0000654 if (InitV.getValueAPF().isNegative() || ExitV.getValueAPF().isNegative())
Devang Patel13877bf2008-11-18 00:40:02 +0000655 return true;
656
657 // If the iteration range can be handled by SIToFPInst then use it.
658 APInt Max = APInt::getSignedMaxValue(32);
Dale Johannesenbae7d6d2009-05-14 16:47:34 +0000659 if (Max.getZExtValue() > static_cast<uint64_t>(abs64(intEV - intIV)))
Devang Patel13877bf2008-11-18 00:40:02 +0000660 return true;
Dan Gohmancafb8132009-02-17 19:13:57 +0000661
Devang Patel13877bf2008-11-18 00:40:02 +0000662 return false;
663}
664
665/// convertToInt - Convert APF to an integer, if possible.
Devang Patelcd402332008-11-17 23:27:13 +0000666static bool convertToInt(const APFloat &APF, uint64_t *intVal) {
667
668 bool isExact = false;
Evan Cheng794a7db2008-11-26 01:11:57 +0000669 if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
670 return false;
Dan Gohmancafb8132009-02-17 19:13:57 +0000671 if (APF.convertToInteger(intVal, 32, APF.isNegative(),
Devang Patelcd402332008-11-17 23:27:13 +0000672 APFloat::rmTowardZero, &isExact)
673 != APFloat::opOK)
674 return false;
Dan Gohmancafb8132009-02-17 19:13:57 +0000675 if (!isExact)
Devang Patelcd402332008-11-17 23:27:13 +0000676 return false;
677 return true;
678
679}
680
Devang Patel58d43d42008-11-03 18:32:19 +0000681/// HandleFloatingPointIV - If the loop has floating induction variable
682/// then insert corresponding integer induction variable if possible.
Devang Patel84e35152008-11-17 21:32:02 +0000683/// For example,
684/// for(double i = 0; i < 10000; ++i)
685/// bar(i)
686/// is converted into
687/// for(int i = 0; i < 10000; ++i)
688/// bar((double)i);
689///
Dan Gohman81db61a2009-05-12 02:17:14 +0000690void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PH) {
Devang Patel58d43d42008-11-03 18:32:19 +0000691
Devang Patel84e35152008-11-17 21:32:02 +0000692 unsigned IncomingEdge = L->contains(PH->getIncomingBlock(0));
693 unsigned BackEdge = IncomingEdge^1;
Dan Gohmancafb8132009-02-17 19:13:57 +0000694
Devang Patel84e35152008-11-17 21:32:02 +0000695 // Check incoming value.
Devang Patelcd402332008-11-17 23:27:13 +0000696 ConstantFP *InitValue = dyn_cast<ConstantFP>(PH->getIncomingValue(IncomingEdge));
697 if (!InitValue) return;
698 uint64_t newInitValue = Type::Int32Ty->getPrimitiveSizeInBits();
699 if (!convertToInt(InitValue->getValueAPF(), &newInitValue))
700 return;
701
702 // Check IV increment. Reject this PH if increement operation is not
703 // an add or increment value can not be represented by an integer.
Dan Gohmancafb8132009-02-17 19:13:57 +0000704 BinaryOperator *Incr =
Devang Patel84e35152008-11-17 21:32:02 +0000705 dyn_cast<BinaryOperator>(PH->getIncomingValue(BackEdge));
706 if (!Incr) return;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000707 if (Incr->getOpcode() != Instruction::FAdd) return;
Devang Patel84e35152008-11-17 21:32:02 +0000708 ConstantFP *IncrValue = NULL;
709 unsigned IncrVIndex = 1;
710 if (Incr->getOperand(1) == PH)
711 IncrVIndex = 0;
712 IncrValue = dyn_cast<ConstantFP>(Incr->getOperand(IncrVIndex));
713 if (!IncrValue) return;
Devang Patelcd402332008-11-17 23:27:13 +0000714 uint64_t newIncrValue = Type::Int32Ty->getPrimitiveSizeInBits();
715 if (!convertToInt(IncrValue->getValueAPF(), &newIncrValue))
716 return;
Dan Gohmancafb8132009-02-17 19:13:57 +0000717
Devang Patelcd402332008-11-17 23:27:13 +0000718 // Check Incr uses. One user is PH and the other users is exit condition used
719 // by the conditional terminator.
Devang Patel84e35152008-11-17 21:32:02 +0000720 Value::use_iterator IncrUse = Incr->use_begin();
721 Instruction *U1 = cast<Instruction>(IncrUse++);
722 if (IncrUse == Incr->use_end()) return;
723 Instruction *U2 = cast<Instruction>(IncrUse++);
724 if (IncrUse != Incr->use_end()) return;
Dan Gohmancafb8132009-02-17 19:13:57 +0000725
Devang Patel84e35152008-11-17 21:32:02 +0000726 // Find exit condition.
727 FCmpInst *EC = dyn_cast<FCmpInst>(U1);
728 if (!EC)
729 EC = dyn_cast<FCmpInst>(U2);
730 if (!EC) return;
731
732 if (BranchInst *BI = dyn_cast<BranchInst>(EC->getParent()->getTerminator())) {
733 if (!BI->isConditional()) return;
734 if (BI->getCondition() != EC) return;
Devang Patel58d43d42008-11-03 18:32:19 +0000735 }
Devang Patel58d43d42008-11-03 18:32:19 +0000736
Devang Patelcd402332008-11-17 23:27:13 +0000737 // Find exit value. If exit value can not be represented as an interger then
738 // do not handle this floating point PH.
Devang Patel84e35152008-11-17 21:32:02 +0000739 ConstantFP *EV = NULL;
740 unsigned EVIndex = 1;
741 if (EC->getOperand(1) == Incr)
742 EVIndex = 0;
743 EV = dyn_cast<ConstantFP>(EC->getOperand(EVIndex));
744 if (!EV) return;
Devang Patel84e35152008-11-17 21:32:02 +0000745 uint64_t intEV = Type::Int32Ty->getPrimitiveSizeInBits();
Devang Patelcd402332008-11-17 23:27:13 +0000746 if (!convertToInt(EV->getValueAPF(), &intEV))
Devang Patel84e35152008-11-17 21:32:02 +0000747 return;
Dan Gohmancafb8132009-02-17 19:13:57 +0000748
Devang Patel84e35152008-11-17 21:32:02 +0000749 // Find new predicate for integer comparison.
750 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
751 switch (EC->getPredicate()) {
752 case CmpInst::FCMP_OEQ:
753 case CmpInst::FCMP_UEQ:
754 NewPred = CmpInst::ICMP_EQ;
755 break;
756 case CmpInst::FCMP_OGT:
757 case CmpInst::FCMP_UGT:
758 NewPred = CmpInst::ICMP_UGT;
759 break;
760 case CmpInst::FCMP_OGE:
761 case CmpInst::FCMP_UGE:
762 NewPred = CmpInst::ICMP_UGE;
763 break;
764 case CmpInst::FCMP_OLT:
765 case CmpInst::FCMP_ULT:
766 NewPred = CmpInst::ICMP_ULT;
767 break;
768 case CmpInst::FCMP_OLE:
769 case CmpInst::FCMP_ULE:
770 NewPred = CmpInst::ICMP_ULE;
771 break;
772 default:
773 break;
Devang Patel58d43d42008-11-03 18:32:19 +0000774 }
Devang Patel84e35152008-11-17 21:32:02 +0000775 if (NewPred == CmpInst::BAD_ICMP_PREDICATE) return;
Dan Gohmancafb8132009-02-17 19:13:57 +0000776
Devang Patel84e35152008-11-17 21:32:02 +0000777 // Insert new integer induction variable.
778 PHINode *NewPHI = PHINode::Create(Type::Int32Ty,
779 PH->getName()+".int", PH);
Devang Patelcd402332008-11-17 23:27:13 +0000780 NewPHI->addIncoming(ConstantInt::get(Type::Int32Ty, newInitValue),
Devang Patel84e35152008-11-17 21:32:02 +0000781 PH->getIncomingBlock(IncomingEdge));
782
Dan Gohmancafb8132009-02-17 19:13:57 +0000783 Value *NewAdd = BinaryOperator::CreateAdd(NewPHI,
784 ConstantInt::get(Type::Int32Ty,
Devang Patelcd402332008-11-17 23:27:13 +0000785 newIncrValue),
Devang Patel84e35152008-11-17 21:32:02 +0000786 Incr->getName()+".int", Incr);
787 NewPHI->addIncoming(NewAdd, PH->getIncomingBlock(BackEdge));
788
Dale Johannesen617d1082009-04-27 21:03:15 +0000789 // The back edge is edge 1 of newPHI, whatever it may have been in the
790 // original PHI.
Devang Patel84e35152008-11-17 21:32:02 +0000791 ConstantInt *NewEV = ConstantInt::get(Type::Int32Ty, intEV);
Dale Johannesen617d1082009-04-27 21:03:15 +0000792 Value *LHS = (EVIndex == 1 ? NewPHI->getIncomingValue(1) : NewEV);
793 Value *RHS = (EVIndex == 1 ? NewEV : NewPHI->getIncomingValue(1));
Dan Gohmancafb8132009-02-17 19:13:57 +0000794 ICmpInst *NewEC = new ICmpInst(NewPred, LHS, RHS, EC->getNameStart(),
Devang Patel84e35152008-11-17 21:32:02 +0000795 EC->getParent()->getTerminator());
Dan Gohmancafb8132009-02-17 19:13:57 +0000796
Dan Gohman81db61a2009-05-12 02:17:14 +0000797 // In the following deltions, PH may become dead and may be deleted.
798 // Use a WeakVH to observe whether this happens.
799 WeakVH WeakPH = PH;
800
Devang Patel84e35152008-11-17 21:32:02 +0000801 // Delete old, floating point, exit comparision instruction.
Dan Gohman14fba292009-05-24 18:09:01 +0000802 NewEC->takeName(EC);
Devang Patel84e35152008-11-17 21:32:02 +0000803 EC->replaceAllUsesWith(NewEC);
Dan Gohman81db61a2009-05-12 02:17:14 +0000804 RecursivelyDeleteTriviallyDeadInstructions(EC);
Dan Gohmancafb8132009-02-17 19:13:57 +0000805
Devang Patel84e35152008-11-17 21:32:02 +0000806 // Delete old, floating point, increment instruction.
807 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
Dan Gohman81db61a2009-05-12 02:17:14 +0000808 RecursivelyDeleteTriviallyDeadInstructions(Incr);
Dan Gohmancafb8132009-02-17 19:13:57 +0000809
Dan Gohman81db61a2009-05-12 02:17:14 +0000810 // Replace floating induction variable, if it isn't already deleted.
811 // Give SIToFPInst preference over UIToFPInst because it is faster on
812 // platforms that are widely used.
813 if (WeakPH && !PH->use_empty()) {
814 if (useSIToFPInst(*InitValue, *EV, newInitValue, intEV)) {
815 SIToFPInst *Conv = new SIToFPInst(NewPHI, PH->getType(), "indvar.conv",
816 PH->getParent()->getFirstNonPHI());
817 PH->replaceAllUsesWith(Conv);
818 } else {
819 UIToFPInst *Conv = new UIToFPInst(NewPHI, PH->getType(), "indvar.conv",
820 PH->getParent()->getFirstNonPHI());
821 PH->replaceAllUsesWith(Conv);
822 }
823 RecursivelyDeleteTriviallyDeadInstructions(PH);
Devang Patelcd402332008-11-17 23:27:13 +0000824 }
Devang Patel58d43d42008-11-03 18:32:19 +0000825
Dan Gohman81db61a2009-05-12 02:17:14 +0000826 // Add a new IVUsers entry for the newly-created integer PHI.
827 IU->AddUsersIfInteresting(NewPHI);
828}