blob: ea083e36ca4d68b03094e4fa17dab7ed338c9ccc [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//
Chris Lattner40bf8b42004-04-02 20:24:31 +000014// If the trip count of a loop is computable, this pass also makes the following
15// changes:
16// 1. The exit condition for the loop is canonicalized to compare the
17// induction value against the exit value. This turns loops like:
18// 'for (i = 7; i*i < 1000; ++i)' into 'for (i = 0; i != 25; ++i)'
19// 2. Any use outside of the loop of an expression derived from the indvar
20// is changed to compute the derived value outside of the loop, eliminating
21// the dependence on the exit value of the induction variable. If the only
22// purpose of the loop is to compute the exit value of some derived
23// expression, this transformation will make the loop dead.
24//
Chris Lattner6148c022001-12-03 17:28:42 +000025//===----------------------------------------------------------------------===//
26
Chris Lattner0e5f4992006-12-19 21:40:18 +000027#define DEBUG_TYPE "indvars"
Chris Lattner022103b2002-05-07 20:03:00 +000028#include "llvm/Transforms/Scalar.h"
Chris Lattner40bf8b42004-04-02 20:24:31 +000029#include "llvm/BasicBlock.h"
Chris Lattner59fdaee2004-04-15 15:21:43 +000030#include "llvm/Constants.h"
Chris Lattner18b3c972003-12-22 05:02:01 +000031#include "llvm/Instructions.h"
Devang Patel7b9f6b12010-03-15 22:23:03 +000032#include "llvm/IntrinsicInst.h"
Owen Andersond672ecb2009-07-03 00:17:18 +000033#include "llvm/LLVMContext.h"
Chris Lattner40bf8b42004-04-02 20:24:31 +000034#include "llvm/Type.h"
Dan Gohman81db61a2009-05-12 02:17:14 +000035#include "llvm/Analysis/Dominators.h"
36#include "llvm/Analysis/IVUsers.h"
Nate Begeman36f891b2005-07-30 00:12:19 +000037#include "llvm/Analysis/ScalarEvolutionExpander.h"
John Criswell47df12d2003-12-18 17:19:19 +000038#include "llvm/Analysis/LoopInfo.h"
Devang Patel5ee99972007-03-07 06:39:01 +000039#include "llvm/Analysis/LoopPass.h"
Chris Lattner455889a2002-02-12 22:39:50 +000040#include "llvm/Support/CFG.h"
Andrew Trick56caa092011-06-28 03:01:46 +000041#include "llvm/Support/CommandLine.h"
Chris Lattneree4f13a2007-01-07 01:14:12 +000042#include "llvm/Support/Debug.h"
Chris Lattnerbdff5482009-08-23 04:37:46 +000043#include "llvm/Support/raw_ostream.h"
John Criswell47df12d2003-12-18 17:19:19 +000044#include "llvm/Transforms/Utils/Local.h"
Dan Gohman81db61a2009-05-12 02:17:14 +000045#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Andrew Trick4b4bb712011-08-10 03:46:27 +000046#include "llvm/Transforms/Utils/SimplifyIndVar.h"
Andrew Trick37da4082011-05-04 02:10:13 +000047#include "llvm/Target/TargetData.h"
Andrew Trick037d1c02011-07-06 20:50:43 +000048#include "llvm/ADT/DenseMap.h"
Reid Spencera54b7cb2007-01-12 07:05:14 +000049#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000050#include "llvm/ADT/Statistic.h"
John Criswell47df12d2003-12-18 17:19:19 +000051using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000052
Andrew Trick2fabd462011-06-21 03:22:38 +000053STATISTIC(NumRemoved , "Number of aux indvars removed");
54STATISTIC(NumWidened , "Number of indvars widened");
55STATISTIC(NumInserted , "Number of canonical indvars added");
56STATISTIC(NumReplaced , "Number of exit values replaced");
57STATISTIC(NumLFTR , "Number of loop exit tests replaced");
Andrew Trick2fabd462011-06-21 03:22:38 +000058STATISTIC(NumElimExt , "Number of IV sign/zero extends eliminated");
Andrew Trick037d1c02011-07-06 20:50:43 +000059STATISTIC(NumElimIV , "Number of congruent IVs eliminated");
Chris Lattner3324e712003-12-22 03:58:44 +000060
Benjamin Kramer0861f572011-11-26 23:01:57 +000061static cl::opt<bool> EnableIVRewrite(
62 "enable-iv-rewrite", cl::Hidden,
63 cl::desc("Enable canonical induction variable rewriting"));
Andrew Trick75ebc0e2011-09-06 20:20:38 +000064
Benjamin Kramer0861f572011-11-26 23:01:57 +000065// Trip count verification can be enabled by default under NDEBUG if we
66// implement a strong expression equivalence checker in SCEV. Until then, we
67// use the verify-indvars flag, which may assert in some cases.
68static cl::opt<bool> VerifyIndvars(
69 "verify-indvars", cl::Hidden,
70 cl::desc("Verify the ScalarEvolution result after running indvars"));
Andrew Trick37da4082011-05-04 02:10:13 +000071
Chris Lattner0e5f4992006-12-19 21:40:18 +000072namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000073 class IndVarSimplify : public LoopPass {
Dan Gohman81db61a2009-05-12 02:17:14 +000074 IVUsers *IU;
Chris Lattner40bf8b42004-04-02 20:24:31 +000075 LoopInfo *LI;
76 ScalarEvolution *SE;
Dan Gohmande53dc02009-06-27 05:16:57 +000077 DominatorTree *DT;
Andrew Trick37da4082011-05-04 02:10:13 +000078 TargetData *TD;
Andrew Trick2fabd462011-06-21 03:22:38 +000079
Andrew Trickb12a7542011-03-17 23:51:11 +000080 SmallVector<WeakVH, 16> DeadInsts;
Chris Lattner15cad752003-12-23 07:47:09 +000081 bool Changed;
Chris Lattner3324e712003-12-22 03:58:44 +000082 public:
Devang Patel794fd752007-05-01 21:15:47 +000083
Dan Gohman5668cf72009-07-15 01:26:32 +000084 static char ID; // Pass identification, replacement for typeid
Andrew Trick2fabd462011-06-21 03:22:38 +000085 IndVarSimplify() : LoopPass(ID), IU(0), LI(0), SE(0), DT(0), TD(0),
Andrew Trick15832f62011-06-28 02:49:20 +000086 Changed(false) {
Owen Anderson081c34b2010-10-19 17:21:58 +000087 initializeIndVarSimplifyPass(*PassRegistry::getPassRegistry());
88 }
Devang Patel794fd752007-05-01 21:15:47 +000089
Dan Gohman5668cf72009-07-15 01:26:32 +000090 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
Dan Gohman60f8a632009-02-17 20:49:49 +000091
Dan Gohman5668cf72009-07-15 01:26:32 +000092 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
93 AU.addRequired<DominatorTree>();
94 AU.addRequired<LoopInfo>();
95 AU.addRequired<ScalarEvolution>();
96 AU.addRequiredID(LoopSimplifyID);
97 AU.addRequiredID(LCSSAID);
Andrew Trickf21bdf42011-09-12 18:28:44 +000098 if (EnableIVRewrite)
Andrew Trick56caa092011-06-28 03:01:46 +000099 AU.addRequired<IVUsers>();
Dan Gohman5668cf72009-07-15 01:26:32 +0000100 AU.addPreserved<ScalarEvolution>();
101 AU.addPreservedID(LoopSimplifyID);
102 AU.addPreservedID(LCSSAID);
Andrew Trickf21bdf42011-09-12 18:28:44 +0000103 if (EnableIVRewrite)
Andrew Trick2fabd462011-06-21 03:22:38 +0000104 AU.addPreserved<IVUsers>();
Dan Gohman5668cf72009-07-15 01:26:32 +0000105 AU.setPreservesCFG();
106 }
Chris Lattner15cad752003-12-23 07:47:09 +0000107
Chris Lattner40bf8b42004-04-02 20:24:31 +0000108 private:
Andrew Trick037d1c02011-07-06 20:50:43 +0000109 virtual void releaseMemory() {
Andrew Trick037d1c02011-07-06 20:50:43 +0000110 DeadInsts.clear();
111 }
112
Andrew Trickb12a7542011-03-17 23:51:11 +0000113 bool isValidRewrite(Value *FromVal, Value *ToVal);
Devang Patel5ee99972007-03-07 06:39:01 +0000114
Andrew Trick1a54bb22011-07-12 00:08:50 +0000115 void HandleFloatingPointIV(Loop *L, PHINode *PH);
116 void RewriteNonIntegerIVs(Loop *L);
117
Andrew Trick4b4bb712011-08-10 03:46:27 +0000118 void SimplifyAndExtend(Loop *L, SCEVExpander &Rewriter, LPPassManager &LPM);
Andrew Trick06988bc2011-08-06 07:00:37 +0000119
Andrew Trick4b4bb712011-08-10 03:46:27 +0000120 void RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter);
121
Dan Gohman454d26d2010-02-22 04:11:59 +0000122 void RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter);
Devang Pateld22a8492008-09-09 21:41:07 +0000123
Andrew Trickfc933c02011-07-18 20:32:31 +0000124 Value *LinearFunctionTestReplace(Loop *L, const SCEV *BackedgeTakenCount,
125 PHINode *IndVar, SCEVExpander &Rewriter);
Dan Gohman81db61a2009-05-12 02:17:14 +0000126
Andrew Trick1a54bb22011-07-12 00:08:50 +0000127 void SinkUnusedInvariants(Loop *L);
Chris Lattner3324e712003-12-22 03:58:44 +0000128 };
Chris Lattner5e761402002-09-10 05:24:05 +0000129}
Chris Lattner394437f2001-12-04 04:32:29 +0000130
Dan Gohman844731a2008-05-13 00:00:25 +0000131char IndVarSimplify::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000132INITIALIZE_PASS_BEGIN(IndVarSimplify, "indvars",
Andrew Trick37da4082011-05-04 02:10:13 +0000133 "Induction Variable Simplification", false, false)
Owen Anderson2ab36d32010-10-12 19:48:12 +0000134INITIALIZE_PASS_DEPENDENCY(DominatorTree)
135INITIALIZE_PASS_DEPENDENCY(LoopInfo)
136INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
137INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
138INITIALIZE_PASS_DEPENDENCY(LCSSA)
139INITIALIZE_PASS_DEPENDENCY(IVUsers)
140INITIALIZE_PASS_END(IndVarSimplify, "indvars",
Andrew Trick37da4082011-05-04 02:10:13 +0000141 "Induction Variable Simplification", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000142
Daniel Dunbar394f0442008-10-22 23:32:42 +0000143Pass *llvm::createIndVarSimplifyPass() {
Chris Lattner3324e712003-12-22 03:58:44 +0000144 return new IndVarSimplify();
Chris Lattner394437f2001-12-04 04:32:29 +0000145}
146
Andrew Trickb12a7542011-03-17 23:51:11 +0000147/// isValidRewrite - Return true if the SCEV expansion generated by the
148/// rewriter can replace the original value. SCEV guarantees that it
149/// produces the same value, but the way it is produced may be illegal IR.
150/// Ideally, this function will only be called for verification.
151bool IndVarSimplify::isValidRewrite(Value *FromVal, Value *ToVal) {
152 // If an SCEV expression subsumed multiple pointers, its expansion could
153 // reassociate the GEP changing the base pointer. This is illegal because the
154 // final address produced by a GEP chain must be inbounds relative to its
155 // underlying object. Otherwise basic alias analysis, among other things,
156 // could fail in a dangerous way. Ultimately, SCEV will be improved to avoid
157 // producing an expression involving multiple pointers. Until then, we must
158 // bail out here.
159 //
160 // Retrieve the pointer operand of the GEP. Don't use GetUnderlyingObject
161 // because it understands lcssa phis while SCEV does not.
162 Value *FromPtr = FromVal;
163 Value *ToPtr = ToVal;
164 if (GEPOperator *GEP = dyn_cast<GEPOperator>(FromVal)) {
165 FromPtr = GEP->getPointerOperand();
166 }
167 if (GEPOperator *GEP = dyn_cast<GEPOperator>(ToVal)) {
168 ToPtr = GEP->getPointerOperand();
169 }
170 if (FromPtr != FromVal || ToPtr != ToVal) {
171 // Quickly check the common case
172 if (FromPtr == ToPtr)
173 return true;
174
175 // SCEV may have rewritten an expression that produces the GEP's pointer
176 // operand. That's ok as long as the pointer operand has the same base
177 // pointer. Unlike GetUnderlyingObject(), getPointerBase() will find the
178 // base of a recurrence. This handles the case in which SCEV expansion
179 // converts a pointer type recurrence into a nonrecurrent pointer base
180 // indexed by an integer recurrence.
181 const SCEV *FromBase = SE->getPointerBase(SE->getSCEV(FromPtr));
182 const SCEV *ToBase = SE->getPointerBase(SE->getSCEV(ToPtr));
183 if (FromBase == ToBase)
184 return true;
185
186 DEBUG(dbgs() << "INDVARS: GEP rewrite bail out "
187 << *FromBase << " != " << *ToBase << "\n");
188
189 return false;
190 }
191 return true;
192}
193
Andrew Trick86c98142011-07-20 05:32:06 +0000194/// Determine the insertion point for this user. By default, insert immediately
195/// before the user. SCEVExpander or LICM will hoist loop invariants out of the
196/// loop. For PHI nodes, there may be multiple uses, so compute the nearest
197/// common dominator for the incoming blocks.
198static Instruction *getInsertPointForUses(Instruction *User, Value *Def,
199 DominatorTree *DT) {
200 PHINode *PHI = dyn_cast<PHINode>(User);
201 if (!PHI)
202 return User;
203
204 Instruction *InsertPt = 0;
205 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i) {
206 if (PHI->getIncomingValue(i) != Def)
207 continue;
208
209 BasicBlock *InsertBB = PHI->getIncomingBlock(i);
210 if (!InsertPt) {
211 InsertPt = InsertBB->getTerminator();
212 continue;
213 }
214 InsertBB = DT->findNearestCommonDominator(InsertPt->getParent(), InsertBB);
215 InsertPt = InsertBB->getTerminator();
216 }
217 assert(InsertPt && "Missing phi operand");
Jay Foad626f52d2011-07-20 08:15:21 +0000218 assert((!isa<Instruction>(Def) ||
219 DT->dominates(cast<Instruction>(Def), InsertPt)) &&
Andrew Trick86c98142011-07-20 05:32:06 +0000220 "def does not dominate all uses");
221 return InsertPt;
222}
223
Andrew Trick1a54bb22011-07-12 00:08:50 +0000224//===----------------------------------------------------------------------===//
225// RewriteNonIntegerIVs and helpers. Prefer integer IVs.
226//===----------------------------------------------------------------------===//
Andrew Trick4dfdf242011-05-03 22:24:10 +0000227
Andrew Trick1a54bb22011-07-12 00:08:50 +0000228/// ConvertToSInt - Convert APF to an integer, if possible.
229static bool ConvertToSInt(const APFloat &APF, int64_t &IntVal) {
230 bool isExact = false;
231 if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
Andrew Trick4dfdf242011-05-03 22:24:10 +0000232 return false;
Andrew Trick1a54bb22011-07-12 00:08:50 +0000233 // See if we can convert this to an int64_t
234 uint64_t UIntVal;
235 if (APF.convertToInteger(&UIntVal, 64, true, APFloat::rmTowardZero,
236 &isExact) != APFloat::opOK || !isExact)
Andrew Trick4dfdf242011-05-03 22:24:10 +0000237 return false;
Andrew Trick1a54bb22011-07-12 00:08:50 +0000238 IntVal = UIntVal;
Andrew Trick4dfdf242011-05-03 22:24:10 +0000239 return true;
240}
241
Andrew Trick1a54bb22011-07-12 00:08:50 +0000242/// HandleFloatingPointIV - If the loop has floating induction variable
243/// then insert corresponding integer induction variable if possible.
244/// For example,
245/// for(double i = 0; i < 10000; ++i)
246/// bar(i)
247/// is converted into
248/// for(int i = 0; i < 10000; ++i)
249/// bar((double)i);
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000250///
Andrew Trick1a54bb22011-07-12 00:08:50 +0000251void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PN) {
252 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
253 unsigned BackEdge = IncomingEdge^1;
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000254
Andrew Trick1a54bb22011-07-12 00:08:50 +0000255 // Check incoming value.
256 ConstantFP *InitValueVal =
257 dyn_cast<ConstantFP>(PN->getIncomingValue(IncomingEdge));
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000258
Andrew Trick1a54bb22011-07-12 00:08:50 +0000259 int64_t InitValue;
260 if (!InitValueVal || !ConvertToSInt(InitValueVal->getValueAPF(), InitValue))
261 return;
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000262
Andrew Trick1a54bb22011-07-12 00:08:50 +0000263 // Check IV increment. Reject this PN if increment operation is not
264 // an add or increment value can not be represented by an integer.
265 BinaryOperator *Incr =
266 dyn_cast<BinaryOperator>(PN->getIncomingValue(BackEdge));
267 if (Incr == 0 || Incr->getOpcode() != Instruction::FAdd) return;
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000268
Andrew Trick1a54bb22011-07-12 00:08:50 +0000269 // If this is not an add of the PHI with a constantfp, or if the constant fp
270 // is not an integer, bail out.
271 ConstantFP *IncValueVal = dyn_cast<ConstantFP>(Incr->getOperand(1));
272 int64_t IncValue;
273 if (IncValueVal == 0 || Incr->getOperand(0) != PN ||
274 !ConvertToSInt(IncValueVal->getValueAPF(), IncValue))
275 return;
276
277 // Check Incr uses. One user is PN and the other user is an exit condition
278 // used by the conditional terminator.
279 Value::use_iterator IncrUse = Incr->use_begin();
280 Instruction *U1 = cast<Instruction>(*IncrUse++);
281 if (IncrUse == Incr->use_end()) return;
282 Instruction *U2 = cast<Instruction>(*IncrUse++);
283 if (IncrUse != Incr->use_end()) return;
284
285 // Find exit condition, which is an fcmp. If it doesn't exist, or if it isn't
286 // only used by a branch, we can't transform it.
287 FCmpInst *Compare = dyn_cast<FCmpInst>(U1);
288 if (!Compare)
289 Compare = dyn_cast<FCmpInst>(U2);
290 if (Compare == 0 || !Compare->hasOneUse() ||
291 !isa<BranchInst>(Compare->use_back()))
292 return;
293
294 BranchInst *TheBr = cast<BranchInst>(Compare->use_back());
295
296 // We need to verify that the branch actually controls the iteration count
297 // of the loop. If not, the new IV can overflow and no one will notice.
298 // The branch block must be in the loop and one of the successors must be out
299 // of the loop.
300 assert(TheBr->isConditional() && "Can't use fcmp if not conditional");
301 if (!L->contains(TheBr->getParent()) ||
302 (L->contains(TheBr->getSuccessor(0)) &&
303 L->contains(TheBr->getSuccessor(1))))
304 return;
305
306
307 // If it isn't a comparison with an integer-as-fp (the exit value), we can't
308 // transform it.
309 ConstantFP *ExitValueVal = dyn_cast<ConstantFP>(Compare->getOperand(1));
310 int64_t ExitValue;
311 if (ExitValueVal == 0 ||
312 !ConvertToSInt(ExitValueVal->getValueAPF(), ExitValue))
313 return;
314
315 // Find new predicate for integer comparison.
316 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
317 switch (Compare->getPredicate()) {
318 default: return; // Unknown comparison.
319 case CmpInst::FCMP_OEQ:
320 case CmpInst::FCMP_UEQ: NewPred = CmpInst::ICMP_EQ; break;
321 case CmpInst::FCMP_ONE:
322 case CmpInst::FCMP_UNE: NewPred = CmpInst::ICMP_NE; break;
323 case CmpInst::FCMP_OGT:
324 case CmpInst::FCMP_UGT: NewPred = CmpInst::ICMP_SGT; break;
325 case CmpInst::FCMP_OGE:
326 case CmpInst::FCMP_UGE: NewPred = CmpInst::ICMP_SGE; break;
327 case CmpInst::FCMP_OLT:
328 case CmpInst::FCMP_ULT: NewPred = CmpInst::ICMP_SLT; break;
329 case CmpInst::FCMP_OLE:
330 case CmpInst::FCMP_ULE: NewPred = CmpInst::ICMP_SLE; break;
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000331 }
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000332
Andrew Trick1a54bb22011-07-12 00:08:50 +0000333 // We convert the floating point induction variable to a signed i32 value if
334 // we can. This is only safe if the comparison will not overflow in a way
335 // that won't be trapped by the integer equivalent operations. Check for this
336 // now.
337 // TODO: We could use i64 if it is native and the range requires it.
Dan Gohmanca9b7032010-04-12 21:13:43 +0000338
Andrew Trick1a54bb22011-07-12 00:08:50 +0000339 // The start/stride/exit values must all fit in signed i32.
340 if (!isInt<32>(InitValue) || !isInt<32>(IncValue) || !isInt<32>(ExitValue))
341 return;
342
343 // If not actually striding (add x, 0.0), avoid touching the code.
344 if (IncValue == 0)
345 return;
346
347 // Positive and negative strides have different safety conditions.
348 if (IncValue > 0) {
349 // If we have a positive stride, we require the init to be less than the
Andrew Trick94f2c232011-09-13 01:59:32 +0000350 // exit value.
351 if (InitValue >= ExitValue)
Andrew Trick1a54bb22011-07-12 00:08:50 +0000352 return;
353
354 uint32_t Range = uint32_t(ExitValue-InitValue);
Andrew Trick94f2c232011-09-13 01:59:32 +0000355 // Check for infinite loop, either:
356 // while (i <= Exit) or until (i > Exit)
357 if (NewPred == CmpInst::ICMP_SLE || NewPred == CmpInst::ICMP_SGT) {
Andrew Trick1a54bb22011-07-12 00:08:50 +0000358 if (++Range == 0) return; // Range overflows.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000359 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000360
Andrew Trick1a54bb22011-07-12 00:08:50 +0000361 unsigned Leftover = Range % uint32_t(IncValue);
362
363 // If this is an equality comparison, we require that the strided value
364 // exactly land on the exit value, otherwise the IV condition will wrap
365 // around and do things the fp IV wouldn't.
366 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
367 Leftover != 0)
368 return;
369
370 // If the stride would wrap around the i32 before exiting, we can't
371 // transform the IV.
372 if (Leftover != 0 && int32_t(ExitValue+IncValue) < ExitValue)
373 return;
374
Chris Lattnerd2440572004-04-15 20:26:22 +0000375 } else {
Andrew Trick1a54bb22011-07-12 00:08:50 +0000376 // If we have a negative stride, we require the init to be greater than the
Andrew Trick94f2c232011-09-13 01:59:32 +0000377 // exit value.
378 if (InitValue <= ExitValue)
Andrew Trick1a54bb22011-07-12 00:08:50 +0000379 return;
380
381 uint32_t Range = uint32_t(InitValue-ExitValue);
Andrew Trick94f2c232011-09-13 01:59:32 +0000382 // Check for infinite loop, either:
383 // while (i >= Exit) or until (i < Exit)
384 if (NewPred == CmpInst::ICMP_SGE || NewPred == CmpInst::ICMP_SLT) {
Andrew Trick1a54bb22011-07-12 00:08:50 +0000385 if (++Range == 0) return; // Range overflows.
386 }
387
388 unsigned Leftover = Range % uint32_t(-IncValue);
389
390 // If this is an equality comparison, we require that the strided value
391 // exactly land on the exit value, otherwise the IV condition will wrap
392 // around and do things the fp IV wouldn't.
393 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
394 Leftover != 0)
395 return;
396
397 // If the stride would wrap around the i32 before exiting, we can't
398 // transform the IV.
399 if (Leftover != 0 && int32_t(ExitValue+IncValue) > ExitValue)
400 return;
Chris Lattnerd2440572004-04-15 20:26:22 +0000401 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000402
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000403 IntegerType *Int32Ty = Type::getInt32Ty(PN->getContext());
Chris Lattner40bf8b42004-04-02 20:24:31 +0000404
Andrew Trick1a54bb22011-07-12 00:08:50 +0000405 // Insert new integer induction variable.
406 PHINode *NewPHI = PHINode::Create(Int32Ty, 2, PN->getName()+".int", PN);
407 NewPHI->addIncoming(ConstantInt::get(Int32Ty, InitValue),
408 PN->getIncomingBlock(IncomingEdge));
Chris Lattner40bf8b42004-04-02 20:24:31 +0000409
Andrew Trick1a54bb22011-07-12 00:08:50 +0000410 Value *NewAdd =
411 BinaryOperator::CreateAdd(NewPHI, ConstantInt::get(Int32Ty, IncValue),
412 Incr->getName()+".int", Incr);
413 NewPHI->addIncoming(NewAdd, PN->getIncomingBlock(BackEdge));
Dan Gohmanc2390b12009-02-12 22:19:27 +0000414
Andrew Trick1a54bb22011-07-12 00:08:50 +0000415 ICmpInst *NewCompare = new ICmpInst(TheBr, NewPred, NewAdd,
416 ConstantInt::get(Int32Ty, ExitValue),
417 Compare->getName());
Dan Gohman81db61a2009-05-12 02:17:14 +0000418
Andrew Trick1a54bb22011-07-12 00:08:50 +0000419 // In the following deletions, PN may become dead and may be deleted.
420 // Use a WeakVH to observe whether this happens.
421 WeakVH WeakPH = PN;
422
423 // Delete the old floating point exit comparison. The branch starts using the
424 // new comparison.
425 NewCompare->takeName(Compare);
426 Compare->replaceAllUsesWith(NewCompare);
427 RecursivelyDeleteTriviallyDeadInstructions(Compare);
428
429 // Delete the old floating point increment.
430 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
431 RecursivelyDeleteTriviallyDeadInstructions(Incr);
432
433 // If the FP induction variable still has uses, this is because something else
434 // in the loop uses its value. In order to canonicalize the induction
435 // variable, we chose to eliminate the IV and rewrite it in terms of an
436 // int->fp cast.
437 //
438 // We give preference to sitofp over uitofp because it is faster on most
439 // platforms.
440 if (WeakPH) {
441 Value *Conv = new SIToFPInst(NewPHI, PN->getType(), "indvar.conv",
Bill Wendlingb05fdd62011-08-24 20:28:43 +0000442 PN->getParent()->getFirstInsertionPt());
Andrew Trick1a54bb22011-07-12 00:08:50 +0000443 PN->replaceAllUsesWith(Conv);
444 RecursivelyDeleteTriviallyDeadInstructions(PN);
445 }
446
447 // Add a new IVUsers entry for the newly-created integer PHI.
448 if (IU)
449 IU->AddUsersIfInteresting(NewPHI);
Andrew Trick4b4bb712011-08-10 03:46:27 +0000450
451 Changed = true;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000452}
453
Andrew Trick1a54bb22011-07-12 00:08:50 +0000454void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) {
455 // First step. Check to see if there are any floating-point recurrences.
456 // If there are, change them into integer recurrences, permitting analysis by
457 // the SCEV routines.
458 //
459 BasicBlock *Header = L->getHeader();
460
461 SmallVector<WeakVH, 8> PHIs;
462 for (BasicBlock::iterator I = Header->begin();
463 PHINode *PN = dyn_cast<PHINode>(I); ++I)
464 PHIs.push_back(PN);
465
466 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
467 if (PHINode *PN = dyn_cast_or_null<PHINode>(&*PHIs[i]))
468 HandleFloatingPointIV(L, PN);
469
470 // If the loop previously had floating-point IV, ScalarEvolution
471 // may not have been able to compute a trip count. Now that we've done some
472 // re-writing, the trip count may be computable.
473 if (Changed)
474 SE->forgetLoop(L);
475}
476
477//===----------------------------------------------------------------------===//
478// RewriteLoopExitValues - Optimize IV users outside the loop.
479// As a side effect, reduces the amount of IV processing within the loop.
480//===----------------------------------------------------------------------===//
481
Chris Lattner40bf8b42004-04-02 20:24:31 +0000482/// RewriteLoopExitValues - Check to see if this loop has a computable
483/// loop-invariant execution count. If so, this means that we can compute the
484/// final value of any expressions that are recurrent in the loop, and
485/// substitute the exit values from the loop into any instructions outside of
486/// the loop that use the final values of the current expressions.
Dan Gohman81db61a2009-05-12 02:17:14 +0000487///
488/// This is mostly redundant with the regular IndVarSimplify activities that
489/// happen later, except that it's more powerful in some cases, because it's
490/// able to brute-force evaluate arbitrary instructions as long as they have
491/// constant operands at the beginning of the loop.
Chris Lattnerf1859892011-01-09 02:16:18 +0000492void IndVarSimplify::RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000493 // Verify the input to the pass in already in LCSSA form.
Dan Gohmanbbf81d82010-03-10 19:38:49 +0000494 assert(L->isLCSSAForm(*DT));
Dan Gohman81db61a2009-05-12 02:17:14 +0000495
Devang Patelb7211a22007-08-21 00:31:24 +0000496 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattner9f3d7382007-03-04 03:43:23 +0000497 L->getUniqueExitBlocks(ExitBlocks);
Misha Brukmanfd939082005-04-21 23:48:37 +0000498
Chris Lattner9f3d7382007-03-04 03:43:23 +0000499 // Find all values that are computed inside the loop, but used outside of it.
500 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
501 // the exit blocks of the loop to find them.
502 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
503 BasicBlock *ExitBB = ExitBlocks[i];
Dan Gohmancafb8132009-02-17 19:13:57 +0000504
Chris Lattner9f3d7382007-03-04 03:43:23 +0000505 // If there are no PHI nodes in this exit block, then no values defined
506 // inside the loop are used on this path, skip it.
507 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
508 if (!PN) continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000509
Chris Lattner9f3d7382007-03-04 03:43:23 +0000510 unsigned NumPreds = PN->getNumIncomingValues();
Dan Gohmancafb8132009-02-17 19:13:57 +0000511
Chris Lattner9f3d7382007-03-04 03:43:23 +0000512 // Iterate over all of the PHI nodes.
513 BasicBlock::iterator BBI = ExitBB->begin();
514 while ((PN = dyn_cast<PHINode>(BBI++))) {
Torok Edwin3790fb02009-05-24 19:36:09 +0000515 if (PN->use_empty())
516 continue; // dead use, don't replace it
Dan Gohman814f2b22010-02-18 21:34:02 +0000517
518 // SCEV only supports integer expressions for now.
519 if (!PN->getType()->isIntegerTy() && !PN->getType()->isPointerTy())
520 continue;
521
Dale Johannesen45a2d7d2010-02-19 07:14:22 +0000522 // It's necessary to tell ScalarEvolution about this explicitly so that
523 // it can walk the def-use list and forget all SCEVs, as it may not be
524 // watching the PHI itself. Once the new exit value is in place, there
525 // may not be a def-use connection between the loop and every instruction
526 // which got a SCEVAddRecExpr for that loop.
527 SE->forgetValue(PN);
528
Chris Lattner9f3d7382007-03-04 03:43:23 +0000529 // Iterate over all of the values in all the PHI nodes.
530 for (unsigned i = 0; i != NumPreds; ++i) {
531 // If the value being merged in is not integer or is not defined
532 // in the loop, skip it.
533 Value *InVal = PN->getIncomingValue(i);
Dan Gohman814f2b22010-02-18 21:34:02 +0000534 if (!isa<Instruction>(InVal))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000535 continue;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000536
Chris Lattner9f3d7382007-03-04 03:43:23 +0000537 // If this pred is for a subloop, not L itself, skip it.
Dan Gohmancafb8132009-02-17 19:13:57 +0000538 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
Chris Lattner9f3d7382007-03-04 03:43:23 +0000539 continue; // The Block is in a subloop, skip it.
540
541 // Check that InVal is defined in the loop.
542 Instruction *Inst = cast<Instruction>(InVal);
Dan Gohman92329c72009-12-18 01:24:09 +0000543 if (!L->contains(Inst))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000544 continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000545
Chris Lattner9f3d7382007-03-04 03:43:23 +0000546 // Okay, this instruction has a user outside of the current loop
547 // and varies predictably *inside* the loop. Evaluate the value it
548 // contains when the loop exits, if possible.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000549 const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
Dan Gohman17ead4f2010-11-17 21:23:15 +0000550 if (!SE->isLoopInvariant(ExitValue, L))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000551 continue;
Chris Lattner9caed542007-03-04 01:00:28 +0000552
Dan Gohman667d7872009-06-26 22:53:46 +0000553 Value *ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), Inst);
Dan Gohmancafb8132009-02-17 19:13:57 +0000554
David Greenef67ef312010-01-05 01:27:06 +0000555 DEBUG(dbgs() << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal << '\n'
Chris Lattnerbdff5482009-08-23 04:37:46 +0000556 << " LoopVal = " << *Inst << "\n");
Chris Lattner9f3d7382007-03-04 03:43:23 +0000557
Andrew Trickb12a7542011-03-17 23:51:11 +0000558 if (!isValidRewrite(Inst, ExitVal)) {
559 DeadInsts.push_back(ExitVal);
560 continue;
561 }
562 Changed = true;
563 ++NumReplaced;
564
Chris Lattner9f3d7382007-03-04 03:43:23 +0000565 PN->setIncomingValue(i, ExitVal);
Dan Gohmancafb8132009-02-17 19:13:57 +0000566
Dan Gohman81db61a2009-05-12 02:17:14 +0000567 // If this instruction is dead now, delete it.
568 RecursivelyDeleteTriviallyDeadInstructions(Inst);
Dan Gohmancafb8132009-02-17 19:13:57 +0000569
Dan Gohman65d1e2b2009-07-14 01:09:02 +0000570 if (NumPreds == 1) {
571 // Completely replace a single-pred PHI. This is safe, because the
572 // NewVal won't be variant in the loop, so we don't need an LCSSA phi
573 // node anymore.
Chris Lattner9f3d7382007-03-04 03:43:23 +0000574 PN->replaceAllUsesWith(ExitVal);
Dan Gohman81db61a2009-05-12 02:17:14 +0000575 RecursivelyDeleteTriviallyDeadInstructions(PN);
Chris Lattnerc9838f22007-03-03 22:48:48 +0000576 }
577 }
Dan Gohman65d1e2b2009-07-14 01:09:02 +0000578 if (NumPreds != 1) {
Dan Gohman667d7872009-06-26 22:53:46 +0000579 // Clone the PHI and delete the original one. This lets IVUsers and
580 // any other maps purge the original user from their records.
Devang Patel50b6e332009-10-27 22:16:29 +0000581 PHINode *NewPN = cast<PHINode>(PN->clone());
Dan Gohman667d7872009-06-26 22:53:46 +0000582 NewPN->takeName(PN);
583 NewPN->insertBefore(PN);
584 PN->replaceAllUsesWith(NewPN);
585 PN->eraseFromParent();
586 }
Chris Lattnerc9838f22007-03-03 22:48:48 +0000587 }
588 }
Dan Gohman472fdf72010-03-20 03:53:53 +0000589
590 // The insertion point instruction may have been deleted; clear it out
591 // so that the rewriter doesn't trip over it later.
592 Rewriter.clearInsertPoint();
Chris Lattner40bf8b42004-04-02 20:24:31 +0000593}
594
Andrew Trick1a54bb22011-07-12 00:08:50 +0000595//===----------------------------------------------------------------------===//
596// Rewrite IV users based on a canonical IV.
Andrew Trickf21bdf42011-09-12 18:28:44 +0000597// Only for use with -enable-iv-rewrite.
Andrew Trick1a54bb22011-07-12 00:08:50 +0000598//===----------------------------------------------------------------------===//
Dale Johannesenc671d892009-04-15 23:31:51 +0000599
Andrew Trick39d78022011-09-09 17:35:10 +0000600/// FIXME: It is an extremely bad idea to indvar substitute anything more
601/// complex than affine induction variables. Doing so will put expensive
602/// polynomial evaluations inside of the loop, and the str reduction pass
603/// currently can only reduce affine polynomials. For now just disable
604/// indvar subst on anything more complex than an affine addrec, unless
605/// it can be expanded to a trivial value.
Andrew Trick1a54bb22011-07-12 00:08:50 +0000606static bool isSafe(const SCEV *S, const Loop *L, ScalarEvolution *SE) {
607 // Loop-invariant values are safe.
608 if (SE->isLoopInvariant(S, L)) return true;
609
610 // Affine addrecs are safe. Non-affine are not, because LSR doesn't know how
611 // to transform them into efficient code.
612 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
613 return AR->isAffine();
614
615 // An add is safe it all its operands are safe.
Andrew Trick39d78022011-09-09 17:35:10 +0000616 if (const SCEVCommutativeExpr *Commutative
617 = dyn_cast<SCEVCommutativeExpr>(S)) {
Andrew Trick1a54bb22011-07-12 00:08:50 +0000618 for (SCEVCommutativeExpr::op_iterator I = Commutative->op_begin(),
619 E = Commutative->op_end(); I != E; ++I)
620 if (!isSafe(*I, L, SE)) return false;
621 return true;
622 }
623
624 // A cast is safe if its operand is.
625 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
626 return isSafe(C->getOperand(), L, SE);
627
628 // A udiv is safe if its operands are.
629 if (const SCEVUDivExpr *UD = dyn_cast<SCEVUDivExpr>(S))
630 return isSafe(UD->getLHS(), L, SE) &&
631 isSafe(UD->getRHS(), L, SE);
632
633 // SCEVUnknown is always safe.
634 if (isa<SCEVUnknown>(S))
635 return true;
636
637 // Nothing else is safe.
638 return false;
639}
640
641void IndVarSimplify::RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter) {
642 // Rewrite all induction variable expressions in terms of the canonical
643 // induction variable.
644 //
645 // If there were induction variables of other sizes or offsets, manually
646 // add the offsets to the primary induction variable and cast, avoiding
647 // the need for the code evaluation methods to insert induction variables
648 // of different sizes.
649 for (IVUsers::iterator UI = IU->begin(), E = IU->end(); UI != E; ++UI) {
650 Value *Op = UI->getOperandValToReplace();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000651 Type *UseTy = Op->getType();
Andrew Trick1a54bb22011-07-12 00:08:50 +0000652 Instruction *User = UI->getUser();
653
654 // Compute the final addrec to expand into code.
655 const SCEV *AR = IU->getReplacementExpr(*UI);
656
657 // Evaluate the expression out of the loop, if possible.
658 if (!L->contains(UI->getUser())) {
659 const SCEV *ExitVal = SE->getSCEVAtScope(AR, L->getParentLoop());
660 if (SE->isLoopInvariant(ExitVal, L))
661 AR = ExitVal;
662 }
663
664 // FIXME: It is an extremely bad idea to indvar substitute anything more
665 // complex than affine induction variables. Doing so will put expensive
666 // polynomial evaluations inside of the loop, and the str reduction pass
667 // currently can only reduce affine polynomials. For now just disable
668 // indvar subst on anything more complex than an affine addrec, unless
669 // it can be expanded to a trivial value.
670 if (!isSafe(AR, L, SE))
671 continue;
672
673 // Determine the insertion point for this user. By default, insert
674 // immediately before the user. The SCEVExpander class will automatically
675 // hoist loop invariants out of the loop. For PHI nodes, there may be
676 // multiple uses, so compute the nearest common dominator for the
677 // incoming blocks.
Andrew Trick86c98142011-07-20 05:32:06 +0000678 Instruction *InsertPt = getInsertPointForUses(User, Op, DT);
Andrew Trick1a54bb22011-07-12 00:08:50 +0000679
680 // Now expand it into actual Instructions and patch it into place.
681 Value *NewVal = Rewriter.expandCodeFor(AR, UseTy, InsertPt);
682
683 DEBUG(dbgs() << "INDVARS: Rewrote IV '" << *AR << "' " << *Op << '\n'
684 << " into = " << *NewVal << "\n");
685
686 if (!isValidRewrite(Op, NewVal)) {
687 DeadInsts.push_back(NewVal);
688 continue;
689 }
690 // Inform ScalarEvolution that this value is changing. The change doesn't
691 // affect its value, but it does potentially affect which use lists the
692 // value will be on after the replacement, which affects ScalarEvolution's
693 // ability to walk use lists and drop dangling pointers when a value is
694 // deleted.
695 SE->forgetValue(User);
696
697 // Patch the new value into place.
698 if (Op->hasName())
699 NewVal->takeName(Op);
700 if (Instruction *NewValI = dyn_cast<Instruction>(NewVal))
701 NewValI->setDebugLoc(User->getDebugLoc());
702 User->replaceUsesOfWith(Op, NewVal);
703 UI->setOperandValToReplace(NewVal);
704
705 ++NumRemoved;
706 Changed = true;
707
708 // The old value may be dead now.
709 DeadInsts.push_back(Op);
710 }
711}
712
713//===----------------------------------------------------------------------===//
714// IV Widening - Extend the width of an IV to cover its widest uses.
715//===----------------------------------------------------------------------===//
716
Andrew Trickf85092c2011-05-20 18:25:42 +0000717namespace {
718 // Collect information about induction variables that are used by sign/zero
719 // extend operations. This information is recorded by CollectExtend and
720 // provides the input to WidenIV.
721 struct WideIVInfo {
Andrew Trick513b1f42011-10-15 01:38:14 +0000722 PHINode *NarrowIV;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000723 Type *WidestNativeType; // Widest integer type created [sz]ext
Andrew Trick4b4bb712011-08-10 03:46:27 +0000724 bool IsSigned; // Was an sext user seen before a zext?
Andrew Trickf85092c2011-05-20 18:25:42 +0000725
Andrew Trick513b1f42011-10-15 01:38:14 +0000726 WideIVInfo() : NarrowIV(0), WidestNativeType(0), IsSigned(false) {}
Andrew Trickf85092c2011-05-20 18:25:42 +0000727 };
Andrew Trick4b4bb712011-08-10 03:46:27 +0000728
729 class WideIVVisitor : public IVVisitor {
730 ScalarEvolution *SE;
731 const TargetData *TD;
732
733 public:
734 WideIVInfo WI;
735
Andrew Trick513b1f42011-10-15 01:38:14 +0000736 WideIVVisitor(PHINode *NarrowIV, ScalarEvolution *SCEV,
737 const TargetData *TData) :
738 SE(SCEV), TD(TData) { WI.NarrowIV = NarrowIV; }
Andrew Trick4b4bb712011-08-10 03:46:27 +0000739
740 // Implement the interface used by simplifyUsersOfIV.
741 virtual void visitCast(CastInst *Cast);
742 };
Andrew Trickf85092c2011-05-20 18:25:42 +0000743}
744
Andrew Trick4b4bb712011-08-10 03:46:27 +0000745/// visitCast - Update information about the induction variable that is
Andrew Trickf85092c2011-05-20 18:25:42 +0000746/// extended by this sign or zero extend operation. This is used to determine
747/// the final width of the IV before actually widening it.
Andrew Trick4b4bb712011-08-10 03:46:27 +0000748void WideIVVisitor::visitCast(CastInst *Cast) {
749 bool IsSigned = Cast->getOpcode() == Instruction::SExt;
750 if (!IsSigned && Cast->getOpcode() != Instruction::ZExt)
751 return;
752
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000753 Type *Ty = Cast->getType();
Andrew Trickf85092c2011-05-20 18:25:42 +0000754 uint64_t Width = SE->getTypeSizeInBits(Ty);
755 if (TD && !TD->isLegalInteger(Width))
756 return;
757
Andrew Trick2fabd462011-06-21 03:22:38 +0000758 if (!WI.WidestNativeType) {
759 WI.WidestNativeType = SE->getEffectiveSCEVType(Ty);
760 WI.IsSigned = IsSigned;
Andrew Trickf85092c2011-05-20 18:25:42 +0000761 return;
762 }
763
764 // We extend the IV to satisfy the sign of its first user, arbitrarily.
Andrew Trick2fabd462011-06-21 03:22:38 +0000765 if (WI.IsSigned != IsSigned)
Andrew Trickf85092c2011-05-20 18:25:42 +0000766 return;
767
Andrew Trick2fabd462011-06-21 03:22:38 +0000768 if (Width > SE->getTypeSizeInBits(WI.WidestNativeType))
769 WI.WidestNativeType = SE->getEffectiveSCEVType(Ty);
Andrew Trickf85092c2011-05-20 18:25:42 +0000770}
771
772namespace {
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000773
774/// NarrowIVDefUse - Record a link in the Narrow IV def-use chain along with the
775/// WideIV that computes the same value as the Narrow IV def. This avoids
776/// caching Use* pointers.
777struct NarrowIVDefUse {
778 Instruction *NarrowDef;
779 Instruction *NarrowUse;
780 Instruction *WideDef;
781
782 NarrowIVDefUse(): NarrowDef(0), NarrowUse(0), WideDef(0) {}
783
784 NarrowIVDefUse(Instruction *ND, Instruction *NU, Instruction *WD):
785 NarrowDef(ND), NarrowUse(NU), WideDef(WD) {}
786};
787
Andrew Trickf85092c2011-05-20 18:25:42 +0000788/// WidenIV - The goal of this transform is to remove sign and zero extends
789/// without creating any new induction variables. To do this, it creates a new
790/// phi of the wider type and redirects all users, either removing extends or
791/// inserting truncs whenever we stop propagating the type.
792///
793class WidenIV {
Andrew Trick2fabd462011-06-21 03:22:38 +0000794 // Parameters
Andrew Trickf85092c2011-05-20 18:25:42 +0000795 PHINode *OrigPhi;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000796 Type *WideType;
Andrew Trickf85092c2011-05-20 18:25:42 +0000797 bool IsSigned;
798
Andrew Trick2fabd462011-06-21 03:22:38 +0000799 // Context
800 LoopInfo *LI;
801 Loop *L;
Andrew Trickf85092c2011-05-20 18:25:42 +0000802 ScalarEvolution *SE;
Andrew Trick2fabd462011-06-21 03:22:38 +0000803 DominatorTree *DT;
Andrew Trickf85092c2011-05-20 18:25:42 +0000804
Andrew Trick2fabd462011-06-21 03:22:38 +0000805 // Result
Andrew Trickf85092c2011-05-20 18:25:42 +0000806 PHINode *WidePhi;
807 Instruction *WideInc;
808 const SCEV *WideIncExpr;
Andrew Trick2fabd462011-06-21 03:22:38 +0000809 SmallVectorImpl<WeakVH> &DeadInsts;
Andrew Trickf85092c2011-05-20 18:25:42 +0000810
Andrew Trick2fabd462011-06-21 03:22:38 +0000811 SmallPtrSet<Instruction*,16> Widened;
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000812 SmallVector<NarrowIVDefUse, 8> NarrowIVUsers;
Andrew Trickf85092c2011-05-20 18:25:42 +0000813
814public:
Andrew Trick513b1f42011-10-15 01:38:14 +0000815 WidenIV(const WideIVInfo &WI, LoopInfo *LInfo,
Andrew Trick2fabd462011-06-21 03:22:38 +0000816 ScalarEvolution *SEv, DominatorTree *DTree,
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000817 SmallVectorImpl<WeakVH> &DI) :
Andrew Trick513b1f42011-10-15 01:38:14 +0000818 OrigPhi(WI.NarrowIV),
Andrew Trick2fabd462011-06-21 03:22:38 +0000819 WideType(WI.WidestNativeType),
820 IsSigned(WI.IsSigned),
Andrew Trickf85092c2011-05-20 18:25:42 +0000821 LI(LInfo),
822 L(LI->getLoopFor(OrigPhi->getParent())),
823 SE(SEv),
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000824 DT(DTree),
Andrew Trickf85092c2011-05-20 18:25:42 +0000825 WidePhi(0),
826 WideInc(0),
Andrew Trick2fabd462011-06-21 03:22:38 +0000827 WideIncExpr(0),
828 DeadInsts(DI) {
Andrew Trickf85092c2011-05-20 18:25:42 +0000829 assert(L->getHeader() == OrigPhi->getParent() && "Phi must be an IV");
830 }
831
Andrew Trick2fabd462011-06-21 03:22:38 +0000832 PHINode *CreateWideIV(SCEVExpander &Rewriter);
Andrew Trickf85092c2011-05-20 18:25:42 +0000833
834protected:
Andrew Trick909ef7d2011-09-28 01:35:36 +0000835 Value *getExtend(Value *NarrowOper, Type *WideType, bool IsSigned,
836 Instruction *Use);
837
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000838 Instruction *CloneIVUser(NarrowIVDefUse DU);
Andrew Trickf85092c2011-05-20 18:25:42 +0000839
Andrew Tricke0dc2fa2011-07-05 18:19:39 +0000840 const SCEVAddRecExpr *GetWideRecurrence(Instruction *NarrowUse);
841
Andrew Trick20151da2011-09-10 01:24:17 +0000842 const SCEVAddRecExpr* GetExtendedOperandRecurrence(NarrowIVDefUse DU);
843
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000844 Instruction *WidenIVUse(NarrowIVDefUse DU);
Andrew Trick4b029152011-07-02 02:34:25 +0000845
846 void pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef);
Andrew Trickf85092c2011-05-20 18:25:42 +0000847};
848} // anonymous namespace
849
Andrew Trick909ef7d2011-09-28 01:35:36 +0000850/// isLoopInvariant - Perform a quick domtree based check for loop invariance
851/// assuming that V is used within the loop. LoopInfo::isLoopInvariant() seems
852/// gratuitous for this purpose.
853static bool isLoopInvariant(Value *V, const Loop *L, const DominatorTree *DT) {
854 Instruction *Inst = dyn_cast<Instruction>(V);
855 if (!Inst)
856 return true;
857
858 return DT->properlyDominates(Inst->getParent(), L->getHeader());
859}
860
861Value *WidenIV::getExtend(Value *NarrowOper, Type *WideType, bool IsSigned,
862 Instruction *Use) {
863 // Set the debug location and conservative insertion point.
864 IRBuilder<> Builder(Use);
865 // Hoist the insertion point into loop preheaders as far as possible.
866 for (const Loop *L = LI->getLoopFor(Use->getParent());
867 L && L->getLoopPreheader() && isLoopInvariant(NarrowOper, L, DT);
868 L = L->getParentLoop())
869 Builder.SetInsertPoint(L->getLoopPreheader()->getTerminator());
870
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000871 return IsSigned ? Builder.CreateSExt(NarrowOper, WideType) :
872 Builder.CreateZExt(NarrowOper, WideType);
Andrew Trickf85092c2011-05-20 18:25:42 +0000873}
874
875/// CloneIVUser - Instantiate a wide operation to replace a narrow
876/// operation. This only needs to handle operations that can evaluation to
877/// SCEVAddRec. It can safely return 0 for any operation we decide not to clone.
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000878Instruction *WidenIV::CloneIVUser(NarrowIVDefUse DU) {
879 unsigned Opcode = DU.NarrowUse->getOpcode();
Andrew Trickf85092c2011-05-20 18:25:42 +0000880 switch (Opcode) {
881 default:
882 return 0;
883 case Instruction::Add:
884 case Instruction::Mul:
885 case Instruction::UDiv:
886 case Instruction::Sub:
887 case Instruction::And:
888 case Instruction::Or:
889 case Instruction::Xor:
890 case Instruction::Shl:
891 case Instruction::LShr:
892 case Instruction::AShr:
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000893 DEBUG(dbgs() << "Cloning IVUser: " << *DU.NarrowUse << "\n");
Andrew Trickf85092c2011-05-20 18:25:42 +0000894
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000895 // Replace NarrowDef operands with WideDef. Otherwise, we don't know
896 // anything about the narrow operand yet so must insert a [sz]ext. It is
897 // probably loop invariant and will be folded or hoisted. If it actually
898 // comes from a widened IV, it should be removed during a future call to
899 // WidenIVUse.
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000900 Value *LHS = (DU.NarrowUse->getOperand(0) == DU.NarrowDef) ? DU.WideDef :
Andrew Trick909ef7d2011-09-28 01:35:36 +0000901 getExtend(DU.NarrowUse->getOperand(0), WideType, IsSigned, DU.NarrowUse);
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000902 Value *RHS = (DU.NarrowUse->getOperand(1) == DU.NarrowDef) ? DU.WideDef :
Andrew Trick909ef7d2011-09-28 01:35:36 +0000903 getExtend(DU.NarrowUse->getOperand(1), WideType, IsSigned, DU.NarrowUse);
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000904
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000905 BinaryOperator *NarrowBO = cast<BinaryOperator>(DU.NarrowUse);
Andrew Trickf85092c2011-05-20 18:25:42 +0000906 BinaryOperator *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(),
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000907 LHS, RHS,
Andrew Trickf85092c2011-05-20 18:25:42 +0000908 NarrowBO->getName());
Andrew Trick909ef7d2011-09-28 01:35:36 +0000909 IRBuilder<> Builder(DU.NarrowUse);
Andrew Trickf85092c2011-05-20 18:25:42 +0000910 Builder.Insert(WideBO);
Andrew Trick6e0ce242011-06-30 19:02:17 +0000911 if (const OverflowingBinaryOperator *OBO =
912 dyn_cast<OverflowingBinaryOperator>(NarrowBO)) {
913 if (OBO->hasNoUnsignedWrap()) WideBO->setHasNoUnsignedWrap();
914 if (OBO->hasNoSignedWrap()) WideBO->setHasNoSignedWrap();
915 }
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000916 return WideBO;
Andrew Trickf85092c2011-05-20 18:25:42 +0000917 }
918 llvm_unreachable(0);
919}
920
Andrew Trick20151da2011-09-10 01:24:17 +0000921/// No-wrap operations can transfer sign extension of their result to their
922/// operands. Generate the SCEV value for the widened operation without
923/// actually modifying the IR yet. If the expression after extending the
924/// operands is an AddRec for this loop, return it.
925const SCEVAddRecExpr* WidenIV::GetExtendedOperandRecurrence(NarrowIVDefUse DU) {
926 // Handle the common case of add<nsw/nuw>
927 if (DU.NarrowUse->getOpcode() != Instruction::Add)
928 return 0;
929
930 // One operand (NarrowDef) has already been extended to WideDef. Now determine
931 // if extending the other will lead to a recurrence.
932 unsigned ExtendOperIdx = DU.NarrowUse->getOperand(0) == DU.NarrowDef ? 1 : 0;
933 assert(DU.NarrowUse->getOperand(1-ExtendOperIdx) == DU.NarrowDef && "bad DU");
934
935 const SCEV *ExtendOperExpr = 0;
936 const OverflowingBinaryOperator *OBO =
937 cast<OverflowingBinaryOperator>(DU.NarrowUse);
938 if (IsSigned && OBO->hasNoSignedWrap())
939 ExtendOperExpr = SE->getSignExtendExpr(
940 SE->getSCEV(DU.NarrowUse->getOperand(ExtendOperIdx)), WideType);
941 else if(!IsSigned && OBO->hasNoUnsignedWrap())
942 ExtendOperExpr = SE->getZeroExtendExpr(
943 SE->getSCEV(DU.NarrowUse->getOperand(ExtendOperIdx)), WideType);
944 else
945 return 0;
946
Andrew Trickecb35ec2011-11-29 02:16:38 +0000947 // When creating this AddExpr, don't apply the current operations NSW or NUW
948 // flags. This instruction may be guarded by control flow that the no-wrap
949 // behavior depends on. Non-control-equivalent instructions can be mapped to
950 // the same SCEV expression, and it would be incorrect to transfer NSW/NUW
951 // semantics to those operations.
Andrew Trick20151da2011-09-10 01:24:17 +0000952 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(
Andrew Trickecb35ec2011-11-29 02:16:38 +0000953 SE->getAddExpr(SE->getSCEV(DU.WideDef), ExtendOperExpr));
Andrew Trick20151da2011-09-10 01:24:17 +0000954
955 if (!AddRec || AddRec->getLoop() != L)
956 return 0;
957 return AddRec;
958}
959
Andrew Trick39d78022011-09-09 17:35:10 +0000960/// GetWideRecurrence - Is this instruction potentially interesting from
961/// IVUsers' perspective after widening it's type? In other words, can the
962/// extend be safely hoisted out of the loop with SCEV reducing the value to a
963/// recurrence on the same loop. If so, return the sign or zero extended
964/// recurrence. Otherwise return NULL.
Andrew Tricke0dc2fa2011-07-05 18:19:39 +0000965const SCEVAddRecExpr *WidenIV::GetWideRecurrence(Instruction *NarrowUse) {
966 if (!SE->isSCEVable(NarrowUse->getType()))
967 return 0;
968
969 const SCEV *NarrowExpr = SE->getSCEV(NarrowUse);
970 if (SE->getTypeSizeInBits(NarrowExpr->getType())
971 >= SE->getTypeSizeInBits(WideType)) {
972 // NarrowUse implicitly widens its operand. e.g. a gep with a narrow
973 // index. So don't follow this use.
974 return 0;
975 }
976
977 const SCEV *WideExpr = IsSigned ?
978 SE->getSignExtendExpr(NarrowExpr, WideType) :
979 SE->getZeroExtendExpr(NarrowExpr, WideType);
980 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(WideExpr);
981 if (!AddRec || AddRec->getLoop() != L)
982 return 0;
Andrew Tricke0dc2fa2011-07-05 18:19:39 +0000983 return AddRec;
984}
985
Andrew Trickf85092c2011-05-20 18:25:42 +0000986/// WidenIVUse - Determine whether an individual user of the narrow IV can be
987/// widened. If so, return the wide clone of the user.
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000988Instruction *WidenIV::WidenIVUse(NarrowIVDefUse DU) {
Andrew Trickcc359d92011-06-29 23:03:57 +0000989
Andrew Trick4b029152011-07-02 02:34:25 +0000990 // Stop traversing the def-use chain at inner-loop phis or post-loop phis.
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000991 if (isa<PHINode>(DU.NarrowUse) &&
992 LI->getLoopFor(DU.NarrowUse->getParent()) != L)
Andrew Trickf85092c2011-05-20 18:25:42 +0000993 return 0;
994
Andrew Trickf85092c2011-05-20 18:25:42 +0000995 // Our raison d'etre! Eliminate sign and zero extension.
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000996 if (IsSigned ? isa<SExtInst>(DU.NarrowUse) : isa<ZExtInst>(DU.NarrowUse)) {
997 Value *NewDef = DU.WideDef;
998 if (DU.NarrowUse->getType() != WideType) {
999 unsigned CastWidth = SE->getTypeSizeInBits(DU.NarrowUse->getType());
Andrew Trick03d3d3b2011-05-25 04:42:22 +00001000 unsigned IVWidth = SE->getTypeSizeInBits(WideType);
1001 if (CastWidth < IVWidth) {
1002 // The cast isn't as wide as the IV, so insert a Trunc.
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001003 IRBuilder<> Builder(DU.NarrowUse);
1004 NewDef = Builder.CreateTrunc(DU.WideDef, DU.NarrowUse->getType());
Andrew Trick03d3d3b2011-05-25 04:42:22 +00001005 }
1006 else {
1007 // A wider extend was hidden behind a narrower one. This may induce
1008 // another round of IV widening in which the intermediate IV becomes
1009 // dead. It should be very rare.
1010 DEBUG(dbgs() << "INDVARS: New IV " << *WidePhi
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001011 << " not wide enough to subsume " << *DU.NarrowUse << "\n");
1012 DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef);
1013 NewDef = DU.NarrowUse;
Andrew Trick03d3d3b2011-05-25 04:42:22 +00001014 }
1015 }
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001016 if (NewDef != DU.NarrowUse) {
1017 DEBUG(dbgs() << "INDVARS: eliminating " << *DU.NarrowUse
1018 << " replaced by " << *DU.WideDef << "\n");
Andrew Trick03d3d3b2011-05-25 04:42:22 +00001019 ++NumElimExt;
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001020 DU.NarrowUse->replaceAllUsesWith(NewDef);
1021 DeadInsts.push_back(DU.NarrowUse);
Andrew Trick03d3d3b2011-05-25 04:42:22 +00001022 }
Andrew Trick2fabd462011-06-21 03:22:38 +00001023 // Now that the extend is gone, we want to expose it's uses for potential
1024 // further simplification. We don't need to directly inform SimplifyIVUsers
1025 // of the new users, because their parent IV will be processed later as a
1026 // new loop phi. If we preserved IVUsers analysis, we would also want to
1027 // push the uses of WideDef here.
Andrew Trickf85092c2011-05-20 18:25:42 +00001028
1029 // No further widening is needed. The deceased [sz]ext had done it for us.
1030 return 0;
1031 }
Andrew Trick4b029152011-07-02 02:34:25 +00001032
1033 // Does this user itself evaluate to a recurrence after widening?
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001034 const SCEVAddRecExpr *WideAddRec = GetWideRecurrence(DU.NarrowUse);
Andrew Trickf85092c2011-05-20 18:25:42 +00001035 if (!WideAddRec) {
Andrew Trick20151da2011-09-10 01:24:17 +00001036 WideAddRec = GetExtendedOperandRecurrence(DU);
1037 }
1038 if (!WideAddRec) {
Andrew Trickf85092c2011-05-20 18:25:42 +00001039 // This user does not evaluate to a recurence after widening, so don't
1040 // follow it. Instead insert a Trunc to kill off the original use,
1041 // eventually isolating the original narrow IV so it can be removed.
Andrew Trick86c98142011-07-20 05:32:06 +00001042 IRBuilder<> Builder(getInsertPointForUses(DU.NarrowUse, DU.NarrowDef, DT));
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001043 Value *Trunc = Builder.CreateTrunc(DU.WideDef, DU.NarrowDef->getType());
1044 DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, Trunc);
Andrew Trickf85092c2011-05-20 18:25:42 +00001045 return 0;
1046 }
Andrew Trickfc933c02011-07-18 20:32:31 +00001047 // Assume block terminators cannot evaluate to a recurrence. We can't to
Andrew Trick4b029152011-07-02 02:34:25 +00001048 // insert a Trunc after a terminator if there happens to be a critical edge.
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001049 assert(DU.NarrowUse != DU.NarrowUse->getParent()->getTerminator() &&
Andrew Trick4b029152011-07-02 02:34:25 +00001050 "SCEV is not expected to evaluate a block terminator");
Andrew Trickcc359d92011-06-29 23:03:57 +00001051
Andrew Trickfcdc9a42011-05-26 00:46:11 +00001052 // Reuse the IV increment that SCEVExpander created as long as it dominates
1053 // NarrowUse.
Andrew Trickf85092c2011-05-20 18:25:42 +00001054 Instruction *WideUse = 0;
Andrew Trick20449412011-10-11 02:28:51 +00001055 if (WideAddRec == WideIncExpr
1056 && SCEVExpander::hoistStep(WideInc, DU.NarrowUse, DT))
Andrew Trickf85092c2011-05-20 18:25:42 +00001057 WideUse = WideInc;
Andrew Trickf85092c2011-05-20 18:25:42 +00001058 else {
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001059 WideUse = CloneIVUser(DU);
Andrew Trickf85092c2011-05-20 18:25:42 +00001060 if (!WideUse)
1061 return 0;
1062 }
Andrew Trick4b029152011-07-02 02:34:25 +00001063 // Evaluation of WideAddRec ensured that the narrow expression could be
1064 // extended outside the loop without overflow. This suggests that the wide use
Andrew Trickf85092c2011-05-20 18:25:42 +00001065 // evaluates to the same expression as the extended narrow use, but doesn't
1066 // absolutely guarantee it. Hence the following failsafe check. In rare cases
Andrew Trick2fabd462011-06-21 03:22:38 +00001067 // where it fails, we simply throw away the newly created wide use.
Andrew Trickf85092c2011-05-20 18:25:42 +00001068 if (WideAddRec != SE->getSCEV(WideUse)) {
1069 DEBUG(dbgs() << "Wide use expression mismatch: " << *WideUse
1070 << ": " << *SE->getSCEV(WideUse) << " != " << *WideAddRec << "\n");
1071 DeadInsts.push_back(WideUse);
1072 return 0;
1073 }
1074
1075 // Returning WideUse pushes it on the worklist.
1076 return WideUse;
1077}
1078
Andrew Trick4b029152011-07-02 02:34:25 +00001079/// pushNarrowIVUsers - Add eligible users of NarrowDef to NarrowIVUsers.
1080///
1081void WidenIV::pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef) {
1082 for (Value::use_iterator UI = NarrowDef->use_begin(),
1083 UE = NarrowDef->use_end(); UI != UE; ++UI) {
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001084 Instruction *NarrowUse = cast<Instruction>(*UI);
Andrew Trick4b029152011-07-02 02:34:25 +00001085
1086 // Handle data flow merges and bizarre phi cycles.
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001087 if (!Widened.insert(NarrowUse))
Andrew Trick4b029152011-07-02 02:34:25 +00001088 continue;
1089
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001090 NarrowIVUsers.push_back(NarrowIVDefUse(NarrowDef, NarrowUse, WideDef));
Andrew Trick4b029152011-07-02 02:34:25 +00001091 }
1092}
1093
Andrew Trickf85092c2011-05-20 18:25:42 +00001094/// CreateWideIV - Process a single induction variable. First use the
1095/// SCEVExpander to create a wide induction variable that evaluates to the same
1096/// recurrence as the original narrow IV. Then use a worklist to forward
Andrew Trick2fabd462011-06-21 03:22:38 +00001097/// traverse the narrow IV's def-use chain. After WidenIVUse has processed all
Andrew Trickf85092c2011-05-20 18:25:42 +00001098/// interesting IV users, the narrow IV will be isolated for removal by
1099/// DeleteDeadPHIs.
1100///
1101/// It would be simpler to delete uses as they are processed, but we must avoid
1102/// invalidating SCEV expressions.
1103///
Andrew Trick2fabd462011-06-21 03:22:38 +00001104PHINode *WidenIV::CreateWideIV(SCEVExpander &Rewriter) {
Andrew Trickf85092c2011-05-20 18:25:42 +00001105 // Is this phi an induction variable?
1106 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(OrigPhi));
1107 if (!AddRec)
Andrew Trick2fabd462011-06-21 03:22:38 +00001108 return NULL;
Andrew Trickf85092c2011-05-20 18:25:42 +00001109
1110 // Widen the induction variable expression.
1111 const SCEV *WideIVExpr = IsSigned ?
1112 SE->getSignExtendExpr(AddRec, WideType) :
1113 SE->getZeroExtendExpr(AddRec, WideType);
1114
1115 assert(SE->getEffectiveSCEVType(WideIVExpr->getType()) == WideType &&
1116 "Expect the new IV expression to preserve its type");
1117
1118 // Can the IV be extended outside the loop without overflow?
1119 AddRec = dyn_cast<SCEVAddRecExpr>(WideIVExpr);
1120 if (!AddRec || AddRec->getLoop() != L)
Andrew Trick2fabd462011-06-21 03:22:38 +00001121 return NULL;
Andrew Trickf85092c2011-05-20 18:25:42 +00001122
Andrew Trick2fabd462011-06-21 03:22:38 +00001123 // An AddRec must have loop-invariant operands. Since this AddRec is
Andrew Trickf85092c2011-05-20 18:25:42 +00001124 // materialized by a loop header phi, the expression cannot have any post-loop
1125 // operands, so they must dominate the loop header.
1126 assert(SE->properlyDominates(AddRec->getStart(), L->getHeader()) &&
1127 SE->properlyDominates(AddRec->getStepRecurrence(*SE), L->getHeader())
1128 && "Loop header phi recurrence inputs do not dominate the loop");
1129
1130 // The rewriter provides a value for the desired IV expression. This may
1131 // either find an existing phi or materialize a new one. Either way, we
1132 // expect a well-formed cyclic phi-with-increments. i.e. any operand not part
1133 // of the phi-SCC dominates the loop entry.
1134 Instruction *InsertPt = L->getHeader()->begin();
1135 WidePhi = cast<PHINode>(Rewriter.expandCodeFor(AddRec, WideType, InsertPt));
1136
1137 // Remembering the WideIV increment generated by SCEVExpander allows
1138 // WidenIVUse to reuse it when widening the narrow IV's increment. We don't
1139 // employ a general reuse mechanism because the call above is the only call to
1140 // SCEVExpander. Henceforth, we produce 1-to-1 narrow to wide uses.
Andrew Trickfcdc9a42011-05-26 00:46:11 +00001141 if (BasicBlock *LatchBlock = L->getLoopLatch()) {
1142 WideInc =
1143 cast<Instruction>(WidePhi->getIncomingValueForBlock(LatchBlock));
1144 WideIncExpr = SE->getSCEV(WideInc);
1145 }
Andrew Trickf85092c2011-05-20 18:25:42 +00001146
1147 DEBUG(dbgs() << "Wide IV: " << *WidePhi << "\n");
1148 ++NumWidened;
1149
1150 // Traverse the def-use chain using a worklist starting at the original IV.
Andrew Trick4b029152011-07-02 02:34:25 +00001151 assert(Widened.empty() && NarrowIVUsers.empty() && "expect initial state" );
Andrew Trickf85092c2011-05-20 18:25:42 +00001152
Andrew Trick4b029152011-07-02 02:34:25 +00001153 Widened.insert(OrigPhi);
1154 pushNarrowIVUsers(OrigPhi, WidePhi);
1155
Andrew Trickf85092c2011-05-20 18:25:42 +00001156 while (!NarrowIVUsers.empty()) {
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001157 NarrowIVDefUse DU = NarrowIVUsers.pop_back_val();
Andrew Trickf85092c2011-05-20 18:25:42 +00001158
Andrew Trickfcdc9a42011-05-26 00:46:11 +00001159 // Process a def-use edge. This may replace the use, so don't hold a
1160 // use_iterator across it.
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001161 Instruction *WideUse = WidenIVUse(DU);
Andrew Trickf85092c2011-05-20 18:25:42 +00001162
Andrew Trickfcdc9a42011-05-26 00:46:11 +00001163 // Follow all def-use edges from the previous narrow use.
Andrew Trick4b029152011-07-02 02:34:25 +00001164 if (WideUse)
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001165 pushNarrowIVUsers(DU.NarrowUse, WideUse);
Andrew Trick4b029152011-07-02 02:34:25 +00001166
Andrew Trickfcdc9a42011-05-26 00:46:11 +00001167 // WidenIVUse may have removed the def-use edge.
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001168 if (DU.NarrowDef->use_empty())
1169 DeadInsts.push_back(DU.NarrowDef);
Andrew Trickf85092c2011-05-20 18:25:42 +00001170 }
Andrew Trick2fabd462011-06-21 03:22:38 +00001171 return WidePhi;
Andrew Trickf85092c2011-05-20 18:25:42 +00001172}
1173
Andrew Trick1a54bb22011-07-12 00:08:50 +00001174//===----------------------------------------------------------------------===//
1175// Simplification of IV users based on SCEV evaluation.
1176//===----------------------------------------------------------------------===//
1177
Andrew Trickaeee4612011-05-12 00:04:28 +00001178
Andrew Trick4b4bb712011-08-10 03:46:27 +00001179/// SimplifyAndExtend - Iteratively perform simplification on a worklist of IV
1180/// users. Each successive simplification may push more users which may
Andrew Trick2fabd462011-06-21 03:22:38 +00001181/// themselves be candidates for simplification.
1182///
Andrew Trick4b4bb712011-08-10 03:46:27 +00001183/// Sign/Zero extend elimination is interleaved with IV simplification.
Andrew Trick2fabd462011-06-21 03:22:38 +00001184///
Andrew Trick4b4bb712011-08-10 03:46:27 +00001185void IndVarSimplify::SimplifyAndExtend(Loop *L,
1186 SCEVExpander &Rewriter,
1187 LPPassManager &LPM) {
Andrew Trick513b1f42011-10-15 01:38:14 +00001188 SmallVector<WideIVInfo, 8> WideIVs;
Andrew Trick15832f62011-06-28 02:49:20 +00001189
Andrew Trick2fabd462011-06-21 03:22:38 +00001190 SmallVector<PHINode*, 8> LoopPhis;
1191 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
1192 LoopPhis.push_back(cast<PHINode>(I));
1193 }
Andrew Trick15832f62011-06-28 02:49:20 +00001194 // Each round of simplification iterates through the SimplifyIVUsers worklist
1195 // for all current phis, then determines whether any IVs can be
1196 // widened. Widening adds new phis to LoopPhis, inducing another round of
1197 // simplification on the wide IVs.
Andrew Trick2fabd462011-06-21 03:22:38 +00001198 while (!LoopPhis.empty()) {
Andrew Trick15832f62011-06-28 02:49:20 +00001199 // Evaluate as many IV expressions as possible before widening any IVs. This
Andrew Trick99a92f62011-06-28 16:45:04 +00001200 // forces SCEV to set no-wrap flags before evaluating sign/zero
Andrew Trick15832f62011-06-28 02:49:20 +00001201 // extension. The first time SCEV attempts to normalize sign/zero extension,
1202 // the result becomes final. So for the most predictable results, we delay
1203 // evaluation of sign/zero extend evaluation until needed, and avoid running
Andrew Trick4b4bb712011-08-10 03:46:27 +00001204 // other SCEV based analysis prior to SimplifyAndExtend.
Andrew Trick15832f62011-06-28 02:49:20 +00001205 do {
1206 PHINode *CurrIV = LoopPhis.pop_back_val();
Andrew Trick2fabd462011-06-21 03:22:38 +00001207
Andrew Trick15832f62011-06-28 02:49:20 +00001208 // Information about sign/zero extensions of CurrIV.
Andrew Trick513b1f42011-10-15 01:38:14 +00001209 WideIVVisitor WIV(CurrIV, SE, TD);
Andrew Trick2fabd462011-06-21 03:22:38 +00001210
Andrew Trickbddb7f82011-08-10 04:22:26 +00001211 Changed |= simplifyUsersOfIV(CurrIV, SE, &LPM, DeadInsts, &WIV);
Andrew Trick2fabd462011-06-21 03:22:38 +00001212
Andrew Trick4b4bb712011-08-10 03:46:27 +00001213 if (WIV.WI.WidestNativeType) {
Andrew Trick513b1f42011-10-15 01:38:14 +00001214 WideIVs.push_back(WIV.WI);
Andrew Trick2fabd462011-06-21 03:22:38 +00001215 }
Andrew Trick15832f62011-06-28 02:49:20 +00001216 } while(!LoopPhis.empty());
1217
Andrew Trick513b1f42011-10-15 01:38:14 +00001218 for (; !WideIVs.empty(); WideIVs.pop_back()) {
1219 WidenIV Widener(WideIVs.back(), LI, SE, DT, DeadInsts);
Andrew Trick2fabd462011-06-21 03:22:38 +00001220 if (PHINode *WidePhi = Widener.CreateWideIV(Rewriter)) {
1221 Changed = true;
1222 LoopPhis.push_back(WidePhi);
1223 }
1224 }
1225 }
1226}
1227
Andrew Trick1a54bb22011-07-12 00:08:50 +00001228//===----------------------------------------------------------------------===//
1229// LinearFunctionTestReplace and its kin. Rewrite the loop exit condition.
1230//===----------------------------------------------------------------------===//
1231
Andrew Trick39d78022011-09-09 17:35:10 +00001232/// Check for expressions that ScalarEvolution generates to compute
1233/// BackedgeTakenInfo. If these expressions have not been reduced, then
1234/// expanding them may incur additional cost (albeit in the loop preheader).
Andrew Trick5241b792011-07-18 18:21:35 +00001235static bool isHighCostExpansion(const SCEV *S, BranchInst *BI,
1236 ScalarEvolution *SE) {
1237 // If the backedge-taken count is a UDiv, it's very likely a UDiv that
1238 // ScalarEvolution's HowFarToZero or HowManyLessThans produced to compute a
1239 // precise expression, rather than a UDiv from the user's code. If we can't
1240 // find a UDiv in the code with some simple searching, assume the former and
1241 // forego rewriting the loop.
1242 if (isa<SCEVUDivExpr>(S)) {
1243 ICmpInst *OrigCond = dyn_cast<ICmpInst>(BI->getCondition());
1244 if (!OrigCond) return true;
1245 const SCEV *R = SE->getSCEV(OrigCond->getOperand(1));
1246 R = SE->getMinusSCEV(R, SE->getConstant(R->getType(), 1));
1247 if (R != S) {
1248 const SCEV *L = SE->getSCEV(OrigCond->getOperand(0));
1249 L = SE->getMinusSCEV(L, SE->getConstant(L->getType(), 1));
1250 if (L != S)
1251 return true;
1252 }
1253 }
1254
Andrew Trickf21bdf42011-09-12 18:28:44 +00001255 if (EnableIVRewrite)
Andrew Trick5241b792011-07-18 18:21:35 +00001256 return false;
1257
1258 // Recurse past add expressions, which commonly occur in the
1259 // BackedgeTakenCount. They may already exist in program code, and if not,
1260 // they are not too expensive rematerialize.
1261 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
1262 for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
1263 I != E; ++I) {
1264 if (isHighCostExpansion(*I, BI, SE))
1265 return true;
1266 }
1267 return false;
1268 }
1269
1270 // HowManyLessThans uses a Max expression whenever the loop is not guarded by
1271 // the exit condition.
1272 if (isa<SCEVSMaxExpr>(S) || isa<SCEVUMaxExpr>(S))
1273 return true;
1274
1275 // If we haven't recognized an expensive SCEV patter, assume its an expression
1276 // produced by program code.
1277 return false;
1278}
1279
Andrew Trick1a54bb22011-07-12 00:08:50 +00001280/// canExpandBackedgeTakenCount - Return true if this loop's backedge taken
1281/// count expression can be safely and cheaply expanded into an instruction
1282/// sequence that can be used by LinearFunctionTestReplace.
Andrew Trickd3714b62011-11-02 17:19:57 +00001283///
1284/// TODO: This fails for pointer-type loop counters with greater than one byte
1285/// strides, consequently preventing LFTR from running. For the purpose of LFTR
1286/// we could skip this check in the case that the LFTR loop counter (chosen by
1287/// FindLoopCounter) is also pointer type. Instead, we could directly convert
1288/// the loop test to an inequality test by checking the target data's alignment
1289/// of element types (given that the initial pointer value originates from or is
1290/// used by ABI constrained operation, as opposed to inttoptr/ptrtoint).
1291/// However, we don't yet have a strong motivation for converting loop tests
1292/// into inequality tests.
Andrew Trick1a54bb22011-07-12 00:08:50 +00001293static bool canExpandBackedgeTakenCount(Loop *L, ScalarEvolution *SE) {
1294 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
1295 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount) ||
1296 BackedgeTakenCount->isZero())
1297 return false;
1298
1299 if (!L->getExitingBlock())
1300 return false;
1301
1302 // Can't rewrite non-branch yet.
1303 BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator());
1304 if (!BI)
1305 return false;
1306
Andrew Trick5241b792011-07-18 18:21:35 +00001307 if (isHighCostExpansion(BackedgeTakenCount, BI, SE))
1308 return false;
1309
Andrew Trick1a54bb22011-07-12 00:08:50 +00001310 return true;
1311}
1312
1313/// getBackedgeIVType - Get the widest type used by the loop test after peeking
1314/// through Truncs.
1315///
Andrew Trickfc933c02011-07-18 20:32:31 +00001316/// TODO: Unnecessary when ForceLFTR is removed.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001317static Type *getBackedgeIVType(Loop *L) {
Andrew Trick1a54bb22011-07-12 00:08:50 +00001318 if (!L->getExitingBlock())
1319 return 0;
1320
1321 // Can't rewrite non-branch yet.
1322 BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator());
1323 if (!BI)
1324 return 0;
1325
1326 ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition());
1327 if (!Cond)
1328 return 0;
1329
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001330 Type *Ty = 0;
Andrew Trick1a54bb22011-07-12 00:08:50 +00001331 for(User::op_iterator OI = Cond->op_begin(), OE = Cond->op_end();
1332 OI != OE; ++OI) {
1333 assert((!Ty || Ty == (*OI)->getType()) && "bad icmp operand types");
1334 TruncInst *Trunc = dyn_cast<TruncInst>(*OI);
1335 if (!Trunc)
1336 continue;
1337
1338 return Trunc->getSrcTy();
1339 }
1340 return Ty;
1341}
1342
Andrew Trickfc933c02011-07-18 20:32:31 +00001343/// getLoopPhiForCounter - Return the loop header phi IFF IncV adds a loop
1344/// invariant value to the phi.
1345static PHINode *getLoopPhiForCounter(Value *IncV, Loop *L, DominatorTree *DT) {
1346 Instruction *IncI = dyn_cast<Instruction>(IncV);
1347 if (!IncI)
1348 return 0;
1349
1350 switch (IncI->getOpcode()) {
1351 case Instruction::Add:
1352 case Instruction::Sub:
1353 break;
1354 case Instruction::GetElementPtr:
1355 // An IV counter must preserve its type.
1356 if (IncI->getNumOperands() == 2)
1357 break;
1358 default:
1359 return 0;
1360 }
1361
1362 PHINode *Phi = dyn_cast<PHINode>(IncI->getOperand(0));
1363 if (Phi && Phi->getParent() == L->getHeader()) {
1364 if (isLoopInvariant(IncI->getOperand(1), L, DT))
1365 return Phi;
1366 return 0;
1367 }
1368 if (IncI->getOpcode() == Instruction::GetElementPtr)
1369 return 0;
1370
1371 // Allow add/sub to be commuted.
1372 Phi = dyn_cast<PHINode>(IncI->getOperand(1));
1373 if (Phi && Phi->getParent() == L->getHeader()) {
1374 if (isLoopInvariant(IncI->getOperand(0), L, DT))
1375 return Phi;
1376 }
1377 return 0;
1378}
1379
1380/// needsLFTR - LinearFunctionTestReplace policy. Return true unless we can show
1381/// that the current exit test is already sufficiently canonical.
1382static bool needsLFTR(Loop *L, DominatorTree *DT) {
1383 assert(L->getExitingBlock() && "expected loop exit");
1384
1385 BasicBlock *LatchBlock = L->getLoopLatch();
1386 // Don't bother with LFTR if the loop is not properly simplified.
1387 if (!LatchBlock)
1388 return false;
1389
1390 BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator());
1391 assert(BI && "expected exit branch");
1392
1393 // Do LFTR to simplify the exit condition to an ICMP.
1394 ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition());
1395 if (!Cond)
1396 return true;
1397
1398 // Do LFTR to simplify the exit ICMP to EQ/NE
1399 ICmpInst::Predicate Pred = Cond->getPredicate();
1400 if (Pred != ICmpInst::ICMP_NE && Pred != ICmpInst::ICMP_EQ)
1401 return true;
1402
1403 // Look for a loop invariant RHS
1404 Value *LHS = Cond->getOperand(0);
1405 Value *RHS = Cond->getOperand(1);
1406 if (!isLoopInvariant(RHS, L, DT)) {
1407 if (!isLoopInvariant(LHS, L, DT))
1408 return true;
1409 std::swap(LHS, RHS);
1410 }
1411 // Look for a simple IV counter LHS
1412 PHINode *Phi = dyn_cast<PHINode>(LHS);
1413 if (!Phi)
1414 Phi = getLoopPhiForCounter(LHS, L, DT);
1415
1416 if (!Phi)
1417 return true;
1418
1419 // Do LFTR if the exit condition's IV is *not* a simple counter.
1420 Value *IncV = Phi->getIncomingValueForBlock(L->getLoopLatch());
1421 return Phi != getLoopPhiForCounter(IncV, L, DT);
1422}
1423
1424/// AlmostDeadIV - Return true if this IV has any uses other than the (soon to
1425/// be rewritten) loop exit test.
1426static bool AlmostDeadIV(PHINode *Phi, BasicBlock *LatchBlock, Value *Cond) {
1427 int LatchIdx = Phi->getBasicBlockIndex(LatchBlock);
1428 Value *IncV = Phi->getIncomingValue(LatchIdx);
1429
1430 for (Value::use_iterator UI = Phi->use_begin(), UE = Phi->use_end();
1431 UI != UE; ++UI) {
1432 if (*UI != Cond && *UI != IncV) return false;
1433 }
1434
1435 for (Value::use_iterator UI = IncV->use_begin(), UE = IncV->use_end();
1436 UI != UE; ++UI) {
1437 if (*UI != Cond && *UI != Phi) return false;
1438 }
1439 return true;
1440}
1441
1442/// FindLoopCounter - Find an affine IV in canonical form.
1443///
Andrew Trickd3714b62011-11-02 17:19:57 +00001444/// BECount may be an i8* pointer type. The pointer difference is already
1445/// valid count without scaling the address stride, so it remains a pointer
1446/// expression as far as SCEV is concerned.
1447///
Andrew Trickfc933c02011-07-18 20:32:31 +00001448/// FIXME: Accept -1 stride and set IVLimit = IVInit - BECount
1449///
1450/// FIXME: Accept non-unit stride as long as SCEV can reduce BECount * Stride.
1451/// This is difficult in general for SCEV because of potential overflow. But we
1452/// could at least handle constant BECounts.
1453static PHINode *
1454FindLoopCounter(Loop *L, const SCEV *BECount,
1455 ScalarEvolution *SE, DominatorTree *DT, const TargetData *TD) {
Andrew Trickfc933c02011-07-18 20:32:31 +00001456 uint64_t BCWidth = SE->getTypeSizeInBits(BECount->getType());
1457
1458 Value *Cond =
1459 cast<BranchInst>(L->getExitingBlock()->getTerminator())->getCondition();
1460
1461 // Loop over all of the PHI nodes, looking for a simple counter.
1462 PHINode *BestPhi = 0;
1463 const SCEV *BestInit = 0;
1464 BasicBlock *LatchBlock = L->getLoopLatch();
1465 assert(LatchBlock && "needsLFTR should guarantee a loop latch");
1466
1467 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
1468 PHINode *Phi = cast<PHINode>(I);
1469 if (!SE->isSCEVable(Phi->getType()))
1470 continue;
1471
Andrew Trickd3714b62011-11-02 17:19:57 +00001472 // Avoid comparing an integer IV against a pointer Limit.
1473 if (BECount->getType()->isPointerTy() && !Phi->getType()->isPointerTy())
1474 continue;
1475
Andrew Trickfc933c02011-07-18 20:32:31 +00001476 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Phi));
1477 if (!AR || AR->getLoop() != L || !AR->isAffine())
1478 continue;
1479
1480 // AR may be a pointer type, while BECount is an integer type.
1481 // AR may be wider than BECount. With eq/ne tests overflow is immaterial.
1482 // AR may not be a narrower type, or we may never exit.
1483 uint64_t PhiWidth = SE->getTypeSizeInBits(AR->getType());
1484 if (PhiWidth < BCWidth || (TD && !TD->isLegalInteger(PhiWidth)))
1485 continue;
1486
1487 const SCEV *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*SE));
1488 if (!Step || !Step->isOne())
1489 continue;
1490
1491 int LatchIdx = Phi->getBasicBlockIndex(LatchBlock);
1492 Value *IncV = Phi->getIncomingValue(LatchIdx);
1493 if (getLoopPhiForCounter(IncV, L, DT) != Phi)
1494 continue;
1495
1496 const SCEV *Init = AR->getStart();
1497
1498 if (BestPhi && !AlmostDeadIV(BestPhi, LatchBlock, Cond)) {
1499 // Don't force a live loop counter if another IV can be used.
1500 if (AlmostDeadIV(Phi, LatchBlock, Cond))
1501 continue;
1502
1503 // Prefer to count-from-zero. This is a more "canonical" counter form. It
1504 // also prefers integer to pointer IVs.
1505 if (BestInit->isZero() != Init->isZero()) {
1506 if (BestInit->isZero())
1507 continue;
1508 }
1509 // If two IVs both count from zero or both count from nonzero then the
1510 // narrower is likely a dead phi that has been widened. Use the wider phi
1511 // to allow the other to be eliminated.
1512 if (PhiWidth <= SE->getTypeSizeInBits(BestPhi->getType()))
1513 continue;
1514 }
1515 BestPhi = Phi;
1516 BestInit = Init;
1517 }
1518 return BestPhi;
1519}
1520
Andrew Trickd3714b62011-11-02 17:19:57 +00001521/// genLoopLimit - Help LinearFunctionTestReplace by generating a value that
1522/// holds the RHS of the new loop test.
1523static Value *genLoopLimit(PHINode *IndVar, const SCEV *IVCount, Loop *L,
1524 SCEVExpander &Rewriter, ScalarEvolution *SE) {
1525 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(IndVar));
1526 assert(AR && AR->getLoop() == L && AR->isAffine() && "bad loop counter");
1527 const SCEV *IVInit = AR->getStart();
1528
1529 // IVInit may be a pointer while IVCount is an integer when FindLoopCounter
1530 // finds a valid pointer IV. Sign extend BECount in order to materialize a
1531 // GEP. Avoid running SCEVExpander on a new pointer value, instead reusing
1532 // the existing GEPs whenever possible.
1533 if (IndVar->getType()->isPointerTy()
1534 && !IVCount->getType()->isPointerTy()) {
1535
1536 Type *OfsTy = SE->getEffectiveSCEVType(IVInit->getType());
1537 const SCEV *IVOffset = SE->getTruncateOrSignExtend(IVCount, OfsTy);
1538
1539 // Expand the code for the iteration count.
1540 assert(SE->isLoopInvariant(IVOffset, L) &&
1541 "Computed iteration count is not loop invariant!");
1542 BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator());
1543 Value *GEPOffset = Rewriter.expandCodeFor(IVOffset, OfsTy, BI);
1544
1545 Value *GEPBase = IndVar->getIncomingValueForBlock(L->getLoopPreheader());
1546 assert(AR->getStart() == SE->getSCEV(GEPBase) && "bad loop counter");
1547 // We could handle pointer IVs other than i8*, but we need to compensate for
1548 // gep index scaling. See canExpandBackedgeTakenCount comments.
1549 assert(SE->getSizeOfExpr(
1550 cast<PointerType>(GEPBase->getType())->getElementType())->isOne()
1551 && "unit stride pointer IV must be i8*");
1552
1553 IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
1554 return Builder.CreateGEP(GEPBase, GEPOffset, "lftr.limit");
1555 }
1556 else {
1557 // In any other case, convert both IVInit and IVCount to integers before
1558 // comparing. This may result in SCEV expension of pointers, but in practice
1559 // SCEV will fold the pointer arithmetic away as such:
1560 // BECount = (IVEnd - IVInit - 1) => IVLimit = IVInit (postinc).
1561 //
1562 // Valid Cases: (1) both integers is most common; (2) both may be pointers
1563 // for simple memset-style loops; (3) IVInit is an integer and IVCount is a
1564 // pointer may occur when enable-iv-rewrite generates a canonical IV on top
1565 // of case #2.
1566
1567 const SCEV *IVLimit = 0;
1568 // For unit stride, IVCount = Start + BECount with 2's complement overflow.
1569 // For non-zero Start, compute IVCount here.
1570 if (AR->getStart()->isZero())
1571 IVLimit = IVCount;
1572 else {
1573 assert(AR->getStepRecurrence(*SE)->isOne() && "only handles unit stride");
1574 const SCEV *IVInit = AR->getStart();
1575
1576 // For integer IVs, truncate the IV before computing IVInit + BECount.
1577 if (SE->getTypeSizeInBits(IVInit->getType())
1578 > SE->getTypeSizeInBits(IVCount->getType()))
1579 IVInit = SE->getTruncateExpr(IVInit, IVCount->getType());
1580
1581 IVLimit = SE->getAddExpr(IVInit, IVCount);
1582 }
1583 // Expand the code for the iteration count.
1584 BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator());
1585 IRBuilder<> Builder(BI);
1586 assert(SE->isLoopInvariant(IVLimit, L) &&
1587 "Computed iteration count is not loop invariant!");
1588 // Ensure that we generate the same type as IndVar, or a smaller integer
1589 // type. In the presence of null pointer values, we have an integer type
1590 // SCEV expression (IVInit) for a pointer type IV value (IndVar).
1591 Type *LimitTy = IVCount->getType()->isPointerTy() ?
1592 IndVar->getType() : IVCount->getType();
1593 return Rewriter.expandCodeFor(IVLimit, LimitTy, BI);
1594 }
1595}
1596
Andrew Trick1a54bb22011-07-12 00:08:50 +00001597/// LinearFunctionTestReplace - This method rewrites the exit condition of the
1598/// loop to be a canonical != comparison against the incremented loop induction
1599/// variable. This pass is able to rewrite the exit tests of any loop where the
1600/// SCEV analysis can determine a loop-invariant trip count of the loop, which
1601/// is actually a much broader range than just linear tests.
Andrew Trickfc933c02011-07-18 20:32:31 +00001602Value *IndVarSimplify::
Andrew Trick1a54bb22011-07-12 00:08:50 +00001603LinearFunctionTestReplace(Loop *L,
1604 const SCEV *BackedgeTakenCount,
1605 PHINode *IndVar,
1606 SCEVExpander &Rewriter) {
1607 assert(canExpandBackedgeTakenCount(L, SE) && "precondition");
Andrew Trick1a54bb22011-07-12 00:08:50 +00001608
Andrew Trickf21bdf42011-09-12 18:28:44 +00001609 // LFTR can ignore IV overflow and truncate to the width of
Andrew Trickfc933c02011-07-18 20:32:31 +00001610 // BECount. This avoids materializing the add(zext(add)) expression.
Andrew Trickf21bdf42011-09-12 18:28:44 +00001611 Type *CntTy = !EnableIVRewrite ?
Andrew Trickfc933c02011-07-18 20:32:31 +00001612 BackedgeTakenCount->getType() : IndVar->getType();
1613
Andrew Trickd3714b62011-11-02 17:19:57 +00001614 const SCEV *IVCount = BackedgeTakenCount;
Andrew Trickfc933c02011-07-18 20:32:31 +00001615
Andrew Trickd3714b62011-11-02 17:19:57 +00001616 // If the exiting block is the same as the backedge block, we prefer to
1617 // compare against the post-incremented value, otherwise we must compare
1618 // against the preincremented value.
Andrew Trick1a54bb22011-07-12 00:08:50 +00001619 Value *CmpIndVar;
Andrew Trick1a54bb22011-07-12 00:08:50 +00001620 if (L->getExitingBlock() == L->getLoopLatch()) {
1621 // Add one to the "backedge-taken" count to get the trip count.
1622 // If this addition may overflow, we have to be more pessimistic and
1623 // cast the induction variable before doing the add.
Andrew Trick1a54bb22011-07-12 00:08:50 +00001624 const SCEV *N =
Andrew Trickd3714b62011-11-02 17:19:57 +00001625 SE->getAddExpr(IVCount, SE->getConstant(IVCount->getType(), 1));
1626 if (CntTy == IVCount->getType())
1627 IVCount = N;
Andrew Trickfc933c02011-07-18 20:32:31 +00001628 else {
Andrew Trickd3714b62011-11-02 17:19:57 +00001629 const SCEV *Zero = SE->getConstant(IVCount->getType(), 0);
Andrew Trickfc933c02011-07-18 20:32:31 +00001630 if ((isa<SCEVConstant>(N) && !N->isZero()) ||
1631 SE->isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) {
1632 // No overflow. Cast the sum.
Andrew Trickd3714b62011-11-02 17:19:57 +00001633 IVCount = SE->getTruncateOrZeroExtend(N, CntTy);
Andrew Trickfc933c02011-07-18 20:32:31 +00001634 } else {
1635 // Potential overflow. Cast before doing the add.
Andrew Trickd3714b62011-11-02 17:19:57 +00001636 IVCount = SE->getTruncateOrZeroExtend(IVCount, CntTy);
1637 IVCount = SE->getAddExpr(IVCount, SE->getConstant(CntTy, 1));
Andrew Trickfc933c02011-07-18 20:32:31 +00001638 }
Andrew Trick1a54bb22011-07-12 00:08:50 +00001639 }
Andrew Trick1a54bb22011-07-12 00:08:50 +00001640 // The BackedgeTaken expression contains the number of times that the
1641 // backedge branches to the loop header. This is one less than the
1642 // number of times the loop executes, so use the incremented indvar.
1643 CmpIndVar = IndVar->getIncomingValueForBlock(L->getExitingBlock());
1644 } else {
Andrew Trickd3714b62011-11-02 17:19:57 +00001645 // We must use the preincremented value...
1646 IVCount = SE->getTruncateOrZeroExtend(IVCount, CntTy);
Andrew Trick1a54bb22011-07-12 00:08:50 +00001647 CmpIndVar = IndVar;
1648 }
1649
Andrew Trickd3714b62011-11-02 17:19:57 +00001650 Value *ExitCnt = genLoopLimit(IndVar, IVCount, L, Rewriter, SE);
1651 assert(ExitCnt->getType()->isPointerTy() == IndVar->getType()->isPointerTy()
1652 && "genLoopLimit missed a cast");
Andrew Trick1a54bb22011-07-12 00:08:50 +00001653
1654 // Insert a new icmp_ne or icmp_eq instruction before the branch.
Andrew Trickd3714b62011-11-02 17:19:57 +00001655 BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator());
Andrew Trickfc933c02011-07-18 20:32:31 +00001656 ICmpInst::Predicate P;
Andrew Trick1a54bb22011-07-12 00:08:50 +00001657 if (L->contains(BI->getSuccessor(0)))
Andrew Trickfc933c02011-07-18 20:32:31 +00001658 P = ICmpInst::ICMP_NE;
Andrew Trick1a54bb22011-07-12 00:08:50 +00001659 else
Andrew Trickfc933c02011-07-18 20:32:31 +00001660 P = ICmpInst::ICMP_EQ;
Andrew Trick1a54bb22011-07-12 00:08:50 +00001661
1662 DEBUG(dbgs() << "INDVARS: Rewriting loop exit condition to:\n"
1663 << " LHS:" << *CmpIndVar << '\n'
1664 << " op:\t"
Andrew Trickfc933c02011-07-18 20:32:31 +00001665 << (P == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
1666 << " RHS:\t" << *ExitCnt << "\n"
Andrew Trickd3714b62011-11-02 17:19:57 +00001667 << " IVCount:\t" << *IVCount << "\n");
Andrew Trick1a54bb22011-07-12 00:08:50 +00001668
Andrew Trickd3714b62011-11-02 17:19:57 +00001669 IRBuilder<> Builder(BI);
Andrew Trickfc933c02011-07-18 20:32:31 +00001670 if (SE->getTypeSizeInBits(CmpIndVar->getType())
Andrew Trickd3714b62011-11-02 17:19:57 +00001671 > SE->getTypeSizeInBits(ExitCnt->getType())) {
1672 CmpIndVar = Builder.CreateTrunc(CmpIndVar, ExitCnt->getType(),
1673 "lftr.wideiv");
Andrew Trickfc933c02011-07-18 20:32:31 +00001674 }
1675
1676 Value *Cond = Builder.CreateICmp(P, CmpIndVar, ExitCnt, "exitcond");
Andrew Trick1a54bb22011-07-12 00:08:50 +00001677 Value *OrigCond = BI->getCondition();
1678 // It's tempting to use replaceAllUsesWith here to fully replace the old
1679 // comparison, but that's not immediately safe, since users of the old
1680 // comparison may not be dominated by the new comparison. Instead, just
1681 // update the branch to use the new comparison; in the common case this
1682 // will make old comparison dead.
1683 BI->setCondition(Cond);
1684 DeadInsts.push_back(OrigCond);
1685
1686 ++NumLFTR;
1687 Changed = true;
1688 return Cond;
1689}
1690
1691//===----------------------------------------------------------------------===//
1692// SinkUnusedInvariants. A late subpass to cleanup loop preheaders.
1693//===----------------------------------------------------------------------===//
1694
1695/// If there's a single exit block, sink any loop-invariant values that
1696/// were defined in the preheader but not used inside the loop into the
1697/// exit block to reduce register pressure in the loop.
1698void IndVarSimplify::SinkUnusedInvariants(Loop *L) {
1699 BasicBlock *ExitBlock = L->getExitBlock();
1700 if (!ExitBlock) return;
1701
1702 BasicBlock *Preheader = L->getLoopPreheader();
1703 if (!Preheader) return;
1704
Bill Wendlingb05fdd62011-08-24 20:28:43 +00001705 Instruction *InsertPt = ExitBlock->getFirstInsertionPt();
Andrew Trick1a54bb22011-07-12 00:08:50 +00001706 BasicBlock::iterator I = Preheader->getTerminator();
1707 while (I != Preheader->begin()) {
1708 --I;
1709 // New instructions were inserted at the end of the preheader.
1710 if (isa<PHINode>(I))
1711 break;
1712
1713 // Don't move instructions which might have side effects, since the side
1714 // effects need to complete before instructions inside the loop. Also don't
1715 // move instructions which might read memory, since the loop may modify
1716 // memory. Note that it's okay if the instruction might have undefined
1717 // behavior: LoopSimplify guarantees that the preheader dominates the exit
1718 // block.
1719 if (I->mayHaveSideEffects() || I->mayReadFromMemory())
1720 continue;
1721
1722 // Skip debug info intrinsics.
1723 if (isa<DbgInfoIntrinsic>(I))
1724 continue;
1725
Bill Wendling2b188812011-08-26 20:40:15 +00001726 // Skip landingpad instructions.
1727 if (isa<LandingPadInst>(I))
1728 continue;
1729
Eli Friedman8ecde6c2011-10-27 01:33:51 +00001730 // Don't sink alloca: we never want to sink static alloca's out of the
1731 // entry block, and correctly sinking dynamic alloca's requires
1732 // checks for stacksave/stackrestore intrinsics.
1733 // FIXME: Refactor this check somehow?
1734 if (isa<AllocaInst>(I))
1735 continue;
Andrew Trick1a54bb22011-07-12 00:08:50 +00001736
1737 // Determine if there is a use in or before the loop (direct or
1738 // otherwise).
1739 bool UsedInLoop = false;
1740 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
1741 UI != UE; ++UI) {
1742 User *U = *UI;
1743 BasicBlock *UseBB = cast<Instruction>(U)->getParent();
1744 if (PHINode *P = dyn_cast<PHINode>(U)) {
1745 unsigned i =
1746 PHINode::getIncomingValueNumForOperand(UI.getOperandNo());
1747 UseBB = P->getIncomingBlock(i);
1748 }
1749 if (UseBB == Preheader || L->contains(UseBB)) {
1750 UsedInLoop = true;
1751 break;
1752 }
1753 }
1754
1755 // If there is, the def must remain in the preheader.
1756 if (UsedInLoop)
1757 continue;
1758
1759 // Otherwise, sink it to the exit block.
1760 Instruction *ToMove = I;
1761 bool Done = false;
1762
1763 if (I != Preheader->begin()) {
1764 // Skip debug info intrinsics.
1765 do {
1766 --I;
1767 } while (isa<DbgInfoIntrinsic>(I) && I != Preheader->begin());
1768
1769 if (isa<DbgInfoIntrinsic>(I) && I == Preheader->begin())
1770 Done = true;
1771 } else {
1772 Done = true;
1773 }
1774
1775 ToMove->moveBefore(InsertPt);
1776 if (Done) break;
1777 InsertPt = ToMove;
1778 }
1779}
1780
1781//===----------------------------------------------------------------------===//
1782// IndVarSimplify driver. Manage several subpasses of IV simplification.
1783//===----------------------------------------------------------------------===//
1784
Dan Gohmanc2390b12009-02-12 22:19:27 +00001785bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
Dan Gohmana5283822010-06-18 01:35:11 +00001786 // If LoopSimplify form is not available, stay out of trouble. Some notes:
1787 // - LSR currently only supports LoopSimplify-form loops. Indvars'
1788 // canonicalization can be a pessimization without LSR to "clean up"
1789 // afterwards.
1790 // - We depend on having a preheader; in particular,
1791 // Loop::getCanonicalInductionVariable only supports loops with preheaders,
1792 // and we're in trouble if we can't find the induction variable even when
1793 // we've manually inserted one.
1794 if (!L->isLoopSimplifyForm())
1795 return false;
1796
Andrew Trickf21bdf42011-09-12 18:28:44 +00001797 if (EnableIVRewrite)
Andrew Trick2fabd462011-06-21 03:22:38 +00001798 IU = &getAnalysis<IVUsers>();
Devang Patel5ee99972007-03-07 06:39:01 +00001799 LI = &getAnalysis<LoopInfo>();
1800 SE = &getAnalysis<ScalarEvolution>();
Dan Gohmande53dc02009-06-27 05:16:57 +00001801 DT = &getAnalysis<DominatorTree>();
Andrew Trick37da4082011-05-04 02:10:13 +00001802 TD = getAnalysisIfAvailable<TargetData>();
1803
Andrew Trickb12a7542011-03-17 23:51:11 +00001804 DeadInsts.clear();
Devang Patel5ee99972007-03-07 06:39:01 +00001805 Changed = false;
Dan Gohman60f8a632009-02-17 20:49:49 +00001806
Dan Gohman2d1be872009-04-16 03:18:22 +00001807 // If there are any floating-point recurrences, attempt to
Dan Gohman60f8a632009-02-17 20:49:49 +00001808 // transform them to use integer recurrences.
1809 RewriteNonIntegerIVs(L);
1810
Dan Gohman0bba49c2009-07-07 17:06:11 +00001811 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
Chris Lattner9caed542007-03-04 01:00:28 +00001812
Dan Gohman667d7872009-06-26 22:53:46 +00001813 // Create a rewriter object which we'll use to transform the code with.
Andrew Trick5e7645b2011-06-28 05:07:32 +00001814 SCEVExpander Rewriter(*SE, "indvars");
Andrew Trick20449412011-10-11 02:28:51 +00001815#ifndef NDEBUG
1816 Rewriter.setDebugType(DEBUG_TYPE);
1817#endif
Andrew Trick156d4602011-06-27 23:17:44 +00001818
1819 // Eliminate redundant IV users.
Andrew Trick15832f62011-06-28 02:49:20 +00001820 //
1821 // Simplification works best when run before other consumers of SCEV. We
1822 // attempt to avoid evaluating SCEVs for sign/zero extend operations until
1823 // other expressions involving loop IVs have been evaluated. This helps SCEV
Andrew Trick99a92f62011-06-28 16:45:04 +00001824 // set no-wrap flags before normalizing sign/zero extension.
Andrew Trickf21bdf42011-09-12 18:28:44 +00001825 if (!EnableIVRewrite) {
Andrew Trick37da4082011-05-04 02:10:13 +00001826 Rewriter.disableCanonicalMode();
Andrew Trick4b4bb712011-08-10 03:46:27 +00001827 SimplifyAndExtend(L, Rewriter, LPM);
Andrew Trick156d4602011-06-27 23:17:44 +00001828 }
Andrew Trick37da4082011-05-04 02:10:13 +00001829
Chris Lattner40bf8b42004-04-02 20:24:31 +00001830 // Check to see if this loop has a computable loop-invariant execution count.
1831 // If so, this means that we can compute the final value of any expressions
1832 // that are recurrent in the loop, and substitute the exit values from the
1833 // loop into any instructions outside of the loop that use the final values of
1834 // the current expressions.
Chris Lattner3dec1f22002-05-10 15:38:35 +00001835 //
Dan Gohman46bdfb02009-02-24 18:55:53 +00001836 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount))
Dan Gohman454d26d2010-02-22 04:11:59 +00001837 RewriteLoopExitValues(L, Rewriter);
Chris Lattner6148c022001-12-03 17:28:42 +00001838
Andrew Trickf85092c2011-05-20 18:25:42 +00001839 // Eliminate redundant IV users.
Andrew Trickf21bdf42011-09-12 18:28:44 +00001840 if (EnableIVRewrite)
Andrew Trickbddb7f82011-08-10 04:22:26 +00001841 Changed |= simplifyIVUsers(IU, SE, &LPM, DeadInsts);
Dan Gohmana590b792010-04-13 01:46:36 +00001842
Andrew Trick6f684b02011-07-16 01:06:48 +00001843 // Eliminate redundant IV cycles.
Andrew Trickf21bdf42011-09-12 18:28:44 +00001844 if (!EnableIVRewrite)
Andrew Trick20449412011-10-11 02:28:51 +00001845 NumElimIV += Rewriter.replaceCongruentIVs(L, DT, DeadInsts);
Andrew Trick037d1c02011-07-06 20:50:43 +00001846
Dan Gohman81db61a2009-05-12 02:17:14 +00001847 // Compute the type of the largest recurrence expression, and decide whether
1848 // a canonical induction variable should be inserted.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001849 Type *LargestType = 0;
Dan Gohman81db61a2009-05-12 02:17:14 +00001850 bool NeedCannIV = false;
Andrew Trick03d3d3b2011-05-25 04:42:22 +00001851 bool ExpandBECount = canExpandBackedgeTakenCount(L, SE);
Andrew Trickf21bdf42011-09-12 18:28:44 +00001852 if (EnableIVRewrite && ExpandBECount) {
Dan Gohman81db61a2009-05-12 02:17:14 +00001853 // If we have a known trip count and a single exit block, we'll be
1854 // rewriting the loop exit test condition below, which requires a
1855 // canonical induction variable.
Andrew Trick4dfdf242011-05-03 22:24:10 +00001856 NeedCannIV = true;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001857 Type *Ty = BackedgeTakenCount->getType();
Andrew Trickf21bdf42011-09-12 18:28:44 +00001858 if (!EnableIVRewrite) {
Andrew Trick03d3d3b2011-05-25 04:42:22 +00001859 // In this mode, SimplifyIVUsers may have already widened the IV used by
1860 // the backedge test and inserted a Trunc on the compare's operand. Get
1861 // the wider type to avoid creating a redundant narrow IV only used by the
1862 // loop test.
1863 LargestType = getBackedgeIVType(L);
1864 }
Andrew Trick4dfdf242011-05-03 22:24:10 +00001865 if (!LargestType ||
1866 SE->getTypeSizeInBits(Ty) >
1867 SE->getTypeSizeInBits(LargestType))
1868 LargestType = SE->getEffectiveSCEVType(Ty);
Chris Lattnerf50af082004-04-17 18:08:33 +00001869 }
Andrew Trickf21bdf42011-09-12 18:28:44 +00001870 if (EnableIVRewrite) {
Andrew Trick37da4082011-05-04 02:10:13 +00001871 for (IVUsers::const_iterator I = IU->begin(), E = IU->end(); I != E; ++I) {
1872 NeedCannIV = true;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001873 Type *Ty =
Andrew Trick37da4082011-05-04 02:10:13 +00001874 SE->getEffectiveSCEVType(I->getOperandValToReplace()->getType());
1875 if (!LargestType ||
1876 SE->getTypeSizeInBits(Ty) >
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001877 SE->getTypeSizeInBits(LargestType))
Andrew Trick37da4082011-05-04 02:10:13 +00001878 LargestType = Ty;
1879 }
Chris Lattner6148c022001-12-03 17:28:42 +00001880 }
1881
Dan Gohmanf451cb82010-02-10 16:03:48 +00001882 // Now that we know the largest of the induction variable expressions
Dan Gohman81db61a2009-05-12 02:17:14 +00001883 // in this loop, insert a canonical induction variable of the largest size.
Dan Gohman43ef3fb2010-07-20 17:18:52 +00001884 PHINode *IndVar = 0;
Dan Gohman81db61a2009-05-12 02:17:14 +00001885 if (NeedCannIV) {
Dan Gohman85669632010-02-25 06:57:05 +00001886 // Check to see if the loop already has any canonical-looking induction
1887 // variables. If any are present and wider than the planned canonical
1888 // induction variable, temporarily remove them, so that the Rewriter
1889 // doesn't attempt to reuse them.
1890 SmallVector<PHINode *, 2> OldCannIVs;
1891 while (PHINode *OldCannIV = L->getCanonicalInductionVariable()) {
Dan Gohman4d8414f2009-06-13 16:25:49 +00001892 if (SE->getTypeSizeInBits(OldCannIV->getType()) >
1893 SE->getTypeSizeInBits(LargestType))
1894 OldCannIV->removeFromParent();
1895 else
Dan Gohman85669632010-02-25 06:57:05 +00001896 break;
1897 OldCannIVs.push_back(OldCannIV);
Dan Gohman4d8414f2009-06-13 16:25:49 +00001898 }
1899
Dan Gohman667d7872009-06-26 22:53:46 +00001900 IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L, LargestType);
Dan Gohman4d8414f2009-06-13 16:25:49 +00001901
Dan Gohmanc2390b12009-02-12 22:19:27 +00001902 ++NumInserted;
1903 Changed = true;
David Greenef67ef312010-01-05 01:27:06 +00001904 DEBUG(dbgs() << "INDVARS: New CanIV: " << *IndVar << '\n');
Dan Gohman4d8414f2009-06-13 16:25:49 +00001905
1906 // Now that the official induction variable is established, reinsert
Dan Gohman85669632010-02-25 06:57:05 +00001907 // any old canonical-looking variables after it so that the IR remains
1908 // consistent. They will be deleted as part of the dead-PHI deletion at
Dan Gohman4d8414f2009-06-13 16:25:49 +00001909 // the end of the pass.
Dan Gohman85669632010-02-25 06:57:05 +00001910 while (!OldCannIVs.empty()) {
1911 PHINode *OldCannIV = OldCannIVs.pop_back_val();
Bill Wendlingb05fdd62011-08-24 20:28:43 +00001912 OldCannIV->insertBefore(L->getHeader()->getFirstInsertionPt());
Dan Gohman85669632010-02-25 06:57:05 +00001913 }
Dan Gohmand19534a2007-06-15 14:38:12 +00001914 }
Andrew Trickf21bdf42011-09-12 18:28:44 +00001915 else if (!EnableIVRewrite && ExpandBECount && needsLFTR(L, DT)) {
Andrew Trickfc933c02011-07-18 20:32:31 +00001916 IndVar = FindLoopCounter(L, BackedgeTakenCount, SE, DT, TD);
1917 }
Dan Gohmanc2390b12009-02-12 22:19:27 +00001918 // If we have a trip count expression, rewrite the loop's exit condition
1919 // using it. We can currently only handle loops with a single exit.
Andrew Trickfc933c02011-07-18 20:32:31 +00001920 Value *NewICmp = 0;
1921 if (ExpandBECount && IndVar) {
Andrew Trick56147692011-07-16 01:18:53 +00001922 // Check preconditions for proper SCEVExpander operation. SCEV does not
1923 // express SCEVExpander's dependencies, such as LoopSimplify. Instead any
1924 // pass that uses the SCEVExpander must do it. This does not work well for
1925 // loop passes because SCEVExpander makes assumptions about all loops, while
1926 // LoopPassManager only forces the current loop to be simplified.
1927 //
1928 // FIXME: SCEV expansion has no way to bail out, so the caller must
1929 // explicitly check any assumptions made by SCEV. Brittle.
1930 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(BackedgeTakenCount);
1931 if (!AR || AR->getLoop()->getLoopPreheader())
1932 NewICmp =
1933 LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar, Rewriter);
Chris Lattnerfcb81f52004-04-22 14:59:40 +00001934 }
Andrew Trickb12a7542011-03-17 23:51:11 +00001935 // Rewrite IV-derived expressions.
Andrew Trickf21bdf42011-09-12 18:28:44 +00001936 if (EnableIVRewrite)
Andrew Trick37da4082011-05-04 02:10:13 +00001937 RewriteIVExpressions(L, Rewriter);
Dan Gohmanc2390b12009-02-12 22:19:27 +00001938
Andrew Trickb12a7542011-03-17 23:51:11 +00001939 // Clear the rewriter cache, because values that are in the rewriter's cache
1940 // can be deleted in the loop below, causing the AssertingVH in the cache to
1941 // trigger.
1942 Rewriter.clear();
1943
1944 // Now that we're done iterating through lists, clean up any instructions
1945 // which are now dead.
1946 while (!DeadInsts.empty())
1947 if (Instruction *Inst =
1948 dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val()))
1949 RecursivelyDeleteTriviallyDeadInstructions(Inst);
1950
Dan Gohman667d7872009-06-26 22:53:46 +00001951 // The Rewriter may not be used from this point on.
Torok Edwin3d431382009-05-24 20:08:21 +00001952
Dan Gohman81db61a2009-05-12 02:17:14 +00001953 // Loop-invariant instructions in the preheader that aren't used in the
1954 // loop may be sunk below the loop to reduce register pressure.
Dan Gohman667d7872009-06-26 22:53:46 +00001955 SinkUnusedInvariants(L);
Dan Gohman81db61a2009-05-12 02:17:14 +00001956
1957 // For completeness, inform IVUsers of the IV use in the newly-created
1958 // loop exit test instruction.
Andrew Trickfc933c02011-07-18 20:32:31 +00001959 if (IU && NewICmp) {
1960 ICmpInst *NewICmpInst = dyn_cast<ICmpInst>(NewICmp);
1961 if (NewICmpInst)
1962 IU->AddUsersIfInteresting(cast<Instruction>(NewICmpInst->getOperand(0)));
1963 }
Dan Gohman81db61a2009-05-12 02:17:14 +00001964 // Clean up dead instructions.
Dan Gohman9fff2182010-01-05 16:31:45 +00001965 Changed |= DeleteDeadPHIs(L->getHeader());
Dan Gohman81db61a2009-05-12 02:17:14 +00001966 // Check a post-condition.
Andrew Trickf6a0dba2011-07-18 18:44:20 +00001967 assert(L->isLCSSAForm(*DT) &&
1968 "Indvars did not leave the loop in lcssa form!");
1969
1970 // Verify that LFTR, and any other change have not interfered with SCEV's
1971 // ability to compute trip count.
1972#ifndef NDEBUG
Andrew Trickf21bdf42011-09-12 18:28:44 +00001973 if (!EnableIVRewrite && VerifyIndvars &&
Andrew Trick75ebc0e2011-09-06 20:20:38 +00001974 !isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
Andrew Trickf6a0dba2011-07-18 18:44:20 +00001975 SE->forgetLoop(L);
1976 const SCEV *NewBECount = SE->getBackedgeTakenCount(L);
1977 if (SE->getTypeSizeInBits(BackedgeTakenCount->getType()) <
1978 SE->getTypeSizeInBits(NewBECount->getType()))
1979 NewBECount = SE->getTruncateOrNoop(NewBECount,
1980 BackedgeTakenCount->getType());
1981 else
1982 BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount,
1983 NewBECount->getType());
1984 assert(BackedgeTakenCount == NewBECount && "indvars must preserve SCEV");
1985 }
1986#endif
1987
Devang Patel5ee99972007-03-07 06:39:01 +00001988 return Changed;
Chris Lattner6148c022001-12-03 17:28:42 +00001989}