blob: 44b83adcb35b91189a6461601d9b38d4ff13af59 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// 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//
14// This transformation makes the following changes to each loop with an
15// 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).
37//
38//===----------------------------------------------------------------------===//
39
40#define DEBUG_TYPE "indvars"
41#include "llvm/Transforms/Scalar.h"
42#include "llvm/BasicBlock.h"
43#include "llvm/Constants.h"
44#include "llvm/Instructions.h"
45#include "llvm/Type.h"
Dan Gohman28055122009-05-12 02:17:14 +000046#include "llvm/Analysis/Dominators.h"
47#include "llvm/Analysis/IVUsers.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000048#include "llvm/Analysis/ScalarEvolutionExpander.h"
49#include "llvm/Analysis/LoopInfo.h"
50#include "llvm/Analysis/LoopPass.h"
51#include "llvm/Support/CFG.h"
52#include "llvm/Support/Compiler.h"
53#include "llvm/Support/Debug.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000054#include "llvm/Transforms/Utils/Local.h"
Dan Gohman28055122009-05-12 02:17:14 +000055#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000056#include "llvm/Support/CommandLine.h"
57#include "llvm/ADT/SmallVector.h"
58#include "llvm/ADT/Statistic.h"
Dan Gohman28055122009-05-12 02:17:14 +000059#include "llvm/ADT/STLExtras.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000060using namespace llvm;
61
62STATISTIC(NumRemoved , "Number of aux indvars removed");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000063STATISTIC(NumInserted, "Number of canonical indvars added");
64STATISTIC(NumReplaced, "Number of exit values replaced");
65STATISTIC(NumLFTR , "Number of loop exit tests replaced");
66
67namespace {
68 class VISIBILITY_HIDDEN IndVarSimplify : public LoopPass {
Dan Gohman28055122009-05-12 02:17:14 +000069 IVUsers *IU;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000070 LoopInfo *LI;
71 ScalarEvolution *SE;
72 bool Changed;
73 public:
74
75 static char ID; // Pass identification, replacement for typeid
Dan Gohman26f8c272008-09-04 17:05:41 +000076 IndVarSimplify() : LoopPass(&ID) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000077
Dan Gohmanf3a060a2009-02-17 20:49:49 +000078 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
79
Dan Gohmanf17a25c2007-07-18 16:29:46 +000080 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman28055122009-05-12 02:17:14 +000081 AU.addRequired<DominatorTree>();
Devang Patele6a8d482007-09-10 18:08:23 +000082 AU.addRequired<ScalarEvolution>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000083 AU.addRequiredID(LCSSAID);
84 AU.addRequiredID(LoopSimplifyID);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000085 AU.addRequired<LoopInfo>();
Dan Gohman28055122009-05-12 02:17:14 +000086 AU.addRequired<IVUsers>();
Dan Gohman0d35b112009-02-23 16:29:41 +000087 AU.addPreserved<ScalarEvolution>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000088 AU.addPreservedID(LoopSimplifyID);
Dan Gohman28055122009-05-12 02:17:14 +000089 AU.addPreserved<IVUsers>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000090 AU.addPreservedID(LCSSAID);
91 AU.setPreservesCFG();
92 }
93
94 private:
95
Dan Gohmanf3a060a2009-02-17 20:49:49 +000096 void RewriteNonIntegerIVs(Loop *L);
97
Dan Gohman28055122009-05-12 02:17:14 +000098 ICmpInst *LinearFunctionTestReplace(Loop *L, SCEVHandle BackedgeTakenCount,
Dan Gohman1247dc32009-02-17 15:57:39 +000099 Value *IndVar,
Dan Gohmancacd2012009-02-12 22:19:27 +0000100 BasicBlock *ExitingBlock,
101 BranchInst *BI,
Dan Gohmanebac2542009-02-23 23:20:35 +0000102 SCEVExpander &Rewriter);
Dan Gohman9a769972009-04-18 17:56:28 +0000103 void RewriteLoopExitValues(Loop *L, const SCEV *BackedgeTakenCount);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000104
Dan Gohman28055122009-05-12 02:17:14 +0000105 void RewriteIVExpressions(Loop *L, const Type *LargestType,
106 SCEVExpander &Rewriter);
Devang Patelbda43802008-09-09 21:41:07 +0000107
Dan Gohman28055122009-05-12 02:17:14 +0000108 void SinkUnusedInvariants(Loop *L, SCEVExpander &Rewriter);
109
110 void FixUsesBeforeDefs(Loop *L, SCEVExpander &Rewriter);
111
112 void HandleFloatingPointIV(Loop *L, PHINode *PH);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000113 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000114}
115
Dan Gohman089efff2008-05-13 00:00:25 +0000116char IndVarSimplify::ID = 0;
117static RegisterPass<IndVarSimplify>
118X("indvars", "Canonicalize Induction Variables");
119
Daniel Dunbar163555a2008-10-22 23:32:42 +0000120Pass *llvm::createIndVarSimplifyPass() {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000121 return new IndVarSimplify();
122}
123
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000124/// LinearFunctionTestReplace - This method rewrites the exit condition of the
125/// loop to be a canonical != comparison against the incremented loop induction
126/// variable. This pass is able to rewrite the exit tests of any loop where the
127/// SCEV analysis can determine a loop-invariant trip count of the loop, which
128/// is actually a much broader range than just linear tests.
Dan Gohman28055122009-05-12 02:17:14 +0000129ICmpInst *IndVarSimplify::LinearFunctionTestReplace(Loop *L,
Dan Gohman76d5a0d2009-02-24 18:55:53 +0000130 SCEVHandle BackedgeTakenCount,
Dan Gohmancacd2012009-02-12 22:19:27 +0000131 Value *IndVar,
132 BasicBlock *ExitingBlock,
133 BranchInst *BI,
Dan Gohmanebac2542009-02-23 23:20:35 +0000134 SCEVExpander &Rewriter) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000135 // If the exiting block is not the same as the backedge block, we must compare
136 // against the preincremented value, otherwise we prefer to compare against
137 // the post-incremented value.
Dan Gohmancacd2012009-02-12 22:19:27 +0000138 Value *CmpIndVar;
Dan Gohman76d5a0d2009-02-24 18:55:53 +0000139 SCEVHandle RHS = BackedgeTakenCount;
Dan Gohmancacd2012009-02-12 22:19:27 +0000140 if (ExitingBlock == L->getLoopLatch()) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +0000141 // Add one to the "backedge-taken" count to get the trip count.
142 // If this addition may overflow, we have to be more pessimistic and
143 // cast the induction variable before doing the add.
144 SCEVHandle Zero = SE->getIntegerSCEV(0, BackedgeTakenCount->getType());
Dan Gohmancacd2012009-02-12 22:19:27 +0000145 SCEVHandle N =
Dan Gohman76d5a0d2009-02-24 18:55:53 +0000146 SE->getAddExpr(BackedgeTakenCount,
147 SE->getIntegerSCEV(1, BackedgeTakenCount->getType()));
Dan Gohmancacd2012009-02-12 22:19:27 +0000148 if ((isa<SCEVConstant>(N) && !N->isZero()) ||
149 SE->isLoopGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) {
150 // No overflow. Cast the sum.
Dan Gohman76d5a0d2009-02-24 18:55:53 +0000151 RHS = SE->getTruncateOrZeroExtend(N, IndVar->getType());
Dan Gohmancacd2012009-02-12 22:19:27 +0000152 } else {
153 // Potential overflow. Cast before doing the add.
Dan Gohman76d5a0d2009-02-24 18:55:53 +0000154 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
155 IndVar->getType());
156 RHS = SE->getAddExpr(RHS,
157 SE->getIntegerSCEV(1, IndVar->getType()));
Dan Gohmancacd2012009-02-12 22:19:27 +0000158 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000159
Dan Gohman76d5a0d2009-02-24 18:55:53 +0000160 // The BackedgeTaken expression contains the number of times that the
161 // backedge branches to the loop header. This is one less than the
162 // number of times the loop executes, so use the incremented indvar.
Dan Gohmancacd2012009-02-12 22:19:27 +0000163 CmpIndVar = L->getCanonicalInductionVariableIncrement();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000164 } else {
165 // We have to use the preincremented value...
Dan Gohman76d5a0d2009-02-24 18:55:53 +0000166 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
167 IndVar->getType());
Dan Gohmancacd2012009-02-12 22:19:27 +0000168 CmpIndVar = IndVar;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000169 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000170
171 // Expand the code for the iteration count into the preheader of the loop.
172 BasicBlock *Preheader = L->getLoopPreheader();
Dan Gohmand0c01232009-05-19 02:15:55 +0000173 Value *ExitCnt = Rewriter.expandCodeFor(RHS, CmpIndVar->getType(),
Dan Gohmancacd2012009-02-12 22:19:27 +0000174 Preheader->getTerminator());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000175
176 // Insert a new icmp_ne or icmp_eq instruction before the branch.
177 ICmpInst::Predicate Opcode;
178 if (L->contains(BI->getSuccessor(0)))
179 Opcode = ICmpInst::ICMP_NE;
180 else
181 Opcode = ICmpInst::ICMP_EQ;
182
Dan Gohmancacd2012009-02-12 22:19:27 +0000183 DOUT << "INDVARS: Rewriting loop exit condition to:\n"
184 << " LHS:" << *CmpIndVar // includes a newline
185 << " op:\t"
Dan Gohman8555ff72009-02-14 02:26:50 +0000186 << (Opcode == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
Dan Gohman76d5a0d2009-02-24 18:55:53 +0000187 << " RHS:\t" << *RHS << "\n";
Dan Gohmancacd2012009-02-12 22:19:27 +0000188
Dan Gohman28055122009-05-12 02:17:14 +0000189 ICmpInst *Cond = new ICmpInst(Opcode, CmpIndVar, ExitCnt, "exitcond", BI);
190
191 Instruction *OrigCond = cast<Instruction>(BI->getCondition());
192 OrigCond->replaceAllUsesWith(Cond);
193 RecursivelyDeleteTriviallyDeadInstructions(OrigCond);
194
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000195 ++NumLFTR;
196 Changed = true;
Dan Gohman28055122009-05-12 02:17:14 +0000197 return Cond;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000198}
199
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000200/// RewriteLoopExitValues - Check to see if this loop has a computable
201/// loop-invariant execution count. If so, this means that we can compute the
202/// final value of any expressions that are recurrent in the loop, and
203/// substitute the exit values from the loop into any instructions outside of
204/// the loop that use the final values of the current expressions.
Dan Gohman28055122009-05-12 02:17:14 +0000205///
206/// This is mostly redundant with the regular IndVarSimplify activities that
207/// happen later, except that it's more powerful in some cases, because it's
208/// able to brute-force evaluate arbitrary instructions as long as they have
209/// constant operands at the beginning of the loop.
Dan Gohman9a769972009-04-18 17:56:28 +0000210void IndVarSimplify::RewriteLoopExitValues(Loop *L,
211 const SCEV *BackedgeTakenCount) {
Dan Gohman28055122009-05-12 02:17:14 +0000212 // Verify the input to the pass in already in LCSSA form.
213 assert(L->isLCSSAForm());
214
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000215 BasicBlock *Preheader = L->getLoopPreheader();
216
217 // Scan all of the instructions in the loop, looking at those that have
218 // extra-loop users and which are recurrences.
Dan Gohmand0c01232009-05-19 02:15:55 +0000219 SCEVExpander Rewriter(*SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000220
221 // We insert the code into the preheader of the loop if the loop contains
222 // multiple exit blocks, or in the exit block if there is exactly one.
223 BasicBlock *BlockToInsertInto;
Devang Patel02451fa2007-08-21 00:31:24 +0000224 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000225 L->getUniqueExitBlocks(ExitBlocks);
226 if (ExitBlocks.size() == 1)
227 BlockToInsertInto = ExitBlocks[0];
228 else
229 BlockToInsertInto = Preheader;
Dan Gohman514277c2008-05-23 21:05:58 +0000230 BasicBlock::iterator InsertPt = BlockToInsertInto->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000231
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000232 std::map<Instruction*, Value*> ExitValues;
233
234 // 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 Gohman963fc812009-02-17 19:13:57 +0000239
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Gohman963fc812009-02-17 19:13:57 +0000244
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000245 unsigned NumPreds = PN->getNumIncomingValues();
Dan Gohman963fc812009-02-17 19:13:57 +0000246
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000247 // Iterate over all of the PHI nodes.
248 BasicBlock::iterator BBI = ExitBB->begin();
249 while ((PN = dyn_cast<PHINode>(BBI++))) {
Dan Gohman963fc812009-02-17 19:13:57 +0000250
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Gohman01c2ee72009-04-16 03:18:22 +0000258 (!isa<IntegerType>(InVal->getType()) &&
259 !isa<PointerType>(InVal->getType())))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000260 continue;
261
262 // If this pred is for a subloop, not L itself, skip it.
Dan Gohman963fc812009-02-17 19:13:57 +0000263 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Gohman963fc812009-02-17 19:13:57 +0000270
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000271 // Okay, this instruction has a user outside of the current loop
272 // and varies predictably *inside* the loop. Evaluate the value it
273 // contains when the loop exits, if possible.
Dan Gohman28055122009-05-12 02:17:14 +0000274 SCEVHandle SH = SE->getSCEV(Inst);
275 SCEVHandle ExitValue = SE->getSCEVAtScope(SH, L->getParentLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000276 if (isa<SCEVCouldNotCompute>(ExitValue) ||
277 !ExitValue->isLoopInvariant(L))
278 continue;
279
280 Changed = true;
281 ++NumReplaced;
Dan Gohman963fc812009-02-17 19:13:57 +0000282
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000283 // See if we already computed the exit value for the instruction, if so,
284 // just reuse it.
285 Value *&ExitVal = ExitValues[Inst];
286 if (!ExitVal)
Dan Gohman01c2ee72009-04-16 03:18:22 +0000287 ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), InsertPt);
Dan Gohman963fc812009-02-17 19:13:57 +0000288
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000289 DOUT << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal
290 << " LoopVal = " << *Inst << "\n";
291
292 PN->setIncomingValue(i, ExitVal);
Dan Gohman963fc812009-02-17 19:13:57 +0000293
Dan Gohman28055122009-05-12 02:17:14 +0000294 // If this instruction is dead now, delete it.
295 RecursivelyDeleteTriviallyDeadInstructions(Inst);
Dan Gohman963fc812009-02-17 19:13:57 +0000296
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000297 // See if this is a single-entry LCSSA PHI node. If so, we can (and
298 // have to) remove
299 // the PHI entirely. This is safe, because the NewVal won't be variant
300 // in the loop, so we don't need an LCSSA phi node anymore.
301 if (NumPreds == 1) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000302 PN->replaceAllUsesWith(ExitVal);
Dan Gohman28055122009-05-12 02:17:14 +0000303 RecursivelyDeleteTriviallyDeadInstructions(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000304 break;
305 }
306 }
307 }
308 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000309}
310
Dan Gohmanf3a060a2009-02-17 20:49:49 +0000311void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000312 // First step. Check to see if there are any floating-point recurrences.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000313 // If there are, change them into integer recurrences, permitting analysis by
314 // the SCEV routines.
315 //
316 BasicBlock *Header = L->getHeader();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000317
Dan Gohman28055122009-05-12 02:17:14 +0000318 SmallVector<WeakVH, 8> PHIs;
319 for (BasicBlock::iterator I = Header->begin();
320 PHINode *PN = dyn_cast<PHINode>(I); ++I)
321 PHIs.push_back(PN);
322
323 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
324 if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i]))
325 HandleFloatingPointIV(L, PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000326
Dan Gohman01c2ee72009-04-16 03:18:22 +0000327 // If the loop previously had floating-point IV, ScalarEvolution
Dan Gohmanf3a060a2009-02-17 20:49:49 +0000328 // may not have been able to compute a trip count. Now that we've done some
329 // re-writing, the trip count may be computable.
330 if (Changed)
Dan Gohman76d5a0d2009-02-24 18:55:53 +0000331 SE->forgetLoopBackedgeTakenCount(L);
Dale Johannesen3c25cb22009-04-15 23:31:51 +0000332}
333
Dan Gohmancacd2012009-02-12 22:19:27 +0000334bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
Dan Gohman28055122009-05-12 02:17:14 +0000335 IU = &getAnalysis<IVUsers>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000336 LI = &getAnalysis<LoopInfo>();
337 SE = &getAnalysis<ScalarEvolution>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000338 Changed = false;
Dan Gohmanf3a060a2009-02-17 20:49:49 +0000339
Dan Gohman01c2ee72009-04-16 03:18:22 +0000340 // If there are any floating-point recurrences, attempt to
Dan Gohmanf3a060a2009-02-17 20:49:49 +0000341 // transform them to use integer recurrences.
342 RewriteNonIntegerIVs(L);
343
Dan Gohmancacd2012009-02-12 22:19:27 +0000344 BasicBlock *Header = L->getHeader();
Dan Gohman28055122009-05-12 02:17:14 +0000345 BasicBlock *ExitingBlock = L->getExitingBlock(); // may be null
346 SCEVHandle BackedgeTakenCount = SE->getBackedgeTakenCount(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000347
348 // Check to see if this loop has a computable loop-invariant execution count.
349 // If so, this means that we can compute the final value of any expressions
350 // that are recurrent in the loop, and substitute the exit values from the
351 // loop into any instructions outside of the loop that use the final values of
352 // the current expressions.
353 //
Dan Gohman76d5a0d2009-02-24 18:55:53 +0000354 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount))
355 RewriteLoopExitValues(L, BackedgeTakenCount);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000356
Dan Gohman28055122009-05-12 02:17:14 +0000357 // Compute the type of the largest recurrence expression, and decide whether
358 // a canonical induction variable should be inserted.
Dan Gohmancacd2012009-02-12 22:19:27 +0000359 const Type *LargestType = 0;
Dan Gohman28055122009-05-12 02:17:14 +0000360 bool NeedCannIV = false;
Dan Gohman76d5a0d2009-02-24 18:55:53 +0000361 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
362 LargestType = BackedgeTakenCount->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000363 LargestType = SE->getEffectiveSCEVType(LargestType);
Dan Gohman28055122009-05-12 02:17:14 +0000364 // If we have a known trip count and a single exit block, we'll be
365 // rewriting the loop exit test condition below, which requires a
366 // canonical induction variable.
367 if (ExitingBlock)
368 NeedCannIV = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000369 }
Dan Gohman28055122009-05-12 02:17:14 +0000370 for (unsigned i = 0, e = IU->StrideOrder.size(); i != e; ++i) {
371 SCEVHandle Stride = IU->StrideOrder[i];
372 const Type *Ty = SE->getEffectiveSCEVType(Stride->getType());
Dan Gohmancacd2012009-02-12 22:19:27 +0000373 if (!LargestType ||
Dan Gohman28055122009-05-12 02:17:14 +0000374 SE->getTypeSizeInBits(Ty) >
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000375 SE->getTypeSizeInBits(LargestType))
Dan Gohman28055122009-05-12 02:17:14 +0000376 LargestType = Ty;
377
378 std::map<SCEVHandle, IVUsersOfOneStride *>::iterator SI =
379 IU->IVUsesByStride.find(IU->StrideOrder[i]);
380 assert(SI != IU->IVUsesByStride.end() && "Stride doesn't exist!");
381
382 if (!SI->second->Users.empty())
383 NeedCannIV = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000384 }
385
386 // Create a rewriter object which we'll use to transform the code with.
Dan Gohmand0c01232009-05-19 02:15:55 +0000387 SCEVExpander Rewriter(*SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000388
Dan Gohman28055122009-05-12 02:17:14 +0000389 // Now that we know the largest of of the induction variable expressions
390 // in this loop, insert a canonical induction variable of the largest size.
Dan Gohmancacd2012009-02-12 22:19:27 +0000391 Value *IndVar = 0;
Dan Gohman28055122009-05-12 02:17:14 +0000392 if (NeedCannIV) {
Dan Gohmancacd2012009-02-12 22:19:27 +0000393 IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L,LargestType);
394 ++NumInserted;
395 Changed = true;
396 DOUT << "INDVARS: New CanIV: " << *IndVar;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000397 }
398
Dan Gohmancacd2012009-02-12 22:19:27 +0000399 // If we have a trip count expression, rewrite the loop's exit condition
400 // using it. We can currently only handle loops with a single exit.
Dan Gohman28055122009-05-12 02:17:14 +0000401 ICmpInst *NewICmp = 0;
402 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) && ExitingBlock) {
403 assert(NeedCannIV &&
404 "LinearFunctionTestReplace requires a canonical induction variable");
Dan Gohmancacd2012009-02-12 22:19:27 +0000405 // Can't rewrite non-branch yet.
Dan Gohman28055122009-05-12 02:17:14 +0000406 if (BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator()))
407 NewICmp = LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar,
408 ExitingBlock, BI, Rewriter);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000409 }
410
Dan Gohman28055122009-05-12 02:17:14 +0000411 Rewriter.setInsertionPoint(Header->getFirstNonPHI());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000412
Dan Gohman28055122009-05-12 02:17:14 +0000413 // Rewrite IV-derived expressions.
414 RewriteIVExpressions(L, LargestType, Rewriter);
Dan Gohmancacd2012009-02-12 22:19:27 +0000415
Dan Gohman28055122009-05-12 02:17:14 +0000416 // Loop-invariant instructions in the preheader that aren't used in the
417 // loop may be sunk below the loop to reduce register pressure.
418 SinkUnusedInvariants(L, Rewriter);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000419
Dan Gohman28055122009-05-12 02:17:14 +0000420 // Reorder instructions to avoid use-before-def conditions.
421 FixUsesBeforeDefs(L, Rewriter);
422
423 // For completeness, inform IVUsers of the IV use in the newly-created
424 // loop exit test instruction.
425 if (NewICmp)
426 IU->AddUsersIfInteresting(cast<Instruction>(NewICmp->getOperand(0)));
427
428 // Clean up dead instructions.
429 DeleteDeadPHIs(L->getHeader());
430 // Check a post-condition.
431 assert(L->isLCSSAForm() && "Indvars did not leave the loop in lcssa form!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000432 return Changed;
433}
Devang Patelbda43802008-09-09 21:41:07 +0000434
Dan Gohman28055122009-05-12 02:17:14 +0000435void IndVarSimplify::RewriteIVExpressions(Loop *L, const Type *LargestType,
436 SCEVExpander &Rewriter) {
437 SmallVector<WeakVH, 16> DeadInsts;
438
439 // Rewrite all induction variable expressions in terms of the canonical
440 // induction variable.
441 //
442 // If there were induction variables of other sizes or offsets, manually
443 // add the offsets to the primary induction variable and cast, avoiding
444 // the need for the code evaluation methods to insert induction variables
445 // of different sizes.
446 for (unsigned i = 0, e = IU->StrideOrder.size(); i != e; ++i) {
447 SCEVHandle Stride = IU->StrideOrder[i];
448
449 std::map<SCEVHandle, IVUsersOfOneStride *>::iterator SI =
450 IU->IVUsesByStride.find(IU->StrideOrder[i]);
451 assert(SI != IU->IVUsesByStride.end() && "Stride doesn't exist!");
452 ilist<IVStrideUse> &List = SI->second->Users;
453 for (ilist<IVStrideUse>::iterator UI = List.begin(),
454 E = List.end(); UI != E; ++UI) {
455 SCEVHandle Offset = UI->getOffset();
456 Value *Op = UI->getOperandValToReplace();
457 Instruction *User = UI->getUser();
458 bool isSigned = UI->isSigned();
459
460 // Compute the final addrec to expand into code.
461 SCEVHandle AR = IU->getReplacementExpr(*UI);
462
463 // FIXME: It is an extremely bad idea to indvar substitute anything more
464 // complex than affine induction variables. Doing so will put expensive
465 // polynomial evaluations inside of the loop, and the str reduction pass
466 // currently can only reduce affine polynomials. For now just disable
467 // indvar subst on anything more complex than an affine addrec, unless
468 // it can be expanded to a trivial value.
469 if (!Stride->isLoopInvariant(L) &&
470 !isa<SCEVConstant>(AR) &&
471 L->contains(User->getParent()))
472 continue;
473
474 Value *NewVal = 0;
475 if (AR->isLoopInvariant(L)) {
476 BasicBlock::iterator I = Rewriter.getInsertionPoint();
477 // Expand loop-invariant values in the loop preheader. They will
478 // be sunk to the exit block later, if possible.
Dan Gohmand0c01232009-05-19 02:15:55 +0000479 NewVal =
Dan Gohman28055122009-05-12 02:17:14 +0000480 Rewriter.expandCodeFor(AR, LargestType,
481 L->getLoopPreheader()->getTerminator());
482 Rewriter.setInsertionPoint(I);
483 ++NumReplaced;
484 } else {
485 const Type *IVTy = Offset->getType();
486 const Type *UseTy = Op->getType();
487
488 // Promote the Offset and Stride up to the canonical induction
489 // variable's bit width.
490 SCEVHandle PromotedOffset = Offset;
491 SCEVHandle PromotedStride = Stride;
492 if (SE->getTypeSizeInBits(IVTy) != SE->getTypeSizeInBits(LargestType)) {
493 // It doesn't matter for correctness whether zero or sign extension
494 // is used here, since the value is truncated away below, but if the
495 // value is signed, sign extension is more likely to be folded.
496 if (isSigned) {
497 PromotedOffset = SE->getSignExtendExpr(PromotedOffset, LargestType);
498 PromotedStride = SE->getSignExtendExpr(PromotedStride, LargestType);
499 } else {
500 PromotedOffset = SE->getZeroExtendExpr(PromotedOffset, LargestType);
501 // If the stride is obviously negative, use sign extension to
502 // produce things like x-1 instead of x+255.
503 if (isa<SCEVConstant>(PromotedStride) &&
504 cast<SCEVConstant>(PromotedStride)
505 ->getValue()->getValue().isNegative())
506 PromotedStride = SE->getSignExtendExpr(PromotedStride,
507 LargestType);
508 else
509 PromotedStride = SE->getZeroExtendExpr(PromotedStride,
510 LargestType);
511 }
512 }
513
514 // Create the SCEV representing the offset from the canonical
515 // induction variable, still in the canonical induction variable's
516 // type, so that all expanded arithmetic is done in the same type.
517 SCEVHandle NewAR = SE->getAddRecExpr(SE->getIntegerSCEV(0, LargestType),
518 PromotedStride, L);
519 // Add the PromotedOffset as a separate step, because it may not be
520 // loop-invariant.
521 NewAR = SE->getAddExpr(NewAR, PromotedOffset);
522
523 // Expand the addrec into instructions.
Dan Gohmand0c01232009-05-19 02:15:55 +0000524 Value *V = Rewriter.expandCodeFor(NewAR);
Dan Gohman28055122009-05-12 02:17:14 +0000525
526 // Insert an explicit cast if necessary to truncate the value
527 // down to the original stride type. This is done outside of
528 // SCEVExpander because in SCEV expressions, a truncate of an
529 // addrec is always folded.
530 if (LargestType != IVTy) {
531 if (SE->getTypeSizeInBits(IVTy) != SE->getTypeSizeInBits(LargestType))
532 NewAR = SE->getTruncateExpr(NewAR, IVTy);
533 if (Rewriter.isInsertedExpression(NewAR))
Dan Gohmand0c01232009-05-19 02:15:55 +0000534 V = Rewriter.expandCodeFor(NewAR);
Dan Gohman28055122009-05-12 02:17:14 +0000535 else {
536 V = Rewriter.InsertCastOfTo(CastInst::getCastOpcode(V, false,
537 IVTy, false),
538 V, IVTy);
539 assert(!isa<SExtInst>(V) && !isa<ZExtInst>(V) &&
540 "LargestType wasn't actually the largest type!");
541 // Force the rewriter to use this trunc whenever this addrec
542 // appears so that it doesn't insert new phi nodes or
543 // arithmetic in a different type.
544 Rewriter.addInsertedValue(V, NewAR);
545 }
546 }
547
548 DOUT << "INDVARS: Made offset-and-trunc IV for offset "
549 << *IVTy << " " << *Offset << ": ";
550 DEBUG(WriteAsOperand(*DOUT, V, false));
551 DOUT << "\n";
552
553 // Now expand it into actual Instructions and patch it into place.
554 NewVal = Rewriter.expandCodeFor(AR, UseTy);
555 }
556
557 // Patch the new value into place.
558 if (Op->hasName())
559 NewVal->takeName(Op);
560 User->replaceUsesOfWith(Op, NewVal);
561 UI->setOperandValToReplace(NewVal);
562 DOUT << "INDVARS: Rewrote IV '" << *AR << "' " << *Op
563 << " into = " << *NewVal << "\n";
564 ++NumRemoved;
565 Changed = true;
566
567 // The old value may be dead now.
568 DeadInsts.push_back(Op);
569 }
570 }
571
572 // Now that we're done iterating through lists, clean up any instructions
573 // which are now dead.
574 while (!DeadInsts.empty()) {
575 Instruction *Inst = dyn_cast_or_null<Instruction>(DeadInsts.pop_back_val());
576 if (Inst)
577 RecursivelyDeleteTriviallyDeadInstructions(Inst);
578 }
579}
580
581/// If there's a single exit block, sink any loop-invariant values that
582/// were defined in the preheader but not used inside the loop into the
583/// exit block to reduce register pressure in the loop.
584void IndVarSimplify::SinkUnusedInvariants(Loop *L, SCEVExpander &Rewriter) {
585 BasicBlock *ExitBlock = L->getExitBlock();
586 if (!ExitBlock) return;
587
588 Instruction *NonPHI = ExitBlock->getFirstNonPHI();
589 BasicBlock *Preheader = L->getLoopPreheader();
590 BasicBlock::iterator I = Preheader->getTerminator();
591 while (I != Preheader->begin()) {
592 --I;
593 // New instructions were inserted at the end of the preheader. Only
594 // consider those new instructions.
595 if (!Rewriter.isInsertedInstruction(I))
596 break;
597 // Determine if there is a use in or before the loop (direct or
598 // otherwise).
599 bool UsedInLoop = false;
600 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
601 UI != UE; ++UI) {
602 BasicBlock *UseBB = cast<Instruction>(UI)->getParent();
603 if (PHINode *P = dyn_cast<PHINode>(UI)) {
604 unsigned i =
605 PHINode::getIncomingValueNumForOperand(UI.getOperandNo());
606 UseBB = P->getIncomingBlock(i);
607 }
608 if (UseBB == Preheader || L->contains(UseBB)) {
609 UsedInLoop = true;
610 break;
611 }
612 }
613 // If there is, the def must remain in the preheader.
614 if (UsedInLoop)
615 continue;
616 // Otherwise, sink it to the exit block.
617 Instruction *ToMove = I;
618 bool Done = false;
619 if (I != Preheader->begin())
620 --I;
621 else
622 Done = true;
623 ToMove->moveBefore(NonPHI);
624 if (Done)
625 break;
626 }
627}
628
629/// Re-schedule the inserted instructions to put defs before uses. This
630/// fixes problems that arrise when SCEV expressions contain loop-variant
631/// values unrelated to the induction variable which are defined inside the
632/// loop. FIXME: It would be better to insert instructions in the right
633/// place so that this step isn't needed.
634void IndVarSimplify::FixUsesBeforeDefs(Loop *L, SCEVExpander &Rewriter) {
635 // Visit all the blocks in the loop in pre-order dom-tree dfs order.
636 DominatorTree *DT = &getAnalysis<DominatorTree>();
637 std::map<Instruction *, unsigned> NumPredsLeft;
638 SmallVector<DomTreeNode *, 16> Worklist;
639 Worklist.push_back(DT->getNode(L->getHeader()));
640 do {
641 DomTreeNode *Node = Worklist.pop_back_val();
642 for (DomTreeNode::iterator I = Node->begin(), E = Node->end(); I != E; ++I)
643 if (L->contains((*I)->getBlock()))
644 Worklist.push_back(*I);
645 BasicBlock *BB = Node->getBlock();
646 // Visit all the instructions in the block top down.
647 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
648 // Count the number of operands that aren't properly dominating.
649 unsigned NumPreds = 0;
650 if (Rewriter.isInsertedInstruction(I) && !isa<PHINode>(I))
651 for (User::op_iterator OI = I->op_begin(), OE = I->op_end();
652 OI != OE; ++OI)
653 if (Instruction *Inst = dyn_cast<Instruction>(OI))
654 if (L->contains(Inst->getParent()) && !NumPredsLeft.count(Inst))
655 ++NumPreds;
656 NumPredsLeft[I] = NumPreds;
657 // Notify uses of the position of this instruction, and move the
658 // users (and their dependents, recursively) into place after this
659 // instruction if it is their last outstanding operand.
660 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
661 UI != UE; ++UI) {
662 Instruction *Inst = cast<Instruction>(UI);
663 std::map<Instruction *, unsigned>::iterator Z = NumPredsLeft.find(Inst);
664 if (Z != NumPredsLeft.end() && Z->second != 0 && --Z->second == 0) {
665 SmallVector<Instruction *, 4> UseWorkList;
666 UseWorkList.push_back(Inst);
667 BasicBlock::iterator InsertPt = next(I);
668 while (isa<PHINode>(InsertPt)) ++InsertPt;
669 do {
670 Instruction *Use = UseWorkList.pop_back_val();
671 Use->moveBefore(InsertPt);
672 NumPredsLeft.erase(Use);
673 for (Value::use_iterator IUI = Use->use_begin(),
674 IUE = Use->use_end(); IUI != IUE; ++IUI) {
675 Instruction *IUIInst = cast<Instruction>(IUI);
676 if (L->contains(IUIInst->getParent()) &&
677 Rewriter.isInsertedInstruction(IUIInst) &&
678 !isa<PHINode>(IUIInst))
679 UseWorkList.push_back(IUIInst);
680 }
681 } while (!UseWorkList.empty());
682 }
683 }
684 }
685 } while (!Worklist.empty());
686}
687
Devang Patelb8ccf572008-11-18 00:40:02 +0000688/// Return true if it is OK to use SIToFPInst for an inducation variable
689/// with given inital and exit values.
690static bool useSIToFPInst(ConstantFP &InitV, ConstantFP &ExitV,
691 uint64_t intIV, uint64_t intEV) {
692
Dan Gohman963fc812009-02-17 19:13:57 +0000693 if (InitV.getValueAPF().isNegative() || ExitV.getValueAPF().isNegative())
Devang Patelb8ccf572008-11-18 00:40:02 +0000694 return true;
695
696 // If the iteration range can be handled by SIToFPInst then use it.
697 APInt Max = APInt::getSignedMaxValue(32);
Dale Johannesen0a12b4c2009-05-14 16:47:34 +0000698 if (Max.getZExtValue() > static_cast<uint64_t>(abs64(intEV - intIV)))
Devang Patelb8ccf572008-11-18 00:40:02 +0000699 return true;
Dan Gohman963fc812009-02-17 19:13:57 +0000700
Devang Patelb8ccf572008-11-18 00:40:02 +0000701 return false;
702}
703
704/// convertToInt - Convert APF to an integer, if possible.
Devang Patele2ba01d2008-11-17 23:27:13 +0000705static bool convertToInt(const APFloat &APF, uint64_t *intVal) {
706
707 bool isExact = false;
Evan Cheng30e65f62008-11-26 01:11:57 +0000708 if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
709 return false;
Dan Gohman963fc812009-02-17 19:13:57 +0000710 if (APF.convertToInteger(intVal, 32, APF.isNegative(),
Devang Patele2ba01d2008-11-17 23:27:13 +0000711 APFloat::rmTowardZero, &isExact)
712 != APFloat::opOK)
713 return false;
Dan Gohman963fc812009-02-17 19:13:57 +0000714 if (!isExact)
Devang Patele2ba01d2008-11-17 23:27:13 +0000715 return false;
716 return true;
717
718}
719
Devang Patel7ca23c92008-11-03 18:32:19 +0000720/// HandleFloatingPointIV - If the loop has floating induction variable
721/// then insert corresponding integer induction variable if possible.
Devang Patelc8dac622008-11-17 21:32:02 +0000722/// For example,
723/// for(double i = 0; i < 10000; ++i)
724/// bar(i)
725/// is converted into
726/// for(int i = 0; i < 10000; ++i)
727/// bar((double)i);
728///
Dan Gohman28055122009-05-12 02:17:14 +0000729void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PH) {
Devang Patel7ca23c92008-11-03 18:32:19 +0000730
Devang Patelc8dac622008-11-17 21:32:02 +0000731 unsigned IncomingEdge = L->contains(PH->getIncomingBlock(0));
732 unsigned BackEdge = IncomingEdge^1;
Dan Gohman963fc812009-02-17 19:13:57 +0000733
Devang Patelc8dac622008-11-17 21:32:02 +0000734 // Check incoming value.
Devang Patele2ba01d2008-11-17 23:27:13 +0000735 ConstantFP *InitValue = dyn_cast<ConstantFP>(PH->getIncomingValue(IncomingEdge));
736 if (!InitValue) return;
737 uint64_t newInitValue = Type::Int32Ty->getPrimitiveSizeInBits();
738 if (!convertToInt(InitValue->getValueAPF(), &newInitValue))
739 return;
740
741 // Check IV increment. Reject this PH if increement operation is not
742 // an add or increment value can not be represented by an integer.
Dan Gohman963fc812009-02-17 19:13:57 +0000743 BinaryOperator *Incr =
Devang Patelc8dac622008-11-17 21:32:02 +0000744 dyn_cast<BinaryOperator>(PH->getIncomingValue(BackEdge));
745 if (!Incr) return;
746 if (Incr->getOpcode() != Instruction::Add) return;
747 ConstantFP *IncrValue = NULL;
748 unsigned IncrVIndex = 1;
749 if (Incr->getOperand(1) == PH)
750 IncrVIndex = 0;
751 IncrValue = dyn_cast<ConstantFP>(Incr->getOperand(IncrVIndex));
752 if (!IncrValue) return;
Devang Patele2ba01d2008-11-17 23:27:13 +0000753 uint64_t newIncrValue = Type::Int32Ty->getPrimitiveSizeInBits();
754 if (!convertToInt(IncrValue->getValueAPF(), &newIncrValue))
755 return;
Dan Gohman963fc812009-02-17 19:13:57 +0000756
Devang Patele2ba01d2008-11-17 23:27:13 +0000757 // Check Incr uses. One user is PH and the other users is exit condition used
758 // by the conditional terminator.
Devang Patelc8dac622008-11-17 21:32:02 +0000759 Value::use_iterator IncrUse = Incr->use_begin();
760 Instruction *U1 = cast<Instruction>(IncrUse++);
761 if (IncrUse == Incr->use_end()) return;
762 Instruction *U2 = cast<Instruction>(IncrUse++);
763 if (IncrUse != Incr->use_end()) return;
Dan Gohman963fc812009-02-17 19:13:57 +0000764
Devang Patelc8dac622008-11-17 21:32:02 +0000765 // Find exit condition.
766 FCmpInst *EC = dyn_cast<FCmpInst>(U1);
767 if (!EC)
768 EC = dyn_cast<FCmpInst>(U2);
769 if (!EC) return;
770
771 if (BranchInst *BI = dyn_cast<BranchInst>(EC->getParent()->getTerminator())) {
772 if (!BI->isConditional()) return;
773 if (BI->getCondition() != EC) return;
Devang Patel7ca23c92008-11-03 18:32:19 +0000774 }
Devang Patel7ca23c92008-11-03 18:32:19 +0000775
Devang Patele2ba01d2008-11-17 23:27:13 +0000776 // Find exit value. If exit value can not be represented as an interger then
777 // do not handle this floating point PH.
Devang Patelc8dac622008-11-17 21:32:02 +0000778 ConstantFP *EV = NULL;
779 unsigned EVIndex = 1;
780 if (EC->getOperand(1) == Incr)
781 EVIndex = 0;
782 EV = dyn_cast<ConstantFP>(EC->getOperand(EVIndex));
783 if (!EV) return;
Devang Patelc8dac622008-11-17 21:32:02 +0000784 uint64_t intEV = Type::Int32Ty->getPrimitiveSizeInBits();
Devang Patele2ba01d2008-11-17 23:27:13 +0000785 if (!convertToInt(EV->getValueAPF(), &intEV))
Devang Patelc8dac622008-11-17 21:32:02 +0000786 return;
Dan Gohman963fc812009-02-17 19:13:57 +0000787
Devang Patelc8dac622008-11-17 21:32:02 +0000788 // Find new predicate for integer comparison.
789 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
790 switch (EC->getPredicate()) {
791 case CmpInst::FCMP_OEQ:
792 case CmpInst::FCMP_UEQ:
793 NewPred = CmpInst::ICMP_EQ;
794 break;
795 case CmpInst::FCMP_OGT:
796 case CmpInst::FCMP_UGT:
797 NewPred = CmpInst::ICMP_UGT;
798 break;
799 case CmpInst::FCMP_OGE:
800 case CmpInst::FCMP_UGE:
801 NewPred = CmpInst::ICMP_UGE;
802 break;
803 case CmpInst::FCMP_OLT:
804 case CmpInst::FCMP_ULT:
805 NewPred = CmpInst::ICMP_ULT;
806 break;
807 case CmpInst::FCMP_OLE:
808 case CmpInst::FCMP_ULE:
809 NewPred = CmpInst::ICMP_ULE;
810 break;
811 default:
812 break;
Devang Patel7ca23c92008-11-03 18:32:19 +0000813 }
Devang Patelc8dac622008-11-17 21:32:02 +0000814 if (NewPred == CmpInst::BAD_ICMP_PREDICATE) return;
Dan Gohman963fc812009-02-17 19:13:57 +0000815
Devang Patelc8dac622008-11-17 21:32:02 +0000816 // Insert new integer induction variable.
817 PHINode *NewPHI = PHINode::Create(Type::Int32Ty,
818 PH->getName()+".int", PH);
Devang Patele2ba01d2008-11-17 23:27:13 +0000819 NewPHI->addIncoming(ConstantInt::get(Type::Int32Ty, newInitValue),
Devang Patelc8dac622008-11-17 21:32:02 +0000820 PH->getIncomingBlock(IncomingEdge));
821
Dan Gohman963fc812009-02-17 19:13:57 +0000822 Value *NewAdd = BinaryOperator::CreateAdd(NewPHI,
823 ConstantInt::get(Type::Int32Ty,
Devang Patele2ba01d2008-11-17 23:27:13 +0000824 newIncrValue),
Devang Patelc8dac622008-11-17 21:32:02 +0000825 Incr->getName()+".int", Incr);
826 NewPHI->addIncoming(NewAdd, PH->getIncomingBlock(BackEdge));
827
Dale Johannesen6cb3e262009-04-27 21:03:15 +0000828 // The back edge is edge 1 of newPHI, whatever it may have been in the
829 // original PHI.
Devang Patelc8dac622008-11-17 21:32:02 +0000830 ConstantInt *NewEV = ConstantInt::get(Type::Int32Ty, intEV);
Dale Johannesen6cb3e262009-04-27 21:03:15 +0000831 Value *LHS = (EVIndex == 1 ? NewPHI->getIncomingValue(1) : NewEV);
832 Value *RHS = (EVIndex == 1 ? NewEV : NewPHI->getIncomingValue(1));
Dan Gohman963fc812009-02-17 19:13:57 +0000833 ICmpInst *NewEC = new ICmpInst(NewPred, LHS, RHS, EC->getNameStart(),
Devang Patelc8dac622008-11-17 21:32:02 +0000834 EC->getParent()->getTerminator());
Dan Gohman963fc812009-02-17 19:13:57 +0000835
Dan Gohman28055122009-05-12 02:17:14 +0000836 // In the following deltions, PH may become dead and may be deleted.
837 // Use a WeakVH to observe whether this happens.
838 WeakVH WeakPH = PH;
839
Devang Patelc8dac622008-11-17 21:32:02 +0000840 // Delete old, floating point, exit comparision instruction.
841 EC->replaceAllUsesWith(NewEC);
Dan Gohman28055122009-05-12 02:17:14 +0000842 RecursivelyDeleteTriviallyDeadInstructions(EC);
Dan Gohman963fc812009-02-17 19:13:57 +0000843
Devang Patelc8dac622008-11-17 21:32:02 +0000844 // Delete old, floating point, increment instruction.
845 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
Dan Gohman28055122009-05-12 02:17:14 +0000846 RecursivelyDeleteTriviallyDeadInstructions(Incr);
Dan Gohman963fc812009-02-17 19:13:57 +0000847
Dan Gohman28055122009-05-12 02:17:14 +0000848 // Replace floating induction variable, if it isn't already deleted.
849 // Give SIToFPInst preference over UIToFPInst because it is faster on
850 // platforms that are widely used.
851 if (WeakPH && !PH->use_empty()) {
852 if (useSIToFPInst(*InitValue, *EV, newInitValue, intEV)) {
853 SIToFPInst *Conv = new SIToFPInst(NewPHI, PH->getType(), "indvar.conv",
854 PH->getParent()->getFirstNonPHI());
855 PH->replaceAllUsesWith(Conv);
856 } else {
857 UIToFPInst *Conv = new UIToFPInst(NewPHI, PH->getType(), "indvar.conv",
858 PH->getParent()->getFirstNonPHI());
859 PH->replaceAllUsesWith(Conv);
860 }
861 RecursivelyDeleteTriviallyDeadInstructions(PH);
Devang Patele2ba01d2008-11-17 23:27:13 +0000862 }
Devang Patel7ca23c92008-11-03 18:32:19 +0000863
Dan Gohman28055122009-05-12 02:17:14 +0000864 // Add a new IVUsers entry for the newly-created integer PHI.
865 IU->AddUsersIfInteresting(NewPHI);
866}