blob: 3d9017d17e33bd142da988dfc7bfa84c0d22855f [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.
20// 3. Any pointer arithmetic recurrences are raised to use array subscripts.
21//
22// If the trip count of a loop is computable, this pass also makes the following
23// changes:
24// 1. The exit condition for the loop is canonicalized to compare the
25// induction value against the exit value. This turns loops like:
26// 'for (i = 7; i*i < 1000; ++i)' into 'for (i = 0; i != 25; ++i)'
27// 2. Any use outside of the loop of an expression derived from the indvar
28// is changed to compute the derived value outside of the loop, eliminating
29// the dependence on the exit value of the induction variable. If the only
30// purpose of the loop is to compute the exit value of some derived
31// expression, this transformation will make the loop dead.
32//
33// This transformation should be followed by strength reduction after all of the
34// desired loop transformations have been performed. Additionally, on targets
35// where it is profitable, the loop could be transformed to count down to zero
36// (the "do loop" optimization).
Chris Lattner6148c022001-12-03 17:28:42 +000037//
38//===----------------------------------------------------------------------===//
39
Chris Lattner0e5f4992006-12-19 21:40:18 +000040#define DEBUG_TYPE "indvars"
Chris Lattner022103b2002-05-07 20:03:00 +000041#include "llvm/Transforms/Scalar.h"
Chris Lattner40bf8b42004-04-02 20:24:31 +000042#include "llvm/BasicBlock.h"
Chris Lattner59fdaee2004-04-15 15:21:43 +000043#include "llvm/Constants.h"
Chris Lattner18b3c972003-12-22 05:02:01 +000044#include "llvm/Instructions.h"
Chris Lattner40bf8b42004-04-02 20:24:31 +000045#include "llvm/Type.h"
Nate Begeman36f891b2005-07-30 00:12:19 +000046#include "llvm/Analysis/ScalarEvolutionExpander.h"
John Criswell47df12d2003-12-18 17:19:19 +000047#include "llvm/Analysis/LoopInfo.h"
Devang Patel5ee99972007-03-07 06:39:01 +000048#include "llvm/Analysis/LoopPass.h"
Chris Lattner455889a2002-02-12 22:39:50 +000049#include "llvm/Support/CFG.h"
Reid Spencer9133fe22007-02-05 23:32:05 +000050#include "llvm/Support/Compiler.h"
Chris Lattneree4f13a2007-01-07 01:14:12 +000051#include "llvm/Support/Debug.h"
Chris Lattnera4b9c782004-10-11 23:06:50 +000052#include "llvm/Support/GetElementPtrTypeIterator.h"
John Criswell47df12d2003-12-18 17:19:19 +000053#include "llvm/Transforms/Utils/Local.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000054#include "llvm/Support/CommandLine.h"
Reid Spencera54b7cb2007-01-12 07:05:14 +000055#include "llvm/ADT/SmallVector.h"
Dan Gohmanc2390b12009-02-12 22:19:27 +000056#include "llvm/ADT/SetVector.h"
Chris Lattner1a6111f2008-11-16 07:17:51 +000057#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000058#include "llvm/ADT/Statistic.h"
John Criswell47df12d2003-12-18 17:19:19 +000059using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000060
Chris Lattner0e5f4992006-12-19 21:40:18 +000061STATISTIC(NumRemoved , "Number of aux indvars removed");
Chris Lattner0e5f4992006-12-19 21:40:18 +000062STATISTIC(NumInserted, "Number of canonical indvars added");
63STATISTIC(NumReplaced, "Number of exit values replaced");
64STATISTIC(NumLFTR , "Number of loop exit tests replaced");
Chris Lattner3324e712003-12-22 03:58:44 +000065
Chris Lattner0e5f4992006-12-19 21:40:18 +000066namespace {
Devang Patel5ee99972007-03-07 06:39:01 +000067 class VISIBILITY_HIDDEN IndVarSimplify : public LoopPass {
Chris Lattner40bf8b42004-04-02 20:24:31 +000068 LoopInfo *LI;
69 ScalarEvolution *SE;
Chris Lattner15cad752003-12-23 07:47:09 +000070 bool Changed;
Chris Lattner3324e712003-12-22 03:58:44 +000071 public:
Devang Patel794fd752007-05-01 21:15:47 +000072
Nick Lewyckyecd94c82007-05-06 13:37:16 +000073 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000074 IndVarSimplify() : LoopPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000075
Dan Gohman60f8a632009-02-17 20:49:49 +000076 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
77
Devang Patel5ee99972007-03-07 06:39:01 +000078 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Devang Patelbc533cd2007-09-10 18:08:23 +000079 AU.addRequired<ScalarEvolution>();
Devang Patel5ee99972007-03-07 06:39:01 +000080 AU.addRequiredID(LCSSAID);
81 AU.addRequiredID(LoopSimplifyID);
Devang Patel5ee99972007-03-07 06:39:01 +000082 AU.addRequired<LoopInfo>();
Dan Gohman474cecf2009-02-23 16:29:41 +000083 AU.addPreserved<ScalarEvolution>();
Devang Patel5ee99972007-03-07 06:39:01 +000084 AU.addPreservedID(LoopSimplifyID);
85 AU.addPreservedID(LCSSAID);
86 AU.setPreservesCFG();
87 }
Chris Lattner15cad752003-12-23 07:47:09 +000088
Chris Lattner40bf8b42004-04-02 20:24:31 +000089 private:
Devang Patel5ee99972007-03-07 06:39:01 +000090
Dan Gohman60f8a632009-02-17 20:49:49 +000091 void RewriteNonIntegerIVs(Loop *L);
92
Dan Gohman46bdfb02009-02-24 18:55:53 +000093 void LinearFunctionTestReplace(Loop *L, SCEVHandle BackedgeTakenCount,
Dan Gohmana5758712009-02-17 15:57:39 +000094 Value *IndVar,
Dan Gohmanc2390b12009-02-12 22:19:27 +000095 BasicBlock *ExitingBlock,
96 BranchInst *BI,
Dan Gohman15cab282009-02-23 23:20:35 +000097 SCEVExpander &Rewriter);
Dan Gohman890f92b2009-04-18 17:56:28 +000098 void RewriteLoopExitValues(Loop *L, const SCEV *BackedgeTakenCount);
Chris Lattner40bf8b42004-04-02 20:24:31 +000099
Chris Lattner1a6111f2008-11-16 07:17:51 +0000100 void DeleteTriviallyDeadInstructions(SmallPtrSet<Instruction*, 16> &Insts);
Devang Pateld22a8492008-09-09 21:41:07 +0000101
Dan Gohmancafb8132009-02-17 19:13:57 +0000102 void HandleFloatingPointIV(Loop *L, PHINode *PH,
Devang Patel84e35152008-11-17 21:32:02 +0000103 SmallPtrSet<Instruction*, 16> &DeadInsts);
Chris Lattner3324e712003-12-22 03:58:44 +0000104 };
Chris Lattner5e761402002-09-10 05:24:05 +0000105}
Chris Lattner394437f2001-12-04 04:32:29 +0000106
Dan Gohman844731a2008-05-13 00:00:25 +0000107char IndVarSimplify::ID = 0;
108static RegisterPass<IndVarSimplify>
109X("indvars", "Canonicalize Induction Variables");
110
Daniel Dunbar394f0442008-10-22 23:32:42 +0000111Pass *llvm::createIndVarSimplifyPass() {
Chris Lattner3324e712003-12-22 03:58:44 +0000112 return new IndVarSimplify();
Chris Lattner394437f2001-12-04 04:32:29 +0000113}
114
Chris Lattner40bf8b42004-04-02 20:24:31 +0000115/// DeleteTriviallyDeadInstructions - If any of the instructions is the
116/// specified set are trivially dead, delete them and see if this makes any of
117/// their operands subsequently dead.
118void IndVarSimplify::
Chris Lattner1a6111f2008-11-16 07:17:51 +0000119DeleteTriviallyDeadInstructions(SmallPtrSet<Instruction*, 16> &Insts) {
Chris Lattner40bf8b42004-04-02 20:24:31 +0000120 while (!Insts.empty()) {
121 Instruction *I = *Insts.begin();
Chris Lattner1a6111f2008-11-16 07:17:51 +0000122 Insts.erase(I);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000123 if (isInstructionTriviallyDead(I)) {
124 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
125 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
126 Insts.insert(U);
Chris Lattneree4f13a2007-01-07 01:14:12 +0000127 DOUT << "INDVARS: Deleting: " << *I;
Chris Lattnera4b9c782004-10-11 23:06:50 +0000128 I->eraseFromParent();
Chris Lattner40bf8b42004-04-02 20:24:31 +0000129 Changed = true;
130 }
131 }
132}
133
Chris Lattner40bf8b42004-04-02 20:24:31 +0000134/// LinearFunctionTestReplace - This method rewrites the exit condition of the
Chris Lattner59fdaee2004-04-15 15:21:43 +0000135/// loop to be a canonical != comparison against the incremented loop induction
136/// variable. This pass is able to rewrite the exit tests of any loop where the
137/// SCEV analysis can determine a loop-invariant trip count of the loop, which
138/// is actually a much broader range than just linear tests.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000139void IndVarSimplify::LinearFunctionTestReplace(Loop *L,
Dan Gohman46bdfb02009-02-24 18:55:53 +0000140 SCEVHandle BackedgeTakenCount,
Dan Gohmanc2390b12009-02-12 22:19:27 +0000141 Value *IndVar,
142 BasicBlock *ExitingBlock,
143 BranchInst *BI,
Dan Gohman15cab282009-02-23 23:20:35 +0000144 SCEVExpander &Rewriter) {
Chris Lattnerd2440572004-04-15 20:26:22 +0000145 // If the exiting block is not the same as the backedge block, we must compare
146 // against the preincremented value, otherwise we prefer to compare against
147 // the post-incremented value.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000148 Value *CmpIndVar;
Dan Gohman46bdfb02009-02-24 18:55:53 +0000149 SCEVHandle RHS = BackedgeTakenCount;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000150 if (ExitingBlock == L->getLoopLatch()) {
Dan Gohman46bdfb02009-02-24 18:55:53 +0000151 // Add one to the "backedge-taken" count to get the trip count.
152 // If this addition may overflow, we have to be more pessimistic and
153 // cast the induction variable before doing the add.
154 SCEVHandle Zero = SE->getIntegerSCEV(0, BackedgeTakenCount->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000155 SCEVHandle N =
Dan Gohman46bdfb02009-02-24 18:55:53 +0000156 SE->getAddExpr(BackedgeTakenCount,
157 SE->getIntegerSCEV(1, BackedgeTakenCount->getType()));
Dan Gohmanc2390b12009-02-12 22:19:27 +0000158 if ((isa<SCEVConstant>(N) && !N->isZero()) ||
159 SE->isLoopGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) {
160 // No overflow. Cast the sum.
Dan Gohman46bdfb02009-02-24 18:55:53 +0000161 RHS = SE->getTruncateOrZeroExtend(N, IndVar->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000162 } else {
163 // Potential overflow. Cast before doing the add.
Dan Gohman46bdfb02009-02-24 18:55:53 +0000164 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
165 IndVar->getType());
166 RHS = SE->getAddExpr(RHS,
167 SE->getIntegerSCEV(1, IndVar->getType()));
Dan Gohmanc2390b12009-02-12 22:19:27 +0000168 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000169
Dan Gohman46bdfb02009-02-24 18:55:53 +0000170 // The BackedgeTaken expression contains the number of times that the
171 // backedge branches to the loop header. This is one less than the
172 // number of times the loop executes, so use the incremented indvar.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000173 CmpIndVar = L->getCanonicalInductionVariableIncrement();
Chris Lattnerd2440572004-04-15 20:26:22 +0000174 } else {
175 // We have to use the preincremented value...
Dan Gohman46bdfb02009-02-24 18:55:53 +0000176 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
177 IndVar->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000178 CmpIndVar = IndVar;
Chris Lattnerd2440572004-04-15 20:26:22 +0000179 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000180
Chris Lattner40bf8b42004-04-02 20:24:31 +0000181 // Expand the code for the iteration count into the preheader of the loop.
182 BasicBlock *Preheader = L->getLoopPreheader();
Dan Gohman2d1be872009-04-16 03:18:22 +0000183 Value *ExitCnt = Rewriter.expandCodeFor(RHS, IndVar->getType(),
Dan Gohmanc2390b12009-02-12 22:19:27 +0000184 Preheader->getTerminator());
Chris Lattner40bf8b42004-04-02 20:24:31 +0000185
Reid Spencere4d87aa2006-12-23 06:05:41 +0000186 // Insert a new icmp_ne or icmp_eq instruction before the branch.
187 ICmpInst::Predicate Opcode;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000188 if (L->contains(BI->getSuccessor(0)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000189 Opcode = ICmpInst::ICMP_NE;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000190 else
Reid Spencere4d87aa2006-12-23 06:05:41 +0000191 Opcode = ICmpInst::ICMP_EQ;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000192
Dan Gohmanc2390b12009-02-12 22:19:27 +0000193 DOUT << "INDVARS: Rewriting loop exit condition to:\n"
194 << " LHS:" << *CmpIndVar // includes a newline
195 << " op:\t"
Dan Gohmanf108e2e2009-02-14 02:26:50 +0000196 << (Opcode == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
Dan Gohman46bdfb02009-02-24 18:55:53 +0000197 << " RHS:\t" << *RHS << "\n";
Dan Gohmanc2390b12009-02-12 22:19:27 +0000198
199 Value *Cond = new ICmpInst(Opcode, CmpIndVar, ExitCnt, "exitcond", BI);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000200 BI->setCondition(Cond);
201 ++NumLFTR;
202 Changed = true;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000203}
204
Chris Lattner40bf8b42004-04-02 20:24:31 +0000205/// RewriteLoopExitValues - Check to see if this loop has a computable
206/// loop-invariant execution count. If so, this means that we can compute the
207/// final value of any expressions that are recurrent in the loop, and
208/// substitute the exit values from the loop into any instructions outside of
209/// the loop that use the final values of the current expressions.
Dan Gohman890f92b2009-04-18 17:56:28 +0000210void IndVarSimplify::RewriteLoopExitValues(Loop *L,
211 const SCEV *BackedgeTakenCount) {
Chris Lattner40bf8b42004-04-02 20:24:31 +0000212 BasicBlock *Preheader = L->getLoopPreheader();
213
214 // Scan all of the instructions in the loop, looking at those that have
215 // extra-loop users and which are recurrences.
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000216 SCEVExpander Rewriter(*SE, *LI);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000217
218 // We insert the code into the preheader of the loop if the loop contains
219 // multiple exit blocks, or in the exit block if there is exactly one.
220 BasicBlock *BlockToInsertInto;
Devang Patelb7211a22007-08-21 00:31:24 +0000221 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattner9f3d7382007-03-04 03:43:23 +0000222 L->getUniqueExitBlocks(ExitBlocks);
Chris Lattnerf1ab4b42004-04-18 22:14:10 +0000223 if (ExitBlocks.size() == 1)
224 BlockToInsertInto = ExitBlocks[0];
Chris Lattner40bf8b42004-04-02 20:24:31 +0000225 else
226 BlockToInsertInto = Preheader;
Dan Gohman02dea8b2008-05-23 21:05:58 +0000227 BasicBlock::iterator InsertPt = BlockToInsertInto->getFirstNonPHI();
Chris Lattner40bf8b42004-04-02 20:24:31 +0000228
Dan Gohman46bdfb02009-02-24 18:55:53 +0000229 bool HasConstantItCount = isa<SCEVConstant>(BackedgeTakenCount);
Chris Lattner20aa0982004-04-17 18:44:09 +0000230
Chris Lattner1a6111f2008-11-16 07:17:51 +0000231 SmallPtrSet<Instruction*, 16> InstructionsToDelete;
Chris Lattner9f3d7382007-03-04 03:43:23 +0000232 std::map<Instruction*, Value*> ExitValues;
Misha Brukmanfd939082005-04-21 23:48:37 +0000233
Chris Lattner9f3d7382007-03-04 03:43:23 +0000234 // Find all values that are computed inside the loop, but used outside of it.
235 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
236 // the exit blocks of the loop to find them.
237 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
238 BasicBlock *ExitBB = ExitBlocks[i];
Dan Gohmancafb8132009-02-17 19:13:57 +0000239
Chris Lattner9f3d7382007-03-04 03:43:23 +0000240 // If there are no PHI nodes in this exit block, then no values defined
241 // inside the loop are used on this path, skip it.
242 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
243 if (!PN) continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000244
Chris Lattner9f3d7382007-03-04 03:43:23 +0000245 unsigned NumPreds = PN->getNumIncomingValues();
Dan Gohmancafb8132009-02-17 19:13:57 +0000246
Chris Lattner9f3d7382007-03-04 03:43:23 +0000247 // Iterate over all of the PHI nodes.
248 BasicBlock::iterator BBI = ExitBB->begin();
249 while ((PN = dyn_cast<PHINode>(BBI++))) {
Dan Gohmancafb8132009-02-17 19:13:57 +0000250
Chris Lattner9f3d7382007-03-04 03:43:23 +0000251 // Iterate over all of the values in all the PHI nodes.
252 for (unsigned i = 0; i != NumPreds; ++i) {
253 // If the value being merged in is not integer or is not defined
254 // in the loop, skip it.
255 Value *InVal = PN->getIncomingValue(i);
256 if (!isa<Instruction>(InVal) ||
257 // SCEV only supports integer expressions for now.
Dan Gohman2d1be872009-04-16 03:18:22 +0000258 (!isa<IntegerType>(InVal->getType()) &&
259 !isa<PointerType>(InVal->getType())))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000260 continue;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000261
Chris Lattner9f3d7382007-03-04 03:43:23 +0000262 // If this pred is for a subloop, not L itself, skip it.
Dan Gohmancafb8132009-02-17 19:13:57 +0000263 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
Chris Lattner9f3d7382007-03-04 03:43:23 +0000264 continue; // The Block is in a subloop, skip it.
265
266 // Check that InVal is defined in the loop.
267 Instruction *Inst = cast<Instruction>(InVal);
268 if (!L->contains(Inst->getParent()))
269 continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000270
Chris Lattner9f3d7382007-03-04 03:43:23 +0000271 // We require that this value either have a computable evolution or that
272 // the loop have a constant iteration count. In the case where the loop
273 // has a constant iteration count, we can sometimes force evaluation of
274 // the exit value through brute force.
275 SCEVHandle SH = SE->getSCEV(Inst);
276 if (!SH->hasComputableLoopEvolution(L) && !HasConstantItCount)
277 continue; // Cannot get exit evolution for the loop value.
Dan Gohmancafb8132009-02-17 19:13:57 +0000278
Chris Lattner9f3d7382007-03-04 03:43:23 +0000279 // Okay, this instruction has a user outside of the current loop
280 // and varies predictably *inside* the loop. Evaluate the value it
281 // contains when the loop exits, if possible.
282 SCEVHandle ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
283 if (isa<SCEVCouldNotCompute>(ExitValue) ||
284 !ExitValue->isLoopInvariant(L))
285 continue;
Chris Lattner9caed542007-03-04 01:00:28 +0000286
Chris Lattner9f3d7382007-03-04 03:43:23 +0000287 Changed = true;
288 ++NumReplaced;
Dan Gohmancafb8132009-02-17 19:13:57 +0000289
Chris Lattner9f3d7382007-03-04 03:43:23 +0000290 // See if we already computed the exit value for the instruction, if so,
291 // just reuse it.
292 Value *&ExitVal = ExitValues[Inst];
293 if (!ExitVal)
Dan Gohman2d1be872009-04-16 03:18:22 +0000294 ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), InsertPt);
Dan Gohmancafb8132009-02-17 19:13:57 +0000295
Chris Lattner9f3d7382007-03-04 03:43:23 +0000296 DOUT << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal
297 << " LoopVal = " << *Inst << "\n";
298
299 PN->setIncomingValue(i, ExitVal);
Dan Gohmancafb8132009-02-17 19:13:57 +0000300
Chris Lattner9f3d7382007-03-04 03:43:23 +0000301 // If this instruction is dead now, schedule it to be removed.
302 if (Inst->use_empty())
303 InstructionsToDelete.insert(Inst);
Dan Gohmancafb8132009-02-17 19:13:57 +0000304
Chris Lattner9f3d7382007-03-04 03:43:23 +0000305 // See if this is a single-entry LCSSA PHI node. If so, we can (and
306 // have to) remove
Chris Lattner9caed542007-03-04 01:00:28 +0000307 // the PHI entirely. This is safe, because the NewVal won't be variant
308 // in the loop, so we don't need an LCSSA phi node anymore.
Chris Lattner9f3d7382007-03-04 03:43:23 +0000309 if (NumPreds == 1) {
310 PN->replaceAllUsesWith(ExitVal);
311 PN->eraseFromParent();
312 break;
Chris Lattnerc9838f22007-03-03 22:48:48 +0000313 }
314 }
Chris Lattnerc9838f22007-03-03 22:48:48 +0000315 }
316 }
Dan Gohmancafb8132009-02-17 19:13:57 +0000317
Chris Lattner40bf8b42004-04-02 20:24:31 +0000318 DeleteTriviallyDeadInstructions(InstructionsToDelete);
319}
320
Dan Gohman60f8a632009-02-17 20:49:49 +0000321void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000322 // First step. Check to see if there are any floating-point recurrences.
Chris Lattner40bf8b42004-04-02 20:24:31 +0000323 // If there are, change them into integer recurrences, permitting analysis by
324 // the SCEV routines.
325 //
326 BasicBlock *Header = L->getHeader();
Misha Brukmanfd939082005-04-21 23:48:37 +0000327
Chris Lattner1a6111f2008-11-16 07:17:51 +0000328 SmallPtrSet<Instruction*, 16> DeadInsts;
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000329 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
330 PHINode *PN = cast<PHINode>(I);
Dan Gohman2d1be872009-04-16 03:18:22 +0000331 HandleFloatingPointIV(L, PN, DeadInsts);
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000332 }
Chris Lattner40bf8b42004-04-02 20:24:31 +0000333
Dan Gohman2d1be872009-04-16 03:18:22 +0000334 // If the loop previously had floating-point IV, ScalarEvolution
Dan Gohman60f8a632009-02-17 20:49:49 +0000335 // may not have been able to compute a trip count. Now that we've done some
336 // re-writing, the trip count may be computable.
337 if (Changed)
Dan Gohman46bdfb02009-02-24 18:55:53 +0000338 SE->forgetLoopBackedgeTakenCount(L);
Dan Gohman60f8a632009-02-17 20:49:49 +0000339
Chris Lattner40bf8b42004-04-02 20:24:31 +0000340 if (!DeadInsts.empty())
341 DeleteTriviallyDeadInstructions(DeadInsts);
Devang Patel5ee99972007-03-07 06:39:01 +0000342}
Chris Lattner40bf8b42004-04-02 20:24:31 +0000343
Dan Gohmanc2390b12009-02-12 22:19:27 +0000344/// getEffectiveIndvarType - Determine the widest type that the
345/// induction-variable PHINode Phi is cast to.
346///
Dan Gohman2d1be872009-04-16 03:18:22 +0000347static const Type *getEffectiveIndvarType(const PHINode *Phi,
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000348 const ScalarEvolution *SE) {
Dan Gohmanc2390b12009-02-12 22:19:27 +0000349 const Type *Ty = Phi->getType();
Chris Lattner3324e712003-12-22 03:58:44 +0000350
Dan Gohmanc2390b12009-02-12 22:19:27 +0000351 for (Value::use_const_iterator UI = Phi->use_begin(), UE = Phi->use_end();
352 UI != UE; ++UI) {
353 const Type *CandidateType = NULL;
354 if (const ZExtInst *ZI = dyn_cast<ZExtInst>(UI))
355 CandidateType = ZI->getDestTy();
356 else if (const SExtInst *SI = dyn_cast<SExtInst>(UI))
357 CandidateType = SI->getDestTy();
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000358 else if (const IntToPtrInst *IP = dyn_cast<IntToPtrInst>(UI))
359 CandidateType = IP->getDestTy();
360 else if (const PtrToIntInst *PI = dyn_cast<PtrToIntInst>(UI))
361 CandidateType = PI->getDestTy();
Dan Gohmanc2390b12009-02-12 22:19:27 +0000362 if (CandidateType &&
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000363 SE->isSCEVable(CandidateType) &&
364 SE->getTypeSizeInBits(CandidateType) > SE->getTypeSizeInBits(Ty))
Dan Gohmanc2390b12009-02-12 22:19:27 +0000365 Ty = CandidateType;
366 }
367
368 return Ty;
369}
370
Dan Gohmand908adf2009-04-27 22:12:34 +0000371/// TestOrigIVForWrap - Analyze the original induction variable that
372/// controls the loop's iteration to determine whether it would ever
373/// undergo signed or unsigned overflow.
Dan Gohmand2067fd2009-02-18 00:52:00 +0000374///
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000375/// In addition to setting the NoSignedWrap and NoUnsignedWrap
376/// variables to true when appropriate (they are not set to false here),
377/// return the PHI for this induction variable. Also record the initial
378/// and final values and the increment; these are not meaningful unless
379/// either NoSignedWrap or NoUnsignedWrap is true, and are always meaningful
380/// in that case, although the final value may be 0 indicating a nonconstant.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000381///
382/// TODO: This duplicates a fair amount of ScalarEvolution logic.
Dan Gohman46bdfb02009-02-24 18:55:53 +0000383/// Perhaps this can be merged with
384/// ScalarEvolution::getBackedgeTakenCount
Dan Gohmanaa036492009-02-14 02:31:09 +0000385/// and/or ScalarEvolution::get{Sign,Zero}ExtendExpr.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000386///
Dan Gohmand2067fd2009-02-18 00:52:00 +0000387static const PHINode *TestOrigIVForWrap(const Loop *L,
388 const BranchInst *BI,
389 const Instruction *OrigCond,
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000390 const ScalarEvolution &SE,
Dan Gohmand2067fd2009-02-18 00:52:00 +0000391 bool &NoSignedWrap,
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000392 bool &NoUnsignedWrap,
393 const ConstantInt* &InitialVal,
394 const ConstantInt* &IncrVal,
395 const ConstantInt* &LimitVal) {
Dan Gohmanc2390b12009-02-12 22:19:27 +0000396 // Verify that the loop is sane and find the exit condition.
397 const ICmpInst *Cmp = dyn_cast<ICmpInst>(OrigCond);
Dan Gohmand2067fd2009-02-18 00:52:00 +0000398 if (!Cmp) return 0;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000399
Dan Gohmanaa036492009-02-14 02:31:09 +0000400 const Value *CmpLHS = Cmp->getOperand(0);
401 const Value *CmpRHS = Cmp->getOperand(1);
402 const BasicBlock *TrueBB = BI->getSuccessor(0);
403 const BasicBlock *FalseBB = BI->getSuccessor(1);
404 ICmpInst::Predicate Pred = Cmp->getPredicate();
Dan Gohmanc2390b12009-02-12 22:19:27 +0000405
Dan Gohmanaa036492009-02-14 02:31:09 +0000406 // Canonicalize a constant to the RHS.
407 if (isa<ConstantInt>(CmpLHS)) {
408 Pred = ICmpInst::getSwappedPredicate(Pred);
409 std::swap(CmpLHS, CmpRHS);
410 }
411 // Canonicalize SLE to SLT.
412 if (Pred == ICmpInst::ICMP_SLE)
413 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
414 if (!CI->getValue().isMaxSignedValue()) {
415 CmpRHS = ConstantInt::get(CI->getValue() + 1);
416 Pred = ICmpInst::ICMP_SLT;
417 }
418 // Canonicalize SGT to SGE.
419 if (Pred == ICmpInst::ICMP_SGT)
420 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
421 if (!CI->getValue().isMaxSignedValue()) {
422 CmpRHS = ConstantInt::get(CI->getValue() + 1);
423 Pred = ICmpInst::ICMP_SGE;
424 }
425 // Canonicalize SGE to SLT.
426 if (Pred == ICmpInst::ICMP_SGE) {
427 std::swap(TrueBB, FalseBB);
428 Pred = ICmpInst::ICMP_SLT;
429 }
430 // Canonicalize ULE to ULT.
431 if (Pred == ICmpInst::ICMP_ULE)
432 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
433 if (!CI->getValue().isMaxValue()) {
434 CmpRHS = ConstantInt::get(CI->getValue() + 1);
435 Pred = ICmpInst::ICMP_ULT;
436 }
437 // Canonicalize UGT to UGE.
438 if (Pred == ICmpInst::ICMP_UGT)
439 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
440 if (!CI->getValue().isMaxValue()) {
441 CmpRHS = ConstantInt::get(CI->getValue() + 1);
442 Pred = ICmpInst::ICMP_UGE;
443 }
444 // Canonicalize UGE to ULT.
445 if (Pred == ICmpInst::ICMP_UGE) {
446 std::swap(TrueBB, FalseBB);
447 Pred = ICmpInst::ICMP_ULT;
448 }
449 // For now, analyze only LT loops for signed overflow.
450 if (Pred != ICmpInst::ICMP_SLT && Pred != ICmpInst::ICMP_ULT)
Dan Gohmand2067fd2009-02-18 00:52:00 +0000451 return 0;
Dan Gohmanaa036492009-02-14 02:31:09 +0000452
453 bool isSigned = Pred == ICmpInst::ICMP_SLT;
454
455 // Get the increment instruction. Look past casts if we will
Dan Gohmanc2390b12009-02-12 22:19:27 +0000456 // be able to prove that the original induction variable doesn't
Dan Gohmanaa036492009-02-14 02:31:09 +0000457 // undergo signed or unsigned overflow, respectively.
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000458 const Value *IncrInst = CmpLHS;
Dan Gohmanaa036492009-02-14 02:31:09 +0000459 if (isSigned) {
460 if (const SExtInst *SI = dyn_cast<SExtInst>(CmpLHS)) {
461 if (!isa<ConstantInt>(CmpRHS) ||
462 !cast<ConstantInt>(CmpRHS)->getValue()
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000463 .isSignedIntN(SE.getTypeSizeInBits(IncrInst->getType())))
Dan Gohmand2067fd2009-02-18 00:52:00 +0000464 return 0;
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000465 IncrInst = SI->getOperand(0);
Dan Gohmanaa036492009-02-14 02:31:09 +0000466 }
467 } else {
468 if (const ZExtInst *ZI = dyn_cast<ZExtInst>(CmpLHS)) {
469 if (!isa<ConstantInt>(CmpRHS) ||
470 !cast<ConstantInt>(CmpRHS)->getValue()
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000471 .isIntN(SE.getTypeSizeInBits(IncrInst->getType())))
Dan Gohmand2067fd2009-02-18 00:52:00 +0000472 return 0;
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000473 IncrInst = ZI->getOperand(0);
Dan Gohmanaa036492009-02-14 02:31:09 +0000474 }
Dan Gohmanc2390b12009-02-12 22:19:27 +0000475 }
476
477 // For now, only analyze induction variables that have simple increments.
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000478 const BinaryOperator *IncrOp = dyn_cast<BinaryOperator>(IncrInst);
479 if (!IncrOp || IncrOp->getOpcode() != Instruction::Add)
480 return 0;
481 IncrVal = dyn_cast<ConstantInt>(IncrOp->getOperand(1));
482 if (!IncrVal)
Dan Gohmand2067fd2009-02-18 00:52:00 +0000483 return 0;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000484
485 // Make sure the PHI looks like a normal IV.
486 const PHINode *PN = dyn_cast<PHINode>(IncrOp->getOperand(0));
487 if (!PN || PN->getNumIncomingValues() != 2)
Dan Gohmand2067fd2009-02-18 00:52:00 +0000488 return 0;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000489 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
490 unsigned BackEdge = !IncomingEdge;
491 if (!L->contains(PN->getIncomingBlock(BackEdge)) ||
492 PN->getIncomingValue(BackEdge) != IncrOp)
Dan Gohmand2067fd2009-02-18 00:52:00 +0000493 return 0;
Dan Gohmanaa036492009-02-14 02:31:09 +0000494 if (!L->contains(TrueBB))
Dan Gohmand2067fd2009-02-18 00:52:00 +0000495 return 0;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000496
497 // For now, only analyze loops with a constant start value, so that
Dan Gohmanaa036492009-02-14 02:31:09 +0000498 // we can easily determine if the start value is not a maximum value
499 // which would wrap on the first iteration.
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000500 InitialVal = dyn_cast<ConstantInt>(PN->getIncomingValue(IncomingEdge));
Dan Gohmancad24c92009-02-18 16:54:33 +0000501 if (!InitialVal)
Dan Gohmand2067fd2009-02-18 00:52:00 +0000502 return 0;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000503
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000504 // The upper limit need not be a constant; we'll check later.
505 LimitVal = dyn_cast<ConstantInt>(CmpRHS);
506
507 // We detect the impossibility of wrapping in two cases, both of
508 // which require starting with a non-max value:
509 // - The IV counts up by one, and the loop iterates only while it remains
510 // less than a limiting value (any) in the same type.
511 // - The IV counts up by a positive increment other than 1, and the
512 // constant limiting value + the increment is less than the max value
513 // (computed as max-increment to avoid overflow)
Dan Gohmanf5a309e2009-02-18 17:22:41 +0000514 if (isSigned && !InitialVal->getValue().isMaxSignedValue()) {
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000515 if (IncrVal->equalsInt(1))
516 NoSignedWrap = true; // LimitVal need not be constant
517 else if (LimitVal) {
518 uint64_t numBits = LimitVal->getValue().getBitWidth();
519 if (IncrVal->getValue().sgt(APInt::getNullValue(numBits)) &&
520 (APInt::getSignedMaxValue(numBits) - IncrVal->getValue())
521 .sgt(LimitVal->getValue()))
522 NoSignedWrap = true;
523 }
524 } else if (!isSigned && !InitialVal->getValue().isMaxValue()) {
525 if (IncrVal->equalsInt(1))
526 NoUnsignedWrap = true; // LimitVal need not be constant
527 else if (LimitVal) {
528 uint64_t numBits = LimitVal->getValue().getBitWidth();
529 if (IncrVal->getValue().ugt(APInt::getNullValue(numBits)) &&
530 (APInt::getMaxValue(numBits) - IncrVal->getValue())
531 .ugt(LimitVal->getValue()))
532 NoUnsignedWrap = true;
533 }
534 }
Dan Gohmand2067fd2009-02-18 00:52:00 +0000535 return PN;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000536}
537
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000538static Value *getSignExtendedTruncVar(const SCEVAddRecExpr *AR,
539 ScalarEvolution *SE,
540 const Type *LargestType, Loop *L,
541 const Type *myType,
Dan Gohman752ec7d2009-04-23 15:16:49 +0000542 SCEVExpander &Rewriter) {
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000543 SCEVHandle ExtendedStart =
544 SE->getSignExtendExpr(AR->getStart(), LargestType);
545 SCEVHandle ExtendedStep =
546 SE->getSignExtendExpr(AR->getStepRecurrence(*SE), LargestType);
547 SCEVHandle ExtendedAddRec =
548 SE->getAddRecExpr(ExtendedStart, ExtendedStep, L);
549 if (LargestType != myType)
550 ExtendedAddRec = SE->getTruncateExpr(ExtendedAddRec, myType);
Dan Gohman752ec7d2009-04-23 15:16:49 +0000551 return Rewriter.expandCodeFor(ExtendedAddRec, myType);
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000552}
553
554static Value *getZeroExtendedTruncVar(const SCEVAddRecExpr *AR,
555 ScalarEvolution *SE,
556 const Type *LargestType, Loop *L,
557 const Type *myType,
Dan Gohman752ec7d2009-04-23 15:16:49 +0000558 SCEVExpander &Rewriter) {
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000559 SCEVHandle ExtendedStart =
560 SE->getZeroExtendExpr(AR->getStart(), LargestType);
561 SCEVHandle ExtendedStep =
562 SE->getZeroExtendExpr(AR->getStepRecurrence(*SE), LargestType);
563 SCEVHandle ExtendedAddRec =
564 SE->getAddRecExpr(ExtendedStart, ExtendedStep, L);
565 if (LargestType != myType)
566 ExtendedAddRec = SE->getTruncateExpr(ExtendedAddRec, myType);
Dan Gohman752ec7d2009-04-23 15:16:49 +0000567 return Rewriter.expandCodeFor(ExtendedAddRec, myType);
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000568}
569
Dale Johannesenc671d892009-04-15 23:31:51 +0000570/// allUsesAreSameTyped - See whether all Uses of I are instructions
571/// with the same Opcode and the same type.
572static bool allUsesAreSameTyped(unsigned int Opcode, Instruction *I) {
573 const Type* firstType = NULL;
574 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
575 UI != UE; ++UI) {
576 Instruction *II = dyn_cast<Instruction>(*UI);
577 if (!II || II->getOpcode() != Opcode)
578 return false;
579 if (!firstType)
580 firstType = II->getType();
581 else if (firstType != II->getType())
582 return false;
583 }
584 return true;
585}
586
Dan Gohmanc2390b12009-02-12 22:19:27 +0000587bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
Devang Patel5ee99972007-03-07 06:39:01 +0000588 LI = &getAnalysis<LoopInfo>();
589 SE = &getAnalysis<ScalarEvolution>();
Devang Patel5ee99972007-03-07 06:39:01 +0000590 Changed = false;
Dan Gohman60f8a632009-02-17 20:49:49 +0000591
Dan Gohman2d1be872009-04-16 03:18:22 +0000592 // If there are any floating-point recurrences, attempt to
Dan Gohman60f8a632009-02-17 20:49:49 +0000593 // transform them to use integer recurrences.
594 RewriteNonIntegerIVs(L);
595
Dan Gohmanc2390b12009-02-12 22:19:27 +0000596 BasicBlock *Header = L->getHeader();
597 BasicBlock *ExitingBlock = L->getExitingBlock();
Chris Lattner1a6111f2008-11-16 07:17:51 +0000598 SmallPtrSet<Instruction*, 16> DeadInsts;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000599
Chris Lattner9caed542007-03-04 01:00:28 +0000600 // Verify the input to the pass in already in LCSSA form.
601 assert(L->isLCSSAForm());
602
Chris Lattner40bf8b42004-04-02 20:24:31 +0000603 // Check to see if this loop has a computable loop-invariant execution count.
604 // If so, this means that we can compute the final value of any expressions
605 // that are recurrent in the loop, and substitute the exit values from the
606 // loop into any instructions outside of the loop that use the final values of
607 // the current expressions.
Chris Lattner3dec1f22002-05-10 15:38:35 +0000608 //
Dan Gohman46bdfb02009-02-24 18:55:53 +0000609 SCEVHandle BackedgeTakenCount = SE->getBackedgeTakenCount(L);
610 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount))
611 RewriteLoopExitValues(L, BackedgeTakenCount);
Chris Lattner6148c022001-12-03 17:28:42 +0000612
Chris Lattner40bf8b42004-04-02 20:24:31 +0000613 // Next, analyze all of the induction variables in the loop, canonicalizing
614 // auxillary induction variables.
615 std::vector<std::pair<PHINode*, SCEVHandle> > IndVars;
616
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000617 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
618 PHINode *PN = cast<PHINode>(I);
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000619 if (SE->isSCEVable(PN->getType())) {
Chris Lattner40bf8b42004-04-02 20:24:31 +0000620 SCEVHandle SCEV = SE->getSCEV(PN);
Dan Gohmancd3eb9b2009-02-14 02:25:19 +0000621 // FIXME: It is an extremely bad idea to indvar substitute anything more
622 // complex than affine induction variables. Doing so will put expensive
623 // polynomial evaluations inside of the loop, and the str reduction pass
624 // currently can only reduce affine polynomials. For now just disable
625 // indvar subst on anything more complex than an affine addrec.
Dan Gohman890f92b2009-04-18 17:56:28 +0000626 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SCEV))
Dan Gohmancd3eb9b2009-02-14 02:25:19 +0000627 if (AR->getLoop() == L && AR->isAffine())
628 IndVars.push_back(std::make_pair(PN, SCEV));
Chris Lattner40bf8b42004-04-02 20:24:31 +0000629 }
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000630 }
Chris Lattner40bf8b42004-04-02 20:24:31 +0000631
Dan Gohmanc2390b12009-02-12 22:19:27 +0000632 // Compute the type of the largest recurrence expression, and collect
633 // the set of the types of the other recurrence expressions.
634 const Type *LargestType = 0;
635 SmallSetVector<const Type *, 4> SizesToInsert;
Dan Gohman46bdfb02009-02-24 18:55:53 +0000636 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
637 LargestType = BackedgeTakenCount->getType();
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000638 LargestType = SE->getEffectiveSCEVType(LargestType);
Dan Gohman2d1be872009-04-16 03:18:22 +0000639 SizesToInsert.insert(LargestType);
Chris Lattnerf50af082004-04-17 18:08:33 +0000640 }
Dan Gohmanc2390b12009-02-12 22:19:27 +0000641 for (unsigned i = 0, e = IndVars.size(); i != e; ++i) {
642 const PHINode *PN = IndVars[i].first;
Dan Gohman2d1be872009-04-16 03:18:22 +0000643 const Type *PNTy = PN->getType();
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000644 PNTy = SE->getEffectiveSCEVType(PNTy);
Dan Gohman2d1be872009-04-16 03:18:22 +0000645 SizesToInsert.insert(PNTy);
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000646 const Type *EffTy = getEffectiveIndvarType(PN, SE);
647 EffTy = SE->getEffectiveSCEVType(EffTy);
Dan Gohmanc2390b12009-02-12 22:19:27 +0000648 SizesToInsert.insert(EffTy);
649 if (!LargestType ||
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000650 SE->getTypeSizeInBits(EffTy) >
651 SE->getTypeSizeInBits(LargestType))
Dan Gohmanc2390b12009-02-12 22:19:27 +0000652 LargestType = EffTy;
Chris Lattner6148c022001-12-03 17:28:42 +0000653 }
654
Chris Lattner40bf8b42004-04-02 20:24:31 +0000655 // Create a rewriter object which we'll use to transform the code with.
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000656 SCEVExpander Rewriter(*SE, *LI);
Chris Lattner15cad752003-12-23 07:47:09 +0000657
Chris Lattner40bf8b42004-04-02 20:24:31 +0000658 // Now that we know the largest of of the induction variables in this loop,
659 // insert a canonical induction variable of the largest size.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000660 Value *IndVar = 0;
661 if (!SizesToInsert.empty()) {
662 IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L,LargestType);
663 ++NumInserted;
664 Changed = true;
665 DOUT << "INDVARS: New CanIV: " << *IndVar;
Dan Gohmand19534a2007-06-15 14:38:12 +0000666 }
Chris Lattner15cad752003-12-23 07:47:09 +0000667
Dan Gohmanc2390b12009-02-12 22:19:27 +0000668 // If we have a trip count expression, rewrite the loop's exit condition
669 // using it. We can currently only handle loops with a single exit.
Dan Gohmanaa036492009-02-14 02:31:09 +0000670 bool NoSignedWrap = false;
671 bool NoUnsignedWrap = false;
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000672 const ConstantInt* InitialVal, * IncrVal, * LimitVal;
Dan Gohmand2067fd2009-02-18 00:52:00 +0000673 const PHINode *OrigControllingPHI = 0;
Dan Gohman46bdfb02009-02-24 18:55:53 +0000674 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) && ExitingBlock)
Dan Gohmanc2390b12009-02-12 22:19:27 +0000675 // Can't rewrite non-branch yet.
676 if (BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator())) {
677 if (Instruction *OrigCond = dyn_cast<Instruction>(BI->getCondition())) {
Dan Gohmanaa036492009-02-14 02:31:09 +0000678 // Determine if the OrigIV will ever undergo overflow.
Dan Gohmand2067fd2009-02-18 00:52:00 +0000679 OrigControllingPHI =
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000680 TestOrigIVForWrap(L, BI, OrigCond, *SE,
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000681 NoSignedWrap, NoUnsignedWrap,
682 InitialVal, IncrVal, LimitVal);
Dan Gohmanc2390b12009-02-12 22:19:27 +0000683
684 // We'll be replacing the original condition, so it'll be dead.
685 DeadInsts.insert(OrigCond);
686 }
687
Dan Gohman46bdfb02009-02-24 18:55:53 +0000688 LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar,
Dan Gohman15cab282009-02-23 23:20:35 +0000689 ExitingBlock, BI, Rewriter);
Dan Gohmanc2390b12009-02-12 22:19:27 +0000690 }
691
Chris Lattner40bf8b42004-04-02 20:24:31 +0000692 // Now that we have a canonical induction variable, we can rewrite any
693 // recurrences in terms of the induction variable. Start with the auxillary
694 // induction variables, and recursively rewrite any of their uses.
Dan Gohman02dea8b2008-05-23 21:05:58 +0000695 BasicBlock::iterator InsertPt = Header->getFirstNonPHI();
Dan Gohman752ec7d2009-04-23 15:16:49 +0000696 Rewriter.setInsertionPoint(InsertPt);
Chris Lattner6148c022001-12-03 17:28:42 +0000697
Chris Lattner5d461d22004-04-21 22:22:01 +0000698 // If there were induction variables of other sizes, cast the primary
699 // induction variable to the right size for them, avoiding the need for the
700 // code evaluation methods to insert induction variables of different sizes.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000701 for (unsigned i = 0, e = SizesToInsert.size(); i != e; ++i) {
702 const Type *Ty = SizesToInsert[i];
703 if (Ty != LargestType) {
704 Instruction *New = new TruncInst(IndVar, Ty, "indvar", InsertPt);
705 Rewriter.addInsertedValue(New, SE->getSCEV(New));
706 DOUT << "INDVARS: Made trunc IV for type " << *Ty << ": "
707 << *New << "\n";
Reid Spencera54b7cb2007-01-12 07:05:14 +0000708 }
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000709 }
710
Chris Lattneree4f13a2007-01-07 01:14:12 +0000711 // Rewrite all induction variables in terms of the canonical induction
712 // variable.
Chris Lattner40bf8b42004-04-02 20:24:31 +0000713 while (!IndVars.empty()) {
714 PHINode *PN = IndVars.back().first;
Dan Gohman890f92b2009-04-18 17:56:28 +0000715 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(IndVars.back().second);
Dan Gohman752ec7d2009-04-23 15:16:49 +0000716 Value *NewVal = Rewriter.expandCodeFor(AR, PN->getType());
Dan Gohman1a5e9362009-02-17 00:10:53 +0000717 DOUT << "INDVARS: Rewrote IV '" << *AR << "' " << *PN
Chris Lattneree4f13a2007-01-07 01:14:12 +0000718 << " into = " << *NewVal << "\n";
Chris Lattner6934a042007-02-11 01:23:03 +0000719 NewVal->takeName(PN);
Chris Lattner5d461d22004-04-21 22:22:01 +0000720
Dan Gohmanc2390b12009-02-12 22:19:27 +0000721 /// If the new canonical induction variable is wider than the original,
722 /// and the original has uses that are casts to wider types, see if the
723 /// truncate and extend can be omitted.
Dan Gohmand2067fd2009-02-18 00:52:00 +0000724 if (PN == OrigControllingPHI && PN->getType() != LargestType)
Dan Gohmanc2390b12009-02-12 22:19:27 +0000725 for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end();
Dan Gohmanaa036492009-02-14 02:31:09 +0000726 UI != UE; ++UI) {
Dale Johannesend3325d282009-04-15 20:41:02 +0000727 Instruction *UInst = dyn_cast<Instruction>(*UI);
728 if (UInst && isa<SExtInst>(UInst) && NoSignedWrap) {
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000729 Value *TruncIndVar = getSignExtendedTruncVar(AR, SE, LargestType, L,
Dan Gohman752ec7d2009-04-23 15:16:49 +0000730 UInst->getType(), Rewriter);
Dale Johannesend3325d282009-04-15 20:41:02 +0000731 UInst->replaceAllUsesWith(TruncIndVar);
732 DeadInsts.insert(UInst);
Dan Gohmanc2390b12009-02-12 22:19:27 +0000733 }
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000734 // See if we can figure out sext(i+constant) doesn't wrap, so we can
735 // use a larger add. This is common in subscripting.
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000736 if (UInst && UInst->getOpcode()==Instruction::Add &&
Evan Chenga8d4d7f2009-04-22 23:09:16 +0000737 !UInst->use_empty() &&
Dale Johannesenc671d892009-04-15 23:31:51 +0000738 allUsesAreSameTyped(Instruction::SExt, UInst) &&
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000739 isa<ConstantInt>(UInst->getOperand(1)) &&
Dale Johannesend3325d282009-04-15 20:41:02 +0000740 NoSignedWrap && LimitVal) {
741 uint64_t oldBitSize = LimitVal->getValue().getBitWidth();
742 uint64_t newBitSize = LargestType->getPrimitiveSizeInBits();
743 ConstantInt* AddRHS = dyn_cast<ConstantInt>(UInst->getOperand(1));
744 if (((APInt::getSignedMaxValue(oldBitSize) - IncrVal->getValue()) -
745 AddRHS->getValue()).sgt(LimitVal->getValue())) {
746 // We've determined this is (i+constant) and it won't overflow.
747 if (isa<SExtInst>(UInst->use_begin())) {
748 SExtInst* oldSext = dyn_cast<SExtInst>(UInst->use_begin());
Evan Cheng9c159492009-04-22 23:39:28 +0000749 uint64_t truncSize = oldSext->getType()->getPrimitiveSizeInBits();
Dale Johannesend3325d282009-04-15 20:41:02 +0000750 Value *TruncIndVar = getSignExtendedTruncVar(AR, SE, LargestType,
Dan Gohman752ec7d2009-04-23 15:16:49 +0000751 L, oldSext->getType(), Rewriter);
Evan Cheng9c159492009-04-22 23:39:28 +0000752 APInt APnewAddRHS = APInt(AddRHS->getValue()).sext(newBitSize);
753 if (newBitSize > truncSize)
754 APnewAddRHS = APnewAddRHS.trunc(truncSize);
755 ConstantInt* newAddRHS =ConstantInt::get(APnewAddRHS);
Dale Johannesend3325d282009-04-15 20:41:02 +0000756 Value *NewAdd =
757 BinaryOperator::CreateAdd(TruncIndVar, newAddRHS,
758 UInst->getName()+".nosex", UInst);
Dale Johannesenc671d892009-04-15 23:31:51 +0000759 for (Value::use_iterator UI2 = UInst->use_begin(),
760 UE2 = UInst->use_end(); UI2 != UE2; ++UI2) {
761 Instruction *II = dyn_cast<Instruction>(UI2);
762 II->replaceAllUsesWith(NewAdd);
763 DeadInsts.insert(II);
764 }
Dale Johannesend3325d282009-04-15 20:41:02 +0000765 DeadInsts.insert(UInst);
766 }
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000767 }
768 }
Dale Johannesenc671d892009-04-15 23:31:51 +0000769 // Try for sext(i | constant). This is safe as long as the
770 // high bit of the constant is not set.
771 if (UInst && UInst->getOpcode()==Instruction::Or &&
Evan Chenga8d4d7f2009-04-22 23:09:16 +0000772 !UInst->use_empty() &&
Dale Johannesenc671d892009-04-15 23:31:51 +0000773 allUsesAreSameTyped(Instruction::SExt, UInst) && NoSignedWrap &&
774 isa<ConstantInt>(UInst->getOperand(1))) {
775 ConstantInt* RHS = dyn_cast<ConstantInt>(UInst->getOperand(1));
776 if (!RHS->getValue().isNegative()) {
777 uint64_t newBitSize = LargestType->getPrimitiveSizeInBits();
778 SExtInst* oldSext = dyn_cast<SExtInst>(UInst->use_begin());
Evan Cheng9c159492009-04-22 23:39:28 +0000779 uint64_t truncSize = oldSext->getType()->getPrimitiveSizeInBits();
Dale Johannesenc671d892009-04-15 23:31:51 +0000780 Value *TruncIndVar = getSignExtendedTruncVar(AR, SE, LargestType,
Dan Gohman752ec7d2009-04-23 15:16:49 +0000781 L, oldSext->getType(), Rewriter);
Evan Cheng9c159492009-04-22 23:39:28 +0000782 APInt APnewOrRHS = APInt(RHS->getValue()).sext(newBitSize);
783 if (newBitSize > truncSize)
784 APnewOrRHS = APnewOrRHS.trunc(truncSize);
785 ConstantInt* newOrRHS =ConstantInt::get(APnewOrRHS);
786 Value *NewOr =
787 BinaryOperator::CreateOr(TruncIndVar, newOrRHS,
Dale Johannesenc671d892009-04-15 23:31:51 +0000788 UInst->getName()+".nosex", UInst);
789 for (Value::use_iterator UI2 = UInst->use_begin(),
790 UE2 = UInst->use_end(); UI2 != UE2; ++UI2) {
791 Instruction *II = dyn_cast<Instruction>(UI2);
Evan Cheng9c159492009-04-22 23:39:28 +0000792 II->replaceAllUsesWith(NewOr);
Dale Johannesenc671d892009-04-15 23:31:51 +0000793 DeadInsts.insert(II);
794 }
795 DeadInsts.insert(UInst);
796 }
797 }
798 // A zext of a signed variable known not to overflow is still safe.
799 if (UInst && isa<ZExtInst>(UInst) && (NoUnsignedWrap || NoSignedWrap)) {
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000800 Value *TruncIndVar = getZeroExtendedTruncVar(AR, SE, LargestType, L,
Dan Gohman752ec7d2009-04-23 15:16:49 +0000801 UInst->getType(), Rewriter);
Dale Johannesend3325d282009-04-15 20:41:02 +0000802 UInst->replaceAllUsesWith(TruncIndVar);
803 DeadInsts.insert(UInst);
804 }
Dale Johannesenc671d892009-04-15 23:31:51 +0000805 // If we have zext(i&constant), it's always safe to use the larger
806 // variable. This is not common but is a bottleneck in Openssl.
Dale Johannesend3325d282009-04-15 20:41:02 +0000807 // (RHS doesn't have to be constant. There should be a better approach
808 // than bottom-up pattern matching for this...)
809 if (UInst && UInst->getOpcode()==Instruction::And &&
Evan Cheng1abe6462009-04-22 22:45:37 +0000810 !UInst->use_empty() &&
Dale Johannesenc671d892009-04-15 23:31:51 +0000811 allUsesAreSameTyped(Instruction::ZExt, UInst) &&
812 isa<ConstantInt>(UInst->getOperand(1))) {
Dale Johannesend3325d282009-04-15 20:41:02 +0000813 uint64_t newBitSize = LargestType->getPrimitiveSizeInBits();
814 ConstantInt* AndRHS = dyn_cast<ConstantInt>(UInst->getOperand(1));
815 ZExtInst* oldZext = dyn_cast<ZExtInst>(UInst->use_begin());
Evan Cheng9c159492009-04-22 23:39:28 +0000816 uint64_t truncSize = oldZext->getType()->getPrimitiveSizeInBits();
Dale Johannesend3325d282009-04-15 20:41:02 +0000817 Value *TruncIndVar = getSignExtendedTruncVar(AR, SE, LargestType,
Dan Gohman752ec7d2009-04-23 15:16:49 +0000818 L, oldZext->getType(), Rewriter);
Evan Cheng9c159492009-04-22 23:39:28 +0000819 APInt APnewAndRHS = APInt(AndRHS->getValue()).zext(newBitSize);
820 if (newBitSize > truncSize)
821 APnewAndRHS = APnewAndRHS.trunc(truncSize);
822 ConstantInt* newAndRHS = ConstantInt::get(APnewAndRHS);
Dale Johannesend3325d282009-04-15 20:41:02 +0000823 Value *NewAnd =
824 BinaryOperator::CreateAnd(TruncIndVar, newAndRHS,
825 UInst->getName()+".nozex", UInst);
Dale Johannesenc671d892009-04-15 23:31:51 +0000826 for (Value::use_iterator UI2 = UInst->use_begin(),
827 UE2 = UInst->use_end(); UI2 != UE2; ++UI2) {
828 Instruction *II = dyn_cast<Instruction>(UI2);
829 II->replaceAllUsesWith(NewAnd);
830 DeadInsts.insert(II);
831 }
Dale Johannesend3325d282009-04-15 20:41:02 +0000832 DeadInsts.insert(UInst);
833 }
834 // If we have zext((i+constant)&constant), we can use the larger
835 // variable even if the add does overflow. This works whenever the
836 // constant being ANDed is the same size as i, which it presumably is.
837 // We don't need to restrict the expression being and'ed to i+const,
838 // but we have to promote everything in it, so it's convenient.
Dale Johannesenc671d892009-04-15 23:31:51 +0000839 // zext((i | constant)&constant) is also valid and accepted here.
840 if (UInst && (UInst->getOpcode()==Instruction::Add ||
841 UInst->getOpcode()==Instruction::Or) &&
Dale Johannesend3325d282009-04-15 20:41:02 +0000842 UInst->hasOneUse() &&
843 isa<ConstantInt>(UInst->getOperand(1))) {
844 uint64_t newBitSize = LargestType->getPrimitiveSizeInBits();
845 ConstantInt* AddRHS = dyn_cast<ConstantInt>(UInst->getOperand(1));
846 Instruction *UInst2 = dyn_cast<Instruction>(UInst->use_begin());
847 if (UInst2 && UInst2->getOpcode() == Instruction::And &&
Evan Chenga8d4d7f2009-04-22 23:09:16 +0000848 !UInst2->use_empty() &&
Dale Johannesenc671d892009-04-15 23:31:51 +0000849 allUsesAreSameTyped(Instruction::ZExt, UInst2) &&
850 isa<ConstantInt>(UInst2->getOperand(1))) {
Dale Johannesend3325d282009-04-15 20:41:02 +0000851 ZExtInst* oldZext = dyn_cast<ZExtInst>(UInst2->use_begin());
Evan Cheng9c159492009-04-22 23:39:28 +0000852 uint64_t truncSize = oldZext->getType()->getPrimitiveSizeInBits();
Dale Johannesend3325d282009-04-15 20:41:02 +0000853 Value *TruncIndVar = getSignExtendedTruncVar(AR, SE, LargestType,
Dan Gohman752ec7d2009-04-23 15:16:49 +0000854 L, oldZext->getType(), Rewriter);
Dale Johannesend3325d282009-04-15 20:41:02 +0000855 ConstantInt* AndRHS = dyn_cast<ConstantInt>(UInst2->getOperand(1));
Evan Cheng9c159492009-04-22 23:39:28 +0000856 APInt APnewAddRHS = APInt(AddRHS->getValue()).zext(newBitSize);
857 if (newBitSize > truncSize)
858 APnewAddRHS = APnewAddRHS.trunc(truncSize);
859 ConstantInt* newAddRHS = ConstantInt::get(APnewAddRHS);
Dale Johannesenc671d892009-04-15 23:31:51 +0000860 Value *NewAdd = ((UInst->getOpcode()==Instruction::Add) ?
Dale Johannesend3325d282009-04-15 20:41:02 +0000861 BinaryOperator::CreateAdd(TruncIndVar, newAddRHS,
Dale Johannesenc671d892009-04-15 23:31:51 +0000862 UInst->getName()+".nozex", UInst2) :
863 BinaryOperator::CreateOr(TruncIndVar, newAddRHS,
864 UInst->getName()+".nozex", UInst2));
Dale Johannesend3325d282009-04-15 20:41:02 +0000865 APInt APcopy2 = APInt(AndRHS->getValue());
866 ConstantInt* newAndRHS = ConstantInt::get(APcopy2.zext(newBitSize));
867 Value *NewAnd =
868 BinaryOperator::CreateAnd(NewAdd, newAndRHS,
869 UInst->getName()+".nozex", UInst2);
Dale Johannesenc671d892009-04-15 23:31:51 +0000870 for (Value::use_iterator UI2 = UInst2->use_begin(),
871 UE2 = UInst2->use_end(); UI2 != UE2; ++UI2) {
872 Instruction *II = dyn_cast<Instruction>(UI2);
873 II->replaceAllUsesWith(NewAnd);
874 DeadInsts.insert(II);
875 }
Dale Johannesend3325d282009-04-15 20:41:02 +0000876 DeadInsts.insert(UInst);
877 DeadInsts.insert(UInst2);
878 }
Dan Gohmanaa036492009-02-14 02:31:09 +0000879 }
880 }
Dan Gohmanc2390b12009-02-12 22:19:27 +0000881
Chris Lattner40bf8b42004-04-02 20:24:31 +0000882 // Replace the old PHI Node with the inserted computation.
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000883 PN->replaceAllUsesWith(NewVal);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000884 DeadInsts.insert(PN);
885 IndVars.pop_back();
886 ++NumRemoved;
Chris Lattner4753bf22001-12-05 19:41:33 +0000887 Changed = true;
Chris Lattner394437f2001-12-04 04:32:29 +0000888 }
889
Chris Lattner1363e852004-04-21 23:36:08 +0000890 DeleteTriviallyDeadInstructions(DeadInsts);
Chris Lattner9caed542007-03-04 01:00:28 +0000891 assert(L->isLCSSAForm());
Devang Patel5ee99972007-03-07 06:39:01 +0000892 return Changed;
Chris Lattner6148c022001-12-03 17:28:42 +0000893}
Devang Pateld22a8492008-09-09 21:41:07 +0000894
Devang Patel13877bf2008-11-18 00:40:02 +0000895/// Return true if it is OK to use SIToFPInst for an inducation variable
896/// with given inital and exit values.
897static bool useSIToFPInst(ConstantFP &InitV, ConstantFP &ExitV,
898 uint64_t intIV, uint64_t intEV) {
899
Dan Gohmancafb8132009-02-17 19:13:57 +0000900 if (InitV.getValueAPF().isNegative() || ExitV.getValueAPF().isNegative())
Devang Patel13877bf2008-11-18 00:40:02 +0000901 return true;
902
903 // If the iteration range can be handled by SIToFPInst then use it.
904 APInt Max = APInt::getSignedMaxValue(32);
Bill Wendling9bef7062008-11-18 10:57:27 +0000905 if (Max.getZExtValue() > static_cast<uint64_t>(abs(intEV - intIV)))
Devang Patel13877bf2008-11-18 00:40:02 +0000906 return true;
Dan Gohmancafb8132009-02-17 19:13:57 +0000907
Devang Patel13877bf2008-11-18 00:40:02 +0000908 return false;
909}
910
911/// convertToInt - Convert APF to an integer, if possible.
Devang Patelcd402332008-11-17 23:27:13 +0000912static bool convertToInt(const APFloat &APF, uint64_t *intVal) {
913
914 bool isExact = false;
Evan Cheng794a7db2008-11-26 01:11:57 +0000915 if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
916 return false;
Dan Gohmancafb8132009-02-17 19:13:57 +0000917 if (APF.convertToInteger(intVal, 32, APF.isNegative(),
Devang Patelcd402332008-11-17 23:27:13 +0000918 APFloat::rmTowardZero, &isExact)
919 != APFloat::opOK)
920 return false;
Dan Gohmancafb8132009-02-17 19:13:57 +0000921 if (!isExact)
Devang Patelcd402332008-11-17 23:27:13 +0000922 return false;
923 return true;
924
925}
926
Devang Patel58d43d42008-11-03 18:32:19 +0000927/// HandleFloatingPointIV - If the loop has floating induction variable
928/// then insert corresponding integer induction variable if possible.
Devang Patel84e35152008-11-17 21:32:02 +0000929/// For example,
930/// for(double i = 0; i < 10000; ++i)
931/// bar(i)
932/// is converted into
933/// for(int i = 0; i < 10000; ++i)
934/// bar((double)i);
935///
Dan Gohmancafb8132009-02-17 19:13:57 +0000936void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PH,
Devang Patel84e35152008-11-17 21:32:02 +0000937 SmallPtrSet<Instruction*, 16> &DeadInsts) {
Devang Patel58d43d42008-11-03 18:32:19 +0000938
Devang Patel84e35152008-11-17 21:32:02 +0000939 unsigned IncomingEdge = L->contains(PH->getIncomingBlock(0));
940 unsigned BackEdge = IncomingEdge^1;
Dan Gohmancafb8132009-02-17 19:13:57 +0000941
Devang Patel84e35152008-11-17 21:32:02 +0000942 // Check incoming value.
Devang Patelcd402332008-11-17 23:27:13 +0000943 ConstantFP *InitValue = dyn_cast<ConstantFP>(PH->getIncomingValue(IncomingEdge));
944 if (!InitValue) return;
945 uint64_t newInitValue = Type::Int32Ty->getPrimitiveSizeInBits();
946 if (!convertToInt(InitValue->getValueAPF(), &newInitValue))
947 return;
948
949 // Check IV increment. Reject this PH if increement operation is not
950 // an add or increment value can not be represented by an integer.
Dan Gohmancafb8132009-02-17 19:13:57 +0000951 BinaryOperator *Incr =
Devang Patel84e35152008-11-17 21:32:02 +0000952 dyn_cast<BinaryOperator>(PH->getIncomingValue(BackEdge));
953 if (!Incr) return;
954 if (Incr->getOpcode() != Instruction::Add) return;
955 ConstantFP *IncrValue = NULL;
956 unsigned IncrVIndex = 1;
957 if (Incr->getOperand(1) == PH)
958 IncrVIndex = 0;
959 IncrValue = dyn_cast<ConstantFP>(Incr->getOperand(IncrVIndex));
960 if (!IncrValue) return;
Devang Patelcd402332008-11-17 23:27:13 +0000961 uint64_t newIncrValue = Type::Int32Ty->getPrimitiveSizeInBits();
962 if (!convertToInt(IncrValue->getValueAPF(), &newIncrValue))
963 return;
Dan Gohmancafb8132009-02-17 19:13:57 +0000964
Devang Patelcd402332008-11-17 23:27:13 +0000965 // Check Incr uses. One user is PH and the other users is exit condition used
966 // by the conditional terminator.
Devang Patel84e35152008-11-17 21:32:02 +0000967 Value::use_iterator IncrUse = Incr->use_begin();
968 Instruction *U1 = cast<Instruction>(IncrUse++);
969 if (IncrUse == Incr->use_end()) return;
970 Instruction *U2 = cast<Instruction>(IncrUse++);
971 if (IncrUse != Incr->use_end()) return;
Dan Gohmancafb8132009-02-17 19:13:57 +0000972
Devang Patel84e35152008-11-17 21:32:02 +0000973 // Find exit condition.
974 FCmpInst *EC = dyn_cast<FCmpInst>(U1);
975 if (!EC)
976 EC = dyn_cast<FCmpInst>(U2);
977 if (!EC) return;
978
979 if (BranchInst *BI = dyn_cast<BranchInst>(EC->getParent()->getTerminator())) {
980 if (!BI->isConditional()) return;
981 if (BI->getCondition() != EC) return;
Devang Patel58d43d42008-11-03 18:32:19 +0000982 }
Devang Patel58d43d42008-11-03 18:32:19 +0000983
Devang Patelcd402332008-11-17 23:27:13 +0000984 // Find exit value. If exit value can not be represented as an interger then
985 // do not handle this floating point PH.
Devang Patel84e35152008-11-17 21:32:02 +0000986 ConstantFP *EV = NULL;
987 unsigned EVIndex = 1;
988 if (EC->getOperand(1) == Incr)
989 EVIndex = 0;
990 EV = dyn_cast<ConstantFP>(EC->getOperand(EVIndex));
991 if (!EV) return;
Devang Patel84e35152008-11-17 21:32:02 +0000992 uint64_t intEV = Type::Int32Ty->getPrimitiveSizeInBits();
Devang Patelcd402332008-11-17 23:27:13 +0000993 if (!convertToInt(EV->getValueAPF(), &intEV))
Devang Patel84e35152008-11-17 21:32:02 +0000994 return;
Dan Gohmancafb8132009-02-17 19:13:57 +0000995
Devang Patel84e35152008-11-17 21:32:02 +0000996 // Find new predicate for integer comparison.
997 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
998 switch (EC->getPredicate()) {
999 case CmpInst::FCMP_OEQ:
1000 case CmpInst::FCMP_UEQ:
1001 NewPred = CmpInst::ICMP_EQ;
1002 break;
1003 case CmpInst::FCMP_OGT:
1004 case CmpInst::FCMP_UGT:
1005 NewPred = CmpInst::ICMP_UGT;
1006 break;
1007 case CmpInst::FCMP_OGE:
1008 case CmpInst::FCMP_UGE:
1009 NewPred = CmpInst::ICMP_UGE;
1010 break;
1011 case CmpInst::FCMP_OLT:
1012 case CmpInst::FCMP_ULT:
1013 NewPred = CmpInst::ICMP_ULT;
1014 break;
1015 case CmpInst::FCMP_OLE:
1016 case CmpInst::FCMP_ULE:
1017 NewPred = CmpInst::ICMP_ULE;
1018 break;
1019 default:
1020 break;
Devang Patel58d43d42008-11-03 18:32:19 +00001021 }
Devang Patel84e35152008-11-17 21:32:02 +00001022 if (NewPred == CmpInst::BAD_ICMP_PREDICATE) return;
Dan Gohmancafb8132009-02-17 19:13:57 +00001023
Devang Patel84e35152008-11-17 21:32:02 +00001024 // Insert new integer induction variable.
1025 PHINode *NewPHI = PHINode::Create(Type::Int32Ty,
1026 PH->getName()+".int", PH);
Devang Patelcd402332008-11-17 23:27:13 +00001027 NewPHI->addIncoming(ConstantInt::get(Type::Int32Ty, newInitValue),
Devang Patel84e35152008-11-17 21:32:02 +00001028 PH->getIncomingBlock(IncomingEdge));
1029
Dan Gohmancafb8132009-02-17 19:13:57 +00001030 Value *NewAdd = BinaryOperator::CreateAdd(NewPHI,
1031 ConstantInt::get(Type::Int32Ty,
Devang Patelcd402332008-11-17 23:27:13 +00001032 newIncrValue),
Devang Patel84e35152008-11-17 21:32:02 +00001033 Incr->getName()+".int", Incr);
1034 NewPHI->addIncoming(NewAdd, PH->getIncomingBlock(BackEdge));
1035
Dale Johannesen617d1082009-04-27 21:03:15 +00001036 // The back edge is edge 1 of newPHI, whatever it may have been in the
1037 // original PHI.
Devang Patel84e35152008-11-17 21:32:02 +00001038 ConstantInt *NewEV = ConstantInt::get(Type::Int32Ty, intEV);
Dale Johannesen617d1082009-04-27 21:03:15 +00001039 Value *LHS = (EVIndex == 1 ? NewPHI->getIncomingValue(1) : NewEV);
1040 Value *RHS = (EVIndex == 1 ? NewEV : NewPHI->getIncomingValue(1));
Dan Gohmancafb8132009-02-17 19:13:57 +00001041 ICmpInst *NewEC = new ICmpInst(NewPred, LHS, RHS, EC->getNameStart(),
Devang Patel84e35152008-11-17 21:32:02 +00001042 EC->getParent()->getTerminator());
Dan Gohmancafb8132009-02-17 19:13:57 +00001043
Devang Patel84e35152008-11-17 21:32:02 +00001044 // Delete old, floating point, exit comparision instruction.
1045 EC->replaceAllUsesWith(NewEC);
1046 DeadInsts.insert(EC);
Dan Gohmancafb8132009-02-17 19:13:57 +00001047
Devang Patel84e35152008-11-17 21:32:02 +00001048 // Delete old, floating point, increment instruction.
1049 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
1050 DeadInsts.insert(Incr);
Dan Gohmancafb8132009-02-17 19:13:57 +00001051
Devang Patel13877bf2008-11-18 00:40:02 +00001052 // Replace floating induction variable. Give SIToFPInst preference over
1053 // UIToFPInst because it is faster on platforms that are widely used.
1054 if (useSIToFPInst(*InitValue, *EV, newInitValue, intEV)) {
Dan Gohmancafb8132009-02-17 19:13:57 +00001055 SIToFPInst *Conv = new SIToFPInst(NewPHI, PH->getType(), "indvar.conv",
Devang Patelcd402332008-11-17 23:27:13 +00001056 PH->getParent()->getFirstNonPHI());
1057 PH->replaceAllUsesWith(Conv);
1058 } else {
Dan Gohmancafb8132009-02-17 19:13:57 +00001059 UIToFPInst *Conv = new UIToFPInst(NewPHI, PH->getType(), "indvar.conv",
Devang Patelcd402332008-11-17 23:27:13 +00001060 PH->getParent()->getFirstNonPHI());
1061 PH->replaceAllUsesWith(Conv);
1062 }
Devang Patel84e35152008-11-17 21:32:02 +00001063 DeadInsts.insert(PH);
Devang Patel58d43d42008-11-03 18:32:19 +00001064}
1065