blob: 636fefaf22eeeffc2bda2556b429644ce7145c3d [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//
Andrew Trick4b4bb712011-08-10 03:46:27 +000014// Additionally, unless -disable-iv-rewrite is on, this transformation makes the
15// following changes to each loop with an identifiable induction variable:
Chris Lattner40bf8b42004-04-02 20:24:31 +000016// 1. All loops are transformed to have a SINGLE canonical induction variable
17// which starts at zero and steps by one.
18// 2. The canonical induction variable is guaranteed to be the first PHI node
19// in the loop header block.
Dan Gohmanea73f3c2009-06-14 22:38:41 +000020// 3. The canonical induction variable is guaranteed to be in a wide enough
21// type so that IV expressions need not be (directly) zero-extended or
22// sign-extended.
23// 4. Any pointer arithmetic recurrences are raised to use array subscripts.
Chris Lattner40bf8b42004-04-02 20:24:31 +000024//
25// If the trip count of a loop is computable, this pass also makes the following
26// changes:
27// 1. The exit condition for the loop is canonicalized to compare the
28// induction value against the exit value. This turns loops like:
29// 'for (i = 7; i*i < 1000; ++i)' into 'for (i = 0; i != 25; ++i)'
30// 2. Any use outside of the loop of an expression derived from the indvar
31// is changed to compute the derived value outside of the loop, eliminating
32// the dependence on the exit value of the induction variable. If the only
33// purpose of the loop is to compute the exit value of some derived
34// expression, this transformation will make the loop dead.
35//
36// This transformation should be followed by strength reduction after all of the
Dan Gohmanc2c4cbf2009-05-19 20:38:47 +000037// desired loop transformations have been performed.
Chris Lattner6148c022001-12-03 17:28:42 +000038//
39//===----------------------------------------------------------------------===//
40
Chris Lattner0e5f4992006-12-19 21:40:18 +000041#define DEBUG_TYPE "indvars"
Chris Lattner022103b2002-05-07 20:03:00 +000042#include "llvm/Transforms/Scalar.h"
Chris Lattner40bf8b42004-04-02 20:24:31 +000043#include "llvm/BasicBlock.h"
Chris Lattner59fdaee2004-04-15 15:21:43 +000044#include "llvm/Constants.h"
Chris Lattner18b3c972003-12-22 05:02:01 +000045#include "llvm/Instructions.h"
Devang Patel7b9f6b12010-03-15 22:23:03 +000046#include "llvm/IntrinsicInst.h"
Owen Andersond672ecb2009-07-03 00:17:18 +000047#include "llvm/LLVMContext.h"
Chris Lattner40bf8b42004-04-02 20:24:31 +000048#include "llvm/Type.h"
Dan Gohman81db61a2009-05-12 02:17:14 +000049#include "llvm/Analysis/Dominators.h"
50#include "llvm/Analysis/IVUsers.h"
Nate Begeman36f891b2005-07-30 00:12:19 +000051#include "llvm/Analysis/ScalarEvolutionExpander.h"
John Criswell47df12d2003-12-18 17:19:19 +000052#include "llvm/Analysis/LoopInfo.h"
Devang Patel5ee99972007-03-07 06:39:01 +000053#include "llvm/Analysis/LoopPass.h"
Chris Lattner455889a2002-02-12 22:39:50 +000054#include "llvm/Support/CFG.h"
Andrew Trick56caa092011-06-28 03:01:46 +000055#include "llvm/Support/CommandLine.h"
Chris Lattneree4f13a2007-01-07 01:14:12 +000056#include "llvm/Support/Debug.h"
Chris Lattnerbdff5482009-08-23 04:37:46 +000057#include "llvm/Support/raw_ostream.h"
John Criswell47df12d2003-12-18 17:19:19 +000058#include "llvm/Transforms/Utils/Local.h"
Dan Gohman81db61a2009-05-12 02:17:14 +000059#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Andrew Trick4b4bb712011-08-10 03:46:27 +000060#include "llvm/Transforms/Utils/SimplifyIndVar.h"
Andrew Trick37da4082011-05-04 02:10:13 +000061#include "llvm/Target/TargetData.h"
Andrew Trick037d1c02011-07-06 20:50:43 +000062#include "llvm/ADT/DenseMap.h"
Reid Spencera54b7cb2007-01-12 07:05:14 +000063#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000064#include "llvm/ADT/Statistic.h"
John Criswell47df12d2003-12-18 17:19:19 +000065using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000066
Andrew Trick2fabd462011-06-21 03:22:38 +000067STATISTIC(NumRemoved , "Number of aux indvars removed");
68STATISTIC(NumWidened , "Number of indvars widened");
69STATISTIC(NumInserted , "Number of canonical indvars added");
70STATISTIC(NumReplaced , "Number of exit values replaced");
71STATISTIC(NumLFTR , "Number of loop exit tests replaced");
Andrew Trick2fabd462011-06-21 03:22:38 +000072STATISTIC(NumElimExt , "Number of IV sign/zero extends eliminated");
Andrew Trick037d1c02011-07-06 20:50:43 +000073STATISTIC(NumElimIV , "Number of congruent IVs eliminated");
Chris Lattner3324e712003-12-22 03:58:44 +000074
Andrew Trick4b4bb712011-08-10 03:46:27 +000075namespace llvm {
76 cl::opt<bool> DisableIVRewrite(
77 "disable-iv-rewrite", cl::Hidden,
78 cl::desc("Disable canonical induction variable rewriting"));
Andrew Trick75ebc0e2011-09-06 20:20:38 +000079
80 // Trip count verification can be enabled by default under NDEBUG if we
81 // implement a strong expression equivalence checker in SCEV. Until then, we
82 // use the verify-indvars flag, which may assert in some cases.
83 cl::opt<bool> VerifyIndvars(
84 "verify-indvars", cl::Hidden,
85 cl::desc("Verify the ScalarEvolution result after running indvars"));
Andrew Trick4b4bb712011-08-10 03:46:27 +000086}
Andrew Trick37da4082011-05-04 02:10:13 +000087
Andrew Trickfc933c02011-07-18 20:32:31 +000088// Temporary flag for use with -disable-iv-rewrite to force a canonical IV for
89// LFTR purposes.
90static cl::opt<bool> ForceLFTR(
91 "force-lftr", cl::Hidden,
92 cl::desc("Enable forced linear function test replacement"));
93
Chris Lattner0e5f4992006-12-19 21:40:18 +000094namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000095 class IndVarSimplify : public LoopPass {
Dan Gohman81db61a2009-05-12 02:17:14 +000096 IVUsers *IU;
Chris Lattner40bf8b42004-04-02 20:24:31 +000097 LoopInfo *LI;
98 ScalarEvolution *SE;
Dan Gohmande53dc02009-06-27 05:16:57 +000099 DominatorTree *DT;
Andrew Trick37da4082011-05-04 02:10:13 +0000100 TargetData *TD;
Andrew Trick2fabd462011-06-21 03:22:38 +0000101
Andrew Trickb12a7542011-03-17 23:51:11 +0000102 SmallVector<WeakVH, 16> DeadInsts;
Chris Lattner15cad752003-12-23 07:47:09 +0000103 bool Changed;
Chris Lattner3324e712003-12-22 03:58:44 +0000104 public:
Devang Patel794fd752007-05-01 21:15:47 +0000105
Dan Gohman5668cf72009-07-15 01:26:32 +0000106 static char ID; // Pass identification, replacement for typeid
Andrew Trick2fabd462011-06-21 03:22:38 +0000107 IndVarSimplify() : LoopPass(ID), IU(0), LI(0), SE(0), DT(0), TD(0),
Andrew Trick15832f62011-06-28 02:49:20 +0000108 Changed(false) {
Owen Anderson081c34b2010-10-19 17:21:58 +0000109 initializeIndVarSimplifyPass(*PassRegistry::getPassRegistry());
110 }
Devang Patel794fd752007-05-01 21:15:47 +0000111
Dan Gohman5668cf72009-07-15 01:26:32 +0000112 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
Dan Gohman60f8a632009-02-17 20:49:49 +0000113
Dan Gohman5668cf72009-07-15 01:26:32 +0000114 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
115 AU.addRequired<DominatorTree>();
116 AU.addRequired<LoopInfo>();
117 AU.addRequired<ScalarEvolution>();
118 AU.addRequiredID(LoopSimplifyID);
119 AU.addRequiredID(LCSSAID);
Andrew Trick56caa092011-06-28 03:01:46 +0000120 if (!DisableIVRewrite)
121 AU.addRequired<IVUsers>();
Dan Gohman5668cf72009-07-15 01:26:32 +0000122 AU.addPreserved<ScalarEvolution>();
123 AU.addPreservedID(LoopSimplifyID);
124 AU.addPreservedID(LCSSAID);
Andrew Trick2fabd462011-06-21 03:22:38 +0000125 if (!DisableIVRewrite)
126 AU.addPreserved<IVUsers>();
Dan Gohman5668cf72009-07-15 01:26:32 +0000127 AU.setPreservesCFG();
128 }
Chris Lattner15cad752003-12-23 07:47:09 +0000129
Chris Lattner40bf8b42004-04-02 20:24:31 +0000130 private:
Andrew Trick037d1c02011-07-06 20:50:43 +0000131 virtual void releaseMemory() {
Andrew Trick037d1c02011-07-06 20:50:43 +0000132 DeadInsts.clear();
133 }
134
Andrew Trickb12a7542011-03-17 23:51:11 +0000135 bool isValidRewrite(Value *FromVal, Value *ToVal);
Devang Patel5ee99972007-03-07 06:39:01 +0000136
Andrew Trick1a54bb22011-07-12 00:08:50 +0000137 void HandleFloatingPointIV(Loop *L, PHINode *PH);
138 void RewriteNonIntegerIVs(Loop *L);
139
Andrew Trick4b4bb712011-08-10 03:46:27 +0000140 void SimplifyAndExtend(Loop *L, SCEVExpander &Rewriter, LPPassManager &LPM);
Andrew Trick06988bc2011-08-06 07:00:37 +0000141
Andrew Trick037d1c02011-07-06 20:50:43 +0000142 void SimplifyCongruentIVs(Loop *L);
143
Andrew Trick4b4bb712011-08-10 03:46:27 +0000144 void RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter);
145
Dan Gohman454d26d2010-02-22 04:11:59 +0000146 void RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter);
Devang Pateld22a8492008-09-09 21:41:07 +0000147
Andrew Trickfc933c02011-07-18 20:32:31 +0000148 Value *LinearFunctionTestReplace(Loop *L, const SCEV *BackedgeTakenCount,
149 PHINode *IndVar, SCEVExpander &Rewriter);
Dan Gohman81db61a2009-05-12 02:17:14 +0000150
Andrew Trick1a54bb22011-07-12 00:08:50 +0000151 void SinkUnusedInvariants(Loop *L);
Chris Lattner3324e712003-12-22 03:58:44 +0000152 };
Chris Lattner5e761402002-09-10 05:24:05 +0000153}
Chris Lattner394437f2001-12-04 04:32:29 +0000154
Dan Gohman844731a2008-05-13 00:00:25 +0000155char IndVarSimplify::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000156INITIALIZE_PASS_BEGIN(IndVarSimplify, "indvars",
Andrew Trick37da4082011-05-04 02:10:13 +0000157 "Induction Variable Simplification", false, false)
Owen Anderson2ab36d32010-10-12 19:48:12 +0000158INITIALIZE_PASS_DEPENDENCY(DominatorTree)
159INITIALIZE_PASS_DEPENDENCY(LoopInfo)
160INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
161INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
162INITIALIZE_PASS_DEPENDENCY(LCSSA)
163INITIALIZE_PASS_DEPENDENCY(IVUsers)
164INITIALIZE_PASS_END(IndVarSimplify, "indvars",
Andrew Trick37da4082011-05-04 02:10:13 +0000165 "Induction Variable Simplification", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000166
Daniel Dunbar394f0442008-10-22 23:32:42 +0000167Pass *llvm::createIndVarSimplifyPass() {
Chris Lattner3324e712003-12-22 03:58:44 +0000168 return new IndVarSimplify();
Chris Lattner394437f2001-12-04 04:32:29 +0000169}
170
Andrew Trickb12a7542011-03-17 23:51:11 +0000171/// isValidRewrite - Return true if the SCEV expansion generated by the
172/// rewriter can replace the original value. SCEV guarantees that it
173/// produces the same value, but the way it is produced may be illegal IR.
174/// Ideally, this function will only be called for verification.
175bool IndVarSimplify::isValidRewrite(Value *FromVal, Value *ToVal) {
176 // If an SCEV expression subsumed multiple pointers, its expansion could
177 // reassociate the GEP changing the base pointer. This is illegal because the
178 // final address produced by a GEP chain must be inbounds relative to its
179 // underlying object. Otherwise basic alias analysis, among other things,
180 // could fail in a dangerous way. Ultimately, SCEV will be improved to avoid
181 // producing an expression involving multiple pointers. Until then, we must
182 // bail out here.
183 //
184 // Retrieve the pointer operand of the GEP. Don't use GetUnderlyingObject
185 // because it understands lcssa phis while SCEV does not.
186 Value *FromPtr = FromVal;
187 Value *ToPtr = ToVal;
188 if (GEPOperator *GEP = dyn_cast<GEPOperator>(FromVal)) {
189 FromPtr = GEP->getPointerOperand();
190 }
191 if (GEPOperator *GEP = dyn_cast<GEPOperator>(ToVal)) {
192 ToPtr = GEP->getPointerOperand();
193 }
194 if (FromPtr != FromVal || ToPtr != ToVal) {
195 // Quickly check the common case
196 if (FromPtr == ToPtr)
197 return true;
198
199 // SCEV may have rewritten an expression that produces the GEP's pointer
200 // operand. That's ok as long as the pointer operand has the same base
201 // pointer. Unlike GetUnderlyingObject(), getPointerBase() will find the
202 // base of a recurrence. This handles the case in which SCEV expansion
203 // converts a pointer type recurrence into a nonrecurrent pointer base
204 // indexed by an integer recurrence.
205 const SCEV *FromBase = SE->getPointerBase(SE->getSCEV(FromPtr));
206 const SCEV *ToBase = SE->getPointerBase(SE->getSCEV(ToPtr));
207 if (FromBase == ToBase)
208 return true;
209
210 DEBUG(dbgs() << "INDVARS: GEP rewrite bail out "
211 << *FromBase << " != " << *ToBase << "\n");
212
213 return false;
214 }
215 return true;
216}
217
Andrew Trick86c98142011-07-20 05:32:06 +0000218/// Determine the insertion point for this user. By default, insert immediately
219/// before the user. SCEVExpander or LICM will hoist loop invariants out of the
220/// loop. For PHI nodes, there may be multiple uses, so compute the nearest
221/// common dominator for the incoming blocks.
222static Instruction *getInsertPointForUses(Instruction *User, Value *Def,
223 DominatorTree *DT) {
224 PHINode *PHI = dyn_cast<PHINode>(User);
225 if (!PHI)
226 return User;
227
228 Instruction *InsertPt = 0;
229 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i) {
230 if (PHI->getIncomingValue(i) != Def)
231 continue;
232
233 BasicBlock *InsertBB = PHI->getIncomingBlock(i);
234 if (!InsertPt) {
235 InsertPt = InsertBB->getTerminator();
236 continue;
237 }
238 InsertBB = DT->findNearestCommonDominator(InsertPt->getParent(), InsertBB);
239 InsertPt = InsertBB->getTerminator();
240 }
241 assert(InsertPt && "Missing phi operand");
Jay Foad626f52d2011-07-20 08:15:21 +0000242 assert((!isa<Instruction>(Def) ||
243 DT->dominates(cast<Instruction>(Def), InsertPt)) &&
Andrew Trick86c98142011-07-20 05:32:06 +0000244 "def does not dominate all uses");
245 return InsertPt;
246}
247
Andrew Trick1a54bb22011-07-12 00:08:50 +0000248//===----------------------------------------------------------------------===//
249// RewriteNonIntegerIVs and helpers. Prefer integer IVs.
250//===----------------------------------------------------------------------===//
Andrew Trick4dfdf242011-05-03 22:24:10 +0000251
Andrew Trick1a54bb22011-07-12 00:08:50 +0000252/// ConvertToSInt - Convert APF to an integer, if possible.
253static bool ConvertToSInt(const APFloat &APF, int64_t &IntVal) {
254 bool isExact = false;
255 if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
Andrew Trick4dfdf242011-05-03 22:24:10 +0000256 return false;
Andrew Trick1a54bb22011-07-12 00:08:50 +0000257 // See if we can convert this to an int64_t
258 uint64_t UIntVal;
259 if (APF.convertToInteger(&UIntVal, 64, true, APFloat::rmTowardZero,
260 &isExact) != APFloat::opOK || !isExact)
Andrew Trick4dfdf242011-05-03 22:24:10 +0000261 return false;
Andrew Trick1a54bb22011-07-12 00:08:50 +0000262 IntVal = UIntVal;
Andrew Trick4dfdf242011-05-03 22:24:10 +0000263 return true;
264}
265
Andrew Trick1a54bb22011-07-12 00:08:50 +0000266/// HandleFloatingPointIV - If the loop has floating induction variable
267/// then insert corresponding integer induction variable if possible.
268/// For example,
269/// for(double i = 0; i < 10000; ++i)
270/// bar(i)
271/// is converted into
272/// for(int i = 0; i < 10000; ++i)
273/// bar((double)i);
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000274///
Andrew Trick1a54bb22011-07-12 00:08:50 +0000275void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PN) {
276 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
277 unsigned BackEdge = IncomingEdge^1;
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000278
Andrew Trick1a54bb22011-07-12 00:08:50 +0000279 // Check incoming value.
280 ConstantFP *InitValueVal =
281 dyn_cast<ConstantFP>(PN->getIncomingValue(IncomingEdge));
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000282
Andrew Trick1a54bb22011-07-12 00:08:50 +0000283 int64_t InitValue;
284 if (!InitValueVal || !ConvertToSInt(InitValueVal->getValueAPF(), InitValue))
285 return;
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000286
Andrew Trick1a54bb22011-07-12 00:08:50 +0000287 // Check IV increment. Reject this PN if increment operation is not
288 // an add or increment value can not be represented by an integer.
289 BinaryOperator *Incr =
290 dyn_cast<BinaryOperator>(PN->getIncomingValue(BackEdge));
291 if (Incr == 0 || Incr->getOpcode() != Instruction::FAdd) return;
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000292
Andrew Trick1a54bb22011-07-12 00:08:50 +0000293 // If this is not an add of the PHI with a constantfp, or if the constant fp
294 // is not an integer, bail out.
295 ConstantFP *IncValueVal = dyn_cast<ConstantFP>(Incr->getOperand(1));
296 int64_t IncValue;
297 if (IncValueVal == 0 || Incr->getOperand(0) != PN ||
298 !ConvertToSInt(IncValueVal->getValueAPF(), IncValue))
299 return;
300
301 // Check Incr uses. One user is PN and the other user is an exit condition
302 // used by the conditional terminator.
303 Value::use_iterator IncrUse = Incr->use_begin();
304 Instruction *U1 = cast<Instruction>(*IncrUse++);
305 if (IncrUse == Incr->use_end()) return;
306 Instruction *U2 = cast<Instruction>(*IncrUse++);
307 if (IncrUse != Incr->use_end()) return;
308
309 // Find exit condition, which is an fcmp. If it doesn't exist, or if it isn't
310 // only used by a branch, we can't transform it.
311 FCmpInst *Compare = dyn_cast<FCmpInst>(U1);
312 if (!Compare)
313 Compare = dyn_cast<FCmpInst>(U2);
314 if (Compare == 0 || !Compare->hasOneUse() ||
315 !isa<BranchInst>(Compare->use_back()))
316 return;
317
318 BranchInst *TheBr = cast<BranchInst>(Compare->use_back());
319
320 // We need to verify that the branch actually controls the iteration count
321 // of the loop. If not, the new IV can overflow and no one will notice.
322 // The branch block must be in the loop and one of the successors must be out
323 // of the loop.
324 assert(TheBr->isConditional() && "Can't use fcmp if not conditional");
325 if (!L->contains(TheBr->getParent()) ||
326 (L->contains(TheBr->getSuccessor(0)) &&
327 L->contains(TheBr->getSuccessor(1))))
328 return;
329
330
331 // If it isn't a comparison with an integer-as-fp (the exit value), we can't
332 // transform it.
333 ConstantFP *ExitValueVal = dyn_cast<ConstantFP>(Compare->getOperand(1));
334 int64_t ExitValue;
335 if (ExitValueVal == 0 ||
336 !ConvertToSInt(ExitValueVal->getValueAPF(), ExitValue))
337 return;
338
339 // Find new predicate for integer comparison.
340 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
341 switch (Compare->getPredicate()) {
342 default: return; // Unknown comparison.
343 case CmpInst::FCMP_OEQ:
344 case CmpInst::FCMP_UEQ: NewPred = CmpInst::ICMP_EQ; break;
345 case CmpInst::FCMP_ONE:
346 case CmpInst::FCMP_UNE: NewPred = CmpInst::ICMP_NE; break;
347 case CmpInst::FCMP_OGT:
348 case CmpInst::FCMP_UGT: NewPred = CmpInst::ICMP_SGT; break;
349 case CmpInst::FCMP_OGE:
350 case CmpInst::FCMP_UGE: NewPred = CmpInst::ICMP_SGE; break;
351 case CmpInst::FCMP_OLT:
352 case CmpInst::FCMP_ULT: NewPred = CmpInst::ICMP_SLT; break;
353 case CmpInst::FCMP_OLE:
354 case CmpInst::FCMP_ULE: NewPred = CmpInst::ICMP_SLE; break;
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000355 }
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000356
Andrew Trick1a54bb22011-07-12 00:08:50 +0000357 // We convert the floating point induction variable to a signed i32 value if
358 // we can. This is only safe if the comparison will not overflow in a way
359 // that won't be trapped by the integer equivalent operations. Check for this
360 // now.
361 // TODO: We could use i64 if it is native and the range requires it.
Dan Gohmanca9b7032010-04-12 21:13:43 +0000362
Andrew Trick1a54bb22011-07-12 00:08:50 +0000363 // The start/stride/exit values must all fit in signed i32.
364 if (!isInt<32>(InitValue) || !isInt<32>(IncValue) || !isInt<32>(ExitValue))
365 return;
366
367 // If not actually striding (add x, 0.0), avoid touching the code.
368 if (IncValue == 0)
369 return;
370
371 // Positive and negative strides have different safety conditions.
372 if (IncValue > 0) {
373 // If we have a positive stride, we require the init to be less than the
374 // exit value and an equality or less than comparison.
375 if (InitValue >= ExitValue ||
376 NewPred == CmpInst::ICMP_SGT || NewPred == CmpInst::ICMP_SGE)
377 return;
378
379 uint32_t Range = uint32_t(ExitValue-InitValue);
380 if (NewPred == CmpInst::ICMP_SLE) {
381 // Normalize SLE -> SLT, check for infinite loop.
382 if (++Range == 0) return; // Range overflows.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000383 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000384
Andrew Trick1a54bb22011-07-12 00:08:50 +0000385 unsigned Leftover = Range % uint32_t(IncValue);
386
387 // If this is an equality comparison, we require that the strided value
388 // exactly land on the exit value, otherwise the IV condition will wrap
389 // around and do things the fp IV wouldn't.
390 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
391 Leftover != 0)
392 return;
393
394 // If the stride would wrap around the i32 before exiting, we can't
395 // transform the IV.
396 if (Leftover != 0 && int32_t(ExitValue+IncValue) < ExitValue)
397 return;
398
Chris Lattnerd2440572004-04-15 20:26:22 +0000399 } else {
Andrew Trick1a54bb22011-07-12 00:08:50 +0000400 // If we have a negative stride, we require the init to be greater than the
401 // exit value and an equality or greater than comparison.
402 if (InitValue >= ExitValue ||
403 NewPred == CmpInst::ICMP_SLT || NewPred == CmpInst::ICMP_SLE)
404 return;
405
406 uint32_t Range = uint32_t(InitValue-ExitValue);
407 if (NewPred == CmpInst::ICMP_SGE) {
408 // Normalize SGE -> SGT, check for infinite loop.
409 if (++Range == 0) return; // Range overflows.
410 }
411
412 unsigned Leftover = Range % uint32_t(-IncValue);
413
414 // If this is an equality comparison, we require that the strided value
415 // exactly land on the exit value, otherwise the IV condition will wrap
416 // around and do things the fp IV wouldn't.
417 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
418 Leftover != 0)
419 return;
420
421 // If the stride would wrap around the i32 before exiting, we can't
422 // transform the IV.
423 if (Leftover != 0 && int32_t(ExitValue+IncValue) > ExitValue)
424 return;
Chris Lattnerd2440572004-04-15 20:26:22 +0000425 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000426
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000427 IntegerType *Int32Ty = Type::getInt32Ty(PN->getContext());
Chris Lattner40bf8b42004-04-02 20:24:31 +0000428
Andrew Trick1a54bb22011-07-12 00:08:50 +0000429 // Insert new integer induction variable.
430 PHINode *NewPHI = PHINode::Create(Int32Ty, 2, PN->getName()+".int", PN);
431 NewPHI->addIncoming(ConstantInt::get(Int32Ty, InitValue),
432 PN->getIncomingBlock(IncomingEdge));
Chris Lattner40bf8b42004-04-02 20:24:31 +0000433
Andrew Trick1a54bb22011-07-12 00:08:50 +0000434 Value *NewAdd =
435 BinaryOperator::CreateAdd(NewPHI, ConstantInt::get(Int32Ty, IncValue),
436 Incr->getName()+".int", Incr);
437 NewPHI->addIncoming(NewAdd, PN->getIncomingBlock(BackEdge));
Dan Gohmanc2390b12009-02-12 22:19:27 +0000438
Andrew Trick1a54bb22011-07-12 00:08:50 +0000439 ICmpInst *NewCompare = new ICmpInst(TheBr, NewPred, NewAdd,
440 ConstantInt::get(Int32Ty, ExitValue),
441 Compare->getName());
Dan Gohman81db61a2009-05-12 02:17:14 +0000442
Andrew Trick1a54bb22011-07-12 00:08:50 +0000443 // In the following deletions, PN may become dead and may be deleted.
444 // Use a WeakVH to observe whether this happens.
445 WeakVH WeakPH = PN;
446
447 // Delete the old floating point exit comparison. The branch starts using the
448 // new comparison.
449 NewCompare->takeName(Compare);
450 Compare->replaceAllUsesWith(NewCompare);
451 RecursivelyDeleteTriviallyDeadInstructions(Compare);
452
453 // Delete the old floating point increment.
454 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
455 RecursivelyDeleteTriviallyDeadInstructions(Incr);
456
457 // If the FP induction variable still has uses, this is because something else
458 // in the loop uses its value. In order to canonicalize the induction
459 // variable, we chose to eliminate the IV and rewrite it in terms of an
460 // int->fp cast.
461 //
462 // We give preference to sitofp over uitofp because it is faster on most
463 // platforms.
464 if (WeakPH) {
465 Value *Conv = new SIToFPInst(NewPHI, PN->getType(), "indvar.conv",
Bill Wendlingb05fdd62011-08-24 20:28:43 +0000466 PN->getParent()->getFirstInsertionPt());
Andrew Trick1a54bb22011-07-12 00:08:50 +0000467 PN->replaceAllUsesWith(Conv);
468 RecursivelyDeleteTriviallyDeadInstructions(PN);
469 }
470
471 // Add a new IVUsers entry for the newly-created integer PHI.
472 if (IU)
473 IU->AddUsersIfInteresting(NewPHI);
Andrew Trick4b4bb712011-08-10 03:46:27 +0000474
475 Changed = true;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000476}
477
Andrew Trick1a54bb22011-07-12 00:08:50 +0000478void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) {
479 // First step. Check to see if there are any floating-point recurrences.
480 // If there are, change them into integer recurrences, permitting analysis by
481 // the SCEV routines.
482 //
483 BasicBlock *Header = L->getHeader();
484
485 SmallVector<WeakVH, 8> PHIs;
486 for (BasicBlock::iterator I = Header->begin();
487 PHINode *PN = dyn_cast<PHINode>(I); ++I)
488 PHIs.push_back(PN);
489
490 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
491 if (PHINode *PN = dyn_cast_or_null<PHINode>(&*PHIs[i]))
492 HandleFloatingPointIV(L, PN);
493
494 // If the loop previously had floating-point IV, ScalarEvolution
495 // may not have been able to compute a trip count. Now that we've done some
496 // re-writing, the trip count may be computable.
497 if (Changed)
498 SE->forgetLoop(L);
499}
500
501//===----------------------------------------------------------------------===//
502// RewriteLoopExitValues - Optimize IV users outside the loop.
503// As a side effect, reduces the amount of IV processing within the loop.
504//===----------------------------------------------------------------------===//
505
Chris Lattner40bf8b42004-04-02 20:24:31 +0000506/// RewriteLoopExitValues - Check to see if this loop has a computable
507/// loop-invariant execution count. If so, this means that we can compute the
508/// final value of any expressions that are recurrent in the loop, and
509/// substitute the exit values from the loop into any instructions outside of
510/// the loop that use the final values of the current expressions.
Dan Gohman81db61a2009-05-12 02:17:14 +0000511///
512/// This is mostly redundant with the regular IndVarSimplify activities that
513/// happen later, except that it's more powerful in some cases, because it's
514/// able to brute-force evaluate arbitrary instructions as long as they have
515/// constant operands at the beginning of the loop.
Chris Lattnerf1859892011-01-09 02:16:18 +0000516void IndVarSimplify::RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000517 // Verify the input to the pass in already in LCSSA form.
Dan Gohmanbbf81d82010-03-10 19:38:49 +0000518 assert(L->isLCSSAForm(*DT));
Dan Gohman81db61a2009-05-12 02:17:14 +0000519
Devang Patelb7211a22007-08-21 00:31:24 +0000520 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattner9f3d7382007-03-04 03:43:23 +0000521 L->getUniqueExitBlocks(ExitBlocks);
Misha Brukmanfd939082005-04-21 23:48:37 +0000522
Chris Lattner9f3d7382007-03-04 03:43:23 +0000523 // Find all values that are computed inside the loop, but used outside of it.
524 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
525 // the exit blocks of the loop to find them.
526 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
527 BasicBlock *ExitBB = ExitBlocks[i];
Dan Gohmancafb8132009-02-17 19:13:57 +0000528
Chris Lattner9f3d7382007-03-04 03:43:23 +0000529 // If there are no PHI nodes in this exit block, then no values defined
530 // inside the loop are used on this path, skip it.
531 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
532 if (!PN) continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000533
Chris Lattner9f3d7382007-03-04 03:43:23 +0000534 unsigned NumPreds = PN->getNumIncomingValues();
Dan Gohmancafb8132009-02-17 19:13:57 +0000535
Chris Lattner9f3d7382007-03-04 03:43:23 +0000536 // Iterate over all of the PHI nodes.
537 BasicBlock::iterator BBI = ExitBB->begin();
538 while ((PN = dyn_cast<PHINode>(BBI++))) {
Torok Edwin3790fb02009-05-24 19:36:09 +0000539 if (PN->use_empty())
540 continue; // dead use, don't replace it
Dan Gohman814f2b22010-02-18 21:34:02 +0000541
542 // SCEV only supports integer expressions for now.
543 if (!PN->getType()->isIntegerTy() && !PN->getType()->isPointerTy())
544 continue;
545
Dale Johannesen45a2d7d2010-02-19 07:14:22 +0000546 // It's necessary to tell ScalarEvolution about this explicitly so that
547 // it can walk the def-use list and forget all SCEVs, as it may not be
548 // watching the PHI itself. Once the new exit value is in place, there
549 // may not be a def-use connection between the loop and every instruction
550 // which got a SCEVAddRecExpr for that loop.
551 SE->forgetValue(PN);
552
Chris Lattner9f3d7382007-03-04 03:43:23 +0000553 // Iterate over all of the values in all the PHI nodes.
554 for (unsigned i = 0; i != NumPreds; ++i) {
555 // If the value being merged in is not integer or is not defined
556 // in the loop, skip it.
557 Value *InVal = PN->getIncomingValue(i);
Dan Gohman814f2b22010-02-18 21:34:02 +0000558 if (!isa<Instruction>(InVal))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000559 continue;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000560
Chris Lattner9f3d7382007-03-04 03:43:23 +0000561 // If this pred is for a subloop, not L itself, skip it.
Dan Gohmancafb8132009-02-17 19:13:57 +0000562 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
Chris Lattner9f3d7382007-03-04 03:43:23 +0000563 continue; // The Block is in a subloop, skip it.
564
565 // Check that InVal is defined in the loop.
566 Instruction *Inst = cast<Instruction>(InVal);
Dan Gohman92329c72009-12-18 01:24:09 +0000567 if (!L->contains(Inst))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000568 continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000569
Chris Lattner9f3d7382007-03-04 03:43:23 +0000570 // Okay, this instruction has a user outside of the current loop
571 // and varies predictably *inside* the loop. Evaluate the value it
572 // contains when the loop exits, if possible.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000573 const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
Dan Gohman17ead4f2010-11-17 21:23:15 +0000574 if (!SE->isLoopInvariant(ExitValue, L))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000575 continue;
Chris Lattner9caed542007-03-04 01:00:28 +0000576
Dan Gohman667d7872009-06-26 22:53:46 +0000577 Value *ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), Inst);
Dan Gohmancafb8132009-02-17 19:13:57 +0000578
David Greenef67ef312010-01-05 01:27:06 +0000579 DEBUG(dbgs() << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal << '\n'
Chris Lattnerbdff5482009-08-23 04:37:46 +0000580 << " LoopVal = " << *Inst << "\n");
Chris Lattner9f3d7382007-03-04 03:43:23 +0000581
Andrew Trickb12a7542011-03-17 23:51:11 +0000582 if (!isValidRewrite(Inst, ExitVal)) {
583 DeadInsts.push_back(ExitVal);
584 continue;
585 }
586 Changed = true;
587 ++NumReplaced;
588
Chris Lattner9f3d7382007-03-04 03:43:23 +0000589 PN->setIncomingValue(i, ExitVal);
Dan Gohmancafb8132009-02-17 19:13:57 +0000590
Dan Gohman81db61a2009-05-12 02:17:14 +0000591 // If this instruction is dead now, delete it.
592 RecursivelyDeleteTriviallyDeadInstructions(Inst);
Dan Gohmancafb8132009-02-17 19:13:57 +0000593
Dan Gohman65d1e2b2009-07-14 01:09:02 +0000594 if (NumPreds == 1) {
595 // Completely replace a single-pred PHI. This is safe, because the
596 // NewVal won't be variant in the loop, so we don't need an LCSSA phi
597 // node anymore.
Chris Lattner9f3d7382007-03-04 03:43:23 +0000598 PN->replaceAllUsesWith(ExitVal);
Dan Gohman81db61a2009-05-12 02:17:14 +0000599 RecursivelyDeleteTriviallyDeadInstructions(PN);
Chris Lattnerc9838f22007-03-03 22:48:48 +0000600 }
601 }
Dan Gohman65d1e2b2009-07-14 01:09:02 +0000602 if (NumPreds != 1) {
Dan Gohman667d7872009-06-26 22:53:46 +0000603 // Clone the PHI and delete the original one. This lets IVUsers and
604 // any other maps purge the original user from their records.
Devang Patel50b6e332009-10-27 22:16:29 +0000605 PHINode *NewPN = cast<PHINode>(PN->clone());
Dan Gohman667d7872009-06-26 22:53:46 +0000606 NewPN->takeName(PN);
607 NewPN->insertBefore(PN);
608 PN->replaceAllUsesWith(NewPN);
609 PN->eraseFromParent();
610 }
Chris Lattnerc9838f22007-03-03 22:48:48 +0000611 }
612 }
Dan Gohman472fdf72010-03-20 03:53:53 +0000613
614 // The insertion point instruction may have been deleted; clear it out
615 // so that the rewriter doesn't trip over it later.
616 Rewriter.clearInsertPoint();
Chris Lattner40bf8b42004-04-02 20:24:31 +0000617}
618
Andrew Trick1a54bb22011-07-12 00:08:50 +0000619//===----------------------------------------------------------------------===//
620// Rewrite IV users based on a canonical IV.
621// To be replaced by -disable-iv-rewrite.
622//===----------------------------------------------------------------------===//
Dale Johannesenc671d892009-04-15 23:31:51 +0000623
Andrew Trick1a54bb22011-07-12 00:08:50 +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, unless
629// it can be expanded to a trivial value.
630static bool isSafe(const SCEV *S, const Loop *L, ScalarEvolution *SE) {
631 // Loop-invariant values are safe.
632 if (SE->isLoopInvariant(S, L)) return true;
633
634 // Affine addrecs are safe. Non-affine are not, because LSR doesn't know how
635 // to transform them into efficient code.
636 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
637 return AR->isAffine();
638
639 // An add is safe it all its operands are safe.
640 if (const SCEVCommutativeExpr *Commutative = dyn_cast<SCEVCommutativeExpr>(S)) {
641 for (SCEVCommutativeExpr::op_iterator I = Commutative->op_begin(),
642 E = Commutative->op_end(); I != E; ++I)
643 if (!isSafe(*I, L, SE)) return false;
644 return true;
645 }
646
647 // A cast is safe if its operand is.
648 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
649 return isSafe(C->getOperand(), L, SE);
650
651 // A udiv is safe if its operands are.
652 if (const SCEVUDivExpr *UD = dyn_cast<SCEVUDivExpr>(S))
653 return isSafe(UD->getLHS(), L, SE) &&
654 isSafe(UD->getRHS(), L, SE);
655
656 // SCEVUnknown is always safe.
657 if (isa<SCEVUnknown>(S))
658 return true;
659
660 // Nothing else is safe.
661 return false;
662}
663
664void IndVarSimplify::RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter) {
665 // Rewrite all induction variable expressions in terms of the canonical
666 // induction variable.
667 //
668 // If there were induction variables of other sizes or offsets, manually
669 // add the offsets to the primary induction variable and cast, avoiding
670 // the need for the code evaluation methods to insert induction variables
671 // of different sizes.
672 for (IVUsers::iterator UI = IU->begin(), E = IU->end(); UI != E; ++UI) {
673 Value *Op = UI->getOperandValToReplace();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000674 Type *UseTy = Op->getType();
Andrew Trick1a54bb22011-07-12 00:08:50 +0000675 Instruction *User = UI->getUser();
676
677 // Compute the final addrec to expand into code.
678 const SCEV *AR = IU->getReplacementExpr(*UI);
679
680 // Evaluate the expression out of the loop, if possible.
681 if (!L->contains(UI->getUser())) {
682 const SCEV *ExitVal = SE->getSCEVAtScope(AR, L->getParentLoop());
683 if (SE->isLoopInvariant(ExitVal, L))
684 AR = ExitVal;
685 }
686
687 // FIXME: It is an extremely bad idea to indvar substitute anything more
688 // complex than affine induction variables. Doing so will put expensive
689 // polynomial evaluations inside of the loop, and the str reduction pass
690 // currently can only reduce affine polynomials. For now just disable
691 // indvar subst on anything more complex than an affine addrec, unless
692 // it can be expanded to a trivial value.
693 if (!isSafe(AR, L, SE))
694 continue;
695
696 // Determine the insertion point for this user. By default, insert
697 // immediately before the user. The SCEVExpander class will automatically
698 // hoist loop invariants out of the loop. For PHI nodes, there may be
699 // multiple uses, so compute the nearest common dominator for the
700 // incoming blocks.
Andrew Trick86c98142011-07-20 05:32:06 +0000701 Instruction *InsertPt = getInsertPointForUses(User, Op, DT);
Andrew Trick1a54bb22011-07-12 00:08:50 +0000702
703 // Now expand it into actual Instructions and patch it into place.
704 Value *NewVal = Rewriter.expandCodeFor(AR, UseTy, InsertPt);
705
706 DEBUG(dbgs() << "INDVARS: Rewrote IV '" << *AR << "' " << *Op << '\n'
707 << " into = " << *NewVal << "\n");
708
709 if (!isValidRewrite(Op, NewVal)) {
710 DeadInsts.push_back(NewVal);
711 continue;
712 }
713 // Inform ScalarEvolution that this value is changing. The change doesn't
714 // affect its value, but it does potentially affect which use lists the
715 // value will be on after the replacement, which affects ScalarEvolution's
716 // ability to walk use lists and drop dangling pointers when a value is
717 // deleted.
718 SE->forgetValue(User);
719
720 // Patch the new value into place.
721 if (Op->hasName())
722 NewVal->takeName(Op);
723 if (Instruction *NewValI = dyn_cast<Instruction>(NewVal))
724 NewValI->setDebugLoc(User->getDebugLoc());
725 User->replaceUsesOfWith(Op, NewVal);
726 UI->setOperandValToReplace(NewVal);
727
728 ++NumRemoved;
729 Changed = true;
730
731 // The old value may be dead now.
732 DeadInsts.push_back(Op);
733 }
734}
735
736//===----------------------------------------------------------------------===//
737// IV Widening - Extend the width of an IV to cover its widest uses.
738//===----------------------------------------------------------------------===//
739
Andrew Trickf85092c2011-05-20 18:25:42 +0000740namespace {
741 // Collect information about induction variables that are used by sign/zero
742 // extend operations. This information is recorded by CollectExtend and
743 // provides the input to WidenIV.
744 struct WideIVInfo {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000745 Type *WidestNativeType; // Widest integer type created [sz]ext
Andrew Trick4b4bb712011-08-10 03:46:27 +0000746 bool IsSigned; // Was an sext user seen before a zext?
Andrew Trickf85092c2011-05-20 18:25:42 +0000747
748 WideIVInfo() : WidestNativeType(0), IsSigned(false) {}
749 };
Andrew Trick4b4bb712011-08-10 03:46:27 +0000750
751 class WideIVVisitor : public IVVisitor {
752 ScalarEvolution *SE;
753 const TargetData *TD;
754
755 public:
756 WideIVInfo WI;
757
758 WideIVVisitor(ScalarEvolution *SCEV, const TargetData *TData) :
759 SE(SCEV), TD(TData) {}
760
761 // Implement the interface used by simplifyUsersOfIV.
762 virtual void visitCast(CastInst *Cast);
763 };
Andrew Trickf85092c2011-05-20 18:25:42 +0000764}
765
Andrew Trick4b4bb712011-08-10 03:46:27 +0000766/// visitCast - Update information about the induction variable that is
Andrew Trickf85092c2011-05-20 18:25:42 +0000767/// extended by this sign or zero extend operation. This is used to determine
768/// the final width of the IV before actually widening it.
Andrew Trick4b4bb712011-08-10 03:46:27 +0000769void WideIVVisitor::visitCast(CastInst *Cast) {
770 bool IsSigned = Cast->getOpcode() == Instruction::SExt;
771 if (!IsSigned && Cast->getOpcode() != Instruction::ZExt)
772 return;
773
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000774 Type *Ty = Cast->getType();
Andrew Trickf85092c2011-05-20 18:25:42 +0000775 uint64_t Width = SE->getTypeSizeInBits(Ty);
776 if (TD && !TD->isLegalInteger(Width))
777 return;
778
Andrew Trick2fabd462011-06-21 03:22:38 +0000779 if (!WI.WidestNativeType) {
780 WI.WidestNativeType = SE->getEffectiveSCEVType(Ty);
781 WI.IsSigned = IsSigned;
Andrew Trickf85092c2011-05-20 18:25:42 +0000782 return;
783 }
784
785 // We extend the IV to satisfy the sign of its first user, arbitrarily.
Andrew Trick2fabd462011-06-21 03:22:38 +0000786 if (WI.IsSigned != IsSigned)
Andrew Trickf85092c2011-05-20 18:25:42 +0000787 return;
788
Andrew Trick2fabd462011-06-21 03:22:38 +0000789 if (Width > SE->getTypeSizeInBits(WI.WidestNativeType))
790 WI.WidestNativeType = SE->getEffectiveSCEVType(Ty);
Andrew Trickf85092c2011-05-20 18:25:42 +0000791}
792
793namespace {
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000794
795/// NarrowIVDefUse - Record a link in the Narrow IV def-use chain along with the
796/// WideIV that computes the same value as the Narrow IV def. This avoids
797/// caching Use* pointers.
798struct NarrowIVDefUse {
799 Instruction *NarrowDef;
800 Instruction *NarrowUse;
801 Instruction *WideDef;
802
803 NarrowIVDefUse(): NarrowDef(0), NarrowUse(0), WideDef(0) {}
804
805 NarrowIVDefUse(Instruction *ND, Instruction *NU, Instruction *WD):
806 NarrowDef(ND), NarrowUse(NU), WideDef(WD) {}
807};
808
Andrew Trickf85092c2011-05-20 18:25:42 +0000809/// WidenIV - The goal of this transform is to remove sign and zero extends
810/// without creating any new induction variables. To do this, it creates a new
811/// phi of the wider type and redirects all users, either removing extends or
812/// inserting truncs whenever we stop propagating the type.
813///
814class WidenIV {
Andrew Trick2fabd462011-06-21 03:22:38 +0000815 // Parameters
Andrew Trickf85092c2011-05-20 18:25:42 +0000816 PHINode *OrigPhi;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000817 Type *WideType;
Andrew Trickf85092c2011-05-20 18:25:42 +0000818 bool IsSigned;
819
Andrew Trick2fabd462011-06-21 03:22:38 +0000820 // Context
821 LoopInfo *LI;
822 Loop *L;
Andrew Trickf85092c2011-05-20 18:25:42 +0000823 ScalarEvolution *SE;
Andrew Trick2fabd462011-06-21 03:22:38 +0000824 DominatorTree *DT;
Andrew Trickf85092c2011-05-20 18:25:42 +0000825
Andrew Trick2fabd462011-06-21 03:22:38 +0000826 // Result
Andrew Trickf85092c2011-05-20 18:25:42 +0000827 PHINode *WidePhi;
828 Instruction *WideInc;
829 const SCEV *WideIncExpr;
Andrew Trick2fabd462011-06-21 03:22:38 +0000830 SmallVectorImpl<WeakVH> &DeadInsts;
Andrew Trickf85092c2011-05-20 18:25:42 +0000831
Andrew Trick2fabd462011-06-21 03:22:38 +0000832 SmallPtrSet<Instruction*,16> Widened;
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000833 SmallVector<NarrowIVDefUse, 8> NarrowIVUsers;
Andrew Trickf85092c2011-05-20 18:25:42 +0000834
835public:
Andrew Trick2fabd462011-06-21 03:22:38 +0000836 WidenIV(PHINode *PN, const WideIVInfo &WI, LoopInfo *LInfo,
837 ScalarEvolution *SEv, DominatorTree *DTree,
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000838 SmallVectorImpl<WeakVH> &DI) :
Andrew Trickf85092c2011-05-20 18:25:42 +0000839 OrigPhi(PN),
Andrew Trick2fabd462011-06-21 03:22:38 +0000840 WideType(WI.WidestNativeType),
841 IsSigned(WI.IsSigned),
Andrew Trickf85092c2011-05-20 18:25:42 +0000842 LI(LInfo),
843 L(LI->getLoopFor(OrigPhi->getParent())),
844 SE(SEv),
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000845 DT(DTree),
Andrew Trickf85092c2011-05-20 18:25:42 +0000846 WidePhi(0),
847 WideInc(0),
Andrew Trick2fabd462011-06-21 03:22:38 +0000848 WideIncExpr(0),
849 DeadInsts(DI) {
Andrew Trickf85092c2011-05-20 18:25:42 +0000850 assert(L->getHeader() == OrigPhi->getParent() && "Phi must be an IV");
851 }
852
Andrew Trick2fabd462011-06-21 03:22:38 +0000853 PHINode *CreateWideIV(SCEVExpander &Rewriter);
Andrew Trickf85092c2011-05-20 18:25:42 +0000854
855protected:
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000856 Instruction *CloneIVUser(NarrowIVDefUse DU);
Andrew Trickf85092c2011-05-20 18:25:42 +0000857
Andrew Tricke0dc2fa2011-07-05 18:19:39 +0000858 const SCEVAddRecExpr *GetWideRecurrence(Instruction *NarrowUse);
859
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000860 Instruction *WidenIVUse(NarrowIVDefUse DU);
Andrew Trick4b029152011-07-02 02:34:25 +0000861
862 void pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef);
Andrew Trickf85092c2011-05-20 18:25:42 +0000863};
864} // anonymous namespace
865
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000866static Value *getExtend( Value *NarrowOper, Type *WideType,
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000867 bool IsSigned, IRBuilder<> &Builder) {
868 return IsSigned ? Builder.CreateSExt(NarrowOper, WideType) :
869 Builder.CreateZExt(NarrowOper, WideType);
Andrew Trickf85092c2011-05-20 18:25:42 +0000870}
871
872/// CloneIVUser - Instantiate a wide operation to replace a narrow
873/// operation. This only needs to handle operations that can evaluation to
874/// SCEVAddRec. It can safely return 0 for any operation we decide not to clone.
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000875Instruction *WidenIV::CloneIVUser(NarrowIVDefUse DU) {
876 unsigned Opcode = DU.NarrowUse->getOpcode();
Andrew Trickf85092c2011-05-20 18:25:42 +0000877 switch (Opcode) {
878 default:
879 return 0;
880 case Instruction::Add:
881 case Instruction::Mul:
882 case Instruction::UDiv:
883 case Instruction::Sub:
884 case Instruction::And:
885 case Instruction::Or:
886 case Instruction::Xor:
887 case Instruction::Shl:
888 case Instruction::LShr:
889 case Instruction::AShr:
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000890 DEBUG(dbgs() << "Cloning IVUser: " << *DU.NarrowUse << "\n");
Andrew Trickf85092c2011-05-20 18:25:42 +0000891
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000892 IRBuilder<> Builder(DU.NarrowUse);
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000893
894 // Replace NarrowDef operands with WideDef. Otherwise, we don't know
895 // anything about the narrow operand yet so must insert a [sz]ext. It is
896 // probably loop invariant and will be folded or hoisted. If it actually
897 // comes from a widened IV, it should be removed during a future call to
898 // WidenIVUse.
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000899 Value *LHS = (DU.NarrowUse->getOperand(0) == DU.NarrowDef) ? DU.WideDef :
900 getExtend(DU.NarrowUse->getOperand(0), WideType, IsSigned, Builder);
901 Value *RHS = (DU.NarrowUse->getOperand(1) == DU.NarrowDef) ? DU.WideDef :
902 getExtend(DU.NarrowUse->getOperand(1), WideType, IsSigned, Builder);
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000903
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000904 BinaryOperator *NarrowBO = cast<BinaryOperator>(DU.NarrowUse);
Andrew Trickf85092c2011-05-20 18:25:42 +0000905 BinaryOperator *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(),
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000906 LHS, RHS,
Andrew Trickf85092c2011-05-20 18:25:42 +0000907 NarrowBO->getName());
Andrew Trickf85092c2011-05-20 18:25:42 +0000908 Builder.Insert(WideBO);
Andrew Trick6e0ce242011-06-30 19:02:17 +0000909 if (const OverflowingBinaryOperator *OBO =
910 dyn_cast<OverflowingBinaryOperator>(NarrowBO)) {
911 if (OBO->hasNoUnsignedWrap()) WideBO->setHasNoUnsignedWrap();
912 if (OBO->hasNoSignedWrap()) WideBO->setHasNoSignedWrap();
913 }
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000914 return WideBO;
Andrew Trickf85092c2011-05-20 18:25:42 +0000915 }
916 llvm_unreachable(0);
917}
918
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000919/// HoistStep - Attempt to hoist an IV increment above a potential use.
920///
921/// To successfully hoist, two criteria must be met:
922/// - IncV operands dominate InsertPos and
923/// - InsertPos dominates IncV
924///
925/// Meeting the second condition means that we don't need to check all of IncV's
926/// existing uses (it's moving up in the domtree).
927///
928/// This does not yet recursively hoist the operands, although that would
929/// not be difficult.
930static bool HoistStep(Instruction *IncV, Instruction *InsertPos,
931 const DominatorTree *DT)
932{
933 if (DT->dominates(IncV, InsertPos))
934 return true;
935
936 if (!DT->dominates(InsertPos->getParent(), IncV->getParent()))
937 return false;
938
939 if (IncV->mayHaveSideEffects())
940 return false;
941
942 // Attempt to hoist IncV
943 for (User::op_iterator OI = IncV->op_begin(), OE = IncV->op_end();
944 OI != OE; ++OI) {
945 Instruction *OInst = dyn_cast<Instruction>(OI);
946 if (OInst && !DT->dominates(OInst, InsertPos))
947 return false;
948 }
949 IncV->moveBefore(InsertPos);
950 return true;
951}
952
Andrew Tricke0dc2fa2011-07-05 18:19:39 +0000953// GetWideRecurrence - Is this instruction potentially interesting from IVUsers'
954// perspective after widening it's type? In other words, can the extend be
955// safely hoisted out of the loop with SCEV reducing the value to a recurrence
956// on the same loop. If so, return the sign or zero extended
957// recurrence. Otherwise return NULL.
958const SCEVAddRecExpr *WidenIV::GetWideRecurrence(Instruction *NarrowUse) {
959 if (!SE->isSCEVable(NarrowUse->getType()))
960 return 0;
961
962 const SCEV *NarrowExpr = SE->getSCEV(NarrowUse);
963 if (SE->getTypeSizeInBits(NarrowExpr->getType())
964 >= SE->getTypeSizeInBits(WideType)) {
965 // NarrowUse implicitly widens its operand. e.g. a gep with a narrow
966 // index. So don't follow this use.
967 return 0;
968 }
969
970 const SCEV *WideExpr = IsSigned ?
971 SE->getSignExtendExpr(NarrowExpr, WideType) :
972 SE->getZeroExtendExpr(NarrowExpr, WideType);
973 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(WideExpr);
974 if (!AddRec || AddRec->getLoop() != L)
975 return 0;
976
977 return AddRec;
978}
979
Andrew Trickf85092c2011-05-20 18:25:42 +0000980/// WidenIVUse - Determine whether an individual user of the narrow IV can be
981/// widened. If so, return the wide clone of the user.
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000982Instruction *WidenIV::WidenIVUse(NarrowIVDefUse DU) {
Andrew Trickcc359d92011-06-29 23:03:57 +0000983
Andrew Trick4b029152011-07-02 02:34:25 +0000984 // Stop traversing the def-use chain at inner-loop phis or post-loop phis.
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000985 if (isa<PHINode>(DU.NarrowUse) &&
986 LI->getLoopFor(DU.NarrowUse->getParent()) != L)
Andrew Trickf85092c2011-05-20 18:25:42 +0000987 return 0;
988
Andrew Trickf85092c2011-05-20 18:25:42 +0000989 // Our raison d'etre! Eliminate sign and zero extension.
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000990 if (IsSigned ? isa<SExtInst>(DU.NarrowUse) : isa<ZExtInst>(DU.NarrowUse)) {
991 Value *NewDef = DU.WideDef;
992 if (DU.NarrowUse->getType() != WideType) {
993 unsigned CastWidth = SE->getTypeSizeInBits(DU.NarrowUse->getType());
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000994 unsigned IVWidth = SE->getTypeSizeInBits(WideType);
995 if (CastWidth < IVWidth) {
996 // The cast isn't as wide as the IV, so insert a Trunc.
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000997 IRBuilder<> Builder(DU.NarrowUse);
998 NewDef = Builder.CreateTrunc(DU.WideDef, DU.NarrowUse->getType());
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000999 }
1000 else {
1001 // A wider extend was hidden behind a narrower one. This may induce
1002 // another round of IV widening in which the intermediate IV becomes
1003 // dead. It should be very rare.
1004 DEBUG(dbgs() << "INDVARS: New IV " << *WidePhi
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001005 << " not wide enough to subsume " << *DU.NarrowUse << "\n");
1006 DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef);
1007 NewDef = DU.NarrowUse;
Andrew Trick03d3d3b2011-05-25 04:42:22 +00001008 }
1009 }
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001010 if (NewDef != DU.NarrowUse) {
1011 DEBUG(dbgs() << "INDVARS: eliminating " << *DU.NarrowUse
1012 << " replaced by " << *DU.WideDef << "\n");
Andrew Trick03d3d3b2011-05-25 04:42:22 +00001013 ++NumElimExt;
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001014 DU.NarrowUse->replaceAllUsesWith(NewDef);
1015 DeadInsts.push_back(DU.NarrowUse);
Andrew Trick03d3d3b2011-05-25 04:42:22 +00001016 }
Andrew Trick2fabd462011-06-21 03:22:38 +00001017 // Now that the extend is gone, we want to expose it's uses for potential
1018 // further simplification. We don't need to directly inform SimplifyIVUsers
1019 // of the new users, because their parent IV will be processed later as a
1020 // new loop phi. If we preserved IVUsers analysis, we would also want to
1021 // push the uses of WideDef here.
Andrew Trickf85092c2011-05-20 18:25:42 +00001022
1023 // No further widening is needed. The deceased [sz]ext had done it for us.
1024 return 0;
1025 }
Andrew Trick4b029152011-07-02 02:34:25 +00001026
1027 // Does this user itself evaluate to a recurrence after widening?
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001028 const SCEVAddRecExpr *WideAddRec = GetWideRecurrence(DU.NarrowUse);
Andrew Trickf85092c2011-05-20 18:25:42 +00001029 if (!WideAddRec) {
1030 // This user does not evaluate to a recurence after widening, so don't
1031 // follow it. Instead insert a Trunc to kill off the original use,
1032 // eventually isolating the original narrow IV so it can be removed.
Andrew Trick86c98142011-07-20 05:32:06 +00001033 IRBuilder<> Builder(getInsertPointForUses(DU.NarrowUse, DU.NarrowDef, DT));
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001034 Value *Trunc = Builder.CreateTrunc(DU.WideDef, DU.NarrowDef->getType());
1035 DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, Trunc);
Andrew Trickf85092c2011-05-20 18:25:42 +00001036 return 0;
1037 }
Andrew Trickfc933c02011-07-18 20:32:31 +00001038 // Assume block terminators cannot evaluate to a recurrence. We can't to
Andrew Trick4b029152011-07-02 02:34:25 +00001039 // insert a Trunc after a terminator if there happens to be a critical edge.
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001040 assert(DU.NarrowUse != DU.NarrowUse->getParent()->getTerminator() &&
Andrew Trick4b029152011-07-02 02:34:25 +00001041 "SCEV is not expected to evaluate a block terminator");
Andrew Trickcc359d92011-06-29 23:03:57 +00001042
Andrew Trickfcdc9a42011-05-26 00:46:11 +00001043 // Reuse the IV increment that SCEVExpander created as long as it dominates
1044 // NarrowUse.
Andrew Trickf85092c2011-05-20 18:25:42 +00001045 Instruction *WideUse = 0;
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001046 if (WideAddRec == WideIncExpr && HoistStep(WideInc, DU.NarrowUse, DT)) {
Andrew Trickf85092c2011-05-20 18:25:42 +00001047 WideUse = WideInc;
1048 }
1049 else {
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001050 WideUse = CloneIVUser(DU);
Andrew Trickf85092c2011-05-20 18:25:42 +00001051 if (!WideUse)
1052 return 0;
1053 }
Andrew Trick4b029152011-07-02 02:34:25 +00001054 // Evaluation of WideAddRec ensured that the narrow expression could be
1055 // extended outside the loop without overflow. This suggests that the wide use
Andrew Trickf85092c2011-05-20 18:25:42 +00001056 // evaluates to the same expression as the extended narrow use, but doesn't
1057 // absolutely guarantee it. Hence the following failsafe check. In rare cases
Andrew Trick2fabd462011-06-21 03:22:38 +00001058 // where it fails, we simply throw away the newly created wide use.
Andrew Trickf85092c2011-05-20 18:25:42 +00001059 if (WideAddRec != SE->getSCEV(WideUse)) {
1060 DEBUG(dbgs() << "Wide use expression mismatch: " << *WideUse
1061 << ": " << *SE->getSCEV(WideUse) << " != " << *WideAddRec << "\n");
1062 DeadInsts.push_back(WideUse);
1063 return 0;
1064 }
1065
1066 // Returning WideUse pushes it on the worklist.
1067 return WideUse;
1068}
1069
Andrew Trick4b029152011-07-02 02:34:25 +00001070/// pushNarrowIVUsers - Add eligible users of NarrowDef to NarrowIVUsers.
1071///
1072void WidenIV::pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef) {
1073 for (Value::use_iterator UI = NarrowDef->use_begin(),
1074 UE = NarrowDef->use_end(); UI != UE; ++UI) {
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001075 Instruction *NarrowUse = cast<Instruction>(*UI);
Andrew Trick4b029152011-07-02 02:34:25 +00001076
1077 // Handle data flow merges and bizarre phi cycles.
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001078 if (!Widened.insert(NarrowUse))
Andrew Trick4b029152011-07-02 02:34:25 +00001079 continue;
1080
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001081 NarrowIVUsers.push_back(NarrowIVDefUse(NarrowDef, NarrowUse, WideDef));
Andrew Trick4b029152011-07-02 02:34:25 +00001082 }
1083}
1084
Andrew Trickf85092c2011-05-20 18:25:42 +00001085/// CreateWideIV - Process a single induction variable. First use the
1086/// SCEVExpander to create a wide induction variable that evaluates to the same
1087/// recurrence as the original narrow IV. Then use a worklist to forward
Andrew Trick2fabd462011-06-21 03:22:38 +00001088/// traverse the narrow IV's def-use chain. After WidenIVUse has processed all
Andrew Trickf85092c2011-05-20 18:25:42 +00001089/// interesting IV users, the narrow IV will be isolated for removal by
1090/// DeleteDeadPHIs.
1091///
1092/// It would be simpler to delete uses as they are processed, but we must avoid
1093/// invalidating SCEV expressions.
1094///
Andrew Trick2fabd462011-06-21 03:22:38 +00001095PHINode *WidenIV::CreateWideIV(SCEVExpander &Rewriter) {
Andrew Trickf85092c2011-05-20 18:25:42 +00001096 // Is this phi an induction variable?
1097 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(OrigPhi));
1098 if (!AddRec)
Andrew Trick2fabd462011-06-21 03:22:38 +00001099 return NULL;
Andrew Trickf85092c2011-05-20 18:25:42 +00001100
1101 // Widen the induction variable expression.
1102 const SCEV *WideIVExpr = IsSigned ?
1103 SE->getSignExtendExpr(AddRec, WideType) :
1104 SE->getZeroExtendExpr(AddRec, WideType);
1105
1106 assert(SE->getEffectiveSCEVType(WideIVExpr->getType()) == WideType &&
1107 "Expect the new IV expression to preserve its type");
1108
1109 // Can the IV be extended outside the loop without overflow?
1110 AddRec = dyn_cast<SCEVAddRecExpr>(WideIVExpr);
1111 if (!AddRec || AddRec->getLoop() != L)
Andrew Trick2fabd462011-06-21 03:22:38 +00001112 return NULL;
Andrew Trickf85092c2011-05-20 18:25:42 +00001113
Andrew Trick2fabd462011-06-21 03:22:38 +00001114 // An AddRec must have loop-invariant operands. Since this AddRec is
Andrew Trickf85092c2011-05-20 18:25:42 +00001115 // materialized by a loop header phi, the expression cannot have any post-loop
1116 // operands, so they must dominate the loop header.
1117 assert(SE->properlyDominates(AddRec->getStart(), L->getHeader()) &&
1118 SE->properlyDominates(AddRec->getStepRecurrence(*SE), L->getHeader())
1119 && "Loop header phi recurrence inputs do not dominate the loop");
1120
1121 // The rewriter provides a value for the desired IV expression. This may
1122 // either find an existing phi or materialize a new one. Either way, we
1123 // expect a well-formed cyclic phi-with-increments. i.e. any operand not part
1124 // of the phi-SCC dominates the loop entry.
1125 Instruction *InsertPt = L->getHeader()->begin();
1126 WidePhi = cast<PHINode>(Rewriter.expandCodeFor(AddRec, WideType, InsertPt));
1127
1128 // Remembering the WideIV increment generated by SCEVExpander allows
1129 // WidenIVUse to reuse it when widening the narrow IV's increment. We don't
1130 // employ a general reuse mechanism because the call above is the only call to
1131 // SCEVExpander. Henceforth, we produce 1-to-1 narrow to wide uses.
Andrew Trickfcdc9a42011-05-26 00:46:11 +00001132 if (BasicBlock *LatchBlock = L->getLoopLatch()) {
1133 WideInc =
1134 cast<Instruction>(WidePhi->getIncomingValueForBlock(LatchBlock));
1135 WideIncExpr = SE->getSCEV(WideInc);
1136 }
Andrew Trickf85092c2011-05-20 18:25:42 +00001137
1138 DEBUG(dbgs() << "Wide IV: " << *WidePhi << "\n");
1139 ++NumWidened;
1140
1141 // Traverse the def-use chain using a worklist starting at the original IV.
Andrew Trick4b029152011-07-02 02:34:25 +00001142 assert(Widened.empty() && NarrowIVUsers.empty() && "expect initial state" );
Andrew Trickf85092c2011-05-20 18:25:42 +00001143
Andrew Trick4b029152011-07-02 02:34:25 +00001144 Widened.insert(OrigPhi);
1145 pushNarrowIVUsers(OrigPhi, WidePhi);
1146
Andrew Trickf85092c2011-05-20 18:25:42 +00001147 while (!NarrowIVUsers.empty()) {
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001148 NarrowIVDefUse DU = NarrowIVUsers.pop_back_val();
Andrew Trickf85092c2011-05-20 18:25:42 +00001149
Andrew Trickfcdc9a42011-05-26 00:46:11 +00001150 // Process a def-use edge. This may replace the use, so don't hold a
1151 // use_iterator across it.
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001152 Instruction *WideUse = WidenIVUse(DU);
Andrew Trickf85092c2011-05-20 18:25:42 +00001153
Andrew Trickfcdc9a42011-05-26 00:46:11 +00001154 // Follow all def-use edges from the previous narrow use.
Andrew Trick4b029152011-07-02 02:34:25 +00001155 if (WideUse)
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001156 pushNarrowIVUsers(DU.NarrowUse, WideUse);
Andrew Trick4b029152011-07-02 02:34:25 +00001157
Andrew Trickfcdc9a42011-05-26 00:46:11 +00001158 // WidenIVUse may have removed the def-use edge.
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001159 if (DU.NarrowDef->use_empty())
1160 DeadInsts.push_back(DU.NarrowDef);
Andrew Trickf85092c2011-05-20 18:25:42 +00001161 }
Andrew Trick2fabd462011-06-21 03:22:38 +00001162 return WidePhi;
Andrew Trickf85092c2011-05-20 18:25:42 +00001163}
1164
Andrew Trick1a54bb22011-07-12 00:08:50 +00001165//===----------------------------------------------------------------------===//
1166// Simplification of IV users based on SCEV evaluation.
1167//===----------------------------------------------------------------------===//
1168
Andrew Trickaeee4612011-05-12 00:04:28 +00001169
Andrew Trick4b4bb712011-08-10 03:46:27 +00001170/// SimplifyAndExtend - Iteratively perform simplification on a worklist of IV
1171/// users. Each successive simplification may push more users which may
Andrew Trick2fabd462011-06-21 03:22:38 +00001172/// themselves be candidates for simplification.
1173///
Andrew Trick4b4bb712011-08-10 03:46:27 +00001174/// Sign/Zero extend elimination is interleaved with IV simplification.
Andrew Trick2fabd462011-06-21 03:22:38 +00001175///
Andrew Trick4b4bb712011-08-10 03:46:27 +00001176void IndVarSimplify::SimplifyAndExtend(Loop *L,
1177 SCEVExpander &Rewriter,
1178 LPPassManager &LPM) {
Andrew Trick15832f62011-06-28 02:49:20 +00001179 std::map<PHINode *, WideIVInfo> WideIVMap;
1180
Andrew Trick2fabd462011-06-21 03:22:38 +00001181 SmallVector<PHINode*, 8> LoopPhis;
1182 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
1183 LoopPhis.push_back(cast<PHINode>(I));
1184 }
Andrew Trick15832f62011-06-28 02:49:20 +00001185 // Each round of simplification iterates through the SimplifyIVUsers worklist
1186 // for all current phis, then determines whether any IVs can be
1187 // widened. Widening adds new phis to LoopPhis, inducing another round of
1188 // simplification on the wide IVs.
Andrew Trick2fabd462011-06-21 03:22:38 +00001189 while (!LoopPhis.empty()) {
Andrew Trick15832f62011-06-28 02:49:20 +00001190 // Evaluate as many IV expressions as possible before widening any IVs. This
Andrew Trick99a92f62011-06-28 16:45:04 +00001191 // forces SCEV to set no-wrap flags before evaluating sign/zero
Andrew Trick15832f62011-06-28 02:49:20 +00001192 // extension. The first time SCEV attempts to normalize sign/zero extension,
1193 // the result becomes final. So for the most predictable results, we delay
1194 // evaluation of sign/zero extend evaluation until needed, and avoid running
Andrew Trick4b4bb712011-08-10 03:46:27 +00001195 // other SCEV based analysis prior to SimplifyAndExtend.
Andrew Trick15832f62011-06-28 02:49:20 +00001196 do {
1197 PHINode *CurrIV = LoopPhis.pop_back_val();
Andrew Trick2fabd462011-06-21 03:22:38 +00001198
Andrew Trick15832f62011-06-28 02:49:20 +00001199 // Information about sign/zero extensions of CurrIV.
Andrew Trick4b4bb712011-08-10 03:46:27 +00001200 WideIVVisitor WIV(SE, TD);
Andrew Trick2fabd462011-06-21 03:22:38 +00001201
Andrew Trickbddb7f82011-08-10 04:22:26 +00001202 Changed |= simplifyUsersOfIV(CurrIV, SE, &LPM, DeadInsts, &WIV);
Andrew Trick2fabd462011-06-21 03:22:38 +00001203
Andrew Trick4b4bb712011-08-10 03:46:27 +00001204 if (WIV.WI.WidestNativeType) {
1205 WideIVMap[CurrIV] = WIV.WI;
Andrew Trick2fabd462011-06-21 03:22:38 +00001206 }
Andrew Trick15832f62011-06-28 02:49:20 +00001207 } while(!LoopPhis.empty());
1208
1209 for (std::map<PHINode *, WideIVInfo>::const_iterator I = WideIVMap.begin(),
1210 E = WideIVMap.end(); I != E; ++I) {
1211 WidenIV Widener(I->first, I->second, LI, SE, DT, DeadInsts);
Andrew Trick2fabd462011-06-21 03:22:38 +00001212 if (PHINode *WidePhi = Widener.CreateWideIV(Rewriter)) {
1213 Changed = true;
1214 LoopPhis.push_back(WidePhi);
1215 }
1216 }
Andrew Trick15832f62011-06-28 02:49:20 +00001217 WideIVMap.clear();
Andrew Trick2fabd462011-06-21 03:22:38 +00001218 }
1219}
1220
Andrew Trick037d1c02011-07-06 20:50:43 +00001221/// SimplifyCongruentIVs - Check for congruent phis in this loop header and
Andrew Trick4b4bb712011-08-10 03:46:27 +00001222/// replace them with their chosen representative.
Andrew Trick037d1c02011-07-06 20:50:43 +00001223///
1224void IndVarSimplify::SimplifyCongruentIVs(Loop *L) {
Andrew Trick6f684b02011-07-16 01:06:48 +00001225 DenseMap<const SCEV *, PHINode *> ExprToIVMap;
Andrew Trick037d1c02011-07-06 20:50:43 +00001226 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
1227 PHINode *Phi = cast<PHINode>(I);
Andrew Trick1a54bb22011-07-12 00:08:50 +00001228 if (!SE->isSCEVable(Phi->getType()))
1229 continue;
1230
Andrew Trick037d1c02011-07-06 20:50:43 +00001231 const SCEV *S = SE->getSCEV(Phi);
Chris Lattnerc30a38f2011-07-21 06:21:31 +00001232 std::pair<DenseMap<const SCEV *, PHINode *>::const_iterator, bool> Tmp =
1233 ExprToIVMap.insert(std::make_pair(S, Phi));
1234 if (Tmp.second)
Andrew Trick037d1c02011-07-06 20:50:43 +00001235 continue;
Chris Lattnerc30a38f2011-07-21 06:21:31 +00001236 PHINode *OrigPhi = Tmp.first->second;
Andrew Trickf22d9572011-07-20 02:08:58 +00001237
1238 // If one phi derives from the other via GEPs, types may differ.
1239 if (OrigPhi->getType() != Phi->getType())
1240 continue;
1241
Andrew Trick037d1c02011-07-06 20:50:43 +00001242 // Replacing the congruent phi is sufficient because acyclic redundancy
1243 // elimination, CSE/GVN, should handle the rest. However, once SCEV proves
1244 // that a phi is congruent, it's almost certain to be the head of an IV
1245 // user cycle that is isomorphic with the original phi. So it's worth
1246 // eagerly cleaning up the common case of a single IV increment.
1247 if (BasicBlock *LatchBlock = L->getLoopLatch()) {
1248 Instruction *OrigInc =
1249 cast<Instruction>(OrigPhi->getIncomingValueForBlock(LatchBlock));
1250 Instruction *IsomorphicInc =
1251 cast<Instruction>(Phi->getIncomingValueForBlock(LatchBlock));
1252 if (OrigInc != IsomorphicInc &&
Andrew Trickf22d9572011-07-20 02:08:58 +00001253 OrigInc->getType() == IsomorphicInc->getType() &&
Andrew Trick037d1c02011-07-06 20:50:43 +00001254 SE->getSCEV(OrigInc) == SE->getSCEV(IsomorphicInc) &&
1255 HoistStep(OrigInc, IsomorphicInc, DT)) {
1256 DEBUG(dbgs() << "INDVARS: Eliminated congruent iv.inc: "
1257 << *IsomorphicInc << '\n');
1258 IsomorphicInc->replaceAllUsesWith(OrigInc);
1259 DeadInsts.push_back(IsomorphicInc);
1260 }
1261 }
1262 DEBUG(dbgs() << "INDVARS: Eliminated congruent iv: " << *Phi << '\n');
1263 ++NumElimIV;
1264 Phi->replaceAllUsesWith(OrigPhi);
1265 DeadInsts.push_back(Phi);
1266 }
1267}
1268
Andrew Trick1a54bb22011-07-12 00:08:50 +00001269//===----------------------------------------------------------------------===//
1270// LinearFunctionTestReplace and its kin. Rewrite the loop exit condition.
1271//===----------------------------------------------------------------------===//
1272
Andrew Trick5241b792011-07-18 18:21:35 +00001273// Check for expressions that ScalarEvolution generates to compute
1274// BackedgeTakenInfo. If these expressions have not been reduced, then expanding
1275// them may incur additional cost (albeit in the loop preheader).
1276static bool isHighCostExpansion(const SCEV *S, BranchInst *BI,
1277 ScalarEvolution *SE) {
1278 // If the backedge-taken count is a UDiv, it's very likely a UDiv that
1279 // ScalarEvolution's HowFarToZero or HowManyLessThans produced to compute a
1280 // precise expression, rather than a UDiv from the user's code. If we can't
1281 // find a UDiv in the code with some simple searching, assume the former and
1282 // forego rewriting the loop.
1283 if (isa<SCEVUDivExpr>(S)) {
1284 ICmpInst *OrigCond = dyn_cast<ICmpInst>(BI->getCondition());
1285 if (!OrigCond) return true;
1286 const SCEV *R = SE->getSCEV(OrigCond->getOperand(1));
1287 R = SE->getMinusSCEV(R, SE->getConstant(R->getType(), 1));
1288 if (R != S) {
1289 const SCEV *L = SE->getSCEV(OrigCond->getOperand(0));
1290 L = SE->getMinusSCEV(L, SE->getConstant(L->getType(), 1));
1291 if (L != S)
1292 return true;
1293 }
1294 }
1295
Andrew Trickfc933c02011-07-18 20:32:31 +00001296 if (!DisableIVRewrite || ForceLFTR)
Andrew Trick5241b792011-07-18 18:21:35 +00001297 return false;
1298
1299 // Recurse past add expressions, which commonly occur in the
1300 // BackedgeTakenCount. They may already exist in program code, and if not,
1301 // they are not too expensive rematerialize.
1302 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
1303 for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
1304 I != E; ++I) {
1305 if (isHighCostExpansion(*I, BI, SE))
1306 return true;
1307 }
1308 return false;
1309 }
1310
1311 // HowManyLessThans uses a Max expression whenever the loop is not guarded by
1312 // the exit condition.
1313 if (isa<SCEVSMaxExpr>(S) || isa<SCEVUMaxExpr>(S))
1314 return true;
1315
1316 // If we haven't recognized an expensive SCEV patter, assume its an expression
1317 // produced by program code.
1318 return false;
1319}
1320
Andrew Trick1a54bb22011-07-12 00:08:50 +00001321/// canExpandBackedgeTakenCount - Return true if this loop's backedge taken
1322/// count expression can be safely and cheaply expanded into an instruction
1323/// sequence that can be used by LinearFunctionTestReplace.
1324static bool canExpandBackedgeTakenCount(Loop *L, ScalarEvolution *SE) {
1325 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
1326 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount) ||
1327 BackedgeTakenCount->isZero())
1328 return false;
1329
1330 if (!L->getExitingBlock())
1331 return false;
1332
1333 // Can't rewrite non-branch yet.
1334 BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator());
1335 if (!BI)
1336 return false;
1337
Andrew Trick5241b792011-07-18 18:21:35 +00001338 if (isHighCostExpansion(BackedgeTakenCount, BI, SE))
1339 return false;
1340
Andrew Trick1a54bb22011-07-12 00:08:50 +00001341 return true;
1342}
1343
1344/// getBackedgeIVType - Get the widest type used by the loop test after peeking
1345/// through Truncs.
1346///
Andrew Trickfc933c02011-07-18 20:32:31 +00001347/// TODO: Unnecessary when ForceLFTR is removed.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001348static Type *getBackedgeIVType(Loop *L) {
Andrew Trick1a54bb22011-07-12 00:08:50 +00001349 if (!L->getExitingBlock())
1350 return 0;
1351
1352 // Can't rewrite non-branch yet.
1353 BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator());
1354 if (!BI)
1355 return 0;
1356
1357 ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition());
1358 if (!Cond)
1359 return 0;
1360
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001361 Type *Ty = 0;
Andrew Trick1a54bb22011-07-12 00:08:50 +00001362 for(User::op_iterator OI = Cond->op_begin(), OE = Cond->op_end();
1363 OI != OE; ++OI) {
1364 assert((!Ty || Ty == (*OI)->getType()) && "bad icmp operand types");
1365 TruncInst *Trunc = dyn_cast<TruncInst>(*OI);
1366 if (!Trunc)
1367 continue;
1368
1369 return Trunc->getSrcTy();
1370 }
1371 return Ty;
1372}
1373
Andrew Trickfc933c02011-07-18 20:32:31 +00001374/// isLoopInvariant - Perform a quick domtree based check for loop invariance
1375/// assuming that V is used within the loop. LoopInfo::isLoopInvariant() seems
1376/// gratuitous for this purpose.
1377static bool isLoopInvariant(Value *V, Loop *L, DominatorTree *DT) {
1378 Instruction *Inst = dyn_cast<Instruction>(V);
1379 if (!Inst)
1380 return true;
1381
1382 return DT->properlyDominates(Inst->getParent(), L->getHeader());
1383}
1384
1385/// getLoopPhiForCounter - Return the loop header phi IFF IncV adds a loop
1386/// invariant value to the phi.
1387static PHINode *getLoopPhiForCounter(Value *IncV, Loop *L, DominatorTree *DT) {
1388 Instruction *IncI = dyn_cast<Instruction>(IncV);
1389 if (!IncI)
1390 return 0;
1391
1392 switch (IncI->getOpcode()) {
1393 case Instruction::Add:
1394 case Instruction::Sub:
1395 break;
1396 case Instruction::GetElementPtr:
1397 // An IV counter must preserve its type.
1398 if (IncI->getNumOperands() == 2)
1399 break;
1400 default:
1401 return 0;
1402 }
1403
1404 PHINode *Phi = dyn_cast<PHINode>(IncI->getOperand(0));
1405 if (Phi && Phi->getParent() == L->getHeader()) {
1406 if (isLoopInvariant(IncI->getOperand(1), L, DT))
1407 return Phi;
1408 return 0;
1409 }
1410 if (IncI->getOpcode() == Instruction::GetElementPtr)
1411 return 0;
1412
1413 // Allow add/sub to be commuted.
1414 Phi = dyn_cast<PHINode>(IncI->getOperand(1));
1415 if (Phi && Phi->getParent() == L->getHeader()) {
1416 if (isLoopInvariant(IncI->getOperand(0), L, DT))
1417 return Phi;
1418 }
1419 return 0;
1420}
1421
1422/// needsLFTR - LinearFunctionTestReplace policy. Return true unless we can show
1423/// that the current exit test is already sufficiently canonical.
1424static bool needsLFTR(Loop *L, DominatorTree *DT) {
1425 assert(L->getExitingBlock() && "expected loop exit");
1426
1427 BasicBlock *LatchBlock = L->getLoopLatch();
1428 // Don't bother with LFTR if the loop is not properly simplified.
1429 if (!LatchBlock)
1430 return false;
1431
1432 BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator());
1433 assert(BI && "expected exit branch");
1434
1435 // Do LFTR to simplify the exit condition to an ICMP.
1436 ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition());
1437 if (!Cond)
1438 return true;
1439
1440 // Do LFTR to simplify the exit ICMP to EQ/NE
1441 ICmpInst::Predicate Pred = Cond->getPredicate();
1442 if (Pred != ICmpInst::ICMP_NE && Pred != ICmpInst::ICMP_EQ)
1443 return true;
1444
1445 // Look for a loop invariant RHS
1446 Value *LHS = Cond->getOperand(0);
1447 Value *RHS = Cond->getOperand(1);
1448 if (!isLoopInvariant(RHS, L, DT)) {
1449 if (!isLoopInvariant(LHS, L, DT))
1450 return true;
1451 std::swap(LHS, RHS);
1452 }
1453 // Look for a simple IV counter LHS
1454 PHINode *Phi = dyn_cast<PHINode>(LHS);
1455 if (!Phi)
1456 Phi = getLoopPhiForCounter(LHS, L, DT);
1457
1458 if (!Phi)
1459 return true;
1460
1461 // Do LFTR if the exit condition's IV is *not* a simple counter.
1462 Value *IncV = Phi->getIncomingValueForBlock(L->getLoopLatch());
1463 return Phi != getLoopPhiForCounter(IncV, L, DT);
1464}
1465
1466/// AlmostDeadIV - Return true if this IV has any uses other than the (soon to
1467/// be rewritten) loop exit test.
1468static bool AlmostDeadIV(PHINode *Phi, BasicBlock *LatchBlock, Value *Cond) {
1469 int LatchIdx = Phi->getBasicBlockIndex(LatchBlock);
1470 Value *IncV = Phi->getIncomingValue(LatchIdx);
1471
1472 for (Value::use_iterator UI = Phi->use_begin(), UE = Phi->use_end();
1473 UI != UE; ++UI) {
1474 if (*UI != Cond && *UI != IncV) return false;
1475 }
1476
1477 for (Value::use_iterator UI = IncV->use_begin(), UE = IncV->use_end();
1478 UI != UE; ++UI) {
1479 if (*UI != Cond && *UI != Phi) return false;
1480 }
1481 return true;
1482}
1483
1484/// FindLoopCounter - Find an affine IV in canonical form.
1485///
1486/// FIXME: Accept -1 stride and set IVLimit = IVInit - BECount
1487///
1488/// FIXME: Accept non-unit stride as long as SCEV can reduce BECount * Stride.
1489/// This is difficult in general for SCEV because of potential overflow. But we
1490/// could at least handle constant BECounts.
1491static PHINode *
1492FindLoopCounter(Loop *L, const SCEV *BECount,
1493 ScalarEvolution *SE, DominatorTree *DT, const TargetData *TD) {
1494 // I'm not sure how BECount could be a pointer type, but we definitely don't
1495 // want to LFTR that.
1496 if (BECount->getType()->isPointerTy())
1497 return 0;
1498
1499 uint64_t BCWidth = SE->getTypeSizeInBits(BECount->getType());
1500
1501 Value *Cond =
1502 cast<BranchInst>(L->getExitingBlock()->getTerminator())->getCondition();
1503
1504 // Loop over all of the PHI nodes, looking for a simple counter.
1505 PHINode *BestPhi = 0;
1506 const SCEV *BestInit = 0;
1507 BasicBlock *LatchBlock = L->getLoopLatch();
1508 assert(LatchBlock && "needsLFTR should guarantee a loop latch");
1509
1510 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
1511 PHINode *Phi = cast<PHINode>(I);
1512 if (!SE->isSCEVable(Phi->getType()))
1513 continue;
1514
1515 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Phi));
1516 if (!AR || AR->getLoop() != L || !AR->isAffine())
1517 continue;
1518
1519 // AR may be a pointer type, while BECount is an integer type.
1520 // AR may be wider than BECount. With eq/ne tests overflow is immaterial.
1521 // AR may not be a narrower type, or we may never exit.
1522 uint64_t PhiWidth = SE->getTypeSizeInBits(AR->getType());
1523 if (PhiWidth < BCWidth || (TD && !TD->isLegalInteger(PhiWidth)))
1524 continue;
1525
1526 const SCEV *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*SE));
1527 if (!Step || !Step->isOne())
1528 continue;
1529
1530 int LatchIdx = Phi->getBasicBlockIndex(LatchBlock);
1531 Value *IncV = Phi->getIncomingValue(LatchIdx);
1532 if (getLoopPhiForCounter(IncV, L, DT) != Phi)
1533 continue;
1534
1535 const SCEV *Init = AR->getStart();
1536
1537 if (BestPhi && !AlmostDeadIV(BestPhi, LatchBlock, Cond)) {
1538 // Don't force a live loop counter if another IV can be used.
1539 if (AlmostDeadIV(Phi, LatchBlock, Cond))
1540 continue;
1541
1542 // Prefer to count-from-zero. This is a more "canonical" counter form. It
1543 // also prefers integer to pointer IVs.
1544 if (BestInit->isZero() != Init->isZero()) {
1545 if (BestInit->isZero())
1546 continue;
1547 }
1548 // If two IVs both count from zero or both count from nonzero then the
1549 // narrower is likely a dead phi that has been widened. Use the wider phi
1550 // to allow the other to be eliminated.
1551 if (PhiWidth <= SE->getTypeSizeInBits(BestPhi->getType()))
1552 continue;
1553 }
1554 BestPhi = Phi;
1555 BestInit = Init;
1556 }
1557 return BestPhi;
1558}
1559
Andrew Trick1a54bb22011-07-12 00:08:50 +00001560/// LinearFunctionTestReplace - This method rewrites the exit condition of the
1561/// loop to be a canonical != comparison against the incremented loop induction
1562/// variable. This pass is able to rewrite the exit tests of any loop where the
1563/// SCEV analysis can determine a loop-invariant trip count of the loop, which
1564/// is actually a much broader range than just linear tests.
Andrew Trickfc933c02011-07-18 20:32:31 +00001565Value *IndVarSimplify::
Andrew Trick1a54bb22011-07-12 00:08:50 +00001566LinearFunctionTestReplace(Loop *L,
1567 const SCEV *BackedgeTakenCount,
1568 PHINode *IndVar,
1569 SCEVExpander &Rewriter) {
1570 assert(canExpandBackedgeTakenCount(L, SE) && "precondition");
1571 BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator());
1572
Andrew Trickfc933c02011-07-18 20:32:31 +00001573 // In DisableIVRewrite mode, IndVar is not necessarily a canonical IV. In this
1574 // mode, LFTR can ignore IV overflow and truncate to the width of
1575 // BECount. This avoids materializing the add(zext(add)) expression.
1576 Type *CntTy = DisableIVRewrite ?
1577 BackedgeTakenCount->getType() : IndVar->getType();
1578
1579 const SCEV *IVLimit = BackedgeTakenCount;
1580
Andrew Trick1a54bb22011-07-12 00:08:50 +00001581 // If the exiting block is not the same as the backedge block, we must compare
1582 // against the preincremented value, otherwise we prefer to compare against
1583 // the post-incremented value.
1584 Value *CmpIndVar;
Andrew Trick1a54bb22011-07-12 00:08:50 +00001585 if (L->getExitingBlock() == L->getLoopLatch()) {
1586 // Add one to the "backedge-taken" count to get the trip count.
1587 // If this addition may overflow, we have to be more pessimistic and
1588 // cast the induction variable before doing the add.
Andrew Trick1a54bb22011-07-12 00:08:50 +00001589 const SCEV *N =
Andrew Trickfc933c02011-07-18 20:32:31 +00001590 SE->getAddExpr(IVLimit, SE->getConstant(IVLimit->getType(), 1));
1591 if (CntTy == IVLimit->getType())
1592 IVLimit = N;
1593 else {
1594 const SCEV *Zero = SE->getConstant(IVLimit->getType(), 0);
1595 if ((isa<SCEVConstant>(N) && !N->isZero()) ||
1596 SE->isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) {
1597 // No overflow. Cast the sum.
1598 IVLimit = SE->getTruncateOrZeroExtend(N, CntTy);
1599 } else {
1600 // Potential overflow. Cast before doing the add.
1601 IVLimit = SE->getTruncateOrZeroExtend(IVLimit, CntTy);
1602 IVLimit = SE->getAddExpr(IVLimit, SE->getConstant(CntTy, 1));
1603 }
Andrew Trick1a54bb22011-07-12 00:08:50 +00001604 }
Andrew Trick1a54bb22011-07-12 00:08:50 +00001605 // The BackedgeTaken expression contains the number of times that the
1606 // backedge branches to the loop header. This is one less than the
1607 // number of times the loop executes, so use the incremented indvar.
1608 CmpIndVar = IndVar->getIncomingValueForBlock(L->getExitingBlock());
1609 } else {
1610 // We have to use the preincremented value...
Andrew Trickfc933c02011-07-18 20:32:31 +00001611 IVLimit = SE->getTruncateOrZeroExtend(IVLimit, CntTy);
Andrew Trick1a54bb22011-07-12 00:08:50 +00001612 CmpIndVar = IndVar;
1613 }
1614
Andrew Trickfc933c02011-07-18 20:32:31 +00001615 // For unit stride, IVLimit = Start + BECount with 2's complement overflow.
1616 // So for, non-zero start compute the IVLimit here.
1617 bool isPtrIV = false;
1618 Type *CmpTy = CntTy;
1619 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(IndVar));
1620 assert(AR && AR->getLoop() == L && AR->isAffine() && "bad loop counter");
1621 if (!AR->getStart()->isZero()) {
1622 assert(AR->getStepRecurrence(*SE)->isOne() && "only handles unit stride");
1623 const SCEV *IVInit = AR->getStart();
1624
1625 // For pointer types, sign extend BECount in order to materialize a GEP.
1626 // Note that for DisableIVRewrite, we never run SCEVExpander on a
1627 // pointer type, because we must preserve the existing GEPs. Instead we
1628 // directly generate a GEP later.
1629 if (IVInit->getType()->isPointerTy()) {
1630 isPtrIV = true;
1631 CmpTy = SE->getEffectiveSCEVType(IVInit->getType());
1632 IVLimit = SE->getTruncateOrSignExtend(IVLimit, CmpTy);
1633 }
1634 // For integer types, truncate the IV before computing IVInit + BECount.
1635 else {
1636 if (SE->getTypeSizeInBits(IVInit->getType())
1637 > SE->getTypeSizeInBits(CmpTy))
1638 IVInit = SE->getTruncateExpr(IVInit, CmpTy);
1639
1640 IVLimit = SE->getAddExpr(IVInit, IVLimit);
1641 }
1642 }
Andrew Trick1a54bb22011-07-12 00:08:50 +00001643 // Expand the code for the iteration count.
Andrew Trickfc933c02011-07-18 20:32:31 +00001644 IRBuilder<> Builder(BI);
1645
1646 assert(SE->isLoopInvariant(IVLimit, L) &&
Andrew Trick1a54bb22011-07-12 00:08:50 +00001647 "Computed iteration count is not loop invariant!");
Andrew Trickfc933c02011-07-18 20:32:31 +00001648 Value *ExitCnt = Rewriter.expandCodeFor(IVLimit, CmpTy, BI);
1649
1650 // Create a gep for IVInit + IVLimit from on an existing pointer base.
1651 assert(isPtrIV == IndVar->getType()->isPointerTy() &&
1652 "IndVar type must match IVInit type");
1653 if (isPtrIV) {
1654 Value *IVStart = IndVar->getIncomingValueForBlock(L->getLoopPreheader());
1655 assert(AR->getStart() == SE->getSCEV(IVStart) && "bad loop counter");
Andrew Trick41e0d4e2011-07-18 21:15:03 +00001656 assert(SE->getSizeOfExpr(
1657 cast<PointerType>(IVStart->getType())->getElementType())->isOne()
1658 && "unit stride pointer IV must be i8*");
Andrew Trickfc933c02011-07-18 20:32:31 +00001659
1660 Builder.SetInsertPoint(L->getLoopPreheader()->getTerminator());
1661 ExitCnt = Builder.CreateGEP(IVStart, ExitCnt, "lftr.limit");
1662 Builder.SetInsertPoint(BI);
1663 }
Andrew Trick1a54bb22011-07-12 00:08:50 +00001664
1665 // Insert a new icmp_ne or icmp_eq instruction before the branch.
Andrew Trickfc933c02011-07-18 20:32:31 +00001666 ICmpInst::Predicate P;
Andrew Trick1a54bb22011-07-12 00:08:50 +00001667 if (L->contains(BI->getSuccessor(0)))
Andrew Trickfc933c02011-07-18 20:32:31 +00001668 P = ICmpInst::ICMP_NE;
Andrew Trick1a54bb22011-07-12 00:08:50 +00001669 else
Andrew Trickfc933c02011-07-18 20:32:31 +00001670 P = ICmpInst::ICMP_EQ;
Andrew Trick1a54bb22011-07-12 00:08:50 +00001671
1672 DEBUG(dbgs() << "INDVARS: Rewriting loop exit condition to:\n"
1673 << " LHS:" << *CmpIndVar << '\n'
1674 << " op:\t"
Andrew Trickfc933c02011-07-18 20:32:31 +00001675 << (P == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
1676 << " RHS:\t" << *ExitCnt << "\n"
1677 << " Expr:\t" << *IVLimit << "\n");
Andrew Trick1a54bb22011-07-12 00:08:50 +00001678
Andrew Trickfc933c02011-07-18 20:32:31 +00001679 if (SE->getTypeSizeInBits(CmpIndVar->getType())
1680 > SE->getTypeSizeInBits(CmpTy)) {
1681 CmpIndVar = Builder.CreateTrunc(CmpIndVar, CmpTy, "lftr.wideiv");
1682 }
1683
1684 Value *Cond = Builder.CreateICmp(P, CmpIndVar, ExitCnt, "exitcond");
Andrew Trick1a54bb22011-07-12 00:08:50 +00001685 Value *OrigCond = BI->getCondition();
1686 // It's tempting to use replaceAllUsesWith here to fully replace the old
1687 // comparison, but that's not immediately safe, since users of the old
1688 // comparison may not be dominated by the new comparison. Instead, just
1689 // update the branch to use the new comparison; in the common case this
1690 // will make old comparison dead.
1691 BI->setCondition(Cond);
1692 DeadInsts.push_back(OrigCond);
1693
1694 ++NumLFTR;
1695 Changed = true;
1696 return Cond;
1697}
1698
1699//===----------------------------------------------------------------------===//
1700// SinkUnusedInvariants. A late subpass to cleanup loop preheaders.
1701//===----------------------------------------------------------------------===//
1702
1703/// If there's a single exit block, sink any loop-invariant values that
1704/// were defined in the preheader but not used inside the loop into the
1705/// exit block to reduce register pressure in the loop.
1706void IndVarSimplify::SinkUnusedInvariants(Loop *L) {
1707 BasicBlock *ExitBlock = L->getExitBlock();
1708 if (!ExitBlock) return;
1709
1710 BasicBlock *Preheader = L->getLoopPreheader();
1711 if (!Preheader) return;
1712
Bill Wendlingb05fdd62011-08-24 20:28:43 +00001713 Instruction *InsertPt = ExitBlock->getFirstInsertionPt();
Andrew Trick1a54bb22011-07-12 00:08:50 +00001714 BasicBlock::iterator I = Preheader->getTerminator();
1715 while (I != Preheader->begin()) {
1716 --I;
1717 // New instructions were inserted at the end of the preheader.
1718 if (isa<PHINode>(I))
1719 break;
1720
1721 // Don't move instructions which might have side effects, since the side
1722 // effects need to complete before instructions inside the loop. Also don't
1723 // move instructions which might read memory, since the loop may modify
1724 // memory. Note that it's okay if the instruction might have undefined
1725 // behavior: LoopSimplify guarantees that the preheader dominates the exit
1726 // block.
1727 if (I->mayHaveSideEffects() || I->mayReadFromMemory())
1728 continue;
1729
1730 // Skip debug info intrinsics.
1731 if (isa<DbgInfoIntrinsic>(I))
1732 continue;
1733
Bill Wendling2b188812011-08-26 20:40:15 +00001734 // Skip landingpad instructions.
1735 if (isa<LandingPadInst>(I))
1736 continue;
1737
Andrew Trick1a54bb22011-07-12 00:08:50 +00001738 // Don't sink static AllocaInsts out of the entry block, which would
1739 // turn them into dynamic allocas!
1740 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
1741 if (AI->isStaticAlloca())
1742 continue;
1743
1744 // Determine if there is a use in or before the loop (direct or
1745 // otherwise).
1746 bool UsedInLoop = false;
1747 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
1748 UI != UE; ++UI) {
1749 User *U = *UI;
1750 BasicBlock *UseBB = cast<Instruction>(U)->getParent();
1751 if (PHINode *P = dyn_cast<PHINode>(U)) {
1752 unsigned i =
1753 PHINode::getIncomingValueNumForOperand(UI.getOperandNo());
1754 UseBB = P->getIncomingBlock(i);
1755 }
1756 if (UseBB == Preheader || L->contains(UseBB)) {
1757 UsedInLoop = true;
1758 break;
1759 }
1760 }
1761
1762 // If there is, the def must remain in the preheader.
1763 if (UsedInLoop)
1764 continue;
1765
1766 // Otherwise, sink it to the exit block.
1767 Instruction *ToMove = I;
1768 bool Done = false;
1769
1770 if (I != Preheader->begin()) {
1771 // Skip debug info intrinsics.
1772 do {
1773 --I;
1774 } while (isa<DbgInfoIntrinsic>(I) && I != Preheader->begin());
1775
1776 if (isa<DbgInfoIntrinsic>(I) && I == Preheader->begin())
1777 Done = true;
1778 } else {
1779 Done = true;
1780 }
1781
1782 ToMove->moveBefore(InsertPt);
1783 if (Done) break;
1784 InsertPt = ToMove;
1785 }
1786}
1787
1788//===----------------------------------------------------------------------===//
1789// IndVarSimplify driver. Manage several subpasses of IV simplification.
1790//===----------------------------------------------------------------------===//
1791
Dan Gohmanc2390b12009-02-12 22:19:27 +00001792bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
Dan Gohmana5283822010-06-18 01:35:11 +00001793 // If LoopSimplify form is not available, stay out of trouble. Some notes:
1794 // - LSR currently only supports LoopSimplify-form loops. Indvars'
1795 // canonicalization can be a pessimization without LSR to "clean up"
1796 // afterwards.
1797 // - We depend on having a preheader; in particular,
1798 // Loop::getCanonicalInductionVariable only supports loops with preheaders,
1799 // and we're in trouble if we can't find the induction variable even when
1800 // we've manually inserted one.
1801 if (!L->isLoopSimplifyForm())
1802 return false;
1803
Andrew Trick2fabd462011-06-21 03:22:38 +00001804 if (!DisableIVRewrite)
1805 IU = &getAnalysis<IVUsers>();
Devang Patel5ee99972007-03-07 06:39:01 +00001806 LI = &getAnalysis<LoopInfo>();
1807 SE = &getAnalysis<ScalarEvolution>();
Dan Gohmande53dc02009-06-27 05:16:57 +00001808 DT = &getAnalysis<DominatorTree>();
Andrew Trick37da4082011-05-04 02:10:13 +00001809 TD = getAnalysisIfAvailable<TargetData>();
1810
Andrew Trickb12a7542011-03-17 23:51:11 +00001811 DeadInsts.clear();
Devang Patel5ee99972007-03-07 06:39:01 +00001812 Changed = false;
Dan Gohman60f8a632009-02-17 20:49:49 +00001813
Dan Gohman2d1be872009-04-16 03:18:22 +00001814 // If there are any floating-point recurrences, attempt to
Dan Gohman60f8a632009-02-17 20:49:49 +00001815 // transform them to use integer recurrences.
1816 RewriteNonIntegerIVs(L);
1817
Dan Gohman0bba49c2009-07-07 17:06:11 +00001818 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
Chris Lattner9caed542007-03-04 01:00:28 +00001819
Dan Gohman667d7872009-06-26 22:53:46 +00001820 // Create a rewriter object which we'll use to transform the code with.
Andrew Trick5e7645b2011-06-28 05:07:32 +00001821 SCEVExpander Rewriter(*SE, "indvars");
Andrew Trick156d4602011-06-27 23:17:44 +00001822
1823 // Eliminate redundant IV users.
Andrew Trick15832f62011-06-28 02:49:20 +00001824 //
1825 // Simplification works best when run before other consumers of SCEV. We
1826 // attempt to avoid evaluating SCEVs for sign/zero extend operations until
1827 // other expressions involving loop IVs have been evaluated. This helps SCEV
Andrew Trick99a92f62011-06-28 16:45:04 +00001828 // set no-wrap flags before normalizing sign/zero extension.
Andrew Trick156d4602011-06-27 23:17:44 +00001829 if (DisableIVRewrite) {
Andrew Trick37da4082011-05-04 02:10:13 +00001830 Rewriter.disableCanonicalMode();
Andrew Trick4b4bb712011-08-10 03:46:27 +00001831 SimplifyAndExtend(L, Rewriter, LPM);
Andrew Trick156d4602011-06-27 23:17:44 +00001832 }
Andrew Trick37da4082011-05-04 02:10:13 +00001833
Chris Lattner40bf8b42004-04-02 20:24:31 +00001834 // Check to see if this loop has a computable loop-invariant execution count.
1835 // If so, this means that we can compute the final value of any expressions
1836 // that are recurrent in the loop, and substitute the exit values from the
1837 // loop into any instructions outside of the loop that use the final values of
1838 // the current expressions.
Chris Lattner3dec1f22002-05-10 15:38:35 +00001839 //
Dan Gohman46bdfb02009-02-24 18:55:53 +00001840 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount))
Dan Gohman454d26d2010-02-22 04:11:59 +00001841 RewriteLoopExitValues(L, Rewriter);
Chris Lattner6148c022001-12-03 17:28:42 +00001842
Andrew Trickf85092c2011-05-20 18:25:42 +00001843 // Eliminate redundant IV users.
Andrew Trick156d4602011-06-27 23:17:44 +00001844 if (!DisableIVRewrite)
Andrew Trickbddb7f82011-08-10 04:22:26 +00001845 Changed |= simplifyIVUsers(IU, SE, &LPM, DeadInsts);
Dan Gohmana590b792010-04-13 01:46:36 +00001846
Andrew Trick6f684b02011-07-16 01:06:48 +00001847 // Eliminate redundant IV cycles.
Andrew Trick037d1c02011-07-06 20:50:43 +00001848 if (DisableIVRewrite)
1849 SimplifyCongruentIVs(L);
1850
Dan Gohman81db61a2009-05-12 02:17:14 +00001851 // Compute the type of the largest recurrence expression, and decide whether
1852 // a canonical induction variable should be inserted.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001853 Type *LargestType = 0;
Dan Gohman81db61a2009-05-12 02:17:14 +00001854 bool NeedCannIV = false;
Andrew Trickfc933c02011-07-18 20:32:31 +00001855 bool ReuseIVForExit = DisableIVRewrite && !ForceLFTR;
Andrew Trick03d3d3b2011-05-25 04:42:22 +00001856 bool ExpandBECount = canExpandBackedgeTakenCount(L, SE);
Andrew Trickfc933c02011-07-18 20:32:31 +00001857 if (ExpandBECount && !ReuseIVForExit) {
Dan Gohman81db61a2009-05-12 02:17:14 +00001858 // If we have a known trip count and a single exit block, we'll be
1859 // rewriting the loop exit test condition below, which requires a
1860 // canonical induction variable.
Andrew Trick4dfdf242011-05-03 22:24:10 +00001861 NeedCannIV = true;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001862 Type *Ty = BackedgeTakenCount->getType();
Andrew Trick03d3d3b2011-05-25 04:42:22 +00001863 if (DisableIVRewrite) {
1864 // In this mode, SimplifyIVUsers may have already widened the IV used by
1865 // the backedge test and inserted a Trunc on the compare's operand. Get
1866 // the wider type to avoid creating a redundant narrow IV only used by the
1867 // loop test.
1868 LargestType = getBackedgeIVType(L);
1869 }
Andrew Trick4dfdf242011-05-03 22:24:10 +00001870 if (!LargestType ||
1871 SE->getTypeSizeInBits(Ty) >
1872 SE->getTypeSizeInBits(LargestType))
1873 LargestType = SE->getEffectiveSCEVType(Ty);
Chris Lattnerf50af082004-04-17 18:08:33 +00001874 }
Andrew Trick37da4082011-05-04 02:10:13 +00001875 if (!DisableIVRewrite) {
1876 for (IVUsers::const_iterator I = IU->begin(), E = IU->end(); I != E; ++I) {
1877 NeedCannIV = true;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001878 Type *Ty =
Andrew Trick37da4082011-05-04 02:10:13 +00001879 SE->getEffectiveSCEVType(I->getOperandValToReplace()->getType());
1880 if (!LargestType ||
1881 SE->getTypeSizeInBits(Ty) >
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001882 SE->getTypeSizeInBits(LargestType))
Andrew Trick37da4082011-05-04 02:10:13 +00001883 LargestType = Ty;
1884 }
Chris Lattner6148c022001-12-03 17:28:42 +00001885 }
1886
Dan Gohmanf451cb82010-02-10 16:03:48 +00001887 // Now that we know the largest of the induction variable expressions
Dan Gohman81db61a2009-05-12 02:17:14 +00001888 // in this loop, insert a canonical induction variable of the largest size.
Dan Gohman43ef3fb2010-07-20 17:18:52 +00001889 PHINode *IndVar = 0;
Dan Gohman81db61a2009-05-12 02:17:14 +00001890 if (NeedCannIV) {
Dan Gohman85669632010-02-25 06:57:05 +00001891 // Check to see if the loop already has any canonical-looking induction
1892 // variables. If any are present and wider than the planned canonical
1893 // induction variable, temporarily remove them, so that the Rewriter
1894 // doesn't attempt to reuse them.
1895 SmallVector<PHINode *, 2> OldCannIVs;
1896 while (PHINode *OldCannIV = L->getCanonicalInductionVariable()) {
Dan Gohman4d8414f2009-06-13 16:25:49 +00001897 if (SE->getTypeSizeInBits(OldCannIV->getType()) >
1898 SE->getTypeSizeInBits(LargestType))
1899 OldCannIV->removeFromParent();
1900 else
Dan Gohman85669632010-02-25 06:57:05 +00001901 break;
1902 OldCannIVs.push_back(OldCannIV);
Dan Gohman4d8414f2009-06-13 16:25:49 +00001903 }
1904
Dan Gohman667d7872009-06-26 22:53:46 +00001905 IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L, LargestType);
Dan Gohman4d8414f2009-06-13 16:25:49 +00001906
Dan Gohmanc2390b12009-02-12 22:19:27 +00001907 ++NumInserted;
1908 Changed = true;
David Greenef67ef312010-01-05 01:27:06 +00001909 DEBUG(dbgs() << "INDVARS: New CanIV: " << *IndVar << '\n');
Dan Gohman4d8414f2009-06-13 16:25:49 +00001910
1911 // Now that the official induction variable is established, reinsert
Dan Gohman85669632010-02-25 06:57:05 +00001912 // any old canonical-looking variables after it so that the IR remains
1913 // consistent. They will be deleted as part of the dead-PHI deletion at
Dan Gohman4d8414f2009-06-13 16:25:49 +00001914 // the end of the pass.
Dan Gohman85669632010-02-25 06:57:05 +00001915 while (!OldCannIVs.empty()) {
1916 PHINode *OldCannIV = OldCannIVs.pop_back_val();
Bill Wendlingb05fdd62011-08-24 20:28:43 +00001917 OldCannIV->insertBefore(L->getHeader()->getFirstInsertionPt());
Dan Gohman85669632010-02-25 06:57:05 +00001918 }
Dan Gohmand19534a2007-06-15 14:38:12 +00001919 }
Andrew Trickfc933c02011-07-18 20:32:31 +00001920 else if (ExpandBECount && ReuseIVForExit && needsLFTR(L, DT)) {
1921 IndVar = FindLoopCounter(L, BackedgeTakenCount, SE, DT, TD);
1922 }
Dan Gohmanc2390b12009-02-12 22:19:27 +00001923 // If we have a trip count expression, rewrite the loop's exit condition
1924 // using it. We can currently only handle loops with a single exit.
Andrew Trickfc933c02011-07-18 20:32:31 +00001925 Value *NewICmp = 0;
1926 if (ExpandBECount && IndVar) {
Andrew Trick56147692011-07-16 01:18:53 +00001927 // Check preconditions for proper SCEVExpander operation. SCEV does not
1928 // express SCEVExpander's dependencies, such as LoopSimplify. Instead any
1929 // pass that uses the SCEVExpander must do it. This does not work well for
1930 // loop passes because SCEVExpander makes assumptions about all loops, while
1931 // LoopPassManager only forces the current loop to be simplified.
1932 //
1933 // FIXME: SCEV expansion has no way to bail out, so the caller must
1934 // explicitly check any assumptions made by SCEV. Brittle.
1935 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(BackedgeTakenCount);
1936 if (!AR || AR->getLoop()->getLoopPreheader())
1937 NewICmp =
1938 LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar, Rewriter);
Chris Lattnerfcb81f52004-04-22 14:59:40 +00001939 }
Andrew Trickb12a7542011-03-17 23:51:11 +00001940 // Rewrite IV-derived expressions.
Andrew Trick37da4082011-05-04 02:10:13 +00001941 if (!DisableIVRewrite)
1942 RewriteIVExpressions(L, Rewriter);
Dan Gohmanc2390b12009-02-12 22:19:27 +00001943
Andrew Trickb12a7542011-03-17 23:51:11 +00001944 // Clear the rewriter cache, because values that are in the rewriter's cache
1945 // can be deleted in the loop below, causing the AssertingVH in the cache to
1946 // trigger.
1947 Rewriter.clear();
1948
1949 // Now that we're done iterating through lists, clean up any instructions
1950 // which are now dead.
1951 while (!DeadInsts.empty())
1952 if (Instruction *Inst =
1953 dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val()))
1954 RecursivelyDeleteTriviallyDeadInstructions(Inst);
1955
Dan Gohman667d7872009-06-26 22:53:46 +00001956 // The Rewriter may not be used from this point on.
Torok Edwin3d431382009-05-24 20:08:21 +00001957
Dan Gohman81db61a2009-05-12 02:17:14 +00001958 // Loop-invariant instructions in the preheader that aren't used in the
1959 // loop may be sunk below the loop to reduce register pressure.
Dan Gohman667d7872009-06-26 22:53:46 +00001960 SinkUnusedInvariants(L);
Dan Gohman81db61a2009-05-12 02:17:14 +00001961
1962 // For completeness, inform IVUsers of the IV use in the newly-created
1963 // loop exit test instruction.
Andrew Trickfc933c02011-07-18 20:32:31 +00001964 if (IU && NewICmp) {
1965 ICmpInst *NewICmpInst = dyn_cast<ICmpInst>(NewICmp);
1966 if (NewICmpInst)
1967 IU->AddUsersIfInteresting(cast<Instruction>(NewICmpInst->getOperand(0)));
1968 }
Dan Gohman81db61a2009-05-12 02:17:14 +00001969 // Clean up dead instructions.
Dan Gohman9fff2182010-01-05 16:31:45 +00001970 Changed |= DeleteDeadPHIs(L->getHeader());
Dan Gohman81db61a2009-05-12 02:17:14 +00001971 // Check a post-condition.
Andrew Trickf6a0dba2011-07-18 18:44:20 +00001972 assert(L->isLCSSAForm(*DT) &&
1973 "Indvars did not leave the loop in lcssa form!");
1974
1975 // Verify that LFTR, and any other change have not interfered with SCEV's
1976 // ability to compute trip count.
1977#ifndef NDEBUG
Andrew Trick75ebc0e2011-09-06 20:20:38 +00001978 if (DisableIVRewrite && VerifyIndvars &&
1979 !isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
Andrew Trickf6a0dba2011-07-18 18:44:20 +00001980 SE->forgetLoop(L);
1981 const SCEV *NewBECount = SE->getBackedgeTakenCount(L);
1982 if (SE->getTypeSizeInBits(BackedgeTakenCount->getType()) <
1983 SE->getTypeSizeInBits(NewBECount->getType()))
1984 NewBECount = SE->getTruncateOrNoop(NewBECount,
1985 BackedgeTakenCount->getType());
1986 else
1987 BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount,
1988 NewBECount->getType());
1989 assert(BackedgeTakenCount == NewBECount && "indvars must preserve SCEV");
1990 }
1991#endif
1992
Devang Patel5ee99972007-03-07 06:39:01 +00001993 return Changed;
Chris Lattner6148c022001-12-03 17:28:42 +00001994}