blob: 4cfe3595beeaa2d075ec7b9dbe1263e410affe22 [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");
62STATISTIC(NumPointer , "Number of pointer indvars promoted");
63STATISTIC(NumInserted, "Number of canonical indvars added");
64STATISTIC(NumReplaced, "Number of exit values replaced");
65STATISTIC(NumLFTR , "Number of loop exit tests replaced");
Chris Lattner3324e712003-12-22 03:58:44 +000066
Chris Lattner0e5f4992006-12-19 21:40:18 +000067namespace {
Devang Patel5ee99972007-03-07 06:39:01 +000068 class VISIBILITY_HIDDEN IndVarSimplify : public LoopPass {
Chris Lattner40bf8b42004-04-02 20:24:31 +000069 LoopInfo *LI;
70 ScalarEvolution *SE;
Chris Lattner15cad752003-12-23 07:47:09 +000071 bool Changed;
Chris Lattner3324e712003-12-22 03:58:44 +000072 public:
Devang Patel794fd752007-05-01 21:15:47 +000073
Nick Lewyckyecd94c82007-05-06 13:37:16 +000074 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000075 IndVarSimplify() : LoopPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000076
Dan Gohman60f8a632009-02-17 20:49:49 +000077 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
78
Devang Patel5ee99972007-03-07 06:39:01 +000079 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Devang Patelbc533cd2007-09-10 18:08:23 +000080 AU.addRequired<ScalarEvolution>();
Devang Patel5ee99972007-03-07 06:39:01 +000081 AU.addRequiredID(LCSSAID);
82 AU.addRequiredID(LoopSimplifyID);
Devang Patel5ee99972007-03-07 06:39:01 +000083 AU.addRequired<LoopInfo>();
84 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
Chris Lattner40bf8b42004-04-02 20:24:31 +000093 void EliminatePointerRecurrence(PHINode *PN, BasicBlock *Preheader,
Chris Lattner1a6111f2008-11-16 07:17:51 +000094 SmallPtrSet<Instruction*, 16> &DeadInsts);
Dan Gohmana5758712009-02-17 15:57:39 +000095 void LinearFunctionTestReplace(Loop *L, SCEVHandle IterationCount,
96 Value *IndVar,
Dan Gohmanc2390b12009-02-12 22:19:27 +000097 BasicBlock *ExitingBlock,
98 BranchInst *BI,
99 SCEVExpander &Rewriter);
Dan Gohman5a6c4482008-08-05 22:34:21 +0000100 void RewriteLoopExitValues(Loop *L, SCEV *IterationCount);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000101
Chris Lattner1a6111f2008-11-16 07:17:51 +0000102 void DeleteTriviallyDeadInstructions(SmallPtrSet<Instruction*, 16> &Insts);
Devang Pateld22a8492008-09-09 21:41:07 +0000103
Dan Gohmancafb8132009-02-17 19:13:57 +0000104 void HandleFloatingPointIV(Loop *L, PHINode *PH,
Devang Patel84e35152008-11-17 21:32:02 +0000105 SmallPtrSet<Instruction*, 16> &DeadInsts);
Chris Lattner3324e712003-12-22 03:58:44 +0000106 };
Chris Lattner5e761402002-09-10 05:24:05 +0000107}
Chris Lattner394437f2001-12-04 04:32:29 +0000108
Dan Gohman844731a2008-05-13 00:00:25 +0000109char IndVarSimplify::ID = 0;
110static RegisterPass<IndVarSimplify>
111X("indvars", "Canonicalize Induction Variables");
112
Daniel Dunbar394f0442008-10-22 23:32:42 +0000113Pass *llvm::createIndVarSimplifyPass() {
Chris Lattner3324e712003-12-22 03:58:44 +0000114 return new IndVarSimplify();
Chris Lattner394437f2001-12-04 04:32:29 +0000115}
116
Chris Lattner40bf8b42004-04-02 20:24:31 +0000117/// DeleteTriviallyDeadInstructions - If any of the instructions is the
118/// specified set are trivially dead, delete them and see if this makes any of
119/// their operands subsequently dead.
120void IndVarSimplify::
Chris Lattner1a6111f2008-11-16 07:17:51 +0000121DeleteTriviallyDeadInstructions(SmallPtrSet<Instruction*, 16> &Insts) {
Chris Lattner40bf8b42004-04-02 20:24:31 +0000122 while (!Insts.empty()) {
123 Instruction *I = *Insts.begin();
Chris Lattner1a6111f2008-11-16 07:17:51 +0000124 Insts.erase(I);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000125 if (isInstructionTriviallyDead(I)) {
126 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
127 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
128 Insts.insert(U);
Dan Gohman5cec4db2007-06-19 14:28:31 +0000129 SE->deleteValueFromRecords(I);
Chris Lattneree4f13a2007-01-07 01:14:12 +0000130 DOUT << "INDVARS: Deleting: " << *I;
Chris Lattnera4b9c782004-10-11 23:06:50 +0000131 I->eraseFromParent();
Chris Lattner40bf8b42004-04-02 20:24:31 +0000132 Changed = true;
133 }
134 }
135}
136
137
138/// EliminatePointerRecurrence - Check to see if this is a trivial GEP pointer
139/// recurrence. If so, change it into an integer recurrence, permitting
140/// analysis by the SCEV routines.
Misha Brukmanfd939082005-04-21 23:48:37 +0000141void IndVarSimplify::EliminatePointerRecurrence(PHINode *PN,
Chris Lattner40bf8b42004-04-02 20:24:31 +0000142 BasicBlock *Preheader,
Chris Lattner1a6111f2008-11-16 07:17:51 +0000143 SmallPtrSet<Instruction*, 16> &DeadInsts) {
Chris Lattner40bf8b42004-04-02 20:24:31 +0000144 assert(PN->getNumIncomingValues() == 2 && "Noncanonicalized loop!");
145 unsigned PreheaderIdx = PN->getBasicBlockIndex(Preheader);
146 unsigned BackedgeIdx = PreheaderIdx^1;
147 if (GetElementPtrInst *GEPI =
Chris Lattnercda9ca52005-08-10 01:12:06 +0000148 dyn_cast<GetElementPtrInst>(PN->getIncomingValue(BackedgeIdx)))
Chris Lattner40bf8b42004-04-02 20:24:31 +0000149 if (GEPI->getOperand(0) == PN) {
Chris Lattnercda9ca52005-08-10 01:12:06 +0000150 assert(GEPI->getNumOperands() == 2 && "GEP types must match!");
Chris Lattneree4f13a2007-01-07 01:14:12 +0000151 DOUT << "INDVARS: Eliminating pointer recurrence: " << *GEPI;
Dan Gohmancafb8132009-02-17 19:13:57 +0000152
Chris Lattner40bf8b42004-04-02 20:24:31 +0000153 // Okay, we found a pointer recurrence. Transform this pointer
154 // recurrence into an integer recurrence. Compute the value that gets
155 // added to the pointer at every iteration.
156 Value *AddedVal = GEPI->getOperand(1);
157
158 // Insert a new integer PHI node into the top of the block.
Gabor Greif051a9502008-04-06 20:25:17 +0000159 PHINode *NewPhi = PHINode::Create(AddedVal->getType(),
160 PN->getName()+".rec", PN);
Chris Lattnerc5c5e6a2004-06-20 05:04:01 +0000161 NewPhi->addIncoming(Constant::getNullValue(NewPhi->getType()), Preheader);
162
Chris Lattner40bf8b42004-04-02 20:24:31 +0000163 // Create the new add instruction.
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000164 Value *NewAdd = BinaryOperator::CreateAdd(NewPhi, AddedVal,
Chris Lattnerc5c5e6a2004-06-20 05:04:01 +0000165 GEPI->getName()+".rec", GEPI);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000166 NewPhi->addIncoming(NewAdd, PN->getIncomingBlock(BackedgeIdx));
Misha Brukmanfd939082005-04-21 23:48:37 +0000167
Chris Lattner40bf8b42004-04-02 20:24:31 +0000168 // Update the existing GEP to use the recurrence.
169 GEPI->setOperand(0, PN->getIncomingValue(PreheaderIdx));
Misha Brukmanfd939082005-04-21 23:48:37 +0000170
Chris Lattner40bf8b42004-04-02 20:24:31 +0000171 // Update the GEP to use the new recurrence we just inserted.
172 GEPI->setOperand(1, NewAdd);
173
Chris Lattnera4b9c782004-10-11 23:06:50 +0000174 // If the incoming value is a constant expr GEP, try peeling out the array
175 // 0 index if possible to make things simpler.
176 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEPI->getOperand(0)))
177 if (CE->getOpcode() == Instruction::GetElementPtr) {
178 unsigned NumOps = CE->getNumOperands();
179 assert(NumOps > 1 && "CE folding didn't work!");
180 if (CE->getOperand(NumOps-1)->isNullValue()) {
181 // Check to make sure the last index really is an array index.
Chris Lattner17300782005-11-18 18:30:47 +0000182 gep_type_iterator GTI = gep_type_begin(CE);
Chris Lattnerceda6052005-11-17 19:35:42 +0000183 for (unsigned i = 1, e = CE->getNumOperands()-1;
Chris Lattnera4b9c782004-10-11 23:06:50 +0000184 i != e; ++i, ++GTI)
185 /*empty*/;
186 if (isa<SequentialType>(*GTI)) {
187 // Pull the last index out of the constant expr GEP.
Chris Lattner55eb1c42007-01-31 04:40:53 +0000188 SmallVector<Value*, 8> CEIdxs(CE->op_begin()+1, CE->op_end()-1);
Chris Lattnera4b9c782004-10-11 23:06:50 +0000189 Constant *NCE = ConstantExpr::getGetElementPtr(CE->getOperand(0),
Chris Lattner55eb1c42007-01-31 04:40:53 +0000190 &CEIdxs[0],
191 CEIdxs.size());
David Greeneb8f74792007-09-04 15:46:09 +0000192 Value *Idx[2];
193 Idx[0] = Constant::getNullValue(Type::Int32Ty);
194 Idx[1] = NewAdd;
Gabor Greif051a9502008-04-06 20:25:17 +0000195 GetElementPtrInst *NGEPI = GetElementPtrInst::Create(
Dan Gohmancafb8132009-02-17 19:13:57 +0000196 NCE, Idx, Idx + 2,
Reid Spencercae57542007-03-02 00:28:52 +0000197 GEPI->getName(), GEPI);
Dan Gohman5cec4db2007-06-19 14:28:31 +0000198 SE->deleteValueFromRecords(GEPI);
Chris Lattnera4b9c782004-10-11 23:06:50 +0000199 GEPI->replaceAllUsesWith(NGEPI);
200 GEPI->eraseFromParent();
201 GEPI = NGEPI;
202 }
203 }
204 }
205
206
Chris Lattner40bf8b42004-04-02 20:24:31 +0000207 // Finally, if there are any other users of the PHI node, we must
208 // insert a new GEP instruction that uses the pre-incremented version
209 // of the induction amount.
210 if (!PN->use_empty()) {
211 BasicBlock::iterator InsertPos = PN; ++InsertPos;
212 while (isa<PHINode>(InsertPos)) ++InsertPos;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000213 Value *PreInc =
Gabor Greif051a9502008-04-06 20:25:17 +0000214 GetElementPtrInst::Create(PN->getIncomingValue(PreheaderIdx),
215 NewPhi, "", InsertPos);
Chris Lattner6934a042007-02-11 01:23:03 +0000216 PreInc->takeName(PN);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000217 PN->replaceAllUsesWith(PreInc);
218 }
219
220 // Delete the old PHI for sure, and the GEP if its otherwise unused.
221 DeadInsts.insert(PN);
222
223 ++NumPointer;
224 Changed = true;
225 }
226}
227
228/// LinearFunctionTestReplace - This method rewrites the exit condition of the
Chris Lattner59fdaee2004-04-15 15:21:43 +0000229/// loop to be a canonical != comparison against the incremented loop induction
230/// variable. This pass is able to rewrite the exit tests of any loop where the
231/// SCEV analysis can determine a loop-invariant trip count of the loop, which
232/// is actually a much broader range than just linear tests.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000233void IndVarSimplify::LinearFunctionTestReplace(Loop *L,
234 SCEVHandle IterationCount,
235 Value *IndVar,
236 BasicBlock *ExitingBlock,
237 BranchInst *BI,
238 SCEVExpander &Rewriter) {
Chris Lattnerd2440572004-04-15 20:26:22 +0000239 // If the exiting block is not the same as the backedge block, we must compare
240 // against the preincremented value, otherwise we prefer to compare against
241 // the post-incremented value.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000242 Value *CmpIndVar;
243 if (ExitingBlock == L->getLoopLatch()) {
244 // What ScalarEvolution calls the "iteration count" is actually the
245 // number of times the branch is taken. Add one to get the number
246 // of times the branch is executed. If this addition may overflow,
247 // we have to be more pessimistic and cast the induction variable
248 // before doing the add.
249 SCEVHandle Zero = SE->getIntegerSCEV(0, IterationCount->getType());
250 SCEVHandle N =
251 SE->getAddExpr(IterationCount,
252 SE->getIntegerSCEV(1, IterationCount->getType()));
253 if ((isa<SCEVConstant>(N) && !N->isZero()) ||
254 SE->isLoopGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) {
255 // No overflow. Cast the sum.
256 IterationCount = SE->getTruncateOrZeroExtend(N, IndVar->getType());
257 } else {
258 // Potential overflow. Cast before doing the add.
259 IterationCount = SE->getTruncateOrZeroExtend(IterationCount,
260 IndVar->getType());
261 IterationCount =
262 SE->getAddExpr(IterationCount,
263 SE->getIntegerSCEV(1, IndVar->getType()));
264 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000265
Chris Lattnerd2440572004-04-15 20:26:22 +0000266 // The IterationCount expression contains the number of times that the
267 // backedge actually branches to the loop header. This is one less than the
268 // number of times the loop executes, so add one to it.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000269 CmpIndVar = L->getCanonicalInductionVariableIncrement();
Chris Lattnerd2440572004-04-15 20:26:22 +0000270 } else {
271 // We have to use the preincremented value...
Dan Gohmanc2390b12009-02-12 22:19:27 +0000272 IterationCount = SE->getTruncateOrZeroExtend(IterationCount,
273 IndVar->getType());
274 CmpIndVar = IndVar;
Chris Lattnerd2440572004-04-15 20:26:22 +0000275 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000276
Chris Lattner40bf8b42004-04-02 20:24:31 +0000277 // Expand the code for the iteration count into the preheader of the loop.
278 BasicBlock *Preheader = L->getLoopPreheader();
Dan Gohmanc2390b12009-02-12 22:19:27 +0000279 Value *ExitCnt = Rewriter.expandCodeFor(IterationCount,
280 Preheader->getTerminator());
Chris Lattner40bf8b42004-04-02 20:24:31 +0000281
Reid Spencere4d87aa2006-12-23 06:05:41 +0000282 // Insert a new icmp_ne or icmp_eq instruction before the branch.
283 ICmpInst::Predicate Opcode;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000284 if (L->contains(BI->getSuccessor(0)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000285 Opcode = ICmpInst::ICMP_NE;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000286 else
Reid Spencere4d87aa2006-12-23 06:05:41 +0000287 Opcode = ICmpInst::ICMP_EQ;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000288
Dan Gohmanc2390b12009-02-12 22:19:27 +0000289 DOUT << "INDVARS: Rewriting loop exit condition to:\n"
290 << " LHS:" << *CmpIndVar // includes a newline
291 << " op:\t"
Dan Gohmanf108e2e2009-02-14 02:26:50 +0000292 << (Opcode == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
Dan Gohmanc2390b12009-02-12 22:19:27 +0000293 << " RHS:\t" << *IterationCount << "\n";
294
295 Value *Cond = new ICmpInst(Opcode, CmpIndVar, ExitCnt, "exitcond", BI);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000296 BI->setCondition(Cond);
297 ++NumLFTR;
298 Changed = true;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000299}
300
Chris Lattner40bf8b42004-04-02 20:24:31 +0000301/// RewriteLoopExitValues - Check to see if this loop has a computable
302/// loop-invariant execution count. If so, this means that we can compute the
303/// final value of any expressions that are recurrent in the loop, and
304/// substitute the exit values from the loop into any instructions outside of
305/// the loop that use the final values of the current expressions.
Dan Gohman5a6c4482008-08-05 22:34:21 +0000306void IndVarSimplify::RewriteLoopExitValues(Loop *L, SCEV *IterationCount) {
Chris Lattner40bf8b42004-04-02 20:24:31 +0000307 BasicBlock *Preheader = L->getLoopPreheader();
308
309 // Scan all of the instructions in the loop, looking at those that have
310 // extra-loop users and which are recurrences.
Chris Lattner4a7553e2004-04-23 21:29:48 +0000311 SCEVExpander Rewriter(*SE, *LI);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000312
313 // We insert the code into the preheader of the loop if the loop contains
314 // multiple exit blocks, or in the exit block if there is exactly one.
315 BasicBlock *BlockToInsertInto;
Devang Patelb7211a22007-08-21 00:31:24 +0000316 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattner9f3d7382007-03-04 03:43:23 +0000317 L->getUniqueExitBlocks(ExitBlocks);
Chris Lattnerf1ab4b42004-04-18 22:14:10 +0000318 if (ExitBlocks.size() == 1)
319 BlockToInsertInto = ExitBlocks[0];
Chris Lattner40bf8b42004-04-02 20:24:31 +0000320 else
321 BlockToInsertInto = Preheader;
Dan Gohman02dea8b2008-05-23 21:05:58 +0000322 BasicBlock::iterator InsertPt = BlockToInsertInto->getFirstNonPHI();
Chris Lattner40bf8b42004-04-02 20:24:31 +0000323
Dan Gohman5a6c4482008-08-05 22:34:21 +0000324 bool HasConstantItCount = isa<SCEVConstant>(IterationCount);
Chris Lattner20aa0982004-04-17 18:44:09 +0000325
Chris Lattner1a6111f2008-11-16 07:17:51 +0000326 SmallPtrSet<Instruction*, 16> InstructionsToDelete;
Chris Lattner9f3d7382007-03-04 03:43:23 +0000327 std::map<Instruction*, Value*> ExitValues;
Misha Brukmanfd939082005-04-21 23:48:37 +0000328
Chris Lattner9f3d7382007-03-04 03:43:23 +0000329 // Find all values that are computed inside the loop, but used outside of it.
330 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
331 // the exit blocks of the loop to find them.
332 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
333 BasicBlock *ExitBB = ExitBlocks[i];
Dan Gohmancafb8132009-02-17 19:13:57 +0000334
Chris Lattner9f3d7382007-03-04 03:43:23 +0000335 // If there are no PHI nodes in this exit block, then no values defined
336 // inside the loop are used on this path, skip it.
337 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
338 if (!PN) continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000339
Chris Lattner9f3d7382007-03-04 03:43:23 +0000340 unsigned NumPreds = PN->getNumIncomingValues();
Dan Gohmancafb8132009-02-17 19:13:57 +0000341
Chris Lattner9f3d7382007-03-04 03:43:23 +0000342 // Iterate over all of the PHI nodes.
343 BasicBlock::iterator BBI = ExitBB->begin();
344 while ((PN = dyn_cast<PHINode>(BBI++))) {
Dan Gohmancafb8132009-02-17 19:13:57 +0000345
Chris Lattner9f3d7382007-03-04 03:43:23 +0000346 // Iterate over all of the values in all the PHI nodes.
347 for (unsigned i = 0; i != NumPreds; ++i) {
348 // If the value being merged in is not integer or is not defined
349 // in the loop, skip it.
350 Value *InVal = PN->getIncomingValue(i);
351 if (!isa<Instruction>(InVal) ||
352 // SCEV only supports integer expressions for now.
353 !isa<IntegerType>(InVal->getType()))
354 continue;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000355
Chris Lattner9f3d7382007-03-04 03:43:23 +0000356 // If this pred is for a subloop, not L itself, skip it.
Dan Gohmancafb8132009-02-17 19:13:57 +0000357 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
Chris Lattner9f3d7382007-03-04 03:43:23 +0000358 continue; // The Block is in a subloop, skip it.
359
360 // Check that InVal is defined in the loop.
361 Instruction *Inst = cast<Instruction>(InVal);
362 if (!L->contains(Inst->getParent()))
363 continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000364
Chris Lattner9f3d7382007-03-04 03:43:23 +0000365 // We require that this value either have a computable evolution or that
366 // the loop have a constant iteration count. In the case where the loop
367 // has a constant iteration count, we can sometimes force evaluation of
368 // the exit value through brute force.
369 SCEVHandle SH = SE->getSCEV(Inst);
370 if (!SH->hasComputableLoopEvolution(L) && !HasConstantItCount)
371 continue; // Cannot get exit evolution for the loop value.
Dan Gohmancafb8132009-02-17 19:13:57 +0000372
Chris Lattner9f3d7382007-03-04 03:43:23 +0000373 // Okay, this instruction has a user outside of the current loop
374 // and varies predictably *inside* the loop. Evaluate the value it
375 // contains when the loop exits, if possible.
376 SCEVHandle ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
377 if (isa<SCEVCouldNotCompute>(ExitValue) ||
378 !ExitValue->isLoopInvariant(L))
379 continue;
Chris Lattner9caed542007-03-04 01:00:28 +0000380
Chris Lattner9f3d7382007-03-04 03:43:23 +0000381 Changed = true;
382 ++NumReplaced;
Dan Gohmancafb8132009-02-17 19:13:57 +0000383
Chris Lattner9f3d7382007-03-04 03:43:23 +0000384 // See if we already computed the exit value for the instruction, if so,
385 // just reuse it.
386 Value *&ExitVal = ExitValues[Inst];
387 if (!ExitVal)
Dan Gohmand19534a2007-06-15 14:38:12 +0000388 ExitVal = Rewriter.expandCodeFor(ExitValue, InsertPt);
Dan Gohmancafb8132009-02-17 19:13:57 +0000389
Chris Lattner9f3d7382007-03-04 03:43:23 +0000390 DOUT << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal
391 << " LoopVal = " << *Inst << "\n";
392
393 PN->setIncomingValue(i, ExitVal);
Dan Gohmancafb8132009-02-17 19:13:57 +0000394
Chris Lattner9f3d7382007-03-04 03:43:23 +0000395 // If this instruction is dead now, schedule it to be removed.
396 if (Inst->use_empty())
397 InstructionsToDelete.insert(Inst);
Dan Gohmancafb8132009-02-17 19:13:57 +0000398
Chris Lattner9f3d7382007-03-04 03:43:23 +0000399 // See if this is a single-entry LCSSA PHI node. If so, we can (and
400 // have to) remove
Chris Lattner9caed542007-03-04 01:00:28 +0000401 // the PHI entirely. This is safe, because the NewVal won't be variant
402 // in the loop, so we don't need an LCSSA phi node anymore.
Chris Lattner9f3d7382007-03-04 03:43:23 +0000403 if (NumPreds == 1) {
Dan Gohman5cec4db2007-06-19 14:28:31 +0000404 SE->deleteValueFromRecords(PN);
Chris Lattner9f3d7382007-03-04 03:43:23 +0000405 PN->replaceAllUsesWith(ExitVal);
406 PN->eraseFromParent();
407 break;
Chris Lattnerc9838f22007-03-03 22:48:48 +0000408 }
409 }
Chris Lattnerc9838f22007-03-03 22:48:48 +0000410 }
411 }
Dan Gohmancafb8132009-02-17 19:13:57 +0000412
Chris Lattner40bf8b42004-04-02 20:24:31 +0000413 DeleteTriviallyDeadInstructions(InstructionsToDelete);
414}
415
Dan Gohman60f8a632009-02-17 20:49:49 +0000416void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) {
Chris Lattner40bf8b42004-04-02 20:24:31 +0000417 // First step. Check to see if there are any trivial GEP pointer recurrences.
418 // If there are, change them into integer recurrences, permitting analysis by
419 // the SCEV routines.
420 //
421 BasicBlock *Header = L->getHeader();
422 BasicBlock *Preheader = L->getLoopPreheader();
Misha Brukmanfd939082005-04-21 23:48:37 +0000423
Chris Lattner1a6111f2008-11-16 07:17:51 +0000424 SmallPtrSet<Instruction*, 16> DeadInsts;
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000425 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
426 PHINode *PN = cast<PHINode>(I);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000427 if (isa<PointerType>(PN->getType()))
428 EliminatePointerRecurrence(PN, Preheader, DeadInsts);
Devang Patel84e35152008-11-17 21:32:02 +0000429 else
430 HandleFloatingPointIV(L, PN, DeadInsts);
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000431 }
Chris Lattner40bf8b42004-04-02 20:24:31 +0000432
Dan Gohman60f8a632009-02-17 20:49:49 +0000433 // If the loop previously had a pointer or floating-point IV, ScalarEvolution
434 // may not have been able to compute a trip count. Now that we've done some
435 // re-writing, the trip count may be computable.
436 if (Changed)
437 SE->forgetLoopIterationCount(L);
438
Chris Lattner40bf8b42004-04-02 20:24:31 +0000439 if (!DeadInsts.empty())
440 DeleteTriviallyDeadInstructions(DeadInsts);
Devang Patel5ee99972007-03-07 06:39:01 +0000441}
Chris Lattner40bf8b42004-04-02 20:24:31 +0000442
Dan Gohmanc2390b12009-02-12 22:19:27 +0000443/// getEffectiveIndvarType - Determine the widest type that the
444/// induction-variable PHINode Phi is cast to.
445///
446static const Type *getEffectiveIndvarType(const PHINode *Phi) {
447 const Type *Ty = Phi->getType();
Chris Lattner3324e712003-12-22 03:58:44 +0000448
Dan Gohmanc2390b12009-02-12 22:19:27 +0000449 for (Value::use_const_iterator UI = Phi->use_begin(), UE = Phi->use_end();
450 UI != UE; ++UI) {
451 const Type *CandidateType = NULL;
452 if (const ZExtInst *ZI = dyn_cast<ZExtInst>(UI))
453 CandidateType = ZI->getDestTy();
454 else if (const SExtInst *SI = dyn_cast<SExtInst>(UI))
455 CandidateType = SI->getDestTy();
456 if (CandidateType &&
457 CandidateType->getPrimitiveSizeInBits() >
458 Ty->getPrimitiveSizeInBits())
459 Ty = CandidateType;
460 }
461
462 return Ty;
463}
464
Dan Gohmanaa036492009-02-14 02:31:09 +0000465/// TestOrigIVForWrap - Analyze the original induction variable
466/// in the loop to determine whether it would ever undergo signed
467/// or unsigned overflow.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000468///
469/// TODO: This duplicates a fair amount of ScalarEvolution logic.
Dan Gohmanaa036492009-02-14 02:31:09 +0000470/// Perhaps this can be merged with ScalarEvolution::getIterationCount
471/// and/or ScalarEvolution::get{Sign,Zero}ExtendExpr.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000472///
Dan Gohmanaa036492009-02-14 02:31:09 +0000473static void TestOrigIVForWrap(const Loop *L,
474 const BranchInst *BI,
475 const Instruction *OrigCond,
476 bool &NoSignedWrap,
477 bool &NoUnsignedWrap) {
Dan Gohmanc2390b12009-02-12 22:19:27 +0000478 // Verify that the loop is sane and find the exit condition.
479 const ICmpInst *Cmp = dyn_cast<ICmpInst>(OrigCond);
Dan Gohmanaa036492009-02-14 02:31:09 +0000480 if (!Cmp) return;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000481
Dan Gohmanaa036492009-02-14 02:31:09 +0000482 const Value *CmpLHS = Cmp->getOperand(0);
483 const Value *CmpRHS = Cmp->getOperand(1);
484 const BasicBlock *TrueBB = BI->getSuccessor(0);
485 const BasicBlock *FalseBB = BI->getSuccessor(1);
486 ICmpInst::Predicate Pred = Cmp->getPredicate();
Dan Gohmanc2390b12009-02-12 22:19:27 +0000487
Dan Gohmanaa036492009-02-14 02:31:09 +0000488 // Canonicalize a constant to the RHS.
489 if (isa<ConstantInt>(CmpLHS)) {
490 Pred = ICmpInst::getSwappedPredicate(Pred);
491 std::swap(CmpLHS, CmpRHS);
492 }
493 // Canonicalize SLE to SLT.
494 if (Pred == ICmpInst::ICMP_SLE)
495 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
496 if (!CI->getValue().isMaxSignedValue()) {
497 CmpRHS = ConstantInt::get(CI->getValue() + 1);
498 Pred = ICmpInst::ICMP_SLT;
499 }
500 // Canonicalize SGT to SGE.
501 if (Pred == ICmpInst::ICMP_SGT)
502 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
503 if (!CI->getValue().isMaxSignedValue()) {
504 CmpRHS = ConstantInt::get(CI->getValue() + 1);
505 Pred = ICmpInst::ICMP_SGE;
506 }
507 // Canonicalize SGE to SLT.
508 if (Pred == ICmpInst::ICMP_SGE) {
509 std::swap(TrueBB, FalseBB);
510 Pred = ICmpInst::ICMP_SLT;
511 }
512 // Canonicalize ULE to ULT.
513 if (Pred == ICmpInst::ICMP_ULE)
514 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
515 if (!CI->getValue().isMaxValue()) {
516 CmpRHS = ConstantInt::get(CI->getValue() + 1);
517 Pred = ICmpInst::ICMP_ULT;
518 }
519 // Canonicalize UGT to UGE.
520 if (Pred == ICmpInst::ICMP_UGT)
521 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
522 if (!CI->getValue().isMaxValue()) {
523 CmpRHS = ConstantInt::get(CI->getValue() + 1);
524 Pred = ICmpInst::ICMP_UGE;
525 }
526 // Canonicalize UGE to ULT.
527 if (Pred == ICmpInst::ICMP_UGE) {
528 std::swap(TrueBB, FalseBB);
529 Pred = ICmpInst::ICMP_ULT;
530 }
531 // For now, analyze only LT loops for signed overflow.
532 if (Pred != ICmpInst::ICMP_SLT && Pred != ICmpInst::ICMP_ULT)
533 return;
534
535 bool isSigned = Pred == ICmpInst::ICMP_SLT;
536
537 // Get the increment instruction. Look past casts if we will
Dan Gohmanc2390b12009-02-12 22:19:27 +0000538 // be able to prove that the original induction variable doesn't
Dan Gohmanaa036492009-02-14 02:31:09 +0000539 // undergo signed or unsigned overflow, respectively.
540 const Value *IncrVal = CmpLHS;
541 if (isSigned) {
542 if (const SExtInst *SI = dyn_cast<SExtInst>(CmpLHS)) {
543 if (!isa<ConstantInt>(CmpRHS) ||
544 !cast<ConstantInt>(CmpRHS)->getValue()
545 .isSignedIntN(IncrVal->getType()->getPrimitiveSizeInBits()))
546 return;
547 IncrVal = SI->getOperand(0);
548 }
549 } else {
550 if (const ZExtInst *ZI = dyn_cast<ZExtInst>(CmpLHS)) {
551 if (!isa<ConstantInt>(CmpRHS) ||
552 !cast<ConstantInt>(CmpRHS)->getValue()
553 .isIntN(IncrVal->getType()->getPrimitiveSizeInBits()))
554 return;
555 IncrVal = ZI->getOperand(0);
556 }
Dan Gohmanc2390b12009-02-12 22:19:27 +0000557 }
558
559 // For now, only analyze induction variables that have simple increments.
560 const BinaryOperator *IncrOp = dyn_cast<BinaryOperator>(IncrVal);
561 if (!IncrOp ||
562 IncrOp->getOpcode() != Instruction::Add ||
563 !isa<ConstantInt>(IncrOp->getOperand(1)) ||
564 !cast<ConstantInt>(IncrOp->getOperand(1))->equalsInt(1))
Dan Gohmanaa036492009-02-14 02:31:09 +0000565 return;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000566
567 // Make sure the PHI looks like a normal IV.
568 const PHINode *PN = dyn_cast<PHINode>(IncrOp->getOperand(0));
569 if (!PN || PN->getNumIncomingValues() != 2)
Dan Gohmanaa036492009-02-14 02:31:09 +0000570 return;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000571 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
572 unsigned BackEdge = !IncomingEdge;
573 if (!L->contains(PN->getIncomingBlock(BackEdge)) ||
574 PN->getIncomingValue(BackEdge) != IncrOp)
Dan Gohmanaa036492009-02-14 02:31:09 +0000575 return;
576 if (!L->contains(TrueBB))
577 return;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000578
579 // For now, only analyze loops with a constant start value, so that
Dan Gohmanaa036492009-02-14 02:31:09 +0000580 // we can easily determine if the start value is not a maximum value
581 // which would wrap on the first iteration.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000582 const Value *InitialVal = PN->getIncomingValue(IncomingEdge);
Dan Gohmanaa036492009-02-14 02:31:09 +0000583 if (!isa<ConstantInt>(InitialVal))
584 return;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000585
Dan Gohmanaa036492009-02-14 02:31:09 +0000586 // The original induction variable will start at some non-max value,
587 // it counts up by one, and the loop iterates only while it remans
588 // less than some value in the same type. As such, it will never wrap.
589 if (isSigned &&
590 !cast<ConstantInt>(InitialVal)->getValue().isMaxSignedValue())
591 NoSignedWrap = true;
592 else if (!isSigned &&
593 !cast<ConstantInt>(InitialVal)->getValue().isMaxValue())
594 NoUnsignedWrap = true;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000595}
596
597bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
Devang Patel5ee99972007-03-07 06:39:01 +0000598 LI = &getAnalysis<LoopInfo>();
599 SE = &getAnalysis<ScalarEvolution>();
Devang Patel5ee99972007-03-07 06:39:01 +0000600 Changed = false;
Dan Gohman60f8a632009-02-17 20:49:49 +0000601
602 // If there are any floating-point or pointer recurrences, attempt to
603 // transform them to use integer recurrences.
604 RewriteNonIntegerIVs(L);
605
Dan Gohmanc2390b12009-02-12 22:19:27 +0000606 BasicBlock *Header = L->getHeader();
607 BasicBlock *ExitingBlock = L->getExitingBlock();
Chris Lattner1a6111f2008-11-16 07:17:51 +0000608 SmallPtrSet<Instruction*, 16> DeadInsts;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000609
Chris Lattner9caed542007-03-04 01:00:28 +0000610 // Verify the input to the pass in already in LCSSA form.
611 assert(L->isLCSSAForm());
612
Chris Lattner40bf8b42004-04-02 20:24:31 +0000613 // Check to see if this loop has a computable loop-invariant execution count.
614 // If so, this means that we can compute the final value of any expressions
615 // that are recurrent in the loop, and substitute the exit values from the
616 // loop into any instructions outside of the loop that use the final values of
617 // the current expressions.
Chris Lattner3dec1f22002-05-10 15:38:35 +0000618 //
Chris Lattner40bf8b42004-04-02 20:24:31 +0000619 SCEVHandle IterationCount = SE->getIterationCount(L);
620 if (!isa<SCEVCouldNotCompute>(IterationCount))
Dan Gohman5a6c4482008-08-05 22:34:21 +0000621 RewriteLoopExitValues(L, IterationCount);
Chris Lattner6148c022001-12-03 17:28:42 +0000622
Chris Lattner40bf8b42004-04-02 20:24:31 +0000623 // Next, analyze all of the induction variables in the loop, canonicalizing
624 // auxillary induction variables.
625 std::vector<std::pair<PHINode*, SCEVHandle> > IndVars;
626
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000627 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
628 PHINode *PN = cast<PHINode>(I);
Chris Lattner42a75512007-01-15 02:27:26 +0000629 if (PN->getType()->isInteger()) { // FIXME: when we have fast-math, enable!
Chris Lattner40bf8b42004-04-02 20:24:31 +0000630 SCEVHandle SCEV = SE->getSCEV(PN);
Dan Gohmancd3eb9b2009-02-14 02:25:19 +0000631 // FIXME: It is an extremely bad idea to indvar substitute anything more
632 // complex than affine induction variables. Doing so will put expensive
633 // polynomial evaluations inside of the loop, and the str reduction pass
634 // currently can only reduce affine polynomials. For now just disable
635 // indvar subst on anything more complex than an affine addrec.
636 if (SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SCEV))
637 if (AR->getLoop() == L && AR->isAffine())
638 IndVars.push_back(std::make_pair(PN, SCEV));
Chris Lattner40bf8b42004-04-02 20:24:31 +0000639 }
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000640 }
Chris Lattner40bf8b42004-04-02 20:24:31 +0000641
Dan Gohmanc2390b12009-02-12 22:19:27 +0000642 // Compute the type of the largest recurrence expression, and collect
643 // the set of the types of the other recurrence expressions.
644 const Type *LargestType = 0;
645 SmallSetVector<const Type *, 4> SizesToInsert;
646 if (!isa<SCEVCouldNotCompute>(IterationCount)) {
647 LargestType = IterationCount->getType();
648 SizesToInsert.insert(IterationCount->getType());
Chris Lattnerf50af082004-04-17 18:08:33 +0000649 }
Dan Gohmanc2390b12009-02-12 22:19:27 +0000650 for (unsigned i = 0, e = IndVars.size(); i != e; ++i) {
651 const PHINode *PN = IndVars[i].first;
652 SizesToInsert.insert(PN->getType());
653 const Type *EffTy = getEffectiveIndvarType(PN);
654 SizesToInsert.insert(EffTy);
655 if (!LargestType ||
656 EffTy->getPrimitiveSizeInBits() >
657 LargestType->getPrimitiveSizeInBits())
658 LargestType = EffTy;
Chris Lattner6148c022001-12-03 17:28:42 +0000659 }
660
Chris Lattner40bf8b42004-04-02 20:24:31 +0000661 // Create a rewriter object which we'll use to transform the code with.
Chris Lattner4a7553e2004-04-23 21:29:48 +0000662 SCEVExpander Rewriter(*SE, *LI);
Chris Lattner15cad752003-12-23 07:47:09 +0000663
Chris Lattner40bf8b42004-04-02 20:24:31 +0000664 // Now that we know the largest of of the induction variables in this loop,
665 // insert a canonical induction variable of the largest size.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000666 Value *IndVar = 0;
667 if (!SizesToInsert.empty()) {
668 IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L,LargestType);
669 ++NumInserted;
670 Changed = true;
671 DOUT << "INDVARS: New CanIV: " << *IndVar;
Dan Gohmand19534a2007-06-15 14:38:12 +0000672 }
Chris Lattner15cad752003-12-23 07:47:09 +0000673
Dan Gohmanc2390b12009-02-12 22:19:27 +0000674 // If we have a trip count expression, rewrite the loop's exit condition
675 // using it. We can currently only handle loops with a single exit.
Dan Gohmanaa036492009-02-14 02:31:09 +0000676 bool NoSignedWrap = false;
677 bool NoUnsignedWrap = false;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000678 if (!isa<SCEVCouldNotCompute>(IterationCount) && ExitingBlock)
679 // Can't rewrite non-branch yet.
680 if (BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator())) {
681 if (Instruction *OrigCond = dyn_cast<Instruction>(BI->getCondition())) {
Dan Gohmanaa036492009-02-14 02:31:09 +0000682 // Determine if the OrigIV will ever undergo overflow.
683 TestOrigIVForWrap(L, BI, OrigCond,
684 NoSignedWrap, NoUnsignedWrap);
Dan Gohmanc2390b12009-02-12 22:19:27 +0000685
686 // We'll be replacing the original condition, so it'll be dead.
687 DeadInsts.insert(OrigCond);
688 }
689
690 LinearFunctionTestReplace(L, IterationCount, IndVar,
691 ExitingBlock, BI, Rewriter);
692 }
693
Chris Lattner40bf8b42004-04-02 20:24:31 +0000694 // Now that we have a canonical induction variable, we can rewrite any
695 // recurrences in terms of the induction variable. Start with the auxillary
696 // induction variables, and recursively rewrite any of their uses.
Dan Gohman02dea8b2008-05-23 21:05:58 +0000697 BasicBlock::iterator InsertPt = Header->getFirstNonPHI();
Chris Lattner6148c022001-12-03 17:28:42 +0000698
Chris Lattner5d461d22004-04-21 22:22:01 +0000699 // If there were induction variables of other sizes, cast the primary
700 // induction variable to the right size for them, avoiding the need for the
701 // code evaluation methods to insert induction variables of different sizes.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000702 for (unsigned i = 0, e = SizesToInsert.size(); i != e; ++i) {
703 const Type *Ty = SizesToInsert[i];
704 if (Ty != LargestType) {
705 Instruction *New = new TruncInst(IndVar, Ty, "indvar", InsertPt);
706 Rewriter.addInsertedValue(New, SE->getSCEV(New));
707 DOUT << "INDVARS: Made trunc IV for type " << *Ty << ": "
708 << *New << "\n";
Reid Spencera54b7cb2007-01-12 07:05:14 +0000709 }
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000710 }
711
Chris Lattneree4f13a2007-01-07 01:14:12 +0000712 // Rewrite all induction variables in terms of the canonical induction
713 // variable.
Chris Lattner40bf8b42004-04-02 20:24:31 +0000714 while (!IndVars.empty()) {
715 PHINode *PN = IndVars.back().first;
Dan Gohman1a5e9362009-02-17 00:10:53 +0000716 SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(IndVars.back().second);
717 Value *NewVal = Rewriter.expandCodeFor(AR, InsertPt);
718 DOUT << "INDVARS: Rewrote IV '" << *AR << "' " << *PN
Chris Lattneree4f13a2007-01-07 01:14:12 +0000719 << " into = " << *NewVal << "\n";
Chris Lattner6934a042007-02-11 01:23:03 +0000720 NewVal->takeName(PN);
Chris Lattner5d461d22004-04-21 22:22:01 +0000721
Dan Gohmanc2390b12009-02-12 22:19:27 +0000722 /// If the new canonical induction variable is wider than the original,
723 /// and the original has uses that are casts to wider types, see if the
724 /// truncate and extend can be omitted.
Dan Gohmanaa036492009-02-14 02:31:09 +0000725 if (PN->getType() != LargestType)
Dan Gohmanc2390b12009-02-12 22:19:27 +0000726 for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end();
Dan Gohmanaa036492009-02-14 02:31:09 +0000727 UI != UE; ++UI) {
728 if (isa<SExtInst>(UI) && NoSignedWrap) {
729 SCEVHandle ExtendedStart =
Dan Gohman1a5e9362009-02-17 00:10:53 +0000730 SE->getSignExtendExpr(AR->getStart(), LargestType);
Dan Gohmanaa036492009-02-14 02:31:09 +0000731 SCEVHandle ExtendedStep =
Dan Gohman1a5e9362009-02-17 00:10:53 +0000732 SE->getSignExtendExpr(AR->getStepRecurrence(*SE), LargestType);
Dan Gohmanaa036492009-02-14 02:31:09 +0000733 SCEVHandle ExtendedAddRec =
734 SE->getAddRecExpr(ExtendedStart, ExtendedStep, L);
735 if (LargestType != UI->getType())
736 ExtendedAddRec = SE->getTruncateExpr(ExtendedAddRec, UI->getType());
737 Value *TruncIndVar = Rewriter.expandCodeFor(ExtendedAddRec, InsertPt);
Dan Gohmanc2390b12009-02-12 22:19:27 +0000738 UI->replaceAllUsesWith(TruncIndVar);
739 if (Instruction *DeadUse = dyn_cast<Instruction>(*UI))
740 DeadInsts.insert(DeadUse);
741 }
Dan Gohmanaa036492009-02-14 02:31:09 +0000742 if (isa<ZExtInst>(UI) && NoUnsignedWrap) {
743 SCEVHandle ExtendedStart =
Dan Gohman1a5e9362009-02-17 00:10:53 +0000744 SE->getZeroExtendExpr(AR->getStart(), LargestType);
Dan Gohmanaa036492009-02-14 02:31:09 +0000745 SCEVHandle ExtendedStep =
Dan Gohman1a5e9362009-02-17 00:10:53 +0000746 SE->getZeroExtendExpr(AR->getStepRecurrence(*SE), LargestType);
Dan Gohmanaa036492009-02-14 02:31:09 +0000747 SCEVHandle ExtendedAddRec =
748 SE->getAddRecExpr(ExtendedStart, ExtendedStep, L);
749 if (LargestType != UI->getType())
750 ExtendedAddRec = SE->getTruncateExpr(ExtendedAddRec, UI->getType());
751 Value *TruncIndVar = Rewriter.expandCodeFor(ExtendedAddRec, InsertPt);
752 UI->replaceAllUsesWith(TruncIndVar);
753 if (Instruction *DeadUse = dyn_cast<Instruction>(*UI))
754 DeadInsts.insert(DeadUse);
755 }
756 }
Dan Gohmanc2390b12009-02-12 22:19:27 +0000757
Chris Lattner40bf8b42004-04-02 20:24:31 +0000758 // Replace the old PHI Node with the inserted computation.
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000759 PN->replaceAllUsesWith(NewVal);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000760 DeadInsts.insert(PN);
761 IndVars.pop_back();
762 ++NumRemoved;
Chris Lattner4753bf22001-12-05 19:41:33 +0000763 Changed = true;
Chris Lattner394437f2001-12-04 04:32:29 +0000764 }
765
Chris Lattner1363e852004-04-21 23:36:08 +0000766 DeleteTriviallyDeadInstructions(DeadInsts);
Chris Lattner9caed542007-03-04 01:00:28 +0000767 assert(L->isLCSSAForm());
Devang Patel5ee99972007-03-07 06:39:01 +0000768 return Changed;
Chris Lattner6148c022001-12-03 17:28:42 +0000769}
Devang Pateld22a8492008-09-09 21:41:07 +0000770
Devang Patel13877bf2008-11-18 00:40:02 +0000771/// Return true if it is OK to use SIToFPInst for an inducation variable
772/// with given inital and exit values.
773static bool useSIToFPInst(ConstantFP &InitV, ConstantFP &ExitV,
774 uint64_t intIV, uint64_t intEV) {
775
Dan Gohmancafb8132009-02-17 19:13:57 +0000776 if (InitV.getValueAPF().isNegative() || ExitV.getValueAPF().isNegative())
Devang Patel13877bf2008-11-18 00:40:02 +0000777 return true;
778
779 // If the iteration range can be handled by SIToFPInst then use it.
780 APInt Max = APInt::getSignedMaxValue(32);
Bill Wendling9bef7062008-11-18 10:57:27 +0000781 if (Max.getZExtValue() > static_cast<uint64_t>(abs(intEV - intIV)))
Devang Patel13877bf2008-11-18 00:40:02 +0000782 return true;
Dan Gohmancafb8132009-02-17 19:13:57 +0000783
Devang Patel13877bf2008-11-18 00:40:02 +0000784 return false;
785}
786
787/// convertToInt - Convert APF to an integer, if possible.
Devang Patelcd402332008-11-17 23:27:13 +0000788static bool convertToInt(const APFloat &APF, uint64_t *intVal) {
789
790 bool isExact = false;
Evan Cheng794a7db2008-11-26 01:11:57 +0000791 if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
792 return false;
Dan Gohmancafb8132009-02-17 19:13:57 +0000793 if (APF.convertToInteger(intVal, 32, APF.isNegative(),
Devang Patelcd402332008-11-17 23:27:13 +0000794 APFloat::rmTowardZero, &isExact)
795 != APFloat::opOK)
796 return false;
Dan Gohmancafb8132009-02-17 19:13:57 +0000797 if (!isExact)
Devang Patelcd402332008-11-17 23:27:13 +0000798 return false;
799 return true;
800
801}
802
Devang Patel58d43d42008-11-03 18:32:19 +0000803/// HandleFloatingPointIV - If the loop has floating induction variable
804/// then insert corresponding integer induction variable if possible.
Devang Patel84e35152008-11-17 21:32:02 +0000805/// For example,
806/// for(double i = 0; i < 10000; ++i)
807/// bar(i)
808/// is converted into
809/// for(int i = 0; i < 10000; ++i)
810/// bar((double)i);
811///
Dan Gohmancafb8132009-02-17 19:13:57 +0000812void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PH,
Devang Patel84e35152008-11-17 21:32:02 +0000813 SmallPtrSet<Instruction*, 16> &DeadInsts) {
Devang Patel58d43d42008-11-03 18:32:19 +0000814
Devang Patel84e35152008-11-17 21:32:02 +0000815 unsigned IncomingEdge = L->contains(PH->getIncomingBlock(0));
816 unsigned BackEdge = IncomingEdge^1;
Dan Gohmancafb8132009-02-17 19:13:57 +0000817
Devang Patel84e35152008-11-17 21:32:02 +0000818 // Check incoming value.
Devang Patelcd402332008-11-17 23:27:13 +0000819 ConstantFP *InitValue = dyn_cast<ConstantFP>(PH->getIncomingValue(IncomingEdge));
820 if (!InitValue) return;
821 uint64_t newInitValue = Type::Int32Ty->getPrimitiveSizeInBits();
822 if (!convertToInt(InitValue->getValueAPF(), &newInitValue))
823 return;
824
825 // Check IV increment. Reject this PH if increement operation is not
826 // an add or increment value can not be represented by an integer.
Dan Gohmancafb8132009-02-17 19:13:57 +0000827 BinaryOperator *Incr =
Devang Patel84e35152008-11-17 21:32:02 +0000828 dyn_cast<BinaryOperator>(PH->getIncomingValue(BackEdge));
829 if (!Incr) return;
830 if (Incr->getOpcode() != Instruction::Add) return;
831 ConstantFP *IncrValue = NULL;
832 unsigned IncrVIndex = 1;
833 if (Incr->getOperand(1) == PH)
834 IncrVIndex = 0;
835 IncrValue = dyn_cast<ConstantFP>(Incr->getOperand(IncrVIndex));
836 if (!IncrValue) return;
Devang Patelcd402332008-11-17 23:27:13 +0000837 uint64_t newIncrValue = Type::Int32Ty->getPrimitiveSizeInBits();
838 if (!convertToInt(IncrValue->getValueAPF(), &newIncrValue))
839 return;
Dan Gohmancafb8132009-02-17 19:13:57 +0000840
Devang Patelcd402332008-11-17 23:27:13 +0000841 // Check Incr uses. One user is PH and the other users is exit condition used
842 // by the conditional terminator.
Devang Patel84e35152008-11-17 21:32:02 +0000843 Value::use_iterator IncrUse = Incr->use_begin();
844 Instruction *U1 = cast<Instruction>(IncrUse++);
845 if (IncrUse == Incr->use_end()) return;
846 Instruction *U2 = cast<Instruction>(IncrUse++);
847 if (IncrUse != Incr->use_end()) return;
Dan Gohmancafb8132009-02-17 19:13:57 +0000848
Devang Patel84e35152008-11-17 21:32:02 +0000849 // Find exit condition.
850 FCmpInst *EC = dyn_cast<FCmpInst>(U1);
851 if (!EC)
852 EC = dyn_cast<FCmpInst>(U2);
853 if (!EC) return;
854
855 if (BranchInst *BI = dyn_cast<BranchInst>(EC->getParent()->getTerminator())) {
856 if (!BI->isConditional()) return;
857 if (BI->getCondition() != EC) return;
Devang Patel58d43d42008-11-03 18:32:19 +0000858 }
Devang Patel58d43d42008-11-03 18:32:19 +0000859
Devang Patelcd402332008-11-17 23:27:13 +0000860 // Find exit value. If exit value can not be represented as an interger then
861 // do not handle this floating point PH.
Devang Patel84e35152008-11-17 21:32:02 +0000862 ConstantFP *EV = NULL;
863 unsigned EVIndex = 1;
864 if (EC->getOperand(1) == Incr)
865 EVIndex = 0;
866 EV = dyn_cast<ConstantFP>(EC->getOperand(EVIndex));
867 if (!EV) return;
Devang Patel84e35152008-11-17 21:32:02 +0000868 uint64_t intEV = Type::Int32Ty->getPrimitiveSizeInBits();
Devang Patelcd402332008-11-17 23:27:13 +0000869 if (!convertToInt(EV->getValueAPF(), &intEV))
Devang Patel84e35152008-11-17 21:32:02 +0000870 return;
Dan Gohmancafb8132009-02-17 19:13:57 +0000871
Devang Patel84e35152008-11-17 21:32:02 +0000872 // Find new predicate for integer comparison.
873 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
874 switch (EC->getPredicate()) {
875 case CmpInst::FCMP_OEQ:
876 case CmpInst::FCMP_UEQ:
877 NewPred = CmpInst::ICMP_EQ;
878 break;
879 case CmpInst::FCMP_OGT:
880 case CmpInst::FCMP_UGT:
881 NewPred = CmpInst::ICMP_UGT;
882 break;
883 case CmpInst::FCMP_OGE:
884 case CmpInst::FCMP_UGE:
885 NewPred = CmpInst::ICMP_UGE;
886 break;
887 case CmpInst::FCMP_OLT:
888 case CmpInst::FCMP_ULT:
889 NewPred = CmpInst::ICMP_ULT;
890 break;
891 case CmpInst::FCMP_OLE:
892 case CmpInst::FCMP_ULE:
893 NewPred = CmpInst::ICMP_ULE;
894 break;
895 default:
896 break;
Devang Patel58d43d42008-11-03 18:32:19 +0000897 }
Devang Patel84e35152008-11-17 21:32:02 +0000898 if (NewPred == CmpInst::BAD_ICMP_PREDICATE) return;
Dan Gohmancafb8132009-02-17 19:13:57 +0000899
Devang Patel84e35152008-11-17 21:32:02 +0000900 // Insert new integer induction variable.
901 PHINode *NewPHI = PHINode::Create(Type::Int32Ty,
902 PH->getName()+".int", PH);
Devang Patelcd402332008-11-17 23:27:13 +0000903 NewPHI->addIncoming(ConstantInt::get(Type::Int32Ty, newInitValue),
Devang Patel84e35152008-11-17 21:32:02 +0000904 PH->getIncomingBlock(IncomingEdge));
905
Dan Gohmancafb8132009-02-17 19:13:57 +0000906 Value *NewAdd = BinaryOperator::CreateAdd(NewPHI,
907 ConstantInt::get(Type::Int32Ty,
Devang Patelcd402332008-11-17 23:27:13 +0000908 newIncrValue),
Devang Patel84e35152008-11-17 21:32:02 +0000909 Incr->getName()+".int", Incr);
910 NewPHI->addIncoming(NewAdd, PH->getIncomingBlock(BackEdge));
911
912 ConstantInt *NewEV = ConstantInt::get(Type::Int32Ty, intEV);
913 Value *LHS = (EVIndex == 1 ? NewPHI->getIncomingValue(BackEdge) : NewEV);
914 Value *RHS = (EVIndex == 1 ? NewEV : NewPHI->getIncomingValue(BackEdge));
Dan Gohmancafb8132009-02-17 19:13:57 +0000915 ICmpInst *NewEC = new ICmpInst(NewPred, LHS, RHS, EC->getNameStart(),
Devang Patel84e35152008-11-17 21:32:02 +0000916 EC->getParent()->getTerminator());
Dan Gohmancafb8132009-02-17 19:13:57 +0000917
Devang Patel84e35152008-11-17 21:32:02 +0000918 // Delete old, floating point, exit comparision instruction.
919 EC->replaceAllUsesWith(NewEC);
920 DeadInsts.insert(EC);
Dan Gohmancafb8132009-02-17 19:13:57 +0000921
Devang Patel84e35152008-11-17 21:32:02 +0000922 // Delete old, floating point, increment instruction.
923 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
924 DeadInsts.insert(Incr);
Dan Gohmancafb8132009-02-17 19:13:57 +0000925
Devang Patel13877bf2008-11-18 00:40:02 +0000926 // Replace floating induction variable. Give SIToFPInst preference over
927 // UIToFPInst because it is faster on platforms that are widely used.
928 if (useSIToFPInst(*InitValue, *EV, newInitValue, intEV)) {
Dan Gohmancafb8132009-02-17 19:13:57 +0000929 SIToFPInst *Conv = new SIToFPInst(NewPHI, PH->getType(), "indvar.conv",
Devang Patelcd402332008-11-17 23:27:13 +0000930 PH->getParent()->getFirstNonPHI());
931 PH->replaceAllUsesWith(Conv);
932 } else {
Dan Gohmancafb8132009-02-17 19:13:57 +0000933 UIToFPInst *Conv = new UIToFPInst(NewPHI, PH->getType(), "indvar.conv",
Devang Patelcd402332008-11-17 23:27:13 +0000934 PH->getParent()->getFirstNonPHI());
935 PH->replaceAllUsesWith(Conv);
936 }
Devang Patel84e35152008-11-17 21:32:02 +0000937 DeadInsts.insert(PH);
Devang Patel58d43d42008-11-03 18:32:19 +0000938}
939