blob: 641be5ce541447c5946cf021695682a473cf6a69 [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
Devang Patel5ee99972007-03-07 06:39:01 +000077 bool runOnLoop(Loop *L, LPPassManager &LPM);
78 bool doInitialization(Loop *L, LPPassManager &LPM);
79 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
Chris Lattner40bf8b42004-04-02 20:24:31 +000091 void EliminatePointerRecurrence(PHINode *PN, BasicBlock *Preheader,
Chris Lattner1a6111f2008-11-16 07:17:51 +000092 SmallPtrSet<Instruction*, 16> &DeadInsts);
Dan Gohmana5758712009-02-17 15:57:39 +000093 void LinearFunctionTestReplace(Loop *L, SCEVHandle IterationCount,
94 Value *IndVar,
Dan Gohmanc2390b12009-02-12 22:19:27 +000095 BasicBlock *ExitingBlock,
96 BranchInst *BI,
97 SCEVExpander &Rewriter);
Dan Gohman5a6c4482008-08-05 22:34:21 +000098 void RewriteLoopExitValues(Loop *L, SCEV *IterationCount);
Chris Lattner40bf8b42004-04-02 20:24:31 +000099
Chris Lattner1a6111f2008-11-16 07:17:51 +0000100 void DeleteTriviallyDeadInstructions(SmallPtrSet<Instruction*, 16> &Insts);
Devang Pateld22a8492008-09-09 21:41:07 +0000101
Devang Patel84e35152008-11-17 21:32:02 +0000102 void HandleFloatingPointIV(Loop *L, PHINode *PH,
103 SmallPtrSet<Instruction*, 16> &DeadInsts);
Chris Lattner3324e712003-12-22 03:58:44 +0000104 };
Chris Lattner5e761402002-09-10 05:24:05 +0000105}
Chris Lattner394437f2001-12-04 04:32:29 +0000106
Dan Gohman844731a2008-05-13 00:00:25 +0000107char IndVarSimplify::ID = 0;
108static RegisterPass<IndVarSimplify>
109X("indvars", "Canonicalize Induction Variables");
110
Daniel Dunbar394f0442008-10-22 23:32:42 +0000111Pass *llvm::createIndVarSimplifyPass() {
Chris Lattner3324e712003-12-22 03:58:44 +0000112 return new IndVarSimplify();
Chris Lattner394437f2001-12-04 04:32:29 +0000113}
114
Chris Lattner40bf8b42004-04-02 20:24:31 +0000115/// DeleteTriviallyDeadInstructions - If any of the instructions is the
116/// specified set are trivially dead, delete them and see if this makes any of
117/// their operands subsequently dead.
118void IndVarSimplify::
Chris Lattner1a6111f2008-11-16 07:17:51 +0000119DeleteTriviallyDeadInstructions(SmallPtrSet<Instruction*, 16> &Insts) {
Chris Lattner40bf8b42004-04-02 20:24:31 +0000120 while (!Insts.empty()) {
121 Instruction *I = *Insts.begin();
Chris Lattner1a6111f2008-11-16 07:17:51 +0000122 Insts.erase(I);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000123 if (isInstructionTriviallyDead(I)) {
124 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
125 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
126 Insts.insert(U);
Dan Gohman5cec4db2007-06-19 14:28:31 +0000127 SE->deleteValueFromRecords(I);
Chris Lattneree4f13a2007-01-07 01:14:12 +0000128 DOUT << "INDVARS: Deleting: " << *I;
Chris Lattnera4b9c782004-10-11 23:06:50 +0000129 I->eraseFromParent();
Chris Lattner40bf8b42004-04-02 20:24:31 +0000130 Changed = true;
131 }
132 }
133}
134
135
136/// EliminatePointerRecurrence - Check to see if this is a trivial GEP pointer
137/// recurrence. If so, change it into an integer recurrence, permitting
138/// analysis by the SCEV routines.
Misha Brukmanfd939082005-04-21 23:48:37 +0000139void IndVarSimplify::EliminatePointerRecurrence(PHINode *PN,
Chris Lattner40bf8b42004-04-02 20:24:31 +0000140 BasicBlock *Preheader,
Chris Lattner1a6111f2008-11-16 07:17:51 +0000141 SmallPtrSet<Instruction*, 16> &DeadInsts) {
Chris Lattner40bf8b42004-04-02 20:24:31 +0000142 assert(PN->getNumIncomingValues() == 2 && "Noncanonicalized loop!");
143 unsigned PreheaderIdx = PN->getBasicBlockIndex(Preheader);
144 unsigned BackedgeIdx = PreheaderIdx^1;
145 if (GetElementPtrInst *GEPI =
Chris Lattnercda9ca52005-08-10 01:12:06 +0000146 dyn_cast<GetElementPtrInst>(PN->getIncomingValue(BackedgeIdx)))
Chris Lattner40bf8b42004-04-02 20:24:31 +0000147 if (GEPI->getOperand(0) == PN) {
Chris Lattnercda9ca52005-08-10 01:12:06 +0000148 assert(GEPI->getNumOperands() == 2 && "GEP types must match!");
Chris Lattneree4f13a2007-01-07 01:14:12 +0000149 DOUT << "INDVARS: Eliminating pointer recurrence: " << *GEPI;
150
Chris Lattner40bf8b42004-04-02 20:24:31 +0000151 // Okay, we found a pointer recurrence. Transform this pointer
152 // recurrence into an integer recurrence. Compute the value that gets
153 // added to the pointer at every iteration.
154 Value *AddedVal = GEPI->getOperand(1);
155
156 // Insert a new integer PHI node into the top of the block.
Gabor Greif051a9502008-04-06 20:25:17 +0000157 PHINode *NewPhi = PHINode::Create(AddedVal->getType(),
158 PN->getName()+".rec", PN);
Chris Lattnerc5c5e6a2004-06-20 05:04:01 +0000159 NewPhi->addIncoming(Constant::getNullValue(NewPhi->getType()), Preheader);
160
Chris Lattner40bf8b42004-04-02 20:24:31 +0000161 // Create the new add instruction.
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000162 Value *NewAdd = BinaryOperator::CreateAdd(NewPhi, AddedVal,
Chris Lattnerc5c5e6a2004-06-20 05:04:01 +0000163 GEPI->getName()+".rec", GEPI);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000164 NewPhi->addIncoming(NewAdd, PN->getIncomingBlock(BackedgeIdx));
Misha Brukmanfd939082005-04-21 23:48:37 +0000165
Chris Lattner40bf8b42004-04-02 20:24:31 +0000166 // Update the existing GEP to use the recurrence.
167 GEPI->setOperand(0, PN->getIncomingValue(PreheaderIdx));
Misha Brukmanfd939082005-04-21 23:48:37 +0000168
Chris Lattner40bf8b42004-04-02 20:24:31 +0000169 // Update the GEP to use the new recurrence we just inserted.
170 GEPI->setOperand(1, NewAdd);
171
Chris Lattnera4b9c782004-10-11 23:06:50 +0000172 // If the incoming value is a constant expr GEP, try peeling out the array
173 // 0 index if possible to make things simpler.
174 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEPI->getOperand(0)))
175 if (CE->getOpcode() == Instruction::GetElementPtr) {
176 unsigned NumOps = CE->getNumOperands();
177 assert(NumOps > 1 && "CE folding didn't work!");
178 if (CE->getOperand(NumOps-1)->isNullValue()) {
179 // Check to make sure the last index really is an array index.
Chris Lattner17300782005-11-18 18:30:47 +0000180 gep_type_iterator GTI = gep_type_begin(CE);
Chris Lattnerceda6052005-11-17 19:35:42 +0000181 for (unsigned i = 1, e = CE->getNumOperands()-1;
Chris Lattnera4b9c782004-10-11 23:06:50 +0000182 i != e; ++i, ++GTI)
183 /*empty*/;
184 if (isa<SequentialType>(*GTI)) {
185 // Pull the last index out of the constant expr GEP.
Chris Lattner55eb1c42007-01-31 04:40:53 +0000186 SmallVector<Value*, 8> CEIdxs(CE->op_begin()+1, CE->op_end()-1);
Chris Lattnera4b9c782004-10-11 23:06:50 +0000187 Constant *NCE = ConstantExpr::getGetElementPtr(CE->getOperand(0),
Chris Lattner55eb1c42007-01-31 04:40:53 +0000188 &CEIdxs[0],
189 CEIdxs.size());
David Greeneb8f74792007-09-04 15:46:09 +0000190 Value *Idx[2];
191 Idx[0] = Constant::getNullValue(Type::Int32Ty);
192 Idx[1] = NewAdd;
Gabor Greif051a9502008-04-06 20:25:17 +0000193 GetElementPtrInst *NGEPI = GetElementPtrInst::Create(
David Greeneb8f74792007-09-04 15:46:09 +0000194 NCE, Idx, Idx + 2,
Reid Spencercae57542007-03-02 00:28:52 +0000195 GEPI->getName(), GEPI);
Dan Gohman5cec4db2007-06-19 14:28:31 +0000196 SE->deleteValueFromRecords(GEPI);
Chris Lattnera4b9c782004-10-11 23:06:50 +0000197 GEPI->replaceAllUsesWith(NGEPI);
198 GEPI->eraseFromParent();
199 GEPI = NGEPI;
200 }
201 }
202 }
203
204
Chris Lattner40bf8b42004-04-02 20:24:31 +0000205 // Finally, if there are any other users of the PHI node, we must
206 // insert a new GEP instruction that uses the pre-incremented version
207 // of the induction amount.
208 if (!PN->use_empty()) {
209 BasicBlock::iterator InsertPos = PN; ++InsertPos;
210 while (isa<PHINode>(InsertPos)) ++InsertPos;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000211 Value *PreInc =
Gabor Greif051a9502008-04-06 20:25:17 +0000212 GetElementPtrInst::Create(PN->getIncomingValue(PreheaderIdx),
213 NewPhi, "", InsertPos);
Chris Lattner6934a042007-02-11 01:23:03 +0000214 PreInc->takeName(PN);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000215 PN->replaceAllUsesWith(PreInc);
216 }
217
218 // Delete the old PHI for sure, and the GEP if its otherwise unused.
219 DeadInsts.insert(PN);
220
221 ++NumPointer;
222 Changed = true;
223 }
224}
225
226/// LinearFunctionTestReplace - This method rewrites the exit condition of the
Chris Lattner59fdaee2004-04-15 15:21:43 +0000227/// loop to be a canonical != comparison against the incremented loop induction
228/// variable. This pass is able to rewrite the exit tests of any loop where the
229/// SCEV analysis can determine a loop-invariant trip count of the loop, which
230/// is actually a much broader range than just linear tests.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000231void IndVarSimplify::LinearFunctionTestReplace(Loop *L,
232 SCEVHandle IterationCount,
233 Value *IndVar,
234 BasicBlock *ExitingBlock,
235 BranchInst *BI,
236 SCEVExpander &Rewriter) {
Chris Lattnerd2440572004-04-15 20:26:22 +0000237 // If the exiting block is not the same as the backedge block, we must compare
238 // against the preincremented value, otherwise we prefer to compare against
239 // the post-incremented value.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000240 Value *CmpIndVar;
241 if (ExitingBlock == L->getLoopLatch()) {
242 // What ScalarEvolution calls the "iteration count" is actually the
243 // number of times the branch is taken. Add one to get the number
244 // of times the branch is executed. If this addition may overflow,
245 // we have to be more pessimistic and cast the induction variable
246 // before doing the add.
247 SCEVHandle Zero = SE->getIntegerSCEV(0, IterationCount->getType());
248 SCEVHandle N =
249 SE->getAddExpr(IterationCount,
250 SE->getIntegerSCEV(1, IterationCount->getType()));
251 if ((isa<SCEVConstant>(N) && !N->isZero()) ||
252 SE->isLoopGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) {
253 // No overflow. Cast the sum.
254 IterationCount = SE->getTruncateOrZeroExtend(N, IndVar->getType());
255 } else {
256 // Potential overflow. Cast before doing the add.
257 IterationCount = SE->getTruncateOrZeroExtend(IterationCount,
258 IndVar->getType());
259 IterationCount =
260 SE->getAddExpr(IterationCount,
261 SE->getIntegerSCEV(1, IndVar->getType()));
262 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000263
Chris Lattnerd2440572004-04-15 20:26:22 +0000264 // The IterationCount expression contains the number of times that the
265 // backedge actually branches to the loop header. This is one less than the
266 // number of times the loop executes, so add one to it.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000267 CmpIndVar = L->getCanonicalInductionVariableIncrement();
Chris Lattnerd2440572004-04-15 20:26:22 +0000268 } else {
269 // We have to use the preincremented value...
Dan Gohmanc2390b12009-02-12 22:19:27 +0000270 IterationCount = SE->getTruncateOrZeroExtend(IterationCount,
271 IndVar->getType());
272 CmpIndVar = IndVar;
Chris Lattnerd2440572004-04-15 20:26:22 +0000273 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000274
Chris Lattner40bf8b42004-04-02 20:24:31 +0000275 // Expand the code for the iteration count into the preheader of the loop.
276 BasicBlock *Preheader = L->getLoopPreheader();
Dan Gohmanc2390b12009-02-12 22:19:27 +0000277 Value *ExitCnt = Rewriter.expandCodeFor(IterationCount,
278 Preheader->getTerminator());
Chris Lattner40bf8b42004-04-02 20:24:31 +0000279
Reid Spencere4d87aa2006-12-23 06:05:41 +0000280 // Insert a new icmp_ne or icmp_eq instruction before the branch.
281 ICmpInst::Predicate Opcode;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000282 if (L->contains(BI->getSuccessor(0)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000283 Opcode = ICmpInst::ICMP_NE;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000284 else
Reid Spencere4d87aa2006-12-23 06:05:41 +0000285 Opcode = ICmpInst::ICMP_EQ;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000286
Dan Gohmanc2390b12009-02-12 22:19:27 +0000287 DOUT << "INDVARS: Rewriting loop exit condition to:\n"
288 << " LHS:" << *CmpIndVar // includes a newline
289 << " op:\t"
Dan Gohmanf108e2e2009-02-14 02:26:50 +0000290 << (Opcode == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
Dan Gohmanc2390b12009-02-12 22:19:27 +0000291 << " RHS:\t" << *IterationCount << "\n";
292
293 Value *Cond = new ICmpInst(Opcode, CmpIndVar, ExitCnt, "exitcond", BI);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000294 BI->setCondition(Cond);
295 ++NumLFTR;
296 Changed = true;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000297}
298
Chris Lattner40bf8b42004-04-02 20:24:31 +0000299/// RewriteLoopExitValues - Check to see if this loop has a computable
300/// loop-invariant execution count. If so, this means that we can compute the
301/// final value of any expressions that are recurrent in the loop, and
302/// substitute the exit values from the loop into any instructions outside of
303/// the loop that use the final values of the current expressions.
Dan Gohman5a6c4482008-08-05 22:34:21 +0000304void IndVarSimplify::RewriteLoopExitValues(Loop *L, SCEV *IterationCount) {
Chris Lattner40bf8b42004-04-02 20:24:31 +0000305 BasicBlock *Preheader = L->getLoopPreheader();
306
307 // Scan all of the instructions in the loop, looking at those that have
308 // extra-loop users and which are recurrences.
Chris Lattner4a7553e2004-04-23 21:29:48 +0000309 SCEVExpander Rewriter(*SE, *LI);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000310
311 // We insert the code into the preheader of the loop if the loop contains
312 // multiple exit blocks, or in the exit block if there is exactly one.
313 BasicBlock *BlockToInsertInto;
Devang Patelb7211a22007-08-21 00:31:24 +0000314 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattner9f3d7382007-03-04 03:43:23 +0000315 L->getUniqueExitBlocks(ExitBlocks);
Chris Lattnerf1ab4b42004-04-18 22:14:10 +0000316 if (ExitBlocks.size() == 1)
317 BlockToInsertInto = ExitBlocks[0];
Chris Lattner40bf8b42004-04-02 20:24:31 +0000318 else
319 BlockToInsertInto = Preheader;
Dan Gohman02dea8b2008-05-23 21:05:58 +0000320 BasicBlock::iterator InsertPt = BlockToInsertInto->getFirstNonPHI();
Chris Lattner40bf8b42004-04-02 20:24:31 +0000321
Dan Gohman5a6c4482008-08-05 22:34:21 +0000322 bool HasConstantItCount = isa<SCEVConstant>(IterationCount);
Chris Lattner20aa0982004-04-17 18:44:09 +0000323
Chris Lattner1a6111f2008-11-16 07:17:51 +0000324 SmallPtrSet<Instruction*, 16> InstructionsToDelete;
Chris Lattner9f3d7382007-03-04 03:43:23 +0000325 std::map<Instruction*, Value*> ExitValues;
Misha Brukmanfd939082005-04-21 23:48:37 +0000326
Chris Lattner9f3d7382007-03-04 03:43:23 +0000327 // Find all values that are computed inside the loop, but used outside of it.
328 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
329 // the exit blocks of the loop to find them.
330 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
331 BasicBlock *ExitBB = ExitBlocks[i];
332
333 // If there are no PHI nodes in this exit block, then no values defined
334 // inside the loop are used on this path, skip it.
335 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
336 if (!PN) continue;
337
338 unsigned NumPreds = PN->getNumIncomingValues();
339
340 // Iterate over all of the PHI nodes.
341 BasicBlock::iterator BBI = ExitBB->begin();
342 while ((PN = dyn_cast<PHINode>(BBI++))) {
Chris Lattnerc9838f22007-03-03 22:48:48 +0000343
Chris Lattner9f3d7382007-03-04 03:43:23 +0000344 // Iterate over all of the values in all the PHI nodes.
345 for (unsigned i = 0; i != NumPreds; ++i) {
346 // If the value being merged in is not integer or is not defined
347 // in the loop, skip it.
348 Value *InVal = PN->getIncomingValue(i);
349 if (!isa<Instruction>(InVal) ||
350 // SCEV only supports integer expressions for now.
351 !isa<IntegerType>(InVal->getType()))
352 continue;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000353
Chris Lattner9f3d7382007-03-04 03:43:23 +0000354 // If this pred is for a subloop, not L itself, skip it.
355 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
356 continue; // The Block is in a subloop, skip it.
357
358 // Check that InVal is defined in the loop.
359 Instruction *Inst = cast<Instruction>(InVal);
360 if (!L->contains(Inst->getParent()))
361 continue;
Chris Lattner9caed542007-03-04 01:00:28 +0000362
Chris Lattner9f3d7382007-03-04 03:43:23 +0000363 // We require that this value either have a computable evolution or that
364 // the loop have a constant iteration count. In the case where the loop
365 // has a constant iteration count, we can sometimes force evaluation of
366 // the exit value through brute force.
367 SCEVHandle SH = SE->getSCEV(Inst);
368 if (!SH->hasComputableLoopEvolution(L) && !HasConstantItCount)
369 continue; // Cannot get exit evolution for the loop value.
370
371 // Okay, this instruction has a user outside of the current loop
372 // and varies predictably *inside* the loop. Evaluate the value it
373 // contains when the loop exits, if possible.
374 SCEVHandle ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
375 if (isa<SCEVCouldNotCompute>(ExitValue) ||
376 !ExitValue->isLoopInvariant(L))
377 continue;
Chris Lattner9caed542007-03-04 01:00:28 +0000378
Chris Lattner9f3d7382007-03-04 03:43:23 +0000379 Changed = true;
380 ++NumReplaced;
381
382 // See if we already computed the exit value for the instruction, if so,
383 // just reuse it.
384 Value *&ExitVal = ExitValues[Inst];
385 if (!ExitVal)
Dan Gohmand19534a2007-06-15 14:38:12 +0000386 ExitVal = Rewriter.expandCodeFor(ExitValue, InsertPt);
Chris Lattner9f3d7382007-03-04 03:43:23 +0000387
388 DOUT << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal
389 << " LoopVal = " << *Inst << "\n";
390
391 PN->setIncomingValue(i, ExitVal);
392
393 // If this instruction is dead now, schedule it to be removed.
394 if (Inst->use_empty())
395 InstructionsToDelete.insert(Inst);
396
397 // See if this is a single-entry LCSSA PHI node. If so, we can (and
398 // have to) remove
Chris Lattner9caed542007-03-04 01:00:28 +0000399 // the PHI entirely. This is safe, because the NewVal won't be variant
400 // in the loop, so we don't need an LCSSA phi node anymore.
Chris Lattner9f3d7382007-03-04 03:43:23 +0000401 if (NumPreds == 1) {
Dan Gohman5cec4db2007-06-19 14:28:31 +0000402 SE->deleteValueFromRecords(PN);
Chris Lattner9f3d7382007-03-04 03:43:23 +0000403 PN->replaceAllUsesWith(ExitVal);
404 PN->eraseFromParent();
405 break;
Chris Lattnerc9838f22007-03-03 22:48:48 +0000406 }
407 }
Chris Lattnerc9838f22007-03-03 22:48:48 +0000408 }
409 }
410
Chris Lattner40bf8b42004-04-02 20:24:31 +0000411 DeleteTriviallyDeadInstructions(InstructionsToDelete);
412}
413
Devang Patel5ee99972007-03-07 06:39:01 +0000414bool IndVarSimplify::doInitialization(Loop *L, LPPassManager &LPM) {
Chris Lattner40bf8b42004-04-02 20:24:31 +0000415
Devang Patel5ee99972007-03-07 06:39:01 +0000416 Changed = false;
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();
Devang Patel5ee99972007-03-07 06:39:01 +0000423 SE = &LPM.getAnalysis<ScalarEvolution>();
Misha Brukmanfd939082005-04-21 23:48:37 +0000424
Chris Lattner1a6111f2008-11-16 07:17:51 +0000425 SmallPtrSet<Instruction*, 16> DeadInsts;
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000426 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
427 PHINode *PN = cast<PHINode>(I);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000428 if (isa<PointerType>(PN->getType()))
429 EliminatePointerRecurrence(PN, Preheader, DeadInsts);
Devang Patel84e35152008-11-17 21:32:02 +0000430 else
431 HandleFloatingPointIV(L, PN, DeadInsts);
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000432 }
Chris Lattner40bf8b42004-04-02 20:24:31 +0000433
434 if (!DeadInsts.empty())
435 DeleteTriviallyDeadInstructions(DeadInsts);
436
Devang Patel5ee99972007-03-07 06:39:01 +0000437 return Changed;
438}
Chris Lattner40bf8b42004-04-02 20:24:31 +0000439
Dan Gohmanc2390b12009-02-12 22:19:27 +0000440/// getEffectiveIndvarType - Determine the widest type that the
441/// induction-variable PHINode Phi is cast to.
442///
443static const Type *getEffectiveIndvarType(const PHINode *Phi) {
444 const Type *Ty = Phi->getType();
Chris Lattner3324e712003-12-22 03:58:44 +0000445
Dan Gohmanc2390b12009-02-12 22:19:27 +0000446 for (Value::use_const_iterator UI = Phi->use_begin(), UE = Phi->use_end();
447 UI != UE; ++UI) {
448 const Type *CandidateType = NULL;
449 if (const ZExtInst *ZI = dyn_cast<ZExtInst>(UI))
450 CandidateType = ZI->getDestTy();
451 else if (const SExtInst *SI = dyn_cast<SExtInst>(UI))
452 CandidateType = SI->getDestTy();
453 if (CandidateType &&
454 CandidateType->getPrimitiveSizeInBits() >
455 Ty->getPrimitiveSizeInBits())
456 Ty = CandidateType;
457 }
458
459 return Ty;
460}
461
Dan Gohmanaa036492009-02-14 02:31:09 +0000462/// TestOrigIVForWrap - Analyze the original induction variable
463/// in the loop to determine whether it would ever undergo signed
464/// or unsigned overflow.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000465///
466/// TODO: This duplicates a fair amount of ScalarEvolution logic.
Dan Gohmanaa036492009-02-14 02:31:09 +0000467/// Perhaps this can be merged with ScalarEvolution::getIterationCount
468/// and/or ScalarEvolution::get{Sign,Zero}ExtendExpr.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000469///
Dan Gohmanaa036492009-02-14 02:31:09 +0000470static void TestOrigIVForWrap(const Loop *L,
471 const BranchInst *BI,
472 const Instruction *OrigCond,
473 bool &NoSignedWrap,
474 bool &NoUnsignedWrap) {
Dan Gohmanc2390b12009-02-12 22:19:27 +0000475 // Verify that the loop is sane and find the exit condition.
476 const ICmpInst *Cmp = dyn_cast<ICmpInst>(OrigCond);
Dan Gohmanaa036492009-02-14 02:31:09 +0000477 if (!Cmp) return;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000478
Dan Gohmanaa036492009-02-14 02:31:09 +0000479 const Value *CmpLHS = Cmp->getOperand(0);
480 const Value *CmpRHS = Cmp->getOperand(1);
481 const BasicBlock *TrueBB = BI->getSuccessor(0);
482 const BasicBlock *FalseBB = BI->getSuccessor(1);
483 ICmpInst::Predicate Pred = Cmp->getPredicate();
Dan Gohmanc2390b12009-02-12 22:19:27 +0000484
Dan Gohmanaa036492009-02-14 02:31:09 +0000485 // Canonicalize a constant to the RHS.
486 if (isa<ConstantInt>(CmpLHS)) {
487 Pred = ICmpInst::getSwappedPredicate(Pred);
488 std::swap(CmpLHS, CmpRHS);
489 }
490 // Canonicalize SLE to SLT.
491 if (Pred == ICmpInst::ICMP_SLE)
492 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
493 if (!CI->getValue().isMaxSignedValue()) {
494 CmpRHS = ConstantInt::get(CI->getValue() + 1);
495 Pred = ICmpInst::ICMP_SLT;
496 }
497 // Canonicalize SGT to SGE.
498 if (Pred == ICmpInst::ICMP_SGT)
499 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
500 if (!CI->getValue().isMaxSignedValue()) {
501 CmpRHS = ConstantInt::get(CI->getValue() + 1);
502 Pred = ICmpInst::ICMP_SGE;
503 }
504 // Canonicalize SGE to SLT.
505 if (Pred == ICmpInst::ICMP_SGE) {
506 std::swap(TrueBB, FalseBB);
507 Pred = ICmpInst::ICMP_SLT;
508 }
509 // Canonicalize ULE to ULT.
510 if (Pred == ICmpInst::ICMP_ULE)
511 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
512 if (!CI->getValue().isMaxValue()) {
513 CmpRHS = ConstantInt::get(CI->getValue() + 1);
514 Pred = ICmpInst::ICMP_ULT;
515 }
516 // Canonicalize UGT to UGE.
517 if (Pred == ICmpInst::ICMP_UGT)
518 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
519 if (!CI->getValue().isMaxValue()) {
520 CmpRHS = ConstantInt::get(CI->getValue() + 1);
521 Pred = ICmpInst::ICMP_UGE;
522 }
523 // Canonicalize UGE to ULT.
524 if (Pred == ICmpInst::ICMP_UGE) {
525 std::swap(TrueBB, FalseBB);
526 Pred = ICmpInst::ICMP_ULT;
527 }
528 // For now, analyze only LT loops for signed overflow.
529 if (Pred != ICmpInst::ICMP_SLT && Pred != ICmpInst::ICMP_ULT)
530 return;
531
532 bool isSigned = Pred == ICmpInst::ICMP_SLT;
533
534 // Get the increment instruction. Look past casts if we will
Dan Gohmanc2390b12009-02-12 22:19:27 +0000535 // be able to prove that the original induction variable doesn't
Dan Gohmanaa036492009-02-14 02:31:09 +0000536 // undergo signed or unsigned overflow, respectively.
537 const Value *IncrVal = CmpLHS;
538 if (isSigned) {
539 if (const SExtInst *SI = dyn_cast<SExtInst>(CmpLHS)) {
540 if (!isa<ConstantInt>(CmpRHS) ||
541 !cast<ConstantInt>(CmpRHS)->getValue()
542 .isSignedIntN(IncrVal->getType()->getPrimitiveSizeInBits()))
543 return;
544 IncrVal = SI->getOperand(0);
545 }
546 } else {
547 if (const ZExtInst *ZI = dyn_cast<ZExtInst>(CmpLHS)) {
548 if (!isa<ConstantInt>(CmpRHS) ||
549 !cast<ConstantInt>(CmpRHS)->getValue()
550 .isIntN(IncrVal->getType()->getPrimitiveSizeInBits()))
551 return;
552 IncrVal = ZI->getOperand(0);
553 }
Dan Gohmanc2390b12009-02-12 22:19:27 +0000554 }
555
556 // For now, only analyze induction variables that have simple increments.
557 const BinaryOperator *IncrOp = dyn_cast<BinaryOperator>(IncrVal);
558 if (!IncrOp ||
559 IncrOp->getOpcode() != Instruction::Add ||
560 !isa<ConstantInt>(IncrOp->getOperand(1)) ||
561 !cast<ConstantInt>(IncrOp->getOperand(1))->equalsInt(1))
Dan Gohmanaa036492009-02-14 02:31:09 +0000562 return;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000563
564 // Make sure the PHI looks like a normal IV.
565 const PHINode *PN = dyn_cast<PHINode>(IncrOp->getOperand(0));
566 if (!PN || PN->getNumIncomingValues() != 2)
Dan Gohmanaa036492009-02-14 02:31:09 +0000567 return;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000568 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
569 unsigned BackEdge = !IncomingEdge;
570 if (!L->contains(PN->getIncomingBlock(BackEdge)) ||
571 PN->getIncomingValue(BackEdge) != IncrOp)
Dan Gohmanaa036492009-02-14 02:31:09 +0000572 return;
573 if (!L->contains(TrueBB))
574 return;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000575
576 // For now, only analyze loops with a constant start value, so that
Dan Gohmanaa036492009-02-14 02:31:09 +0000577 // we can easily determine if the start value is not a maximum value
578 // which would wrap on the first iteration.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000579 const Value *InitialVal = PN->getIncomingValue(IncomingEdge);
Dan Gohmanaa036492009-02-14 02:31:09 +0000580 if (!isa<ConstantInt>(InitialVal))
581 return;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000582
Dan Gohmanaa036492009-02-14 02:31:09 +0000583 // The original induction variable will start at some non-max value,
584 // it counts up by one, and the loop iterates only while it remans
585 // less than some value in the same type. As such, it will never wrap.
586 if (isSigned &&
587 !cast<ConstantInt>(InitialVal)->getValue().isMaxSignedValue())
588 NoSignedWrap = true;
589 else if (!isSigned &&
590 !cast<ConstantInt>(InitialVal)->getValue().isMaxValue())
591 NoUnsignedWrap = true;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000592}
593
594bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
Devang Patel5ee99972007-03-07 06:39:01 +0000595 LI = &getAnalysis<LoopInfo>();
596 SE = &getAnalysis<ScalarEvolution>();
597
598 Changed = false;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000599 BasicBlock *Header = L->getHeader();
600 BasicBlock *ExitingBlock = L->getExitingBlock();
Chris Lattner1a6111f2008-11-16 07:17:51 +0000601 SmallPtrSet<Instruction*, 16> DeadInsts;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000602
Chris Lattner9caed542007-03-04 01:00:28 +0000603 // Verify the input to the pass in already in LCSSA form.
604 assert(L->isLCSSAForm());
605
Chris Lattner40bf8b42004-04-02 20:24:31 +0000606 // Check to see if this loop has a computable loop-invariant execution count.
607 // If so, this means that we can compute the final value of any expressions
608 // that are recurrent in the loop, and substitute the exit values from the
609 // loop into any instructions outside of the loop that use the final values of
610 // the current expressions.
Chris Lattner3dec1f22002-05-10 15:38:35 +0000611 //
Chris Lattner40bf8b42004-04-02 20:24:31 +0000612 SCEVHandle IterationCount = SE->getIterationCount(L);
613 if (!isa<SCEVCouldNotCompute>(IterationCount))
Dan Gohman5a6c4482008-08-05 22:34:21 +0000614 RewriteLoopExitValues(L, IterationCount);
Chris Lattner6148c022001-12-03 17:28:42 +0000615
Chris Lattner40bf8b42004-04-02 20:24:31 +0000616 // Next, analyze all of the induction variables in the loop, canonicalizing
617 // auxillary induction variables.
618 std::vector<std::pair<PHINode*, SCEVHandle> > IndVars;
619
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000620 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
621 PHINode *PN = cast<PHINode>(I);
Chris Lattner42a75512007-01-15 02:27:26 +0000622 if (PN->getType()->isInteger()) { // FIXME: when we have fast-math, enable!
Chris Lattner40bf8b42004-04-02 20:24:31 +0000623 SCEVHandle SCEV = SE->getSCEV(PN);
Dan Gohmancd3eb9b2009-02-14 02:25:19 +0000624 // FIXME: It is an extremely bad idea to indvar substitute anything more
625 // complex than affine induction variables. Doing so will put expensive
626 // polynomial evaluations inside of the loop, and the str reduction pass
627 // currently can only reduce affine polynomials. For now just disable
628 // indvar subst on anything more complex than an affine addrec.
629 if (SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SCEV))
630 if (AR->getLoop() == L && AR->isAffine())
631 IndVars.push_back(std::make_pair(PN, SCEV));
Chris Lattner40bf8b42004-04-02 20:24:31 +0000632 }
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000633 }
Chris Lattner40bf8b42004-04-02 20:24:31 +0000634
Dan Gohmanc2390b12009-02-12 22:19:27 +0000635 // Compute the type of the largest recurrence expression, and collect
636 // the set of the types of the other recurrence expressions.
637 const Type *LargestType = 0;
638 SmallSetVector<const Type *, 4> SizesToInsert;
639 if (!isa<SCEVCouldNotCompute>(IterationCount)) {
640 LargestType = IterationCount->getType();
641 SizesToInsert.insert(IterationCount->getType());
Chris Lattnerf50af082004-04-17 18:08:33 +0000642 }
Dan Gohmanc2390b12009-02-12 22:19:27 +0000643 for (unsigned i = 0, e = IndVars.size(); i != e; ++i) {
644 const PHINode *PN = IndVars[i].first;
645 SizesToInsert.insert(PN->getType());
646 const Type *EffTy = getEffectiveIndvarType(PN);
647 SizesToInsert.insert(EffTy);
648 if (!LargestType ||
649 EffTy->getPrimitiveSizeInBits() >
650 LargestType->getPrimitiveSizeInBits())
651 LargestType = EffTy;
Chris Lattner6148c022001-12-03 17:28:42 +0000652 }
653
Chris Lattner40bf8b42004-04-02 20:24:31 +0000654 // Create a rewriter object which we'll use to transform the code with.
Chris Lattner4a7553e2004-04-23 21:29:48 +0000655 SCEVExpander Rewriter(*SE, *LI);
Chris Lattner15cad752003-12-23 07:47:09 +0000656
Chris Lattner40bf8b42004-04-02 20:24:31 +0000657 // Now that we know the largest of of the induction variables in this loop,
658 // insert a canonical induction variable of the largest size.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000659 Value *IndVar = 0;
660 if (!SizesToInsert.empty()) {
661 IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L,LargestType);
662 ++NumInserted;
663 Changed = true;
664 DOUT << "INDVARS: New CanIV: " << *IndVar;
Dan Gohmand19534a2007-06-15 14:38:12 +0000665 }
Chris Lattner15cad752003-12-23 07:47:09 +0000666
Dan Gohmanc2390b12009-02-12 22:19:27 +0000667 // If we have a trip count expression, rewrite the loop's exit condition
668 // using it. We can currently only handle loops with a single exit.
Dan Gohmanaa036492009-02-14 02:31:09 +0000669 bool NoSignedWrap = false;
670 bool NoUnsignedWrap = false;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000671 if (!isa<SCEVCouldNotCompute>(IterationCount) && ExitingBlock)
672 // Can't rewrite non-branch yet.
673 if (BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator())) {
674 if (Instruction *OrigCond = dyn_cast<Instruction>(BI->getCondition())) {
Dan Gohmanaa036492009-02-14 02:31:09 +0000675 // Determine if the OrigIV will ever undergo overflow.
676 TestOrigIVForWrap(L, BI, OrigCond,
677 NoSignedWrap, NoUnsignedWrap);
Dan Gohmanc2390b12009-02-12 22:19:27 +0000678
679 // We'll be replacing the original condition, so it'll be dead.
680 DeadInsts.insert(OrigCond);
681 }
682
683 LinearFunctionTestReplace(L, IterationCount, IndVar,
684 ExitingBlock, BI, Rewriter);
685 }
686
Chris Lattner40bf8b42004-04-02 20:24:31 +0000687 // Now that we have a canonical induction variable, we can rewrite any
688 // recurrences in terms of the induction variable. Start with the auxillary
689 // induction variables, and recursively rewrite any of their uses.
Dan Gohman02dea8b2008-05-23 21:05:58 +0000690 BasicBlock::iterator InsertPt = Header->getFirstNonPHI();
Chris Lattner6148c022001-12-03 17:28:42 +0000691
Chris Lattner5d461d22004-04-21 22:22:01 +0000692 // If there were induction variables of other sizes, cast the primary
693 // induction variable to the right size for them, avoiding the need for the
694 // code evaluation methods to insert induction variables of different sizes.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000695 for (unsigned i = 0, e = SizesToInsert.size(); i != e; ++i) {
696 const Type *Ty = SizesToInsert[i];
697 if (Ty != LargestType) {
698 Instruction *New = new TruncInst(IndVar, Ty, "indvar", InsertPt);
699 Rewriter.addInsertedValue(New, SE->getSCEV(New));
700 DOUT << "INDVARS: Made trunc IV for type " << *Ty << ": "
701 << *New << "\n";
Reid Spencera54b7cb2007-01-12 07:05:14 +0000702 }
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000703 }
704
Chris Lattneree4f13a2007-01-07 01:14:12 +0000705 // Rewrite all induction variables in terms of the canonical induction
706 // variable.
Chris Lattner40bf8b42004-04-02 20:24:31 +0000707 while (!IndVars.empty()) {
708 PHINode *PN = IndVars.back().first;
Dan Gohman1a5e9362009-02-17 00:10:53 +0000709 SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(IndVars.back().second);
710 Value *NewVal = Rewriter.expandCodeFor(AR, InsertPt);
711 DOUT << "INDVARS: Rewrote IV '" << *AR << "' " << *PN
Chris Lattneree4f13a2007-01-07 01:14:12 +0000712 << " into = " << *NewVal << "\n";
Chris Lattner6934a042007-02-11 01:23:03 +0000713 NewVal->takeName(PN);
Chris Lattner5d461d22004-04-21 22:22:01 +0000714
Dan Gohmanc2390b12009-02-12 22:19:27 +0000715 /// If the new canonical induction variable is wider than the original,
716 /// and the original has uses that are casts to wider types, see if the
717 /// truncate and extend can be omitted.
Dan Gohmanaa036492009-02-14 02:31:09 +0000718 if (PN->getType() != LargestType)
Dan Gohmanc2390b12009-02-12 22:19:27 +0000719 for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end();
Dan Gohmanaa036492009-02-14 02:31:09 +0000720 UI != UE; ++UI) {
721 if (isa<SExtInst>(UI) && NoSignedWrap) {
722 SCEVHandle ExtendedStart =
Dan Gohman1a5e9362009-02-17 00:10:53 +0000723 SE->getSignExtendExpr(AR->getStart(), LargestType);
Dan Gohmanaa036492009-02-14 02:31:09 +0000724 SCEVHandle ExtendedStep =
Dan Gohman1a5e9362009-02-17 00:10:53 +0000725 SE->getSignExtendExpr(AR->getStepRecurrence(*SE), LargestType);
Dan Gohmanaa036492009-02-14 02:31:09 +0000726 SCEVHandle ExtendedAddRec =
727 SE->getAddRecExpr(ExtendedStart, ExtendedStep, L);
728 if (LargestType != UI->getType())
729 ExtendedAddRec = SE->getTruncateExpr(ExtendedAddRec, UI->getType());
730 Value *TruncIndVar = Rewriter.expandCodeFor(ExtendedAddRec, InsertPt);
Dan Gohmanc2390b12009-02-12 22:19:27 +0000731 UI->replaceAllUsesWith(TruncIndVar);
732 if (Instruction *DeadUse = dyn_cast<Instruction>(*UI))
733 DeadInsts.insert(DeadUse);
734 }
Dan Gohmanaa036492009-02-14 02:31:09 +0000735 if (isa<ZExtInst>(UI) && NoUnsignedWrap) {
736 SCEVHandle ExtendedStart =
Dan Gohman1a5e9362009-02-17 00:10:53 +0000737 SE->getZeroExtendExpr(AR->getStart(), LargestType);
Dan Gohmanaa036492009-02-14 02:31:09 +0000738 SCEVHandle ExtendedStep =
Dan Gohman1a5e9362009-02-17 00:10:53 +0000739 SE->getZeroExtendExpr(AR->getStepRecurrence(*SE), LargestType);
Dan Gohmanaa036492009-02-14 02:31:09 +0000740 SCEVHandle ExtendedAddRec =
741 SE->getAddRecExpr(ExtendedStart, ExtendedStep, L);
742 if (LargestType != UI->getType())
743 ExtendedAddRec = SE->getTruncateExpr(ExtendedAddRec, UI->getType());
744 Value *TruncIndVar = Rewriter.expandCodeFor(ExtendedAddRec, InsertPt);
745 UI->replaceAllUsesWith(TruncIndVar);
746 if (Instruction *DeadUse = dyn_cast<Instruction>(*UI))
747 DeadInsts.insert(DeadUse);
748 }
749 }
Dan Gohmanc2390b12009-02-12 22:19:27 +0000750
Chris Lattner40bf8b42004-04-02 20:24:31 +0000751 // Replace the old PHI Node with the inserted computation.
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000752 PN->replaceAllUsesWith(NewVal);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000753 DeadInsts.insert(PN);
754 IndVars.pop_back();
755 ++NumRemoved;
Chris Lattner4753bf22001-12-05 19:41:33 +0000756 Changed = true;
Chris Lattner394437f2001-12-04 04:32:29 +0000757 }
758
Chris Lattner1363e852004-04-21 23:36:08 +0000759 DeleteTriviallyDeadInstructions(DeadInsts);
Chris Lattner9caed542007-03-04 01:00:28 +0000760 assert(L->isLCSSAForm());
Devang Patel5ee99972007-03-07 06:39:01 +0000761 return Changed;
Chris Lattner6148c022001-12-03 17:28:42 +0000762}
Devang Pateld22a8492008-09-09 21:41:07 +0000763
Devang Patel13877bf2008-11-18 00:40:02 +0000764/// Return true if it is OK to use SIToFPInst for an inducation variable
765/// with given inital and exit values.
766static bool useSIToFPInst(ConstantFP &InitV, ConstantFP &ExitV,
767 uint64_t intIV, uint64_t intEV) {
768
769 if (InitV.getValueAPF().isNegative() || ExitV.getValueAPF().isNegative())
770 return true;
771
772 // If the iteration range can be handled by SIToFPInst then use it.
773 APInt Max = APInt::getSignedMaxValue(32);
Bill Wendling9bef7062008-11-18 10:57:27 +0000774 if (Max.getZExtValue() > static_cast<uint64_t>(abs(intEV - intIV)))
Devang Patel13877bf2008-11-18 00:40:02 +0000775 return true;
776
777 return false;
778}
779
780/// convertToInt - Convert APF to an integer, if possible.
Devang Patelcd402332008-11-17 23:27:13 +0000781static bool convertToInt(const APFloat &APF, uint64_t *intVal) {
782
783 bool isExact = false;
Evan Cheng794a7db2008-11-26 01:11:57 +0000784 if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
785 return false;
Devang Patelcd402332008-11-17 23:27:13 +0000786 if (APF.convertToInteger(intVal, 32, APF.isNegative(),
787 APFloat::rmTowardZero, &isExact)
788 != APFloat::opOK)
789 return false;
790 if (!isExact)
791 return false;
792 return true;
793
794}
795
Devang Patel58d43d42008-11-03 18:32:19 +0000796/// HandleFloatingPointIV - If the loop has floating induction variable
797/// then insert corresponding integer induction variable if possible.
Devang Patel84e35152008-11-17 21:32:02 +0000798/// For example,
799/// for(double i = 0; i < 10000; ++i)
800/// bar(i)
801/// is converted into
802/// for(int i = 0; i < 10000; ++i)
803/// bar((double)i);
804///
805void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PH,
806 SmallPtrSet<Instruction*, 16> &DeadInsts) {
Devang Patel58d43d42008-11-03 18:32:19 +0000807
Devang Patel84e35152008-11-17 21:32:02 +0000808 unsigned IncomingEdge = L->contains(PH->getIncomingBlock(0));
809 unsigned BackEdge = IncomingEdge^1;
810
811 // Check incoming value.
Devang Patelcd402332008-11-17 23:27:13 +0000812 ConstantFP *InitValue = dyn_cast<ConstantFP>(PH->getIncomingValue(IncomingEdge));
813 if (!InitValue) return;
814 uint64_t newInitValue = Type::Int32Ty->getPrimitiveSizeInBits();
815 if (!convertToInt(InitValue->getValueAPF(), &newInitValue))
816 return;
817
818 // Check IV increment. Reject this PH if increement operation is not
819 // an add or increment value can not be represented by an integer.
Devang Patel84e35152008-11-17 21:32:02 +0000820 BinaryOperator *Incr =
821 dyn_cast<BinaryOperator>(PH->getIncomingValue(BackEdge));
822 if (!Incr) return;
823 if (Incr->getOpcode() != Instruction::Add) return;
824 ConstantFP *IncrValue = NULL;
825 unsigned IncrVIndex = 1;
826 if (Incr->getOperand(1) == PH)
827 IncrVIndex = 0;
828 IncrValue = dyn_cast<ConstantFP>(Incr->getOperand(IncrVIndex));
829 if (!IncrValue) return;
Devang Patelcd402332008-11-17 23:27:13 +0000830 uint64_t newIncrValue = Type::Int32Ty->getPrimitiveSizeInBits();
831 if (!convertToInt(IncrValue->getValueAPF(), &newIncrValue))
832 return;
Devang Patel84e35152008-11-17 21:32:02 +0000833
Devang Patelcd402332008-11-17 23:27:13 +0000834 // Check Incr uses. One user is PH and the other users is exit condition used
835 // by the conditional terminator.
Devang Patel84e35152008-11-17 21:32:02 +0000836 Value::use_iterator IncrUse = Incr->use_begin();
837 Instruction *U1 = cast<Instruction>(IncrUse++);
838 if (IncrUse == Incr->use_end()) return;
839 Instruction *U2 = cast<Instruction>(IncrUse++);
840 if (IncrUse != Incr->use_end()) return;
841
842 // Find exit condition.
843 FCmpInst *EC = dyn_cast<FCmpInst>(U1);
844 if (!EC)
845 EC = dyn_cast<FCmpInst>(U2);
846 if (!EC) return;
847
848 if (BranchInst *BI = dyn_cast<BranchInst>(EC->getParent()->getTerminator())) {
849 if (!BI->isConditional()) return;
850 if (BI->getCondition() != EC) return;
Devang Patel58d43d42008-11-03 18:32:19 +0000851 }
Devang Patel58d43d42008-11-03 18:32:19 +0000852
Devang Patelcd402332008-11-17 23:27:13 +0000853 // Find exit value. If exit value can not be represented as an interger then
854 // do not handle this floating point PH.
Devang Patel84e35152008-11-17 21:32:02 +0000855 ConstantFP *EV = NULL;
856 unsigned EVIndex = 1;
857 if (EC->getOperand(1) == Incr)
858 EVIndex = 0;
859 EV = dyn_cast<ConstantFP>(EC->getOperand(EVIndex));
860 if (!EV) return;
Devang Patel84e35152008-11-17 21:32:02 +0000861 uint64_t intEV = Type::Int32Ty->getPrimitiveSizeInBits();
Devang Patelcd402332008-11-17 23:27:13 +0000862 if (!convertToInt(EV->getValueAPF(), &intEV))
Devang Patel84e35152008-11-17 21:32:02 +0000863 return;
Devang Patel84e35152008-11-17 21:32:02 +0000864
865 // Find new predicate for integer comparison.
866 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
867 switch (EC->getPredicate()) {
868 case CmpInst::FCMP_OEQ:
869 case CmpInst::FCMP_UEQ:
870 NewPred = CmpInst::ICMP_EQ;
871 break;
872 case CmpInst::FCMP_OGT:
873 case CmpInst::FCMP_UGT:
874 NewPred = CmpInst::ICMP_UGT;
875 break;
876 case CmpInst::FCMP_OGE:
877 case CmpInst::FCMP_UGE:
878 NewPred = CmpInst::ICMP_UGE;
879 break;
880 case CmpInst::FCMP_OLT:
881 case CmpInst::FCMP_ULT:
882 NewPred = CmpInst::ICMP_ULT;
883 break;
884 case CmpInst::FCMP_OLE:
885 case CmpInst::FCMP_ULE:
886 NewPred = CmpInst::ICMP_ULE;
887 break;
888 default:
889 break;
Devang Patel58d43d42008-11-03 18:32:19 +0000890 }
Devang Patel84e35152008-11-17 21:32:02 +0000891 if (NewPred == CmpInst::BAD_ICMP_PREDICATE) return;
892
893 // Insert new integer induction variable.
894 PHINode *NewPHI = PHINode::Create(Type::Int32Ty,
895 PH->getName()+".int", PH);
Devang Patelcd402332008-11-17 23:27:13 +0000896 NewPHI->addIncoming(ConstantInt::get(Type::Int32Ty, newInitValue),
Devang Patel84e35152008-11-17 21:32:02 +0000897 PH->getIncomingBlock(IncomingEdge));
898
899 Value *NewAdd = BinaryOperator::CreateAdd(NewPHI,
Devang Patelcd402332008-11-17 23:27:13 +0000900 ConstantInt::get(Type::Int32Ty,
901 newIncrValue),
Devang Patel84e35152008-11-17 21:32:02 +0000902 Incr->getName()+".int", Incr);
903 NewPHI->addIncoming(NewAdd, PH->getIncomingBlock(BackEdge));
904
905 ConstantInt *NewEV = ConstantInt::get(Type::Int32Ty, intEV);
906 Value *LHS = (EVIndex == 1 ? NewPHI->getIncomingValue(BackEdge) : NewEV);
907 Value *RHS = (EVIndex == 1 ? NewEV : NewPHI->getIncomingValue(BackEdge));
908 ICmpInst *NewEC = new ICmpInst(NewPred, LHS, RHS, EC->getNameStart(),
909 EC->getParent()->getTerminator());
910
911 // Delete old, floating point, exit comparision instruction.
912 EC->replaceAllUsesWith(NewEC);
913 DeadInsts.insert(EC);
914
915 // Delete old, floating point, increment instruction.
916 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
917 DeadInsts.insert(Incr);
918
Devang Patel13877bf2008-11-18 00:40:02 +0000919 // Replace floating induction variable. Give SIToFPInst preference over
920 // UIToFPInst because it is faster on platforms that are widely used.
921 if (useSIToFPInst(*InitValue, *EV, newInitValue, intEV)) {
Devang Patelcd402332008-11-17 23:27:13 +0000922 SIToFPInst *Conv = new SIToFPInst(NewPHI, PH->getType(), "indvar.conv",
923 PH->getParent()->getFirstNonPHI());
924 PH->replaceAllUsesWith(Conv);
925 } else {
926 UIToFPInst *Conv = new UIToFPInst(NewPHI, PH->getType(), "indvar.conv",
927 PH->getParent()->getFirstNonPHI());
928 PH->replaceAllUsesWith(Conv);
929 }
Devang Patel84e35152008-11-17 21:32:02 +0000930 DeadInsts.insert(PH);
Devang Patel58d43d42008-11-03 18:32:19 +0000931}
932