blob: 14f995bec263dfa4c8bcd76e9e414d201dcc91cd [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"));
79}
Andrew Trick37da4082011-05-04 02:10:13 +000080
Andrew Trickfc933c02011-07-18 20:32:31 +000081// Temporary flag for use with -disable-iv-rewrite to force a canonical IV for
82// LFTR purposes.
83static cl::opt<bool> ForceLFTR(
84 "force-lftr", cl::Hidden,
85 cl::desc("Enable forced linear function test replacement"));
86
Chris Lattner0e5f4992006-12-19 21:40:18 +000087namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000088 class IndVarSimplify : public LoopPass {
Dan Gohman81db61a2009-05-12 02:17:14 +000089 IVUsers *IU;
Chris Lattner40bf8b42004-04-02 20:24:31 +000090 LoopInfo *LI;
91 ScalarEvolution *SE;
Dan Gohmande53dc02009-06-27 05:16:57 +000092 DominatorTree *DT;
Andrew Trick37da4082011-05-04 02:10:13 +000093 TargetData *TD;
Andrew Trick2fabd462011-06-21 03:22:38 +000094
Andrew Trickb12a7542011-03-17 23:51:11 +000095 SmallVector<WeakVH, 16> DeadInsts;
Chris Lattner15cad752003-12-23 07:47:09 +000096 bool Changed;
Chris Lattner3324e712003-12-22 03:58:44 +000097 public:
Devang Patel794fd752007-05-01 21:15:47 +000098
Dan Gohman5668cf72009-07-15 01:26:32 +000099 static char ID; // Pass identification, replacement for typeid
Andrew Trick2fabd462011-06-21 03:22:38 +0000100 IndVarSimplify() : LoopPass(ID), IU(0), LI(0), SE(0), DT(0), TD(0),
Andrew Trick15832f62011-06-28 02:49:20 +0000101 Changed(false) {
Owen Anderson081c34b2010-10-19 17:21:58 +0000102 initializeIndVarSimplifyPass(*PassRegistry::getPassRegistry());
103 }
Devang Patel794fd752007-05-01 21:15:47 +0000104
Dan Gohman5668cf72009-07-15 01:26:32 +0000105 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
Dan Gohman60f8a632009-02-17 20:49:49 +0000106
Dan Gohman5668cf72009-07-15 01:26:32 +0000107 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
108 AU.addRequired<DominatorTree>();
109 AU.addRequired<LoopInfo>();
110 AU.addRequired<ScalarEvolution>();
111 AU.addRequiredID(LoopSimplifyID);
112 AU.addRequiredID(LCSSAID);
Andrew Trick56caa092011-06-28 03:01:46 +0000113 if (!DisableIVRewrite)
114 AU.addRequired<IVUsers>();
Dan Gohman5668cf72009-07-15 01:26:32 +0000115 AU.addPreserved<ScalarEvolution>();
116 AU.addPreservedID(LoopSimplifyID);
117 AU.addPreservedID(LCSSAID);
Andrew Trick2fabd462011-06-21 03:22:38 +0000118 if (!DisableIVRewrite)
119 AU.addPreserved<IVUsers>();
Dan Gohman5668cf72009-07-15 01:26:32 +0000120 AU.setPreservesCFG();
121 }
Chris Lattner15cad752003-12-23 07:47:09 +0000122
Chris Lattner40bf8b42004-04-02 20:24:31 +0000123 private:
Andrew Trick037d1c02011-07-06 20:50:43 +0000124 virtual void releaseMemory() {
Andrew Trick037d1c02011-07-06 20:50:43 +0000125 DeadInsts.clear();
126 }
127
Andrew Trickb12a7542011-03-17 23:51:11 +0000128 bool isValidRewrite(Value *FromVal, Value *ToVal);
Devang Patel5ee99972007-03-07 06:39:01 +0000129
Andrew Trick1a54bb22011-07-12 00:08:50 +0000130 void HandleFloatingPointIV(Loop *L, PHINode *PH);
131 void RewriteNonIntegerIVs(Loop *L);
132
Andrew Trick4b4bb712011-08-10 03:46:27 +0000133 void SimplifyAndExtend(Loop *L, SCEVExpander &Rewriter, LPPassManager &LPM);
Andrew Trick06988bc2011-08-06 07:00:37 +0000134
Andrew Trick037d1c02011-07-06 20:50:43 +0000135 void SimplifyCongruentIVs(Loop *L);
136
Andrew Trick4b4bb712011-08-10 03:46:27 +0000137 void RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter);
138
Dan Gohman454d26d2010-02-22 04:11:59 +0000139 void RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter);
Devang Pateld22a8492008-09-09 21:41:07 +0000140
Andrew Trickfc933c02011-07-18 20:32:31 +0000141 Value *LinearFunctionTestReplace(Loop *L, const SCEV *BackedgeTakenCount,
142 PHINode *IndVar, SCEVExpander &Rewriter);
Dan Gohman81db61a2009-05-12 02:17:14 +0000143
Andrew Trick1a54bb22011-07-12 00:08:50 +0000144 void SinkUnusedInvariants(Loop *L);
Chris Lattner3324e712003-12-22 03:58:44 +0000145 };
Chris Lattner5e761402002-09-10 05:24:05 +0000146}
Chris Lattner394437f2001-12-04 04:32:29 +0000147
Dan Gohman844731a2008-05-13 00:00:25 +0000148char IndVarSimplify::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000149INITIALIZE_PASS_BEGIN(IndVarSimplify, "indvars",
Andrew Trick37da4082011-05-04 02:10:13 +0000150 "Induction Variable Simplification", false, false)
Owen Anderson2ab36d32010-10-12 19:48:12 +0000151INITIALIZE_PASS_DEPENDENCY(DominatorTree)
152INITIALIZE_PASS_DEPENDENCY(LoopInfo)
153INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
154INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
155INITIALIZE_PASS_DEPENDENCY(LCSSA)
156INITIALIZE_PASS_DEPENDENCY(IVUsers)
157INITIALIZE_PASS_END(IndVarSimplify, "indvars",
Andrew Trick37da4082011-05-04 02:10:13 +0000158 "Induction Variable Simplification", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000159
Daniel Dunbar394f0442008-10-22 23:32:42 +0000160Pass *llvm::createIndVarSimplifyPass() {
Chris Lattner3324e712003-12-22 03:58:44 +0000161 return new IndVarSimplify();
Chris Lattner394437f2001-12-04 04:32:29 +0000162}
163
Andrew Trickb12a7542011-03-17 23:51:11 +0000164/// isValidRewrite - Return true if the SCEV expansion generated by the
165/// rewriter can replace the original value. SCEV guarantees that it
166/// produces the same value, but the way it is produced may be illegal IR.
167/// Ideally, this function will only be called for verification.
168bool IndVarSimplify::isValidRewrite(Value *FromVal, Value *ToVal) {
169 // If an SCEV expression subsumed multiple pointers, its expansion could
170 // reassociate the GEP changing the base pointer. This is illegal because the
171 // final address produced by a GEP chain must be inbounds relative to its
172 // underlying object. Otherwise basic alias analysis, among other things,
173 // could fail in a dangerous way. Ultimately, SCEV will be improved to avoid
174 // producing an expression involving multiple pointers. Until then, we must
175 // bail out here.
176 //
177 // Retrieve the pointer operand of the GEP. Don't use GetUnderlyingObject
178 // because it understands lcssa phis while SCEV does not.
179 Value *FromPtr = FromVal;
180 Value *ToPtr = ToVal;
181 if (GEPOperator *GEP = dyn_cast<GEPOperator>(FromVal)) {
182 FromPtr = GEP->getPointerOperand();
183 }
184 if (GEPOperator *GEP = dyn_cast<GEPOperator>(ToVal)) {
185 ToPtr = GEP->getPointerOperand();
186 }
187 if (FromPtr != FromVal || ToPtr != ToVal) {
188 // Quickly check the common case
189 if (FromPtr == ToPtr)
190 return true;
191
192 // SCEV may have rewritten an expression that produces the GEP's pointer
193 // operand. That's ok as long as the pointer operand has the same base
194 // pointer. Unlike GetUnderlyingObject(), getPointerBase() will find the
195 // base of a recurrence. This handles the case in which SCEV expansion
196 // converts a pointer type recurrence into a nonrecurrent pointer base
197 // indexed by an integer recurrence.
198 const SCEV *FromBase = SE->getPointerBase(SE->getSCEV(FromPtr));
199 const SCEV *ToBase = SE->getPointerBase(SE->getSCEV(ToPtr));
200 if (FromBase == ToBase)
201 return true;
202
203 DEBUG(dbgs() << "INDVARS: GEP rewrite bail out "
204 << *FromBase << " != " << *ToBase << "\n");
205
206 return false;
207 }
208 return true;
209}
210
Andrew Trick86c98142011-07-20 05:32:06 +0000211/// Determine the insertion point for this user. By default, insert immediately
212/// before the user. SCEVExpander or LICM will hoist loop invariants out of the
213/// loop. For PHI nodes, there may be multiple uses, so compute the nearest
214/// common dominator for the incoming blocks.
215static Instruction *getInsertPointForUses(Instruction *User, Value *Def,
216 DominatorTree *DT) {
217 PHINode *PHI = dyn_cast<PHINode>(User);
218 if (!PHI)
219 return User;
220
221 Instruction *InsertPt = 0;
222 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i) {
223 if (PHI->getIncomingValue(i) != Def)
224 continue;
225
226 BasicBlock *InsertBB = PHI->getIncomingBlock(i);
227 if (!InsertPt) {
228 InsertPt = InsertBB->getTerminator();
229 continue;
230 }
231 InsertBB = DT->findNearestCommonDominator(InsertPt->getParent(), InsertBB);
232 InsertPt = InsertBB->getTerminator();
233 }
234 assert(InsertPt && "Missing phi operand");
Jay Foad626f52d2011-07-20 08:15:21 +0000235 assert((!isa<Instruction>(Def) ||
236 DT->dominates(cast<Instruction>(Def), InsertPt)) &&
Andrew Trick86c98142011-07-20 05:32:06 +0000237 "def does not dominate all uses");
238 return InsertPt;
239}
240
Andrew Trick1a54bb22011-07-12 00:08:50 +0000241//===----------------------------------------------------------------------===//
242// RewriteNonIntegerIVs and helpers. Prefer integer IVs.
243//===----------------------------------------------------------------------===//
Andrew Trick4dfdf242011-05-03 22:24:10 +0000244
Andrew Trick1a54bb22011-07-12 00:08:50 +0000245/// ConvertToSInt - Convert APF to an integer, if possible.
246static bool ConvertToSInt(const APFloat &APF, int64_t &IntVal) {
247 bool isExact = false;
248 if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
Andrew Trick4dfdf242011-05-03 22:24:10 +0000249 return false;
Andrew Trick1a54bb22011-07-12 00:08:50 +0000250 // See if we can convert this to an int64_t
251 uint64_t UIntVal;
252 if (APF.convertToInteger(&UIntVal, 64, true, APFloat::rmTowardZero,
253 &isExact) != APFloat::opOK || !isExact)
Andrew Trick4dfdf242011-05-03 22:24:10 +0000254 return false;
Andrew Trick1a54bb22011-07-12 00:08:50 +0000255 IntVal = UIntVal;
Andrew Trick4dfdf242011-05-03 22:24:10 +0000256 return true;
257}
258
Andrew Trick1a54bb22011-07-12 00:08:50 +0000259/// HandleFloatingPointIV - If the loop has floating induction variable
260/// then insert corresponding integer induction variable if possible.
261/// For example,
262/// for(double i = 0; i < 10000; ++i)
263/// bar(i)
264/// is converted into
265/// for(int i = 0; i < 10000; ++i)
266/// bar((double)i);
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000267///
Andrew Trick1a54bb22011-07-12 00:08:50 +0000268void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PN) {
269 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
270 unsigned BackEdge = IncomingEdge^1;
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000271
Andrew Trick1a54bb22011-07-12 00:08:50 +0000272 // Check incoming value.
273 ConstantFP *InitValueVal =
274 dyn_cast<ConstantFP>(PN->getIncomingValue(IncomingEdge));
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000275
Andrew Trick1a54bb22011-07-12 00:08:50 +0000276 int64_t InitValue;
277 if (!InitValueVal || !ConvertToSInt(InitValueVal->getValueAPF(), InitValue))
278 return;
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000279
Andrew Trick1a54bb22011-07-12 00:08:50 +0000280 // Check IV increment. Reject this PN if increment operation is not
281 // an add or increment value can not be represented by an integer.
282 BinaryOperator *Incr =
283 dyn_cast<BinaryOperator>(PN->getIncomingValue(BackEdge));
284 if (Incr == 0 || Incr->getOpcode() != Instruction::FAdd) return;
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000285
Andrew Trick1a54bb22011-07-12 00:08:50 +0000286 // If this is not an add of the PHI with a constantfp, or if the constant fp
287 // is not an integer, bail out.
288 ConstantFP *IncValueVal = dyn_cast<ConstantFP>(Incr->getOperand(1));
289 int64_t IncValue;
290 if (IncValueVal == 0 || Incr->getOperand(0) != PN ||
291 !ConvertToSInt(IncValueVal->getValueAPF(), IncValue))
292 return;
293
294 // Check Incr uses. One user is PN and the other user is an exit condition
295 // used by the conditional terminator.
296 Value::use_iterator IncrUse = Incr->use_begin();
297 Instruction *U1 = cast<Instruction>(*IncrUse++);
298 if (IncrUse == Incr->use_end()) return;
299 Instruction *U2 = cast<Instruction>(*IncrUse++);
300 if (IncrUse != Incr->use_end()) return;
301
302 // Find exit condition, which is an fcmp. If it doesn't exist, or if it isn't
303 // only used by a branch, we can't transform it.
304 FCmpInst *Compare = dyn_cast<FCmpInst>(U1);
305 if (!Compare)
306 Compare = dyn_cast<FCmpInst>(U2);
307 if (Compare == 0 || !Compare->hasOneUse() ||
308 !isa<BranchInst>(Compare->use_back()))
309 return;
310
311 BranchInst *TheBr = cast<BranchInst>(Compare->use_back());
312
313 // We need to verify that the branch actually controls the iteration count
314 // of the loop. If not, the new IV can overflow and no one will notice.
315 // The branch block must be in the loop and one of the successors must be out
316 // of the loop.
317 assert(TheBr->isConditional() && "Can't use fcmp if not conditional");
318 if (!L->contains(TheBr->getParent()) ||
319 (L->contains(TheBr->getSuccessor(0)) &&
320 L->contains(TheBr->getSuccessor(1))))
321 return;
322
323
324 // If it isn't a comparison with an integer-as-fp (the exit value), we can't
325 // transform it.
326 ConstantFP *ExitValueVal = dyn_cast<ConstantFP>(Compare->getOperand(1));
327 int64_t ExitValue;
328 if (ExitValueVal == 0 ||
329 !ConvertToSInt(ExitValueVal->getValueAPF(), ExitValue))
330 return;
331
332 // Find new predicate for integer comparison.
333 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
334 switch (Compare->getPredicate()) {
335 default: return; // Unknown comparison.
336 case CmpInst::FCMP_OEQ:
337 case CmpInst::FCMP_UEQ: NewPred = CmpInst::ICMP_EQ; break;
338 case CmpInst::FCMP_ONE:
339 case CmpInst::FCMP_UNE: NewPred = CmpInst::ICMP_NE; break;
340 case CmpInst::FCMP_OGT:
341 case CmpInst::FCMP_UGT: NewPred = CmpInst::ICMP_SGT; break;
342 case CmpInst::FCMP_OGE:
343 case CmpInst::FCMP_UGE: NewPred = CmpInst::ICMP_SGE; break;
344 case CmpInst::FCMP_OLT:
345 case CmpInst::FCMP_ULT: NewPred = CmpInst::ICMP_SLT; break;
346 case CmpInst::FCMP_OLE:
347 case CmpInst::FCMP_ULE: NewPred = CmpInst::ICMP_SLE; break;
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000348 }
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000349
Andrew Trick1a54bb22011-07-12 00:08:50 +0000350 // We convert the floating point induction variable to a signed i32 value if
351 // we can. This is only safe if the comparison will not overflow in a way
352 // that won't be trapped by the integer equivalent operations. Check for this
353 // now.
354 // TODO: We could use i64 if it is native and the range requires it.
Dan Gohmanca9b7032010-04-12 21:13:43 +0000355
Andrew Trick1a54bb22011-07-12 00:08:50 +0000356 // The start/stride/exit values must all fit in signed i32.
357 if (!isInt<32>(InitValue) || !isInt<32>(IncValue) || !isInt<32>(ExitValue))
358 return;
359
360 // If not actually striding (add x, 0.0), avoid touching the code.
361 if (IncValue == 0)
362 return;
363
364 // Positive and negative strides have different safety conditions.
365 if (IncValue > 0) {
366 // If we have a positive stride, we require the init to be less than the
367 // exit value and an equality or less than comparison.
368 if (InitValue >= ExitValue ||
369 NewPred == CmpInst::ICMP_SGT || NewPred == CmpInst::ICMP_SGE)
370 return;
371
372 uint32_t Range = uint32_t(ExitValue-InitValue);
373 if (NewPred == CmpInst::ICMP_SLE) {
374 // Normalize SLE -> SLT, check for infinite loop.
375 if (++Range == 0) return; // Range overflows.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000376 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000377
Andrew Trick1a54bb22011-07-12 00:08:50 +0000378 unsigned Leftover = Range % uint32_t(IncValue);
379
380 // If this is an equality comparison, we require that the strided value
381 // exactly land on the exit value, otherwise the IV condition will wrap
382 // around and do things the fp IV wouldn't.
383 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
384 Leftover != 0)
385 return;
386
387 // If the stride would wrap around the i32 before exiting, we can't
388 // transform the IV.
389 if (Leftover != 0 && int32_t(ExitValue+IncValue) < ExitValue)
390 return;
391
Chris Lattnerd2440572004-04-15 20:26:22 +0000392 } else {
Andrew Trick1a54bb22011-07-12 00:08:50 +0000393 // If we have a negative stride, we require the init to be greater than the
394 // exit value and an equality or greater than comparison.
395 if (InitValue >= ExitValue ||
396 NewPred == CmpInst::ICMP_SLT || NewPred == CmpInst::ICMP_SLE)
397 return;
398
399 uint32_t Range = uint32_t(InitValue-ExitValue);
400 if (NewPred == CmpInst::ICMP_SGE) {
401 // Normalize SGE -> SGT, check for infinite loop.
402 if (++Range == 0) return; // Range overflows.
403 }
404
405 unsigned Leftover = Range % uint32_t(-IncValue);
406
407 // If this is an equality comparison, we require that the strided value
408 // exactly land on the exit value, otherwise the IV condition will wrap
409 // around and do things the fp IV wouldn't.
410 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
411 Leftover != 0)
412 return;
413
414 // If the stride would wrap around the i32 before exiting, we can't
415 // transform the IV.
416 if (Leftover != 0 && int32_t(ExitValue+IncValue) > ExitValue)
417 return;
Chris Lattnerd2440572004-04-15 20:26:22 +0000418 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000419
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000420 IntegerType *Int32Ty = Type::getInt32Ty(PN->getContext());
Chris Lattner40bf8b42004-04-02 20:24:31 +0000421
Andrew Trick1a54bb22011-07-12 00:08:50 +0000422 // Insert new integer induction variable.
423 PHINode *NewPHI = PHINode::Create(Int32Ty, 2, PN->getName()+".int", PN);
424 NewPHI->addIncoming(ConstantInt::get(Int32Ty, InitValue),
425 PN->getIncomingBlock(IncomingEdge));
Chris Lattner40bf8b42004-04-02 20:24:31 +0000426
Andrew Trick1a54bb22011-07-12 00:08:50 +0000427 Value *NewAdd =
428 BinaryOperator::CreateAdd(NewPHI, ConstantInt::get(Int32Ty, IncValue),
429 Incr->getName()+".int", Incr);
430 NewPHI->addIncoming(NewAdd, PN->getIncomingBlock(BackEdge));
Dan Gohmanc2390b12009-02-12 22:19:27 +0000431
Andrew Trick1a54bb22011-07-12 00:08:50 +0000432 ICmpInst *NewCompare = new ICmpInst(TheBr, NewPred, NewAdd,
433 ConstantInt::get(Int32Ty, ExitValue),
434 Compare->getName());
Dan Gohman81db61a2009-05-12 02:17:14 +0000435
Andrew Trick1a54bb22011-07-12 00:08:50 +0000436 // In the following deletions, PN may become dead and may be deleted.
437 // Use a WeakVH to observe whether this happens.
438 WeakVH WeakPH = PN;
439
440 // Delete the old floating point exit comparison. The branch starts using the
441 // new comparison.
442 NewCompare->takeName(Compare);
443 Compare->replaceAllUsesWith(NewCompare);
444 RecursivelyDeleteTriviallyDeadInstructions(Compare);
445
446 // Delete the old floating point increment.
447 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
448 RecursivelyDeleteTriviallyDeadInstructions(Incr);
449
450 // If the FP induction variable still has uses, this is because something else
451 // in the loop uses its value. In order to canonicalize the induction
452 // variable, we chose to eliminate the IV and rewrite it in terms of an
453 // int->fp cast.
454 //
455 // We give preference to sitofp over uitofp because it is faster on most
456 // platforms.
457 if (WeakPH) {
458 Value *Conv = new SIToFPInst(NewPHI, PN->getType(), "indvar.conv",
459 PN->getParent()->getFirstNonPHI());
460 PN->replaceAllUsesWith(Conv);
461 RecursivelyDeleteTriviallyDeadInstructions(PN);
462 }
463
464 // Add a new IVUsers entry for the newly-created integer PHI.
465 if (IU)
466 IU->AddUsersIfInteresting(NewPHI);
Andrew Trick4b4bb712011-08-10 03:46:27 +0000467
468 Changed = true;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000469}
470
Andrew Trick1a54bb22011-07-12 00:08:50 +0000471void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) {
472 // First step. Check to see if there are any floating-point recurrences.
473 // If there are, change them into integer recurrences, permitting analysis by
474 // the SCEV routines.
475 //
476 BasicBlock *Header = L->getHeader();
477
478 SmallVector<WeakVH, 8> PHIs;
479 for (BasicBlock::iterator I = Header->begin();
480 PHINode *PN = dyn_cast<PHINode>(I); ++I)
481 PHIs.push_back(PN);
482
483 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
484 if (PHINode *PN = dyn_cast_or_null<PHINode>(&*PHIs[i]))
485 HandleFloatingPointIV(L, PN);
486
487 // If the loop previously had floating-point IV, ScalarEvolution
488 // may not have been able to compute a trip count. Now that we've done some
489 // re-writing, the trip count may be computable.
490 if (Changed)
491 SE->forgetLoop(L);
492}
493
494//===----------------------------------------------------------------------===//
495// RewriteLoopExitValues - Optimize IV users outside the loop.
496// As a side effect, reduces the amount of IV processing within the loop.
497//===----------------------------------------------------------------------===//
498
Chris Lattner40bf8b42004-04-02 20:24:31 +0000499/// RewriteLoopExitValues - Check to see if this loop has a computable
500/// loop-invariant execution count. If so, this means that we can compute the
501/// final value of any expressions that are recurrent in the loop, and
502/// substitute the exit values from the loop into any instructions outside of
503/// the loop that use the final values of the current expressions.
Dan Gohman81db61a2009-05-12 02:17:14 +0000504///
505/// This is mostly redundant with the regular IndVarSimplify activities that
506/// happen later, except that it's more powerful in some cases, because it's
507/// able to brute-force evaluate arbitrary instructions as long as they have
508/// constant operands at the beginning of the loop.
Chris Lattnerf1859892011-01-09 02:16:18 +0000509void IndVarSimplify::RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000510 // Verify the input to the pass in already in LCSSA form.
Dan Gohmanbbf81d82010-03-10 19:38:49 +0000511 assert(L->isLCSSAForm(*DT));
Dan Gohman81db61a2009-05-12 02:17:14 +0000512
Devang Patelb7211a22007-08-21 00:31:24 +0000513 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattner9f3d7382007-03-04 03:43:23 +0000514 L->getUniqueExitBlocks(ExitBlocks);
Misha Brukmanfd939082005-04-21 23:48:37 +0000515
Chris Lattner9f3d7382007-03-04 03:43:23 +0000516 // Find all values that are computed inside the loop, but used outside of it.
517 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
518 // the exit blocks of the loop to find them.
519 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
520 BasicBlock *ExitBB = ExitBlocks[i];
Dan Gohmancafb8132009-02-17 19:13:57 +0000521
Chris Lattner9f3d7382007-03-04 03:43:23 +0000522 // If there are no PHI nodes in this exit block, then no values defined
523 // inside the loop are used on this path, skip it.
524 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
525 if (!PN) continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000526
Chris Lattner9f3d7382007-03-04 03:43:23 +0000527 unsigned NumPreds = PN->getNumIncomingValues();
Dan Gohmancafb8132009-02-17 19:13:57 +0000528
Chris Lattner9f3d7382007-03-04 03:43:23 +0000529 // Iterate over all of the PHI nodes.
530 BasicBlock::iterator BBI = ExitBB->begin();
531 while ((PN = dyn_cast<PHINode>(BBI++))) {
Torok Edwin3790fb02009-05-24 19:36:09 +0000532 if (PN->use_empty())
533 continue; // dead use, don't replace it
Dan Gohman814f2b22010-02-18 21:34:02 +0000534
535 // SCEV only supports integer expressions for now.
536 if (!PN->getType()->isIntegerTy() && !PN->getType()->isPointerTy())
537 continue;
538
Dale Johannesen45a2d7d2010-02-19 07:14:22 +0000539 // It's necessary to tell ScalarEvolution about this explicitly so that
540 // it can walk the def-use list and forget all SCEVs, as it may not be
541 // watching the PHI itself. Once the new exit value is in place, there
542 // may not be a def-use connection between the loop and every instruction
543 // which got a SCEVAddRecExpr for that loop.
544 SE->forgetValue(PN);
545
Chris Lattner9f3d7382007-03-04 03:43:23 +0000546 // Iterate over all of the values in all the PHI nodes.
547 for (unsigned i = 0; i != NumPreds; ++i) {
548 // If the value being merged in is not integer or is not defined
549 // in the loop, skip it.
550 Value *InVal = PN->getIncomingValue(i);
Dan Gohman814f2b22010-02-18 21:34:02 +0000551 if (!isa<Instruction>(InVal))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000552 continue;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000553
Chris Lattner9f3d7382007-03-04 03:43:23 +0000554 // If this pred is for a subloop, not L itself, skip it.
Dan Gohmancafb8132009-02-17 19:13:57 +0000555 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
Chris Lattner9f3d7382007-03-04 03:43:23 +0000556 continue; // The Block is in a subloop, skip it.
557
558 // Check that InVal is defined in the loop.
559 Instruction *Inst = cast<Instruction>(InVal);
Dan Gohman92329c72009-12-18 01:24:09 +0000560 if (!L->contains(Inst))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000561 continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000562
Chris Lattner9f3d7382007-03-04 03:43:23 +0000563 // Okay, this instruction has a user outside of the current loop
564 // and varies predictably *inside* the loop. Evaluate the value it
565 // contains when the loop exits, if possible.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000566 const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
Dan Gohman17ead4f2010-11-17 21:23:15 +0000567 if (!SE->isLoopInvariant(ExitValue, L))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000568 continue;
Chris Lattner9caed542007-03-04 01:00:28 +0000569
Dan Gohman667d7872009-06-26 22:53:46 +0000570 Value *ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), Inst);
Dan Gohmancafb8132009-02-17 19:13:57 +0000571
David Greenef67ef312010-01-05 01:27:06 +0000572 DEBUG(dbgs() << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal << '\n'
Chris Lattnerbdff5482009-08-23 04:37:46 +0000573 << " LoopVal = " << *Inst << "\n");
Chris Lattner9f3d7382007-03-04 03:43:23 +0000574
Andrew Trickb12a7542011-03-17 23:51:11 +0000575 if (!isValidRewrite(Inst, ExitVal)) {
576 DeadInsts.push_back(ExitVal);
577 continue;
578 }
579 Changed = true;
580 ++NumReplaced;
581
Chris Lattner9f3d7382007-03-04 03:43:23 +0000582 PN->setIncomingValue(i, ExitVal);
Dan Gohmancafb8132009-02-17 19:13:57 +0000583
Dan Gohman81db61a2009-05-12 02:17:14 +0000584 // If this instruction is dead now, delete it.
585 RecursivelyDeleteTriviallyDeadInstructions(Inst);
Dan Gohmancafb8132009-02-17 19:13:57 +0000586
Dan Gohman65d1e2b2009-07-14 01:09:02 +0000587 if (NumPreds == 1) {
588 // Completely replace a single-pred PHI. This is safe, because the
589 // NewVal won't be variant in the loop, so we don't need an LCSSA phi
590 // node anymore.
Chris Lattner9f3d7382007-03-04 03:43:23 +0000591 PN->replaceAllUsesWith(ExitVal);
Dan Gohman81db61a2009-05-12 02:17:14 +0000592 RecursivelyDeleteTriviallyDeadInstructions(PN);
Chris Lattnerc9838f22007-03-03 22:48:48 +0000593 }
594 }
Dan Gohman65d1e2b2009-07-14 01:09:02 +0000595 if (NumPreds != 1) {
Dan Gohman667d7872009-06-26 22:53:46 +0000596 // Clone the PHI and delete the original one. This lets IVUsers and
597 // any other maps purge the original user from their records.
Devang Patel50b6e332009-10-27 22:16:29 +0000598 PHINode *NewPN = cast<PHINode>(PN->clone());
Dan Gohman667d7872009-06-26 22:53:46 +0000599 NewPN->takeName(PN);
600 NewPN->insertBefore(PN);
601 PN->replaceAllUsesWith(NewPN);
602 PN->eraseFromParent();
603 }
Chris Lattnerc9838f22007-03-03 22:48:48 +0000604 }
605 }
Dan Gohman472fdf72010-03-20 03:53:53 +0000606
607 // The insertion point instruction may have been deleted; clear it out
608 // so that the rewriter doesn't trip over it later.
609 Rewriter.clearInsertPoint();
Chris Lattner40bf8b42004-04-02 20:24:31 +0000610}
611
Andrew Trick1a54bb22011-07-12 00:08:50 +0000612//===----------------------------------------------------------------------===//
613// Rewrite IV users based on a canonical IV.
614// To be replaced by -disable-iv-rewrite.
615//===----------------------------------------------------------------------===//
Dale Johannesenc671d892009-04-15 23:31:51 +0000616
Andrew Trick1a54bb22011-07-12 00:08:50 +0000617// FIXME: It is an extremely bad idea to indvar substitute anything more
618// complex than affine induction variables. Doing so will put expensive
619// polynomial evaluations inside of the loop, and the str reduction pass
620// currently can only reduce affine polynomials. For now just disable
621// indvar subst on anything more complex than an affine addrec, unless
622// it can be expanded to a trivial value.
623static bool isSafe(const SCEV *S, const Loop *L, ScalarEvolution *SE) {
624 // Loop-invariant values are safe.
625 if (SE->isLoopInvariant(S, L)) return true;
626
627 // Affine addrecs are safe. Non-affine are not, because LSR doesn't know how
628 // to transform them into efficient code.
629 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
630 return AR->isAffine();
631
632 // An add is safe it all its operands are safe.
633 if (const SCEVCommutativeExpr *Commutative = dyn_cast<SCEVCommutativeExpr>(S)) {
634 for (SCEVCommutativeExpr::op_iterator I = Commutative->op_begin(),
635 E = Commutative->op_end(); I != E; ++I)
636 if (!isSafe(*I, L, SE)) return false;
637 return true;
638 }
639
640 // A cast is safe if its operand is.
641 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
642 return isSafe(C->getOperand(), L, SE);
643
644 // A udiv is safe if its operands are.
645 if (const SCEVUDivExpr *UD = dyn_cast<SCEVUDivExpr>(S))
646 return isSafe(UD->getLHS(), L, SE) &&
647 isSafe(UD->getRHS(), L, SE);
648
649 // SCEVUnknown is always safe.
650 if (isa<SCEVUnknown>(S))
651 return true;
652
653 // Nothing else is safe.
654 return false;
655}
656
657void IndVarSimplify::RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter) {
658 // Rewrite all induction variable expressions in terms of the canonical
659 // induction variable.
660 //
661 // If there were induction variables of other sizes or offsets, manually
662 // add the offsets to the primary induction variable and cast, avoiding
663 // the need for the code evaluation methods to insert induction variables
664 // of different sizes.
665 for (IVUsers::iterator UI = IU->begin(), E = IU->end(); UI != E; ++UI) {
666 Value *Op = UI->getOperandValToReplace();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000667 Type *UseTy = Op->getType();
Andrew Trick1a54bb22011-07-12 00:08:50 +0000668 Instruction *User = UI->getUser();
669
670 // Compute the final addrec to expand into code.
671 const SCEV *AR = IU->getReplacementExpr(*UI);
672
673 // Evaluate the expression out of the loop, if possible.
674 if (!L->contains(UI->getUser())) {
675 const SCEV *ExitVal = SE->getSCEVAtScope(AR, L->getParentLoop());
676 if (SE->isLoopInvariant(ExitVal, L))
677 AR = ExitVal;
678 }
679
680 // FIXME: It is an extremely bad idea to indvar substitute anything more
681 // complex than affine induction variables. Doing so will put expensive
682 // polynomial evaluations inside of the loop, and the str reduction pass
683 // currently can only reduce affine polynomials. For now just disable
684 // indvar subst on anything more complex than an affine addrec, unless
685 // it can be expanded to a trivial value.
686 if (!isSafe(AR, L, SE))
687 continue;
688
689 // Determine the insertion point for this user. By default, insert
690 // immediately before the user. The SCEVExpander class will automatically
691 // hoist loop invariants out of the loop. For PHI nodes, there may be
692 // multiple uses, so compute the nearest common dominator for the
693 // incoming blocks.
Andrew Trick86c98142011-07-20 05:32:06 +0000694 Instruction *InsertPt = getInsertPointForUses(User, Op, DT);
Andrew Trick1a54bb22011-07-12 00:08:50 +0000695
696 // Now expand it into actual Instructions and patch it into place.
697 Value *NewVal = Rewriter.expandCodeFor(AR, UseTy, InsertPt);
698
699 DEBUG(dbgs() << "INDVARS: Rewrote IV '" << *AR << "' " << *Op << '\n'
700 << " into = " << *NewVal << "\n");
701
702 if (!isValidRewrite(Op, NewVal)) {
703 DeadInsts.push_back(NewVal);
704 continue;
705 }
706 // Inform ScalarEvolution that this value is changing. The change doesn't
707 // affect its value, but it does potentially affect which use lists the
708 // value will be on after the replacement, which affects ScalarEvolution's
709 // ability to walk use lists and drop dangling pointers when a value is
710 // deleted.
711 SE->forgetValue(User);
712
713 // Patch the new value into place.
714 if (Op->hasName())
715 NewVal->takeName(Op);
716 if (Instruction *NewValI = dyn_cast<Instruction>(NewVal))
717 NewValI->setDebugLoc(User->getDebugLoc());
718 User->replaceUsesOfWith(Op, NewVal);
719 UI->setOperandValToReplace(NewVal);
720
721 ++NumRemoved;
722 Changed = true;
723
724 // The old value may be dead now.
725 DeadInsts.push_back(Op);
726 }
727}
728
729//===----------------------------------------------------------------------===//
730// IV Widening - Extend the width of an IV to cover its widest uses.
731//===----------------------------------------------------------------------===//
732
Andrew Trickf85092c2011-05-20 18:25:42 +0000733namespace {
734 // Collect information about induction variables that are used by sign/zero
735 // extend operations. This information is recorded by CollectExtend and
736 // provides the input to WidenIV.
737 struct WideIVInfo {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000738 Type *WidestNativeType; // Widest integer type created [sz]ext
Andrew Trick4b4bb712011-08-10 03:46:27 +0000739 bool IsSigned; // Was an sext user seen before a zext?
Andrew Trickf85092c2011-05-20 18:25:42 +0000740
741 WideIVInfo() : WidestNativeType(0), IsSigned(false) {}
742 };
Andrew Trick4b4bb712011-08-10 03:46:27 +0000743
744 class WideIVVisitor : public IVVisitor {
745 ScalarEvolution *SE;
746 const TargetData *TD;
747
748 public:
749 WideIVInfo WI;
750
751 WideIVVisitor(ScalarEvolution *SCEV, const TargetData *TData) :
752 SE(SCEV), TD(TData) {}
753
754 // Implement the interface used by simplifyUsersOfIV.
755 virtual void visitCast(CastInst *Cast);
756 };
Andrew Trickf85092c2011-05-20 18:25:42 +0000757}
758
Andrew Trick4b4bb712011-08-10 03:46:27 +0000759/// visitCast - Update information about the induction variable that is
Andrew Trickf85092c2011-05-20 18:25:42 +0000760/// extended by this sign or zero extend operation. This is used to determine
761/// the final width of the IV before actually widening it.
Andrew Trick4b4bb712011-08-10 03:46:27 +0000762void WideIVVisitor::visitCast(CastInst *Cast) {
763 bool IsSigned = Cast->getOpcode() == Instruction::SExt;
764 if (!IsSigned && Cast->getOpcode() != Instruction::ZExt)
765 return;
766
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000767 Type *Ty = Cast->getType();
Andrew Trickf85092c2011-05-20 18:25:42 +0000768 uint64_t Width = SE->getTypeSizeInBits(Ty);
769 if (TD && !TD->isLegalInteger(Width))
770 return;
771
Andrew Trick2fabd462011-06-21 03:22:38 +0000772 if (!WI.WidestNativeType) {
773 WI.WidestNativeType = SE->getEffectiveSCEVType(Ty);
774 WI.IsSigned = IsSigned;
Andrew Trickf85092c2011-05-20 18:25:42 +0000775 return;
776 }
777
778 // We extend the IV to satisfy the sign of its first user, arbitrarily.
Andrew Trick2fabd462011-06-21 03:22:38 +0000779 if (WI.IsSigned != IsSigned)
Andrew Trickf85092c2011-05-20 18:25:42 +0000780 return;
781
Andrew Trick2fabd462011-06-21 03:22:38 +0000782 if (Width > SE->getTypeSizeInBits(WI.WidestNativeType))
783 WI.WidestNativeType = SE->getEffectiveSCEVType(Ty);
Andrew Trickf85092c2011-05-20 18:25:42 +0000784}
785
786namespace {
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000787
788/// NarrowIVDefUse - Record a link in the Narrow IV def-use chain along with the
789/// WideIV that computes the same value as the Narrow IV def. This avoids
790/// caching Use* pointers.
791struct NarrowIVDefUse {
792 Instruction *NarrowDef;
793 Instruction *NarrowUse;
794 Instruction *WideDef;
795
796 NarrowIVDefUse(): NarrowDef(0), NarrowUse(0), WideDef(0) {}
797
798 NarrowIVDefUse(Instruction *ND, Instruction *NU, Instruction *WD):
799 NarrowDef(ND), NarrowUse(NU), WideDef(WD) {}
800};
801
Andrew Trickf85092c2011-05-20 18:25:42 +0000802/// WidenIV - The goal of this transform is to remove sign and zero extends
803/// without creating any new induction variables. To do this, it creates a new
804/// phi of the wider type and redirects all users, either removing extends or
805/// inserting truncs whenever we stop propagating the type.
806///
807class WidenIV {
Andrew Trick2fabd462011-06-21 03:22:38 +0000808 // Parameters
Andrew Trickf85092c2011-05-20 18:25:42 +0000809 PHINode *OrigPhi;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000810 Type *WideType;
Andrew Trickf85092c2011-05-20 18:25:42 +0000811 bool IsSigned;
812
Andrew Trick2fabd462011-06-21 03:22:38 +0000813 // Context
814 LoopInfo *LI;
815 Loop *L;
Andrew Trickf85092c2011-05-20 18:25:42 +0000816 ScalarEvolution *SE;
Andrew Trick2fabd462011-06-21 03:22:38 +0000817 DominatorTree *DT;
Andrew Trickf85092c2011-05-20 18:25:42 +0000818
Andrew Trick2fabd462011-06-21 03:22:38 +0000819 // Result
Andrew Trickf85092c2011-05-20 18:25:42 +0000820 PHINode *WidePhi;
821 Instruction *WideInc;
822 const SCEV *WideIncExpr;
Andrew Trick2fabd462011-06-21 03:22:38 +0000823 SmallVectorImpl<WeakVH> &DeadInsts;
Andrew Trickf85092c2011-05-20 18:25:42 +0000824
Andrew Trick2fabd462011-06-21 03:22:38 +0000825 SmallPtrSet<Instruction*,16> Widened;
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000826 SmallVector<NarrowIVDefUse, 8> NarrowIVUsers;
Andrew Trickf85092c2011-05-20 18:25:42 +0000827
828public:
Andrew Trick2fabd462011-06-21 03:22:38 +0000829 WidenIV(PHINode *PN, const WideIVInfo &WI, LoopInfo *LInfo,
830 ScalarEvolution *SEv, DominatorTree *DTree,
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000831 SmallVectorImpl<WeakVH> &DI) :
Andrew Trickf85092c2011-05-20 18:25:42 +0000832 OrigPhi(PN),
Andrew Trick2fabd462011-06-21 03:22:38 +0000833 WideType(WI.WidestNativeType),
834 IsSigned(WI.IsSigned),
Andrew Trickf85092c2011-05-20 18:25:42 +0000835 LI(LInfo),
836 L(LI->getLoopFor(OrigPhi->getParent())),
837 SE(SEv),
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000838 DT(DTree),
Andrew Trickf85092c2011-05-20 18:25:42 +0000839 WidePhi(0),
840 WideInc(0),
Andrew Trick2fabd462011-06-21 03:22:38 +0000841 WideIncExpr(0),
842 DeadInsts(DI) {
Andrew Trickf85092c2011-05-20 18:25:42 +0000843 assert(L->getHeader() == OrigPhi->getParent() && "Phi must be an IV");
844 }
845
Andrew Trick2fabd462011-06-21 03:22:38 +0000846 PHINode *CreateWideIV(SCEVExpander &Rewriter);
Andrew Trickf85092c2011-05-20 18:25:42 +0000847
848protected:
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000849 Instruction *CloneIVUser(NarrowIVDefUse DU);
Andrew Trickf85092c2011-05-20 18:25:42 +0000850
Andrew Tricke0dc2fa2011-07-05 18:19:39 +0000851 const SCEVAddRecExpr *GetWideRecurrence(Instruction *NarrowUse);
852
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000853 Instruction *WidenIVUse(NarrowIVDefUse DU);
Andrew Trick4b029152011-07-02 02:34:25 +0000854
855 void pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef);
Andrew Trickf85092c2011-05-20 18:25:42 +0000856};
857} // anonymous namespace
858
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000859static Value *getExtend( Value *NarrowOper, Type *WideType,
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000860 bool IsSigned, IRBuilder<> &Builder) {
861 return IsSigned ? Builder.CreateSExt(NarrowOper, WideType) :
862 Builder.CreateZExt(NarrowOper, WideType);
Andrew Trickf85092c2011-05-20 18:25:42 +0000863}
864
865/// CloneIVUser - Instantiate a wide operation to replace a narrow
866/// operation. This only needs to handle operations that can evaluation to
867/// SCEVAddRec. It can safely return 0 for any operation we decide not to clone.
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000868Instruction *WidenIV::CloneIVUser(NarrowIVDefUse DU) {
869 unsigned Opcode = DU.NarrowUse->getOpcode();
Andrew Trickf85092c2011-05-20 18:25:42 +0000870 switch (Opcode) {
871 default:
872 return 0;
873 case Instruction::Add:
874 case Instruction::Mul:
875 case Instruction::UDiv:
876 case Instruction::Sub:
877 case Instruction::And:
878 case Instruction::Or:
879 case Instruction::Xor:
880 case Instruction::Shl:
881 case Instruction::LShr:
882 case Instruction::AShr:
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000883 DEBUG(dbgs() << "Cloning IVUser: " << *DU.NarrowUse << "\n");
Andrew Trickf85092c2011-05-20 18:25:42 +0000884
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000885 IRBuilder<> Builder(DU.NarrowUse);
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000886
887 // Replace NarrowDef operands with WideDef. Otherwise, we don't know
888 // anything about the narrow operand yet so must insert a [sz]ext. It is
889 // probably loop invariant and will be folded or hoisted. If it actually
890 // comes from a widened IV, it should be removed during a future call to
891 // WidenIVUse.
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000892 Value *LHS = (DU.NarrowUse->getOperand(0) == DU.NarrowDef) ? DU.WideDef :
893 getExtend(DU.NarrowUse->getOperand(0), WideType, IsSigned, Builder);
894 Value *RHS = (DU.NarrowUse->getOperand(1) == DU.NarrowDef) ? DU.WideDef :
895 getExtend(DU.NarrowUse->getOperand(1), WideType, IsSigned, Builder);
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000896
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000897 BinaryOperator *NarrowBO = cast<BinaryOperator>(DU.NarrowUse);
Andrew Trickf85092c2011-05-20 18:25:42 +0000898 BinaryOperator *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(),
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000899 LHS, RHS,
Andrew Trickf85092c2011-05-20 18:25:42 +0000900 NarrowBO->getName());
Andrew Trickf85092c2011-05-20 18:25:42 +0000901 Builder.Insert(WideBO);
Andrew Trick6e0ce242011-06-30 19:02:17 +0000902 if (const OverflowingBinaryOperator *OBO =
903 dyn_cast<OverflowingBinaryOperator>(NarrowBO)) {
904 if (OBO->hasNoUnsignedWrap()) WideBO->setHasNoUnsignedWrap();
905 if (OBO->hasNoSignedWrap()) WideBO->setHasNoSignedWrap();
906 }
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000907 return WideBO;
Andrew Trickf85092c2011-05-20 18:25:42 +0000908 }
909 llvm_unreachable(0);
910}
911
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000912/// HoistStep - Attempt to hoist an IV increment above a potential use.
913///
914/// To successfully hoist, two criteria must be met:
915/// - IncV operands dominate InsertPos and
916/// - InsertPos dominates IncV
917///
918/// Meeting the second condition means that we don't need to check all of IncV's
919/// existing uses (it's moving up in the domtree).
920///
921/// This does not yet recursively hoist the operands, although that would
922/// not be difficult.
923static bool HoistStep(Instruction *IncV, Instruction *InsertPos,
924 const DominatorTree *DT)
925{
926 if (DT->dominates(IncV, InsertPos))
927 return true;
928
929 if (!DT->dominates(InsertPos->getParent(), IncV->getParent()))
930 return false;
931
932 if (IncV->mayHaveSideEffects())
933 return false;
934
935 // Attempt to hoist IncV
936 for (User::op_iterator OI = IncV->op_begin(), OE = IncV->op_end();
937 OI != OE; ++OI) {
938 Instruction *OInst = dyn_cast<Instruction>(OI);
939 if (OInst && !DT->dominates(OInst, InsertPos))
940 return false;
941 }
942 IncV->moveBefore(InsertPos);
943 return true;
944}
945
Andrew Tricke0dc2fa2011-07-05 18:19:39 +0000946// GetWideRecurrence - Is this instruction potentially interesting from IVUsers'
947// perspective after widening it's type? In other words, can the extend be
948// safely hoisted out of the loop with SCEV reducing the value to a recurrence
949// on the same loop. If so, return the sign or zero extended
950// recurrence. Otherwise return NULL.
951const SCEVAddRecExpr *WidenIV::GetWideRecurrence(Instruction *NarrowUse) {
952 if (!SE->isSCEVable(NarrowUse->getType()))
953 return 0;
954
955 const SCEV *NarrowExpr = SE->getSCEV(NarrowUse);
956 if (SE->getTypeSizeInBits(NarrowExpr->getType())
957 >= SE->getTypeSizeInBits(WideType)) {
958 // NarrowUse implicitly widens its operand. e.g. a gep with a narrow
959 // index. So don't follow this use.
960 return 0;
961 }
962
963 const SCEV *WideExpr = IsSigned ?
964 SE->getSignExtendExpr(NarrowExpr, WideType) :
965 SE->getZeroExtendExpr(NarrowExpr, WideType);
966 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(WideExpr);
967 if (!AddRec || AddRec->getLoop() != L)
968 return 0;
969
970 return AddRec;
971}
972
Andrew Trickf85092c2011-05-20 18:25:42 +0000973/// WidenIVUse - Determine whether an individual user of the narrow IV can be
974/// widened. If so, return the wide clone of the user.
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000975Instruction *WidenIV::WidenIVUse(NarrowIVDefUse DU) {
Andrew Trickcc359d92011-06-29 23:03:57 +0000976
Andrew Trick4b029152011-07-02 02:34:25 +0000977 // Stop traversing the def-use chain at inner-loop phis or post-loop phis.
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000978 if (isa<PHINode>(DU.NarrowUse) &&
979 LI->getLoopFor(DU.NarrowUse->getParent()) != L)
Andrew Trickf85092c2011-05-20 18:25:42 +0000980 return 0;
981
Andrew Trickf85092c2011-05-20 18:25:42 +0000982 // Our raison d'etre! Eliminate sign and zero extension.
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000983 if (IsSigned ? isa<SExtInst>(DU.NarrowUse) : isa<ZExtInst>(DU.NarrowUse)) {
984 Value *NewDef = DU.WideDef;
985 if (DU.NarrowUse->getType() != WideType) {
986 unsigned CastWidth = SE->getTypeSizeInBits(DU.NarrowUse->getType());
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000987 unsigned IVWidth = SE->getTypeSizeInBits(WideType);
988 if (CastWidth < IVWidth) {
989 // The cast isn't as wide as the IV, so insert a Trunc.
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000990 IRBuilder<> Builder(DU.NarrowUse);
991 NewDef = Builder.CreateTrunc(DU.WideDef, DU.NarrowUse->getType());
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000992 }
993 else {
994 // A wider extend was hidden behind a narrower one. This may induce
995 // another round of IV widening in which the intermediate IV becomes
996 // dead. It should be very rare.
997 DEBUG(dbgs() << "INDVARS: New IV " << *WidePhi
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000998 << " not wide enough to subsume " << *DU.NarrowUse << "\n");
999 DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef);
1000 NewDef = DU.NarrowUse;
Andrew Trick03d3d3b2011-05-25 04:42:22 +00001001 }
1002 }
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001003 if (NewDef != DU.NarrowUse) {
1004 DEBUG(dbgs() << "INDVARS: eliminating " << *DU.NarrowUse
1005 << " replaced by " << *DU.WideDef << "\n");
Andrew Trick03d3d3b2011-05-25 04:42:22 +00001006 ++NumElimExt;
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001007 DU.NarrowUse->replaceAllUsesWith(NewDef);
1008 DeadInsts.push_back(DU.NarrowUse);
Andrew Trick03d3d3b2011-05-25 04:42:22 +00001009 }
Andrew Trick2fabd462011-06-21 03:22:38 +00001010 // Now that the extend is gone, we want to expose it's uses for potential
1011 // further simplification. We don't need to directly inform SimplifyIVUsers
1012 // of the new users, because their parent IV will be processed later as a
1013 // new loop phi. If we preserved IVUsers analysis, we would also want to
1014 // push the uses of WideDef here.
Andrew Trickf85092c2011-05-20 18:25:42 +00001015
1016 // No further widening is needed. The deceased [sz]ext had done it for us.
1017 return 0;
1018 }
Andrew Trick4b029152011-07-02 02:34:25 +00001019
1020 // Does this user itself evaluate to a recurrence after widening?
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001021 const SCEVAddRecExpr *WideAddRec = GetWideRecurrence(DU.NarrowUse);
Andrew Trickf85092c2011-05-20 18:25:42 +00001022 if (!WideAddRec) {
1023 // This user does not evaluate to a recurence after widening, so don't
1024 // follow it. Instead insert a Trunc to kill off the original use,
1025 // eventually isolating the original narrow IV so it can be removed.
Andrew Trick86c98142011-07-20 05:32:06 +00001026 IRBuilder<> Builder(getInsertPointForUses(DU.NarrowUse, DU.NarrowDef, DT));
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001027 Value *Trunc = Builder.CreateTrunc(DU.WideDef, DU.NarrowDef->getType());
1028 DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, Trunc);
Andrew Trickf85092c2011-05-20 18:25:42 +00001029 return 0;
1030 }
Andrew Trickfc933c02011-07-18 20:32:31 +00001031 // Assume block terminators cannot evaluate to a recurrence. We can't to
Andrew Trick4b029152011-07-02 02:34:25 +00001032 // insert a Trunc after a terminator if there happens to be a critical edge.
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001033 assert(DU.NarrowUse != DU.NarrowUse->getParent()->getTerminator() &&
Andrew Trick4b029152011-07-02 02:34:25 +00001034 "SCEV is not expected to evaluate a block terminator");
Andrew Trickcc359d92011-06-29 23:03:57 +00001035
Andrew Trickfcdc9a42011-05-26 00:46:11 +00001036 // Reuse the IV increment that SCEVExpander created as long as it dominates
1037 // NarrowUse.
Andrew Trickf85092c2011-05-20 18:25:42 +00001038 Instruction *WideUse = 0;
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001039 if (WideAddRec == WideIncExpr && HoistStep(WideInc, DU.NarrowUse, DT)) {
Andrew Trickf85092c2011-05-20 18:25:42 +00001040 WideUse = WideInc;
1041 }
1042 else {
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001043 WideUse = CloneIVUser(DU);
Andrew Trickf85092c2011-05-20 18:25:42 +00001044 if (!WideUse)
1045 return 0;
1046 }
Andrew Trick4b029152011-07-02 02:34:25 +00001047 // Evaluation of WideAddRec ensured that the narrow expression could be
1048 // extended outside the loop without overflow. This suggests that the wide use
Andrew Trickf85092c2011-05-20 18:25:42 +00001049 // evaluates to the same expression as the extended narrow use, but doesn't
1050 // absolutely guarantee it. Hence the following failsafe check. In rare cases
Andrew Trick2fabd462011-06-21 03:22:38 +00001051 // where it fails, we simply throw away the newly created wide use.
Andrew Trickf85092c2011-05-20 18:25:42 +00001052 if (WideAddRec != SE->getSCEV(WideUse)) {
1053 DEBUG(dbgs() << "Wide use expression mismatch: " << *WideUse
1054 << ": " << *SE->getSCEV(WideUse) << " != " << *WideAddRec << "\n");
1055 DeadInsts.push_back(WideUse);
1056 return 0;
1057 }
1058
1059 // Returning WideUse pushes it on the worklist.
1060 return WideUse;
1061}
1062
Andrew Trick4b029152011-07-02 02:34:25 +00001063/// pushNarrowIVUsers - Add eligible users of NarrowDef to NarrowIVUsers.
1064///
1065void WidenIV::pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef) {
1066 for (Value::use_iterator UI = NarrowDef->use_begin(),
1067 UE = NarrowDef->use_end(); UI != UE; ++UI) {
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001068 Instruction *NarrowUse = cast<Instruction>(*UI);
Andrew Trick4b029152011-07-02 02:34:25 +00001069
1070 // Handle data flow merges and bizarre phi cycles.
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001071 if (!Widened.insert(NarrowUse))
Andrew Trick4b029152011-07-02 02:34:25 +00001072 continue;
1073
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001074 NarrowIVUsers.push_back(NarrowIVDefUse(NarrowDef, NarrowUse, WideDef));
Andrew Trick4b029152011-07-02 02:34:25 +00001075 }
1076}
1077
Andrew Trickf85092c2011-05-20 18:25:42 +00001078/// CreateWideIV - Process a single induction variable. First use the
1079/// SCEVExpander to create a wide induction variable that evaluates to the same
1080/// recurrence as the original narrow IV. Then use a worklist to forward
Andrew Trick2fabd462011-06-21 03:22:38 +00001081/// traverse the narrow IV's def-use chain. After WidenIVUse has processed all
Andrew Trickf85092c2011-05-20 18:25:42 +00001082/// interesting IV users, the narrow IV will be isolated for removal by
1083/// DeleteDeadPHIs.
1084///
1085/// It would be simpler to delete uses as they are processed, but we must avoid
1086/// invalidating SCEV expressions.
1087///
Andrew Trick2fabd462011-06-21 03:22:38 +00001088PHINode *WidenIV::CreateWideIV(SCEVExpander &Rewriter) {
Andrew Trickf85092c2011-05-20 18:25:42 +00001089 // Is this phi an induction variable?
1090 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(OrigPhi));
1091 if (!AddRec)
Andrew Trick2fabd462011-06-21 03:22:38 +00001092 return NULL;
Andrew Trickf85092c2011-05-20 18:25:42 +00001093
1094 // Widen the induction variable expression.
1095 const SCEV *WideIVExpr = IsSigned ?
1096 SE->getSignExtendExpr(AddRec, WideType) :
1097 SE->getZeroExtendExpr(AddRec, WideType);
1098
1099 assert(SE->getEffectiveSCEVType(WideIVExpr->getType()) == WideType &&
1100 "Expect the new IV expression to preserve its type");
1101
1102 // Can the IV be extended outside the loop without overflow?
1103 AddRec = dyn_cast<SCEVAddRecExpr>(WideIVExpr);
1104 if (!AddRec || AddRec->getLoop() != L)
Andrew Trick2fabd462011-06-21 03:22:38 +00001105 return NULL;
Andrew Trickf85092c2011-05-20 18:25:42 +00001106
Andrew Trick2fabd462011-06-21 03:22:38 +00001107 // An AddRec must have loop-invariant operands. Since this AddRec is
Andrew Trickf85092c2011-05-20 18:25:42 +00001108 // materialized by a loop header phi, the expression cannot have any post-loop
1109 // operands, so they must dominate the loop header.
1110 assert(SE->properlyDominates(AddRec->getStart(), L->getHeader()) &&
1111 SE->properlyDominates(AddRec->getStepRecurrence(*SE), L->getHeader())
1112 && "Loop header phi recurrence inputs do not dominate the loop");
1113
1114 // The rewriter provides a value for the desired IV expression. This may
1115 // either find an existing phi or materialize a new one. Either way, we
1116 // expect a well-formed cyclic phi-with-increments. i.e. any operand not part
1117 // of the phi-SCC dominates the loop entry.
1118 Instruction *InsertPt = L->getHeader()->begin();
1119 WidePhi = cast<PHINode>(Rewriter.expandCodeFor(AddRec, WideType, InsertPt));
1120
1121 // Remembering the WideIV increment generated by SCEVExpander allows
1122 // WidenIVUse to reuse it when widening the narrow IV's increment. We don't
1123 // employ a general reuse mechanism because the call above is the only call to
1124 // SCEVExpander. Henceforth, we produce 1-to-1 narrow to wide uses.
Andrew Trickfcdc9a42011-05-26 00:46:11 +00001125 if (BasicBlock *LatchBlock = L->getLoopLatch()) {
1126 WideInc =
1127 cast<Instruction>(WidePhi->getIncomingValueForBlock(LatchBlock));
1128 WideIncExpr = SE->getSCEV(WideInc);
1129 }
Andrew Trickf85092c2011-05-20 18:25:42 +00001130
1131 DEBUG(dbgs() << "Wide IV: " << *WidePhi << "\n");
1132 ++NumWidened;
1133
1134 // Traverse the def-use chain using a worklist starting at the original IV.
Andrew Trick4b029152011-07-02 02:34:25 +00001135 assert(Widened.empty() && NarrowIVUsers.empty() && "expect initial state" );
Andrew Trickf85092c2011-05-20 18:25:42 +00001136
Andrew Trick4b029152011-07-02 02:34:25 +00001137 Widened.insert(OrigPhi);
1138 pushNarrowIVUsers(OrigPhi, WidePhi);
1139
Andrew Trickf85092c2011-05-20 18:25:42 +00001140 while (!NarrowIVUsers.empty()) {
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001141 NarrowIVDefUse DU = NarrowIVUsers.pop_back_val();
Andrew Trickf85092c2011-05-20 18:25:42 +00001142
Andrew Trickfcdc9a42011-05-26 00:46:11 +00001143 // Process a def-use edge. This may replace the use, so don't hold a
1144 // use_iterator across it.
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001145 Instruction *WideUse = WidenIVUse(DU);
Andrew Trickf85092c2011-05-20 18:25:42 +00001146
Andrew Trickfcdc9a42011-05-26 00:46:11 +00001147 // Follow all def-use edges from the previous narrow use.
Andrew Trick4b029152011-07-02 02:34:25 +00001148 if (WideUse)
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001149 pushNarrowIVUsers(DU.NarrowUse, WideUse);
Andrew Trick4b029152011-07-02 02:34:25 +00001150
Andrew Trickfcdc9a42011-05-26 00:46:11 +00001151 // WidenIVUse may have removed the def-use edge.
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001152 if (DU.NarrowDef->use_empty())
1153 DeadInsts.push_back(DU.NarrowDef);
Andrew Trickf85092c2011-05-20 18:25:42 +00001154 }
Andrew Trick2fabd462011-06-21 03:22:38 +00001155 return WidePhi;
Andrew Trickf85092c2011-05-20 18:25:42 +00001156}
1157
Andrew Trick1a54bb22011-07-12 00:08:50 +00001158//===----------------------------------------------------------------------===//
1159// Simplification of IV users based on SCEV evaluation.
1160//===----------------------------------------------------------------------===//
1161
Andrew Trickaeee4612011-05-12 00:04:28 +00001162
Andrew Trick4b4bb712011-08-10 03:46:27 +00001163/// SimplifyAndExtend - Iteratively perform simplification on a worklist of IV
1164/// users. Each successive simplification may push more users which may
Andrew Trick2fabd462011-06-21 03:22:38 +00001165/// themselves be candidates for simplification.
1166///
Andrew Trick4b4bb712011-08-10 03:46:27 +00001167/// Sign/Zero extend elimination is interleaved with IV simplification.
Andrew Trick2fabd462011-06-21 03:22:38 +00001168///
Andrew Trick4b4bb712011-08-10 03:46:27 +00001169void IndVarSimplify::SimplifyAndExtend(Loop *L,
1170 SCEVExpander &Rewriter,
1171 LPPassManager &LPM) {
Andrew Trick15832f62011-06-28 02:49:20 +00001172 std::map<PHINode *, WideIVInfo> WideIVMap;
1173
Andrew Trick2fabd462011-06-21 03:22:38 +00001174 SmallVector<PHINode*, 8> LoopPhis;
1175 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
1176 LoopPhis.push_back(cast<PHINode>(I));
1177 }
Andrew Trick15832f62011-06-28 02:49:20 +00001178 // Each round of simplification iterates through the SimplifyIVUsers worklist
1179 // for all current phis, then determines whether any IVs can be
1180 // widened. Widening adds new phis to LoopPhis, inducing another round of
1181 // simplification on the wide IVs.
Andrew Trick2fabd462011-06-21 03:22:38 +00001182 while (!LoopPhis.empty()) {
Andrew Trick15832f62011-06-28 02:49:20 +00001183 // Evaluate as many IV expressions as possible before widening any IVs. This
Andrew Trick99a92f62011-06-28 16:45:04 +00001184 // forces SCEV to set no-wrap flags before evaluating sign/zero
Andrew Trick15832f62011-06-28 02:49:20 +00001185 // extension. The first time SCEV attempts to normalize sign/zero extension,
1186 // the result becomes final. So for the most predictable results, we delay
1187 // evaluation of sign/zero extend evaluation until needed, and avoid running
Andrew Trick4b4bb712011-08-10 03:46:27 +00001188 // other SCEV based analysis prior to SimplifyAndExtend.
Andrew Trick15832f62011-06-28 02:49:20 +00001189 do {
1190 PHINode *CurrIV = LoopPhis.pop_back_val();
Andrew Trick2fabd462011-06-21 03:22:38 +00001191
Andrew Trick15832f62011-06-28 02:49:20 +00001192 // Information about sign/zero extensions of CurrIV.
Andrew Trick4b4bb712011-08-10 03:46:27 +00001193 WideIVVisitor WIV(SE, TD);
Andrew Trick2fabd462011-06-21 03:22:38 +00001194
Andrew Trick4b4bb712011-08-10 03:46:27 +00001195 Changed |= simplifyUsersOfIV(CurrIV, &LPM, DeadInsts, &WIV);
Andrew Trick2fabd462011-06-21 03:22:38 +00001196
Andrew Trick4b4bb712011-08-10 03:46:27 +00001197 if (WIV.WI.WidestNativeType) {
1198 WideIVMap[CurrIV] = WIV.WI;
Andrew Trick2fabd462011-06-21 03:22:38 +00001199 }
Andrew Trick15832f62011-06-28 02:49:20 +00001200 } while(!LoopPhis.empty());
1201
1202 for (std::map<PHINode *, WideIVInfo>::const_iterator I = WideIVMap.begin(),
1203 E = WideIVMap.end(); I != E; ++I) {
1204 WidenIV Widener(I->first, I->second, LI, SE, DT, DeadInsts);
Andrew Trick2fabd462011-06-21 03:22:38 +00001205 if (PHINode *WidePhi = Widener.CreateWideIV(Rewriter)) {
1206 Changed = true;
1207 LoopPhis.push_back(WidePhi);
1208 }
1209 }
Andrew Trick15832f62011-06-28 02:49:20 +00001210 WideIVMap.clear();
Andrew Trick2fabd462011-06-21 03:22:38 +00001211 }
1212}
1213
Andrew Trick037d1c02011-07-06 20:50:43 +00001214/// SimplifyCongruentIVs - Check for congruent phis in this loop header and
Andrew Trick4b4bb712011-08-10 03:46:27 +00001215/// replace them with their chosen representative.
Andrew Trick037d1c02011-07-06 20:50:43 +00001216///
1217void IndVarSimplify::SimplifyCongruentIVs(Loop *L) {
Andrew Trick6f684b02011-07-16 01:06:48 +00001218 DenseMap<const SCEV *, PHINode *> ExprToIVMap;
Andrew Trick037d1c02011-07-06 20:50:43 +00001219 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
1220 PHINode *Phi = cast<PHINode>(I);
Andrew Trick1a54bb22011-07-12 00:08:50 +00001221 if (!SE->isSCEVable(Phi->getType()))
1222 continue;
1223
Andrew Trick037d1c02011-07-06 20:50:43 +00001224 const SCEV *S = SE->getSCEV(Phi);
Chris Lattnerc30a38f2011-07-21 06:21:31 +00001225 std::pair<DenseMap<const SCEV *, PHINode *>::const_iterator, bool> Tmp =
1226 ExprToIVMap.insert(std::make_pair(S, Phi));
1227 if (Tmp.second)
Andrew Trick037d1c02011-07-06 20:50:43 +00001228 continue;
Chris Lattnerc30a38f2011-07-21 06:21:31 +00001229 PHINode *OrigPhi = Tmp.first->second;
Andrew Trickf22d9572011-07-20 02:08:58 +00001230
1231 // If one phi derives from the other via GEPs, types may differ.
1232 if (OrigPhi->getType() != Phi->getType())
1233 continue;
1234
Andrew Trick037d1c02011-07-06 20:50:43 +00001235 // Replacing the congruent phi is sufficient because acyclic redundancy
1236 // elimination, CSE/GVN, should handle the rest. However, once SCEV proves
1237 // that a phi is congruent, it's almost certain to be the head of an IV
1238 // user cycle that is isomorphic with the original phi. So it's worth
1239 // eagerly cleaning up the common case of a single IV increment.
1240 if (BasicBlock *LatchBlock = L->getLoopLatch()) {
1241 Instruction *OrigInc =
1242 cast<Instruction>(OrigPhi->getIncomingValueForBlock(LatchBlock));
1243 Instruction *IsomorphicInc =
1244 cast<Instruction>(Phi->getIncomingValueForBlock(LatchBlock));
1245 if (OrigInc != IsomorphicInc &&
Andrew Trickf22d9572011-07-20 02:08:58 +00001246 OrigInc->getType() == IsomorphicInc->getType() &&
Andrew Trick037d1c02011-07-06 20:50:43 +00001247 SE->getSCEV(OrigInc) == SE->getSCEV(IsomorphicInc) &&
1248 HoistStep(OrigInc, IsomorphicInc, DT)) {
1249 DEBUG(dbgs() << "INDVARS: Eliminated congruent iv.inc: "
1250 << *IsomorphicInc << '\n');
1251 IsomorphicInc->replaceAllUsesWith(OrigInc);
1252 DeadInsts.push_back(IsomorphicInc);
1253 }
1254 }
1255 DEBUG(dbgs() << "INDVARS: Eliminated congruent iv: " << *Phi << '\n');
1256 ++NumElimIV;
1257 Phi->replaceAllUsesWith(OrigPhi);
1258 DeadInsts.push_back(Phi);
1259 }
1260}
1261
Andrew Trick1a54bb22011-07-12 00:08:50 +00001262//===----------------------------------------------------------------------===//
1263// LinearFunctionTestReplace and its kin. Rewrite the loop exit condition.
1264//===----------------------------------------------------------------------===//
1265
Andrew Trick5241b792011-07-18 18:21:35 +00001266// Check for expressions that ScalarEvolution generates to compute
1267// BackedgeTakenInfo. If these expressions have not been reduced, then expanding
1268// them may incur additional cost (albeit in the loop preheader).
1269static bool isHighCostExpansion(const SCEV *S, BranchInst *BI,
1270 ScalarEvolution *SE) {
1271 // If the backedge-taken count is a UDiv, it's very likely a UDiv that
1272 // ScalarEvolution's HowFarToZero or HowManyLessThans produced to compute a
1273 // precise expression, rather than a UDiv from the user's code. If we can't
1274 // find a UDiv in the code with some simple searching, assume the former and
1275 // forego rewriting the loop.
1276 if (isa<SCEVUDivExpr>(S)) {
1277 ICmpInst *OrigCond = dyn_cast<ICmpInst>(BI->getCondition());
1278 if (!OrigCond) return true;
1279 const SCEV *R = SE->getSCEV(OrigCond->getOperand(1));
1280 R = SE->getMinusSCEV(R, SE->getConstant(R->getType(), 1));
1281 if (R != S) {
1282 const SCEV *L = SE->getSCEV(OrigCond->getOperand(0));
1283 L = SE->getMinusSCEV(L, SE->getConstant(L->getType(), 1));
1284 if (L != S)
1285 return true;
1286 }
1287 }
1288
Andrew Trickfc933c02011-07-18 20:32:31 +00001289 if (!DisableIVRewrite || ForceLFTR)
Andrew Trick5241b792011-07-18 18:21:35 +00001290 return false;
1291
1292 // Recurse past add expressions, which commonly occur in the
1293 // BackedgeTakenCount. They may already exist in program code, and if not,
1294 // they are not too expensive rematerialize.
1295 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
1296 for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
1297 I != E; ++I) {
1298 if (isHighCostExpansion(*I, BI, SE))
1299 return true;
1300 }
1301 return false;
1302 }
1303
1304 // HowManyLessThans uses a Max expression whenever the loop is not guarded by
1305 // the exit condition.
1306 if (isa<SCEVSMaxExpr>(S) || isa<SCEVUMaxExpr>(S))
1307 return true;
1308
1309 // If we haven't recognized an expensive SCEV patter, assume its an expression
1310 // produced by program code.
1311 return false;
1312}
1313
Andrew Trick1a54bb22011-07-12 00:08:50 +00001314/// canExpandBackedgeTakenCount - Return true if this loop's backedge taken
1315/// count expression can be safely and cheaply expanded into an instruction
1316/// sequence that can be used by LinearFunctionTestReplace.
1317static bool canExpandBackedgeTakenCount(Loop *L, ScalarEvolution *SE) {
1318 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
1319 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount) ||
1320 BackedgeTakenCount->isZero())
1321 return false;
1322
1323 if (!L->getExitingBlock())
1324 return false;
1325
1326 // Can't rewrite non-branch yet.
1327 BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator());
1328 if (!BI)
1329 return false;
1330
Andrew Trick5241b792011-07-18 18:21:35 +00001331 if (isHighCostExpansion(BackedgeTakenCount, BI, SE))
1332 return false;
1333
Andrew Trick1a54bb22011-07-12 00:08:50 +00001334 return true;
1335}
1336
1337/// getBackedgeIVType - Get the widest type used by the loop test after peeking
1338/// through Truncs.
1339///
Andrew Trickfc933c02011-07-18 20:32:31 +00001340/// TODO: Unnecessary when ForceLFTR is removed.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001341static Type *getBackedgeIVType(Loop *L) {
Andrew Trick1a54bb22011-07-12 00:08:50 +00001342 if (!L->getExitingBlock())
1343 return 0;
1344
1345 // Can't rewrite non-branch yet.
1346 BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator());
1347 if (!BI)
1348 return 0;
1349
1350 ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition());
1351 if (!Cond)
1352 return 0;
1353
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001354 Type *Ty = 0;
Andrew Trick1a54bb22011-07-12 00:08:50 +00001355 for(User::op_iterator OI = Cond->op_begin(), OE = Cond->op_end();
1356 OI != OE; ++OI) {
1357 assert((!Ty || Ty == (*OI)->getType()) && "bad icmp operand types");
1358 TruncInst *Trunc = dyn_cast<TruncInst>(*OI);
1359 if (!Trunc)
1360 continue;
1361
1362 return Trunc->getSrcTy();
1363 }
1364 return Ty;
1365}
1366
Andrew Trickfc933c02011-07-18 20:32:31 +00001367/// isLoopInvariant - Perform a quick domtree based check for loop invariance
1368/// assuming that V is used within the loop. LoopInfo::isLoopInvariant() seems
1369/// gratuitous for this purpose.
1370static bool isLoopInvariant(Value *V, Loop *L, DominatorTree *DT) {
1371 Instruction *Inst = dyn_cast<Instruction>(V);
1372 if (!Inst)
1373 return true;
1374
1375 return DT->properlyDominates(Inst->getParent(), L->getHeader());
1376}
1377
1378/// getLoopPhiForCounter - Return the loop header phi IFF IncV adds a loop
1379/// invariant value to the phi.
1380static PHINode *getLoopPhiForCounter(Value *IncV, Loop *L, DominatorTree *DT) {
1381 Instruction *IncI = dyn_cast<Instruction>(IncV);
1382 if (!IncI)
1383 return 0;
1384
1385 switch (IncI->getOpcode()) {
1386 case Instruction::Add:
1387 case Instruction::Sub:
1388 break;
1389 case Instruction::GetElementPtr:
1390 // An IV counter must preserve its type.
1391 if (IncI->getNumOperands() == 2)
1392 break;
1393 default:
1394 return 0;
1395 }
1396
1397 PHINode *Phi = dyn_cast<PHINode>(IncI->getOperand(0));
1398 if (Phi && Phi->getParent() == L->getHeader()) {
1399 if (isLoopInvariant(IncI->getOperand(1), L, DT))
1400 return Phi;
1401 return 0;
1402 }
1403 if (IncI->getOpcode() == Instruction::GetElementPtr)
1404 return 0;
1405
1406 // Allow add/sub to be commuted.
1407 Phi = dyn_cast<PHINode>(IncI->getOperand(1));
1408 if (Phi && Phi->getParent() == L->getHeader()) {
1409 if (isLoopInvariant(IncI->getOperand(0), L, DT))
1410 return Phi;
1411 }
1412 return 0;
1413}
1414
1415/// needsLFTR - LinearFunctionTestReplace policy. Return true unless we can show
1416/// that the current exit test is already sufficiently canonical.
1417static bool needsLFTR(Loop *L, DominatorTree *DT) {
1418 assert(L->getExitingBlock() && "expected loop exit");
1419
1420 BasicBlock *LatchBlock = L->getLoopLatch();
1421 // Don't bother with LFTR if the loop is not properly simplified.
1422 if (!LatchBlock)
1423 return false;
1424
1425 BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator());
1426 assert(BI && "expected exit branch");
1427
1428 // Do LFTR to simplify the exit condition to an ICMP.
1429 ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition());
1430 if (!Cond)
1431 return true;
1432
1433 // Do LFTR to simplify the exit ICMP to EQ/NE
1434 ICmpInst::Predicate Pred = Cond->getPredicate();
1435 if (Pred != ICmpInst::ICMP_NE && Pred != ICmpInst::ICMP_EQ)
1436 return true;
1437
1438 // Look for a loop invariant RHS
1439 Value *LHS = Cond->getOperand(0);
1440 Value *RHS = Cond->getOperand(1);
1441 if (!isLoopInvariant(RHS, L, DT)) {
1442 if (!isLoopInvariant(LHS, L, DT))
1443 return true;
1444 std::swap(LHS, RHS);
1445 }
1446 // Look for a simple IV counter LHS
1447 PHINode *Phi = dyn_cast<PHINode>(LHS);
1448 if (!Phi)
1449 Phi = getLoopPhiForCounter(LHS, L, DT);
1450
1451 if (!Phi)
1452 return true;
1453
1454 // Do LFTR if the exit condition's IV is *not* a simple counter.
1455 Value *IncV = Phi->getIncomingValueForBlock(L->getLoopLatch());
1456 return Phi != getLoopPhiForCounter(IncV, L, DT);
1457}
1458
1459/// AlmostDeadIV - Return true if this IV has any uses other than the (soon to
1460/// be rewritten) loop exit test.
1461static bool AlmostDeadIV(PHINode *Phi, BasicBlock *LatchBlock, Value *Cond) {
1462 int LatchIdx = Phi->getBasicBlockIndex(LatchBlock);
1463 Value *IncV = Phi->getIncomingValue(LatchIdx);
1464
1465 for (Value::use_iterator UI = Phi->use_begin(), UE = Phi->use_end();
1466 UI != UE; ++UI) {
1467 if (*UI != Cond && *UI != IncV) return false;
1468 }
1469
1470 for (Value::use_iterator UI = IncV->use_begin(), UE = IncV->use_end();
1471 UI != UE; ++UI) {
1472 if (*UI != Cond && *UI != Phi) return false;
1473 }
1474 return true;
1475}
1476
1477/// FindLoopCounter - Find an affine IV in canonical form.
1478///
1479/// FIXME: Accept -1 stride and set IVLimit = IVInit - BECount
1480///
1481/// FIXME: Accept non-unit stride as long as SCEV can reduce BECount * Stride.
1482/// This is difficult in general for SCEV because of potential overflow. But we
1483/// could at least handle constant BECounts.
1484static PHINode *
1485FindLoopCounter(Loop *L, const SCEV *BECount,
1486 ScalarEvolution *SE, DominatorTree *DT, const TargetData *TD) {
1487 // I'm not sure how BECount could be a pointer type, but we definitely don't
1488 // want to LFTR that.
1489 if (BECount->getType()->isPointerTy())
1490 return 0;
1491
1492 uint64_t BCWidth = SE->getTypeSizeInBits(BECount->getType());
1493
1494 Value *Cond =
1495 cast<BranchInst>(L->getExitingBlock()->getTerminator())->getCondition();
1496
1497 // Loop over all of the PHI nodes, looking for a simple counter.
1498 PHINode *BestPhi = 0;
1499 const SCEV *BestInit = 0;
1500 BasicBlock *LatchBlock = L->getLoopLatch();
1501 assert(LatchBlock && "needsLFTR should guarantee a loop latch");
1502
1503 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
1504 PHINode *Phi = cast<PHINode>(I);
1505 if (!SE->isSCEVable(Phi->getType()))
1506 continue;
1507
1508 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Phi));
1509 if (!AR || AR->getLoop() != L || !AR->isAffine())
1510 continue;
1511
1512 // AR may be a pointer type, while BECount is an integer type.
1513 // AR may be wider than BECount. With eq/ne tests overflow is immaterial.
1514 // AR may not be a narrower type, or we may never exit.
1515 uint64_t PhiWidth = SE->getTypeSizeInBits(AR->getType());
1516 if (PhiWidth < BCWidth || (TD && !TD->isLegalInteger(PhiWidth)))
1517 continue;
1518
1519 const SCEV *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*SE));
1520 if (!Step || !Step->isOne())
1521 continue;
1522
1523 int LatchIdx = Phi->getBasicBlockIndex(LatchBlock);
1524 Value *IncV = Phi->getIncomingValue(LatchIdx);
1525 if (getLoopPhiForCounter(IncV, L, DT) != Phi)
1526 continue;
1527
1528 const SCEV *Init = AR->getStart();
1529
1530 if (BestPhi && !AlmostDeadIV(BestPhi, LatchBlock, Cond)) {
1531 // Don't force a live loop counter if another IV can be used.
1532 if (AlmostDeadIV(Phi, LatchBlock, Cond))
1533 continue;
1534
1535 // Prefer to count-from-zero. This is a more "canonical" counter form. It
1536 // also prefers integer to pointer IVs.
1537 if (BestInit->isZero() != Init->isZero()) {
1538 if (BestInit->isZero())
1539 continue;
1540 }
1541 // If two IVs both count from zero or both count from nonzero then the
1542 // narrower is likely a dead phi that has been widened. Use the wider phi
1543 // to allow the other to be eliminated.
1544 if (PhiWidth <= SE->getTypeSizeInBits(BestPhi->getType()))
1545 continue;
1546 }
1547 BestPhi = Phi;
1548 BestInit = Init;
1549 }
1550 return BestPhi;
1551}
1552
Andrew Trick1a54bb22011-07-12 00:08:50 +00001553/// LinearFunctionTestReplace - This method rewrites the exit condition of the
1554/// loop to be a canonical != comparison against the incremented loop induction
1555/// variable. This pass is able to rewrite the exit tests of any loop where the
1556/// SCEV analysis can determine a loop-invariant trip count of the loop, which
1557/// is actually a much broader range than just linear tests.
Andrew Trickfc933c02011-07-18 20:32:31 +00001558Value *IndVarSimplify::
Andrew Trick1a54bb22011-07-12 00:08:50 +00001559LinearFunctionTestReplace(Loop *L,
1560 const SCEV *BackedgeTakenCount,
1561 PHINode *IndVar,
1562 SCEVExpander &Rewriter) {
1563 assert(canExpandBackedgeTakenCount(L, SE) && "precondition");
1564 BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator());
1565
Andrew Trickfc933c02011-07-18 20:32:31 +00001566 // In DisableIVRewrite mode, IndVar is not necessarily a canonical IV. In this
1567 // mode, LFTR can ignore IV overflow and truncate to the width of
1568 // BECount. This avoids materializing the add(zext(add)) expression.
1569 Type *CntTy = DisableIVRewrite ?
1570 BackedgeTakenCount->getType() : IndVar->getType();
1571
1572 const SCEV *IVLimit = BackedgeTakenCount;
1573
Andrew Trick1a54bb22011-07-12 00:08:50 +00001574 // If the exiting block is not the same as the backedge block, we must compare
1575 // against the preincremented value, otherwise we prefer to compare against
1576 // the post-incremented value.
1577 Value *CmpIndVar;
Andrew Trick1a54bb22011-07-12 00:08:50 +00001578 if (L->getExitingBlock() == L->getLoopLatch()) {
1579 // Add one to the "backedge-taken" count to get the trip count.
1580 // If this addition may overflow, we have to be more pessimistic and
1581 // cast the induction variable before doing the add.
Andrew Trick1a54bb22011-07-12 00:08:50 +00001582 const SCEV *N =
Andrew Trickfc933c02011-07-18 20:32:31 +00001583 SE->getAddExpr(IVLimit, SE->getConstant(IVLimit->getType(), 1));
1584 if (CntTy == IVLimit->getType())
1585 IVLimit = N;
1586 else {
1587 const SCEV *Zero = SE->getConstant(IVLimit->getType(), 0);
1588 if ((isa<SCEVConstant>(N) && !N->isZero()) ||
1589 SE->isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) {
1590 // No overflow. Cast the sum.
1591 IVLimit = SE->getTruncateOrZeroExtend(N, CntTy);
1592 } else {
1593 // Potential overflow. Cast before doing the add.
1594 IVLimit = SE->getTruncateOrZeroExtend(IVLimit, CntTy);
1595 IVLimit = SE->getAddExpr(IVLimit, SE->getConstant(CntTy, 1));
1596 }
Andrew Trick1a54bb22011-07-12 00:08:50 +00001597 }
Andrew Trick1a54bb22011-07-12 00:08:50 +00001598 // The BackedgeTaken expression contains the number of times that the
1599 // backedge branches to the loop header. This is one less than the
1600 // number of times the loop executes, so use the incremented indvar.
1601 CmpIndVar = IndVar->getIncomingValueForBlock(L->getExitingBlock());
1602 } else {
1603 // We have to use the preincremented value...
Andrew Trickfc933c02011-07-18 20:32:31 +00001604 IVLimit = SE->getTruncateOrZeroExtend(IVLimit, CntTy);
Andrew Trick1a54bb22011-07-12 00:08:50 +00001605 CmpIndVar = IndVar;
1606 }
1607
Andrew Trickfc933c02011-07-18 20:32:31 +00001608 // For unit stride, IVLimit = Start + BECount with 2's complement overflow.
1609 // So for, non-zero start compute the IVLimit here.
1610 bool isPtrIV = false;
1611 Type *CmpTy = CntTy;
1612 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(IndVar));
1613 assert(AR && AR->getLoop() == L && AR->isAffine() && "bad loop counter");
1614 if (!AR->getStart()->isZero()) {
1615 assert(AR->getStepRecurrence(*SE)->isOne() && "only handles unit stride");
1616 const SCEV *IVInit = AR->getStart();
1617
1618 // For pointer types, sign extend BECount in order to materialize a GEP.
1619 // Note that for DisableIVRewrite, we never run SCEVExpander on a
1620 // pointer type, because we must preserve the existing GEPs. Instead we
1621 // directly generate a GEP later.
1622 if (IVInit->getType()->isPointerTy()) {
1623 isPtrIV = true;
1624 CmpTy = SE->getEffectiveSCEVType(IVInit->getType());
1625 IVLimit = SE->getTruncateOrSignExtend(IVLimit, CmpTy);
1626 }
1627 // For integer types, truncate the IV before computing IVInit + BECount.
1628 else {
1629 if (SE->getTypeSizeInBits(IVInit->getType())
1630 > SE->getTypeSizeInBits(CmpTy))
1631 IVInit = SE->getTruncateExpr(IVInit, CmpTy);
1632
1633 IVLimit = SE->getAddExpr(IVInit, IVLimit);
1634 }
1635 }
Andrew Trick1a54bb22011-07-12 00:08:50 +00001636 // Expand the code for the iteration count.
Andrew Trickfc933c02011-07-18 20:32:31 +00001637 IRBuilder<> Builder(BI);
1638
1639 assert(SE->isLoopInvariant(IVLimit, L) &&
Andrew Trick1a54bb22011-07-12 00:08:50 +00001640 "Computed iteration count is not loop invariant!");
Andrew Trickfc933c02011-07-18 20:32:31 +00001641 Value *ExitCnt = Rewriter.expandCodeFor(IVLimit, CmpTy, BI);
1642
1643 // Create a gep for IVInit + IVLimit from on an existing pointer base.
1644 assert(isPtrIV == IndVar->getType()->isPointerTy() &&
1645 "IndVar type must match IVInit type");
1646 if (isPtrIV) {
1647 Value *IVStart = IndVar->getIncomingValueForBlock(L->getLoopPreheader());
1648 assert(AR->getStart() == SE->getSCEV(IVStart) && "bad loop counter");
Andrew Trick41e0d4e2011-07-18 21:15:03 +00001649 assert(SE->getSizeOfExpr(
1650 cast<PointerType>(IVStart->getType())->getElementType())->isOne()
1651 && "unit stride pointer IV must be i8*");
Andrew Trickfc933c02011-07-18 20:32:31 +00001652
1653 Builder.SetInsertPoint(L->getLoopPreheader()->getTerminator());
1654 ExitCnt = Builder.CreateGEP(IVStart, ExitCnt, "lftr.limit");
1655 Builder.SetInsertPoint(BI);
1656 }
Andrew Trick1a54bb22011-07-12 00:08:50 +00001657
1658 // Insert a new icmp_ne or icmp_eq instruction before the branch.
Andrew Trickfc933c02011-07-18 20:32:31 +00001659 ICmpInst::Predicate P;
Andrew Trick1a54bb22011-07-12 00:08:50 +00001660 if (L->contains(BI->getSuccessor(0)))
Andrew Trickfc933c02011-07-18 20:32:31 +00001661 P = ICmpInst::ICMP_NE;
Andrew Trick1a54bb22011-07-12 00:08:50 +00001662 else
Andrew Trickfc933c02011-07-18 20:32:31 +00001663 P = ICmpInst::ICMP_EQ;
Andrew Trick1a54bb22011-07-12 00:08:50 +00001664
1665 DEBUG(dbgs() << "INDVARS: Rewriting loop exit condition to:\n"
1666 << " LHS:" << *CmpIndVar << '\n'
1667 << " op:\t"
Andrew Trickfc933c02011-07-18 20:32:31 +00001668 << (P == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
1669 << " RHS:\t" << *ExitCnt << "\n"
1670 << " Expr:\t" << *IVLimit << "\n");
Andrew Trick1a54bb22011-07-12 00:08:50 +00001671
Andrew Trickfc933c02011-07-18 20:32:31 +00001672 if (SE->getTypeSizeInBits(CmpIndVar->getType())
1673 > SE->getTypeSizeInBits(CmpTy)) {
1674 CmpIndVar = Builder.CreateTrunc(CmpIndVar, CmpTy, "lftr.wideiv");
1675 }
1676
1677 Value *Cond = Builder.CreateICmp(P, CmpIndVar, ExitCnt, "exitcond");
Andrew Trick1a54bb22011-07-12 00:08:50 +00001678 Value *OrigCond = BI->getCondition();
1679 // It's tempting to use replaceAllUsesWith here to fully replace the old
1680 // comparison, but that's not immediately safe, since users of the old
1681 // comparison may not be dominated by the new comparison. Instead, just
1682 // update the branch to use the new comparison; in the common case this
1683 // will make old comparison dead.
1684 BI->setCondition(Cond);
1685 DeadInsts.push_back(OrigCond);
1686
1687 ++NumLFTR;
1688 Changed = true;
1689 return Cond;
1690}
1691
1692//===----------------------------------------------------------------------===//
1693// SinkUnusedInvariants. A late subpass to cleanup loop preheaders.
1694//===----------------------------------------------------------------------===//
1695
1696/// If there's a single exit block, sink any loop-invariant values that
1697/// were defined in the preheader but not used inside the loop into the
1698/// exit block to reduce register pressure in the loop.
1699void IndVarSimplify::SinkUnusedInvariants(Loop *L) {
1700 BasicBlock *ExitBlock = L->getExitBlock();
1701 if (!ExitBlock) return;
1702
1703 BasicBlock *Preheader = L->getLoopPreheader();
1704 if (!Preheader) return;
1705
1706 Instruction *InsertPt = ExitBlock->getFirstNonPHI();
1707 BasicBlock::iterator I = Preheader->getTerminator();
1708 while (I != Preheader->begin()) {
1709 --I;
1710 // New instructions were inserted at the end of the preheader.
1711 if (isa<PHINode>(I))
1712 break;
1713
1714 // Don't move instructions which might have side effects, since the side
1715 // effects need to complete before instructions inside the loop. Also don't
1716 // move instructions which might read memory, since the loop may modify
1717 // memory. Note that it's okay if the instruction might have undefined
1718 // behavior: LoopSimplify guarantees that the preheader dominates the exit
1719 // block.
1720 if (I->mayHaveSideEffects() || I->mayReadFromMemory())
1721 continue;
1722
1723 // Skip debug info intrinsics.
1724 if (isa<DbgInfoIntrinsic>(I))
1725 continue;
1726
1727 // Don't sink static AllocaInsts out of the entry block, which would
1728 // turn them into dynamic allocas!
1729 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
1730 if (AI->isStaticAlloca())
1731 continue;
1732
1733 // Determine if there is a use in or before the loop (direct or
1734 // otherwise).
1735 bool UsedInLoop = false;
1736 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
1737 UI != UE; ++UI) {
1738 User *U = *UI;
1739 BasicBlock *UseBB = cast<Instruction>(U)->getParent();
1740 if (PHINode *P = dyn_cast<PHINode>(U)) {
1741 unsigned i =
1742 PHINode::getIncomingValueNumForOperand(UI.getOperandNo());
1743 UseBB = P->getIncomingBlock(i);
1744 }
1745 if (UseBB == Preheader || L->contains(UseBB)) {
1746 UsedInLoop = true;
1747 break;
1748 }
1749 }
1750
1751 // If there is, the def must remain in the preheader.
1752 if (UsedInLoop)
1753 continue;
1754
1755 // Otherwise, sink it to the exit block.
1756 Instruction *ToMove = I;
1757 bool Done = false;
1758
1759 if (I != Preheader->begin()) {
1760 // Skip debug info intrinsics.
1761 do {
1762 --I;
1763 } while (isa<DbgInfoIntrinsic>(I) && I != Preheader->begin());
1764
1765 if (isa<DbgInfoIntrinsic>(I) && I == Preheader->begin())
1766 Done = true;
1767 } else {
1768 Done = true;
1769 }
1770
1771 ToMove->moveBefore(InsertPt);
1772 if (Done) break;
1773 InsertPt = ToMove;
1774 }
1775}
1776
1777//===----------------------------------------------------------------------===//
1778// IndVarSimplify driver. Manage several subpasses of IV simplification.
1779//===----------------------------------------------------------------------===//
1780
Dan Gohmanc2390b12009-02-12 22:19:27 +00001781bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
Dan Gohmana5283822010-06-18 01:35:11 +00001782 // If LoopSimplify form is not available, stay out of trouble. Some notes:
1783 // - LSR currently only supports LoopSimplify-form loops. Indvars'
1784 // canonicalization can be a pessimization without LSR to "clean up"
1785 // afterwards.
1786 // - We depend on having a preheader; in particular,
1787 // Loop::getCanonicalInductionVariable only supports loops with preheaders,
1788 // and we're in trouble if we can't find the induction variable even when
1789 // we've manually inserted one.
1790 if (!L->isLoopSimplifyForm())
1791 return false;
1792
Andrew Trick2fabd462011-06-21 03:22:38 +00001793 if (!DisableIVRewrite)
1794 IU = &getAnalysis<IVUsers>();
Devang Patel5ee99972007-03-07 06:39:01 +00001795 LI = &getAnalysis<LoopInfo>();
1796 SE = &getAnalysis<ScalarEvolution>();
Dan Gohmande53dc02009-06-27 05:16:57 +00001797 DT = &getAnalysis<DominatorTree>();
Andrew Trick37da4082011-05-04 02:10:13 +00001798 TD = getAnalysisIfAvailable<TargetData>();
1799
Andrew Trickb12a7542011-03-17 23:51:11 +00001800 DeadInsts.clear();
Devang Patel5ee99972007-03-07 06:39:01 +00001801 Changed = false;
Dan Gohman60f8a632009-02-17 20:49:49 +00001802
Dan Gohman2d1be872009-04-16 03:18:22 +00001803 // If there are any floating-point recurrences, attempt to
Dan Gohman60f8a632009-02-17 20:49:49 +00001804 // transform them to use integer recurrences.
1805 RewriteNonIntegerIVs(L);
1806
Dan Gohman0bba49c2009-07-07 17:06:11 +00001807 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
Chris Lattner9caed542007-03-04 01:00:28 +00001808
Dan Gohman667d7872009-06-26 22:53:46 +00001809 // Create a rewriter object which we'll use to transform the code with.
Andrew Trick5e7645b2011-06-28 05:07:32 +00001810 SCEVExpander Rewriter(*SE, "indvars");
Andrew Trick156d4602011-06-27 23:17:44 +00001811
1812 // Eliminate redundant IV users.
Andrew Trick15832f62011-06-28 02:49:20 +00001813 //
1814 // Simplification works best when run before other consumers of SCEV. We
1815 // attempt to avoid evaluating SCEVs for sign/zero extend operations until
1816 // other expressions involving loop IVs have been evaluated. This helps SCEV
Andrew Trick99a92f62011-06-28 16:45:04 +00001817 // set no-wrap flags before normalizing sign/zero extension.
Andrew Trick156d4602011-06-27 23:17:44 +00001818 if (DisableIVRewrite) {
Andrew Trick37da4082011-05-04 02:10:13 +00001819 Rewriter.disableCanonicalMode();
Andrew Trick4b4bb712011-08-10 03:46:27 +00001820 SimplifyAndExtend(L, Rewriter, LPM);
Andrew Trick156d4602011-06-27 23:17:44 +00001821 }
Andrew Trick37da4082011-05-04 02:10:13 +00001822
Chris Lattner40bf8b42004-04-02 20:24:31 +00001823 // Check to see if this loop has a computable loop-invariant execution count.
1824 // If so, this means that we can compute the final value of any expressions
1825 // that are recurrent in the loop, and substitute the exit values from the
1826 // loop into any instructions outside of the loop that use the final values of
1827 // the current expressions.
Chris Lattner3dec1f22002-05-10 15:38:35 +00001828 //
Dan Gohman46bdfb02009-02-24 18:55:53 +00001829 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount))
Dan Gohman454d26d2010-02-22 04:11:59 +00001830 RewriteLoopExitValues(L, Rewriter);
Chris Lattner6148c022001-12-03 17:28:42 +00001831
Andrew Trickf85092c2011-05-20 18:25:42 +00001832 // Eliminate redundant IV users.
Andrew Trick156d4602011-06-27 23:17:44 +00001833 if (!DisableIVRewrite)
Andrew Trick4b4bb712011-08-10 03:46:27 +00001834 Changed |= simplifyIVUsers(IU, &LPM, DeadInsts);
Dan Gohmana590b792010-04-13 01:46:36 +00001835
Andrew Trick6f684b02011-07-16 01:06:48 +00001836 // Eliminate redundant IV cycles.
Andrew Trick037d1c02011-07-06 20:50:43 +00001837 if (DisableIVRewrite)
1838 SimplifyCongruentIVs(L);
1839
Dan Gohman81db61a2009-05-12 02:17:14 +00001840 // Compute the type of the largest recurrence expression, and decide whether
1841 // a canonical induction variable should be inserted.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001842 Type *LargestType = 0;
Dan Gohman81db61a2009-05-12 02:17:14 +00001843 bool NeedCannIV = false;
Andrew Trickfc933c02011-07-18 20:32:31 +00001844 bool ReuseIVForExit = DisableIVRewrite && !ForceLFTR;
Andrew Trick03d3d3b2011-05-25 04:42:22 +00001845 bool ExpandBECount = canExpandBackedgeTakenCount(L, SE);
Andrew Trickfc933c02011-07-18 20:32:31 +00001846 if (ExpandBECount && !ReuseIVForExit) {
Dan Gohman81db61a2009-05-12 02:17:14 +00001847 // If we have a known trip count and a single exit block, we'll be
1848 // rewriting the loop exit test condition below, which requires a
1849 // canonical induction variable.
Andrew Trick4dfdf242011-05-03 22:24:10 +00001850 NeedCannIV = true;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001851 Type *Ty = BackedgeTakenCount->getType();
Andrew Trick03d3d3b2011-05-25 04:42:22 +00001852 if (DisableIVRewrite) {
1853 // In this mode, SimplifyIVUsers may have already widened the IV used by
1854 // the backedge test and inserted a Trunc on the compare's operand. Get
1855 // the wider type to avoid creating a redundant narrow IV only used by the
1856 // loop test.
1857 LargestType = getBackedgeIVType(L);
1858 }
Andrew Trick4dfdf242011-05-03 22:24:10 +00001859 if (!LargestType ||
1860 SE->getTypeSizeInBits(Ty) >
1861 SE->getTypeSizeInBits(LargestType))
1862 LargestType = SE->getEffectiveSCEVType(Ty);
Chris Lattnerf50af082004-04-17 18:08:33 +00001863 }
Andrew Trick37da4082011-05-04 02:10:13 +00001864 if (!DisableIVRewrite) {
1865 for (IVUsers::const_iterator I = IU->begin(), E = IU->end(); I != E; ++I) {
1866 NeedCannIV = true;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001867 Type *Ty =
Andrew Trick37da4082011-05-04 02:10:13 +00001868 SE->getEffectiveSCEVType(I->getOperandValToReplace()->getType());
1869 if (!LargestType ||
1870 SE->getTypeSizeInBits(Ty) >
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001871 SE->getTypeSizeInBits(LargestType))
Andrew Trick37da4082011-05-04 02:10:13 +00001872 LargestType = Ty;
1873 }
Chris Lattner6148c022001-12-03 17:28:42 +00001874 }
1875
Dan Gohmanf451cb82010-02-10 16:03:48 +00001876 // Now that we know the largest of the induction variable expressions
Dan Gohman81db61a2009-05-12 02:17:14 +00001877 // in this loop, insert a canonical induction variable of the largest size.
Dan Gohman43ef3fb2010-07-20 17:18:52 +00001878 PHINode *IndVar = 0;
Dan Gohman81db61a2009-05-12 02:17:14 +00001879 if (NeedCannIV) {
Dan Gohman85669632010-02-25 06:57:05 +00001880 // Check to see if the loop already has any canonical-looking induction
1881 // variables. If any are present and wider than the planned canonical
1882 // induction variable, temporarily remove them, so that the Rewriter
1883 // doesn't attempt to reuse them.
1884 SmallVector<PHINode *, 2> OldCannIVs;
1885 while (PHINode *OldCannIV = L->getCanonicalInductionVariable()) {
Dan Gohman4d8414f2009-06-13 16:25:49 +00001886 if (SE->getTypeSizeInBits(OldCannIV->getType()) >
1887 SE->getTypeSizeInBits(LargestType))
1888 OldCannIV->removeFromParent();
1889 else
Dan Gohman85669632010-02-25 06:57:05 +00001890 break;
1891 OldCannIVs.push_back(OldCannIV);
Dan Gohman4d8414f2009-06-13 16:25:49 +00001892 }
1893
Dan Gohman667d7872009-06-26 22:53:46 +00001894 IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L, LargestType);
Dan Gohman4d8414f2009-06-13 16:25:49 +00001895
Dan Gohmanc2390b12009-02-12 22:19:27 +00001896 ++NumInserted;
1897 Changed = true;
David Greenef67ef312010-01-05 01:27:06 +00001898 DEBUG(dbgs() << "INDVARS: New CanIV: " << *IndVar << '\n');
Dan Gohman4d8414f2009-06-13 16:25:49 +00001899
1900 // Now that the official induction variable is established, reinsert
Dan Gohman85669632010-02-25 06:57:05 +00001901 // any old canonical-looking variables after it so that the IR remains
1902 // consistent. They will be deleted as part of the dead-PHI deletion at
Dan Gohman4d8414f2009-06-13 16:25:49 +00001903 // the end of the pass.
Dan Gohman85669632010-02-25 06:57:05 +00001904 while (!OldCannIVs.empty()) {
1905 PHINode *OldCannIV = OldCannIVs.pop_back_val();
1906 OldCannIV->insertBefore(L->getHeader()->getFirstNonPHI());
1907 }
Dan Gohmand19534a2007-06-15 14:38:12 +00001908 }
Andrew Trickfc933c02011-07-18 20:32:31 +00001909 else if (ExpandBECount && ReuseIVForExit && needsLFTR(L, DT)) {
1910 IndVar = FindLoopCounter(L, BackedgeTakenCount, SE, DT, TD);
1911 }
Dan Gohmanc2390b12009-02-12 22:19:27 +00001912 // If we have a trip count expression, rewrite the loop's exit condition
1913 // using it. We can currently only handle loops with a single exit.
Andrew Trickfc933c02011-07-18 20:32:31 +00001914 Value *NewICmp = 0;
1915 if (ExpandBECount && IndVar) {
Andrew Trick56147692011-07-16 01:18:53 +00001916 // Check preconditions for proper SCEVExpander operation. SCEV does not
1917 // express SCEVExpander's dependencies, such as LoopSimplify. Instead any
1918 // pass that uses the SCEVExpander must do it. This does not work well for
1919 // loop passes because SCEVExpander makes assumptions about all loops, while
1920 // LoopPassManager only forces the current loop to be simplified.
1921 //
1922 // FIXME: SCEV expansion has no way to bail out, so the caller must
1923 // explicitly check any assumptions made by SCEV. Brittle.
1924 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(BackedgeTakenCount);
1925 if (!AR || AR->getLoop()->getLoopPreheader())
1926 NewICmp =
1927 LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar, Rewriter);
Chris Lattnerfcb81f52004-04-22 14:59:40 +00001928 }
Andrew Trickb12a7542011-03-17 23:51:11 +00001929 // Rewrite IV-derived expressions.
Andrew Trick37da4082011-05-04 02:10:13 +00001930 if (!DisableIVRewrite)
1931 RewriteIVExpressions(L, Rewriter);
Dan Gohmanc2390b12009-02-12 22:19:27 +00001932
Andrew Trickb12a7542011-03-17 23:51:11 +00001933 // Clear the rewriter cache, because values that are in the rewriter's cache
1934 // can be deleted in the loop below, causing the AssertingVH in the cache to
1935 // trigger.
1936 Rewriter.clear();
1937
1938 // Now that we're done iterating through lists, clean up any instructions
1939 // which are now dead.
1940 while (!DeadInsts.empty())
1941 if (Instruction *Inst =
1942 dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val()))
1943 RecursivelyDeleteTriviallyDeadInstructions(Inst);
1944
Dan Gohman667d7872009-06-26 22:53:46 +00001945 // The Rewriter may not be used from this point on.
Torok Edwin3d431382009-05-24 20:08:21 +00001946
Dan Gohman81db61a2009-05-12 02:17:14 +00001947 // Loop-invariant instructions in the preheader that aren't used in the
1948 // loop may be sunk below the loop to reduce register pressure.
Dan Gohman667d7872009-06-26 22:53:46 +00001949 SinkUnusedInvariants(L);
Dan Gohman81db61a2009-05-12 02:17:14 +00001950
1951 // For completeness, inform IVUsers of the IV use in the newly-created
1952 // loop exit test instruction.
Andrew Trickfc933c02011-07-18 20:32:31 +00001953 if (IU && NewICmp) {
1954 ICmpInst *NewICmpInst = dyn_cast<ICmpInst>(NewICmp);
1955 if (NewICmpInst)
1956 IU->AddUsersIfInteresting(cast<Instruction>(NewICmpInst->getOperand(0)));
1957 }
Dan Gohman81db61a2009-05-12 02:17:14 +00001958 // Clean up dead instructions.
Dan Gohman9fff2182010-01-05 16:31:45 +00001959 Changed |= DeleteDeadPHIs(L->getHeader());
Dan Gohman81db61a2009-05-12 02:17:14 +00001960 // Check a post-condition.
Andrew Trickf6a0dba2011-07-18 18:44:20 +00001961 assert(L->isLCSSAForm(*DT) &&
1962 "Indvars did not leave the loop in lcssa form!");
1963
1964 // Verify that LFTR, and any other change have not interfered with SCEV's
1965 // ability to compute trip count.
1966#ifndef NDEBUG
1967 if (DisableIVRewrite && !isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
1968 SE->forgetLoop(L);
1969 const SCEV *NewBECount = SE->getBackedgeTakenCount(L);
1970 if (SE->getTypeSizeInBits(BackedgeTakenCount->getType()) <
1971 SE->getTypeSizeInBits(NewBECount->getType()))
1972 NewBECount = SE->getTruncateOrNoop(NewBECount,
1973 BackedgeTakenCount->getType());
1974 else
1975 BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount,
1976 NewBECount->getType());
1977 assert(BackedgeTakenCount == NewBECount && "indvars must preserve SCEV");
1978 }
1979#endif
1980
Devang Patel5ee99972007-03-07 06:39:01 +00001981 return Changed;
Chris Lattner6148c022001-12-03 17:28:42 +00001982}