blob: 221fe57581ca62851f54f3aa953166b5b5707f42 [file] [log] [blame]
Chris Lattner476e6df2001-12-03 17:28:42 +00001//===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-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 Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner476e6df2001-12-03 17:28:42 +00009//
Chris Lattnere61b67d2004-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 Lattnere61b67d2004-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 Lattner476e6df2001-12-03 17:28:42 +000025//===----------------------------------------------------------------------===//
26
Sanjoy Das4d4339d2016-06-05 18:01:19 +000027#include "llvm/Transforms/Scalar/IndVarSimplify.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000028#include "llvm/ADT/APFloat.h"
29#include "llvm/ADT/APInt.h"
30#include "llvm/ADT/ArrayRef.h"
31#include "llvm/ADT/DenseMap.h"
32#include "llvm/ADT/None.h"
33#include "llvm/ADT/Optional.h"
34#include "llvm/ADT/STLExtras.h"
35#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000036#include "llvm/ADT/SmallVector.h"
37#include "llvm/ADT/Statistic.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000038#include "llvm/ADT/iterator_range.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000039#include "llvm/Analysis/LoopInfo.h"
40#include "llvm/Analysis/LoopPass.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000041#include "llvm/Analysis/ScalarEvolution.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +000042#include "llvm/Analysis/ScalarEvolutionExpander.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000043#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000044#include "llvm/Analysis/TargetLibraryInfo.h"
Jingyue Wu8a12cea2014-11-12 18:09:15 +000045#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000046#include "llvm/IR/BasicBlock.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000047#include "llvm/IR/Constant.h"
48#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000049#include "llvm/IR/Constants.h"
50#include "llvm/IR/DataLayout.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000051#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000052#include "llvm/IR/Dominators.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000053#include "llvm/IR/Function.h"
54#include "llvm/IR/IRBuilder.h"
55#include "llvm/IR/InstrTypes.h"
56#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000057#include "llvm/IR/Instructions.h"
58#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000059#include "llvm/IR/Intrinsics.h"
60#include "llvm/IR/Module.h"
61#include "llvm/IR/Operator.h"
62#include "llvm/IR/PassManager.h"
Sanjoy Das6f062c82015-07-09 18:46:12 +000063#include "llvm/IR/PatternMatch.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000064#include "llvm/IR/Type.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000065#include "llvm/IR/Use.h"
66#include "llvm/IR/User.h"
67#include "llvm/IR/Value.h"
68#include "llvm/IR/ValueHandle.h"
69#include "llvm/Pass.h"
70#include "llvm/Support/Casting.h"
Andrew Trick56b315a2011-06-28 03:01:46 +000071#include "llvm/Support/CommandLine.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000072#include "llvm/Support/Compiler.h"
Chris Lattner08165592007-01-07 01:14:12 +000073#include "llvm/Support/Debug.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000074#include "llvm/Support/ErrorHandling.h"
75#include "llvm/Support/MathExtras.h"
Chris Lattnerb25de3f2009-08-23 04:37:46 +000076#include "llvm/Support/raw_ostream.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +000077#include "llvm/Transforms/Scalar.h"
78#include "llvm/Transforms/Scalar/LoopPassManager.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000079#include "llvm/Transforms/Utils/BasicBlockUtils.h"
80#include "llvm/Transforms/Utils/Local.h"
Sanjoy Das683bf072015-12-08 00:13:21 +000081#include "llvm/Transforms/Utils/LoopUtils.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000082#include "llvm/Transforms/Utils/SimplifyIndVar.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000083#include <cassert>
84#include <cstdint>
85#include <utility>
86
John Criswellb22e9b42003-12-18 17:19:19 +000087using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000088
Chandler Carruth964daaa2014-04-22 02:55:47 +000089#define DEBUG_TYPE "indvars"
90
Andrew Trick69d44522011-06-21 03:22:38 +000091STATISTIC(NumWidened , "Number of indvars widened");
Andrew Trick69d44522011-06-21 03:22:38 +000092STATISTIC(NumReplaced , "Number of exit values replaced");
93STATISTIC(NumLFTR , "Number of loop exit tests replaced");
Andrew Trick69d44522011-06-21 03:22:38 +000094STATISTIC(NumElimExt , "Number of IV sign/zero extends eliminated");
Andrew Trick32390552011-07-06 20:50:43 +000095STATISTIC(NumElimIV , "Number of congruent IVs eliminated");
Chris Lattnerd3678bc2003-12-22 03:58:44 +000096
Benjamin Kramer7ba71be2011-11-26 23:01:57 +000097// Trip count verification can be enabled by default under NDEBUG if we
98// implement a strong expression equivalence checker in SCEV. Until then, we
99// use the verify-indvars flag, which may assert in some cases.
100static cl::opt<bool> VerifyIndvars(
101 "verify-indvars", cl::Hidden,
102 cl::desc("Verify the ScalarEvolution result after running indvars"));
Andrew Trick1abe2962011-05-04 02:10:13 +0000103
Wei Mie2538b52015-05-28 21:49:07 +0000104enum ReplaceExitVal { NeverRepl, OnlyCheapRepl, AlwaysRepl };
105
106static cl::opt<ReplaceExitVal> ReplaceExitValue(
107 "replexitval", cl::Hidden, cl::init(OnlyCheapRepl),
108 cl::desc("Choose the strategy to replace exit value in IndVarSimplify"),
109 cl::values(clEnumValN(NeverRepl, "never", "never replace exit value"),
110 clEnumValN(OnlyCheapRepl, "cheap",
111 "only replace exit value when the cost is cheap"),
112 clEnumValN(AlwaysRepl, "always",
Mehdi Amini732afdd2016-10-08 19:41:06 +0000113 "always replace exit value whenever possible")));
Wei Mie2538b52015-05-28 21:49:07 +0000114
Artur Pilipenkof2d5dc52016-10-19 18:59:03 +0000115static cl::opt<bool> UsePostIncrementRanges(
116 "indvars-post-increment-ranges", cl::Hidden,
117 cl::desc("Use post increment control-dependent ranges in IndVarSimplify"),
118 cl::init(true));
119
Serguei Katkov38414b52017-06-09 06:11:59 +0000120static cl::opt<bool>
121DisableLFTR("disable-lftr", cl::Hidden, cl::init(false),
122 cl::desc("Disable Linear Function Test Replace optimization"));
123
Wei Mie2538b52015-05-28 21:49:07 +0000124namespace {
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000125
Wei Mie2538b52015-05-28 21:49:07 +0000126struct RewritePhi;
Wei Mie2538b52015-05-28 21:49:07 +0000127
Sanjoy Das496f2742016-05-29 21:42:00 +0000128class IndVarSimplify {
129 LoopInfo *LI;
130 ScalarEvolution *SE;
131 DominatorTree *DT;
132 const DataLayout &DL;
133 TargetLibraryInfo *TLI;
Sanjoy Dase1e352d2015-09-20 18:42:50 +0000134 const TargetTransformInfo *TTI;
Andrew Trick69d44522011-06-21 03:22:38 +0000135
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000136 SmallVector<WeakTrackingVH, 16> DeadInsts;
Sanjoy Das496f2742016-05-29 21:42:00 +0000137 bool Changed = false;
Andrew Trick32390552011-07-06 20:50:43 +0000138
Sanjoy Dase1e352d2015-09-20 18:42:50 +0000139 bool isValidRewrite(Value *FromVal, Value *ToVal);
Devang Patel2ac57e12007-03-07 06:39:01 +0000140
Sanjoy Dasb873cbe2015-10-13 07:17:38 +0000141 void handleFloatingPointIV(Loop *L, PHINode *PH);
142 void rewriteNonIntegerIVs(Loop *L);
Andrew Trickcdc22972011-07-12 00:08:50 +0000143
Justin Bogner843fb202015-12-15 19:40:57 +0000144 void simplifyAndExtend(Loop *L, SCEVExpander &Rewriter, LoopInfo *LI);
Andrew Trick6d45a012011-08-06 07:00:37 +0000145
Sanjoy Dasb873cbe2015-10-13 07:17:38 +0000146 bool canLoopBeDeleted(Loop *L, SmallVector<RewritePhi, 8> &RewritePhiSet);
147 void rewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter);
Chen Li5cde8382016-01-27 07:40:41 +0000148 void rewriteFirstIterationLoopExitValues(Loop *L);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000149
Sanjoy Dasb873cbe2015-10-13 07:17:38 +0000150 Value *linearFunctionTestReplace(Loop *L, const SCEV *BackedgeTakenCount,
Sanjoy Dase1e352d2015-09-20 18:42:50 +0000151 PHINode *IndVar, SCEVExpander &Rewriter);
Dan Gohmand76d71a2009-05-12 02:17:14 +0000152
Sanjoy Dasb873cbe2015-10-13 07:17:38 +0000153 void sinkUnusedInvariants(Loop *L);
Sanjoy Das6f062c82015-07-09 18:46:12 +0000154
Sanjoy Dasb873cbe2015-10-13 07:17:38 +0000155 Value *expandSCEVIfNeeded(SCEVExpander &Rewriter, const SCEV *S, Loop *L,
Sanjoy Dase1e352d2015-09-20 18:42:50 +0000156 Instruction *InsertPt, Type *Ty);
Sanjoy Das496f2742016-05-29 21:42:00 +0000157
158public:
159 IndVarSimplify(LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT,
160 const DataLayout &DL, TargetLibraryInfo *TLI,
161 TargetTransformInfo *TTI)
162 : LI(LI), SE(SE), DT(DT), DL(DL), TLI(TLI), TTI(TTI) {}
163
164 bool run(Loop *L);
Sanjoy Dase1e352d2015-09-20 18:42:50 +0000165};
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000166
167} // end anonymous namespace
Chris Lattner91daaab2001-12-04 04:32:29 +0000168
Sanjoy Das9119bf42015-09-20 06:58:03 +0000169/// Return true if the SCEV expansion generated by the rewriter can replace the
170/// original value. SCEV guarantees that it produces the same value, but the way
171/// it is produced may be illegal IR. Ideally, this function will only be
172/// called for verification.
Andrew Trick87716c92011-03-17 23:51:11 +0000173bool IndVarSimplify::isValidRewrite(Value *FromVal, Value *ToVal) {
174 // If an SCEV expression subsumed multiple pointers, its expansion could
175 // reassociate the GEP changing the base pointer. This is illegal because the
176 // final address produced by a GEP chain must be inbounds relative to its
177 // underlying object. Otherwise basic alias analysis, among other things,
178 // could fail in a dangerous way. Ultimately, SCEV will be improved to avoid
179 // producing an expression involving multiple pointers. Until then, we must
180 // bail out here.
181 //
182 // Retrieve the pointer operand of the GEP. Don't use GetUnderlyingObject
183 // because it understands lcssa phis while SCEV does not.
184 Value *FromPtr = FromVal;
185 Value *ToPtr = ToVal;
Sanjoy Dasb873cbe2015-10-13 07:17:38 +0000186 if (auto *GEP = dyn_cast<GEPOperator>(FromVal)) {
Andrew Trick87716c92011-03-17 23:51:11 +0000187 FromPtr = GEP->getPointerOperand();
188 }
Sanjoy Dasb873cbe2015-10-13 07:17:38 +0000189 if (auto *GEP = dyn_cast<GEPOperator>(ToVal)) {
Andrew Trick87716c92011-03-17 23:51:11 +0000190 ToPtr = GEP->getPointerOperand();
191 }
192 if (FromPtr != FromVal || ToPtr != ToVal) {
193 // Quickly check the common case
194 if (FromPtr == ToPtr)
195 return true;
196
197 // SCEV may have rewritten an expression that produces the GEP's pointer
198 // operand. That's ok as long as the pointer operand has the same base
199 // pointer. Unlike GetUnderlyingObject(), getPointerBase() will find the
200 // base of a recurrence. This handles the case in which SCEV expansion
201 // converts a pointer type recurrence into a nonrecurrent pointer base
202 // indexed by an integer recurrence.
Nadav Rotem3924cb02011-12-05 06:29:09 +0000203
204 // If the GEP base pointer is a vector of pointers, abort.
205 if (!FromPtr->getType()->isPointerTy() || !ToPtr->getType()->isPointerTy())
206 return false;
207
Andrew Trick87716c92011-03-17 23:51:11 +0000208 const SCEV *FromBase = SE->getPointerBase(SE->getSCEV(FromPtr));
209 const SCEV *ToBase = SE->getPointerBase(SE->getSCEV(ToPtr));
210 if (FromBase == ToBase)
211 return true;
212
213 DEBUG(dbgs() << "INDVARS: GEP rewrite bail out "
214 << *FromBase << " != " << *ToBase << "\n");
215
216 return false;
217 }
218 return true;
219}
220
Andrew Trick638b3552011-07-20 05:32:06 +0000221/// Determine the insertion point for this user. By default, insert immediately
222/// before the user. SCEVExpander or LICM will hoist loop invariants out of the
223/// loop. For PHI nodes, there may be multiple uses, so compute the nearest
224/// common dominator for the incoming blocks.
225static Instruction *getInsertPointForUses(Instruction *User, Value *Def,
Sanjoy Das683bf072015-12-08 00:13:21 +0000226 DominatorTree *DT, LoopInfo *LI) {
Andrew Trick638b3552011-07-20 05:32:06 +0000227 PHINode *PHI = dyn_cast<PHINode>(User);
228 if (!PHI)
229 return User;
230
Craig Topperf40110f2014-04-25 05:29:35 +0000231 Instruction *InsertPt = nullptr;
Andrew Trick638b3552011-07-20 05:32:06 +0000232 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i) {
233 if (PHI->getIncomingValue(i) != Def)
234 continue;
235
236 BasicBlock *InsertBB = PHI->getIncomingBlock(i);
237 if (!InsertPt) {
238 InsertPt = InsertBB->getTerminator();
239 continue;
240 }
241 InsertBB = DT->findNearestCommonDominator(InsertPt->getParent(), InsertBB);
242 InsertPt = InsertBB->getTerminator();
243 }
244 assert(InsertPt && "Missing phi operand");
Sanjoy Das683bf072015-12-08 00:13:21 +0000245
246 auto *DefI = dyn_cast<Instruction>(Def);
247 if (!DefI)
248 return InsertPt;
249
250 assert(DT->dominates(DefI, InsertPt) && "def does not dominate all uses");
251
252 auto *L = LI->getLoopFor(DefI->getParent());
253 assert(!L || L->contains(LI->getLoopFor(InsertPt->getParent())));
254
255 for (auto *DTN = (*DT)[InsertPt->getParent()]; DTN; DTN = DTN->getIDom())
256 if (LI->getLoopFor(DTN->getBlock()) == L)
257 return DTN->getBlock()->getTerminator();
258
259 llvm_unreachable("DefI dominates InsertPt!");
Andrew Trick638b3552011-07-20 05:32:06 +0000260}
261
Andrew Trickcdc22972011-07-12 00:08:50 +0000262//===----------------------------------------------------------------------===//
Sanjoy Dasb873cbe2015-10-13 07:17:38 +0000263// rewriteNonIntegerIVs and helpers. Prefer integer IVs.
Andrew Trickcdc22972011-07-12 00:08:50 +0000264//===----------------------------------------------------------------------===//
Andrew Trick38c4e342011-05-03 22:24:10 +0000265
Sanjoy Das9119bf42015-09-20 06:58:03 +0000266/// Convert APF to an integer, if possible.
Andrew Trickcdc22972011-07-12 00:08:50 +0000267static bool ConvertToSInt(const APFloat &APF, int64_t &IntVal) {
268 bool isExact = false;
Andrew Trickcdc22972011-07-12 00:08:50 +0000269 // See if we can convert this to an int64_t
270 uint64_t UIntVal;
Simon Pilgrim00b34992017-03-20 14:40:12 +0000271 if (APF.convertToInteger(makeMutableArrayRef(UIntVal), 64, true,
272 APFloat::rmTowardZero, &isExact) != APFloat::opOK ||
273 !isExact)
Andrew Trick38c4e342011-05-03 22:24:10 +0000274 return false;
Andrew Trickcdc22972011-07-12 00:08:50 +0000275 IntVal = UIntVal;
Andrew Trick38c4e342011-05-03 22:24:10 +0000276 return true;
277}
278
Sanjoy Das9119bf42015-09-20 06:58:03 +0000279/// If the loop has floating induction variable then insert corresponding
280/// integer induction variable if possible.
Andrew Trickcdc22972011-07-12 00:08:50 +0000281/// For example,
282/// for(double i = 0; i < 10000; ++i)
283/// bar(i)
284/// is converted into
285/// for(int i = 0; i < 10000; ++i)
286/// bar((double)i);
Sanjoy Dasb873cbe2015-10-13 07:17:38 +0000287void IndVarSimplify::handleFloatingPointIV(Loop *L, PHINode *PN) {
Andrew Trickcdc22972011-07-12 00:08:50 +0000288 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
289 unsigned BackEdge = IncomingEdge^1;
Andrew Trickeb3c36e2011-05-25 04:42:22 +0000290
Andrew Trickcdc22972011-07-12 00:08:50 +0000291 // Check incoming value.
Sanjoy Dasb873cbe2015-10-13 07:17:38 +0000292 auto *InitValueVal = dyn_cast<ConstantFP>(PN->getIncomingValue(IncomingEdge));
Andrew Trickeb3c36e2011-05-25 04:42:22 +0000293
Andrew Trickcdc22972011-07-12 00:08:50 +0000294 int64_t InitValue;
295 if (!InitValueVal || !ConvertToSInt(InitValueVal->getValueAPF(), InitValue))
296 return;
Andrew Trickeb3c36e2011-05-25 04:42:22 +0000297
Andrew Trickcdc22972011-07-12 00:08:50 +0000298 // Check IV increment. Reject this PN if increment operation is not
299 // an add or increment value can not be represented by an integer.
Sanjoy Dasb873cbe2015-10-13 07:17:38 +0000300 auto *Incr = dyn_cast<BinaryOperator>(PN->getIncomingValue(BackEdge));
Craig Topperf40110f2014-04-25 05:29:35 +0000301 if (Incr == nullptr || Incr->getOpcode() != Instruction::FAdd) return;
Andrew Trickeb3c36e2011-05-25 04:42:22 +0000302
Andrew Trickcdc22972011-07-12 00:08:50 +0000303 // If this is not an add of the PHI with a constantfp, or if the constant fp
304 // is not an integer, bail out.
305 ConstantFP *IncValueVal = dyn_cast<ConstantFP>(Incr->getOperand(1));
306 int64_t IncValue;
Craig Topperf40110f2014-04-25 05:29:35 +0000307 if (IncValueVal == nullptr || Incr->getOperand(0) != PN ||
Andrew Trickcdc22972011-07-12 00:08:50 +0000308 !ConvertToSInt(IncValueVal->getValueAPF(), IncValue))
309 return;
310
311 // Check Incr uses. One user is PN and the other user is an exit condition
312 // used by the conditional terminator.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000313 Value::user_iterator IncrUse = Incr->user_begin();
Andrew Trickcdc22972011-07-12 00:08:50 +0000314 Instruction *U1 = cast<Instruction>(*IncrUse++);
Chandler Carruthcdf47882014-03-09 03:16:01 +0000315 if (IncrUse == Incr->user_end()) return;
Andrew Trickcdc22972011-07-12 00:08:50 +0000316 Instruction *U2 = cast<Instruction>(*IncrUse++);
Chandler Carruthcdf47882014-03-09 03:16:01 +0000317 if (IncrUse != Incr->user_end()) return;
Andrew Trickcdc22972011-07-12 00:08:50 +0000318
319 // Find exit condition, which is an fcmp. If it doesn't exist, or if it isn't
320 // only used by a branch, we can't transform it.
321 FCmpInst *Compare = dyn_cast<FCmpInst>(U1);
322 if (!Compare)
323 Compare = dyn_cast<FCmpInst>(U2);
Craig Topperf40110f2014-04-25 05:29:35 +0000324 if (!Compare || !Compare->hasOneUse() ||
Chandler Carruthcdf47882014-03-09 03:16:01 +0000325 !isa<BranchInst>(Compare->user_back()))
Andrew Trickcdc22972011-07-12 00:08:50 +0000326 return;
327
Chandler Carruthcdf47882014-03-09 03:16:01 +0000328 BranchInst *TheBr = cast<BranchInst>(Compare->user_back());
Andrew Trickcdc22972011-07-12 00:08:50 +0000329
330 // We need to verify that the branch actually controls the iteration count
331 // of the loop. If not, the new IV can overflow and no one will notice.
332 // The branch block must be in the loop and one of the successors must be out
333 // of the loop.
334 assert(TheBr->isConditional() && "Can't use fcmp if not conditional");
335 if (!L->contains(TheBr->getParent()) ||
336 (L->contains(TheBr->getSuccessor(0)) &&
337 L->contains(TheBr->getSuccessor(1))))
338 return;
339
Andrew Trickcdc22972011-07-12 00:08:50 +0000340 // If it isn't a comparison with an integer-as-fp (the exit value), we can't
341 // transform it.
342 ConstantFP *ExitValueVal = dyn_cast<ConstantFP>(Compare->getOperand(1));
343 int64_t ExitValue;
Craig Topperf40110f2014-04-25 05:29:35 +0000344 if (ExitValueVal == nullptr ||
Andrew Trickcdc22972011-07-12 00:08:50 +0000345 !ConvertToSInt(ExitValueVal->getValueAPF(), ExitValue))
346 return;
347
348 // Find new predicate for integer comparison.
349 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
350 switch (Compare->getPredicate()) {
351 default: return; // Unknown comparison.
352 case CmpInst::FCMP_OEQ:
353 case CmpInst::FCMP_UEQ: NewPred = CmpInst::ICMP_EQ; break;
354 case CmpInst::FCMP_ONE:
355 case CmpInst::FCMP_UNE: NewPred = CmpInst::ICMP_NE; break;
356 case CmpInst::FCMP_OGT:
357 case CmpInst::FCMP_UGT: NewPred = CmpInst::ICMP_SGT; break;
358 case CmpInst::FCMP_OGE:
359 case CmpInst::FCMP_UGE: NewPred = CmpInst::ICMP_SGE; break;
360 case CmpInst::FCMP_OLT:
361 case CmpInst::FCMP_ULT: NewPred = CmpInst::ICMP_SLT; break;
362 case CmpInst::FCMP_OLE:
363 case CmpInst::FCMP_ULE: NewPred = CmpInst::ICMP_SLE; break;
Andrew Trickeb3c36e2011-05-25 04:42:22 +0000364 }
Andrew Trickeb3c36e2011-05-25 04:42:22 +0000365
Andrew Trickcdc22972011-07-12 00:08:50 +0000366 // We convert the floating point induction variable to a signed i32 value if
367 // we can. This is only safe if the comparison will not overflow in a way
368 // that won't be trapped by the integer equivalent operations. Check for this
369 // now.
370 // TODO: We could use i64 if it is native and the range requires it.
Dan Gohman4a645b82010-04-12 21:13:43 +0000371
Andrew Trickcdc22972011-07-12 00:08:50 +0000372 // The start/stride/exit values must all fit in signed i32.
373 if (!isInt<32>(InitValue) || !isInt<32>(IncValue) || !isInt<32>(ExitValue))
374 return;
375
376 // If not actually striding (add x, 0.0), avoid touching the code.
377 if (IncValue == 0)
378 return;
379
380 // Positive and negative strides have different safety conditions.
381 if (IncValue > 0) {
382 // If we have a positive stride, we require the init to be less than the
Andrew Trick3de5b8e2011-09-13 01:59:32 +0000383 // exit value.
384 if (InitValue >= ExitValue)
Andrew Trickcdc22972011-07-12 00:08:50 +0000385 return;
386
387 uint32_t Range = uint32_t(ExitValue-InitValue);
Andrew Trick3de5b8e2011-09-13 01:59:32 +0000388 // Check for infinite loop, either:
389 // while (i <= Exit) or until (i > Exit)
390 if (NewPred == CmpInst::ICMP_SLE || NewPred == CmpInst::ICMP_SGT) {
Andrew Trickcdc22972011-07-12 00:08:50 +0000391 if (++Range == 0) return; // Range overflows.
Dan Gohmaneb6be652009-02-12 22:19:27 +0000392 }
Chris Lattner0cec5cb2004-04-15 15:21:43 +0000393
Andrew Trickcdc22972011-07-12 00:08:50 +0000394 unsigned Leftover = Range % uint32_t(IncValue);
395
396 // If this is an equality comparison, we require that the strided value
397 // exactly land on the exit value, otherwise the IV condition will wrap
398 // around and do things the fp IV wouldn't.
399 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
400 Leftover != 0)
401 return;
402
403 // If the stride would wrap around the i32 before exiting, we can't
404 // transform the IV.
405 if (Leftover != 0 && int32_t(ExitValue+IncValue) < ExitValue)
406 return;
Chris Lattnerd7a559e2004-04-15 20:26:22 +0000407 } else {
Andrew Trickcdc22972011-07-12 00:08:50 +0000408 // If we have a negative stride, we require the init to be greater than the
Andrew Trick3de5b8e2011-09-13 01:59:32 +0000409 // exit value.
410 if (InitValue <= ExitValue)
Andrew Trickcdc22972011-07-12 00:08:50 +0000411 return;
412
413 uint32_t Range = uint32_t(InitValue-ExitValue);
Andrew Trick3de5b8e2011-09-13 01:59:32 +0000414 // Check for infinite loop, either:
415 // while (i >= Exit) or until (i < Exit)
416 if (NewPred == CmpInst::ICMP_SGE || NewPred == CmpInst::ICMP_SLT) {
Andrew Trickcdc22972011-07-12 00:08:50 +0000417 if (++Range == 0) return; // Range overflows.
418 }
419
420 unsigned Leftover = Range % uint32_t(-IncValue);
421
422 // If this is an equality comparison, we require that the strided value
423 // exactly land on the exit value, otherwise the IV condition will wrap
424 // around and do things the fp IV wouldn't.
425 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
426 Leftover != 0)
427 return;
428
429 // If the stride would wrap around the i32 before exiting, we can't
430 // transform the IV.
431 if (Leftover != 0 && int32_t(ExitValue+IncValue) > ExitValue)
432 return;
Chris Lattnerd7a559e2004-04-15 20:26:22 +0000433 }
Chris Lattner0cec5cb2004-04-15 15:21:43 +0000434
Chris Lattner229907c2011-07-18 04:54:35 +0000435 IntegerType *Int32Ty = Type::getInt32Ty(PN->getContext());
Chris Lattnere61b67d2004-04-02 20:24:31 +0000436
Andrew Trickcdc22972011-07-12 00:08:50 +0000437 // Insert new integer induction variable.
438 PHINode *NewPHI = PHINode::Create(Int32Ty, 2, PN->getName()+".int", PN);
439 NewPHI->addIncoming(ConstantInt::get(Int32Ty, InitValue),
440 PN->getIncomingBlock(IncomingEdge));
Chris Lattnere61b67d2004-04-02 20:24:31 +0000441
Andrew Trickcdc22972011-07-12 00:08:50 +0000442 Value *NewAdd =
443 BinaryOperator::CreateAdd(NewPHI, ConstantInt::get(Int32Ty, IncValue),
444 Incr->getName()+".int", Incr);
445 NewPHI->addIncoming(NewAdd, PN->getIncomingBlock(BackEdge));
Dan Gohmaneb6be652009-02-12 22:19:27 +0000446
Andrew Trickcdc22972011-07-12 00:08:50 +0000447 ICmpInst *NewCompare = new ICmpInst(TheBr, NewPred, NewAdd,
448 ConstantInt::get(Int32Ty, ExitValue),
449 Compare->getName());
Dan Gohmand76d71a2009-05-12 02:17:14 +0000450
Andrew Trickcdc22972011-07-12 00:08:50 +0000451 // In the following deletions, PN may become dead and may be deleted.
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000452 // Use a WeakTrackingVH to observe whether this happens.
453 WeakTrackingVH WeakPH = PN;
Andrew Trickcdc22972011-07-12 00:08:50 +0000454
455 // Delete the old floating point exit comparison. The branch starts using the
456 // new comparison.
457 NewCompare->takeName(Compare);
458 Compare->replaceAllUsesWith(NewCompare);
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000459 RecursivelyDeleteTriviallyDeadInstructions(Compare, TLI);
Andrew Trickcdc22972011-07-12 00:08:50 +0000460
461 // Delete the old floating point increment.
462 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000463 RecursivelyDeleteTriviallyDeadInstructions(Incr, TLI);
Andrew Trickcdc22972011-07-12 00:08:50 +0000464
465 // If the FP induction variable still has uses, this is because something else
466 // in the loop uses its value. In order to canonicalize the induction
467 // variable, we chose to eliminate the IV and rewrite it in terms of an
468 // int->fp cast.
469 //
470 // We give preference to sitofp over uitofp because it is faster on most
471 // platforms.
472 if (WeakPH) {
473 Value *Conv = new SIToFPInst(NewPHI, PN->getType(), "indvar.conv",
Duncan P. N. Exon Smith3a9c9e32015-10-13 18:26:00 +0000474 &*PN->getParent()->getFirstInsertionPt());
Andrew Trickcdc22972011-07-12 00:08:50 +0000475 PN->replaceAllUsesWith(Conv);
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000476 RecursivelyDeleteTriviallyDeadInstructions(PN, TLI);
Andrew Trickcdc22972011-07-12 00:08:50 +0000477 }
Andrew Trick3ec331e2011-08-10 03:46:27 +0000478 Changed = true;
Chris Lattnere61b67d2004-04-02 20:24:31 +0000479}
480
Sanjoy Dasb873cbe2015-10-13 07:17:38 +0000481void IndVarSimplify::rewriteNonIntegerIVs(Loop *L) {
Andrew Trickcdc22972011-07-12 00:08:50 +0000482 // First step. Check to see if there are any floating-point recurrences.
483 // If there are, change them into integer recurrences, permitting analysis by
484 // the SCEV routines.
Andrew Trickcdc22972011-07-12 00:08:50 +0000485 BasicBlock *Header = L->getHeader();
486
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000487 SmallVector<WeakTrackingVH, 8> PHIs;
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000488 for (PHINode &PN : Header->phis())
489 PHIs.push_back(&PN);
Andrew Trickcdc22972011-07-12 00:08:50 +0000490
491 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
492 if (PHINode *PN = dyn_cast_or_null<PHINode>(&*PHIs[i]))
Sanjoy Dasb873cbe2015-10-13 07:17:38 +0000493 handleFloatingPointIV(L, PN);
Andrew Trickcdc22972011-07-12 00:08:50 +0000494
495 // If the loop previously had floating-point IV, ScalarEvolution
496 // may not have been able to compute a trip count. Now that we've done some
497 // re-writing, the trip count may be computable.
498 if (Changed)
499 SE->forgetLoop(L);
500}
501
Wei Mie2538b52015-05-28 21:49:07 +0000502namespace {
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000503
Wei Mie2538b52015-05-28 21:49:07 +0000504// Collect information about PHI nodes which can be transformed in
Sanjoy Dasb873cbe2015-10-13 07:17:38 +0000505// rewriteLoopExitValues.
Wei Mie2538b52015-05-28 21:49:07 +0000506struct RewritePhi {
507 PHINode *PN;
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000508
509 // Ith incoming value.
510 unsigned Ith;
511
512 // Exit value after expansion.
513 Value *Val;
514
515 // High Cost when expansion.
516 bool HighCost;
Wei Mie2538b52015-05-28 21:49:07 +0000517
Sanjoy Dasde475902016-01-17 18:12:52 +0000518 RewritePhi(PHINode *P, unsigned I, Value *V, bool H)
519 : PN(P), Ith(I), Val(V), HighCost(H) {}
Wei Mie2538b52015-05-28 21:49:07 +0000520};
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000521
522} // end anonymous namespace
Wei Mie2538b52015-05-28 21:49:07 +0000523
Sanjoy Dasb873cbe2015-10-13 07:17:38 +0000524Value *IndVarSimplify::expandSCEVIfNeeded(SCEVExpander &Rewriter, const SCEV *S,
Sanjoy Das6f062c82015-07-09 18:46:12 +0000525 Loop *L, Instruction *InsertPt,
Igor Laevsky4709c032015-08-10 18:23:58 +0000526 Type *ResultTy) {
Sanjoy Das6f062c82015-07-09 18:46:12 +0000527 // Before expanding S into an expensive LLVM expression, see if we can use an
Igor Laevsky4709c032015-08-10 18:23:58 +0000528 // already existing value as the expansion for S.
Wei Mi57543502016-08-09 20:40:03 +0000529 if (Value *ExistingValue = Rewriter.getExactExistingExpansion(S, InsertPt, L))
Sanjoy Das8a5526e2015-09-15 23:45:39 +0000530 if (ExistingValue->getType() == ResultTy)
531 return ExistingValue;
Sanjoy Das6f062c82015-07-09 18:46:12 +0000532
533 // We didn't find anything, fall back to using SCEVExpander.
Sanjoy Das6f062c82015-07-09 18:46:12 +0000534 return Rewriter.expandCodeFor(S, ResultTy, InsertPt);
535}
536
Andrew Trickcdc22972011-07-12 00:08:50 +0000537//===----------------------------------------------------------------------===//
Sanjoy Dasb873cbe2015-10-13 07:17:38 +0000538// rewriteLoopExitValues - Optimize IV users outside the loop.
Andrew Trickcdc22972011-07-12 00:08:50 +0000539// As a side effect, reduces the amount of IV processing within the loop.
540//===----------------------------------------------------------------------===//
541
Sanjoy Das9119bf42015-09-20 06:58:03 +0000542/// Check to see if this loop has a computable loop-invariant execution count.
543/// If so, this means that we can compute the final value of any expressions
544/// that are recurrent in the loop, and substitute the exit values from the loop
545/// into any instructions outside of the loop that use the final values of the
546/// current expressions.
Dan Gohmand76d71a2009-05-12 02:17:14 +0000547///
548/// This is mostly redundant with the regular IndVarSimplify activities that
549/// happen later, except that it's more powerful in some cases, because it's
550/// able to brute-force evaluate arbitrary instructions as long as they have
551/// constant operands at the beginning of the loop.
Sanjoy Dasb873cbe2015-10-13 07:17:38 +0000552void IndVarSimplify::rewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter) {
Sanjoy Das683bf072015-12-08 00:13:21 +0000553 // Check a pre-condition.
Igor Laevsky04423cf2016-10-11 13:37:22 +0000554 assert(L->isRecursivelyLCSSAForm(*DT, *LI) &&
555 "Indvars did not preserve LCSSA!");
Dan Gohmand76d71a2009-05-12 02:17:14 +0000556
Devang Patelb5933bb2007-08-21 00:31:24 +0000557 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000558 L->getUniqueExitBlocks(ExitBlocks);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000559
Wei Mie2538b52015-05-28 21:49:07 +0000560 SmallVector<RewritePhi, 8> RewritePhiSet;
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000561 // Find all values that are computed inside the loop, but used outside of it.
562 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
563 // the exit blocks of the loop to find them.
Sanjoy Das8fdf87c2016-01-27 17:05:03 +0000564 for (BasicBlock *ExitBB : ExitBlocks) {
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000565 // If there are no PHI nodes in this exit block, then no values defined
566 // inside the loop are used on this path, skip it.
567 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
568 if (!PN) continue;
Dan Gohmanf84d42f2009-02-17 19:13:57 +0000569
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000570 unsigned NumPreds = PN->getNumIncomingValues();
Dan Gohmanf84d42f2009-02-17 19:13:57 +0000571
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000572 // Iterate over all of the PHI nodes.
573 BasicBlock::iterator BBI = ExitBB->begin();
574 while ((PN = dyn_cast<PHINode>(BBI++))) {
Torok Edwin5349cf52009-05-24 19:36:09 +0000575 if (PN->use_empty())
576 continue; // dead use, don't replace it
Dan Gohmanc43d2642010-02-18 21:34:02 +0000577
Sanjoy Das2f7a7442016-01-27 17:05:06 +0000578 if (!SE->isSCEVable(PN->getType()))
Dan Gohmanc43d2642010-02-18 21:34:02 +0000579 continue;
580
Dale Johannesen1d6827a2010-02-19 07:14:22 +0000581 // It's necessary to tell ScalarEvolution about this explicitly so that
582 // it can walk the def-use list and forget all SCEVs, as it may not be
583 // watching the PHI itself. Once the new exit value is in place, there
584 // may not be a def-use connection between the loop and every instruction
585 // which got a SCEVAddRecExpr for that loop.
586 SE->forgetValue(PN);
587
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000588 // Iterate over all of the values in all the PHI nodes.
589 for (unsigned i = 0; i != NumPreds; ++i) {
590 // If the value being merged in is not integer or is not defined
591 // in the loop, skip it.
592 Value *InVal = PN->getIncomingValue(i);
Dan Gohmanc43d2642010-02-18 21:34:02 +0000593 if (!isa<Instruction>(InVal))
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000594 continue;
Chris Lattnere61b67d2004-04-02 20:24:31 +0000595
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000596 // If this pred is for a subloop, not L itself, skip it.
Dan Gohmanf84d42f2009-02-17 19:13:57 +0000597 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000598 continue; // The Block is in a subloop, skip it.
599
600 // Check that InVal is defined in the loop.
601 Instruction *Inst = cast<Instruction>(InVal);
Dan Gohman18fa5682009-12-18 01:24:09 +0000602 if (!L->contains(Inst))
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000603 continue;
Dan Gohmanf84d42f2009-02-17 19:13:57 +0000604
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000605 // Okay, this instruction has a user outside of the current loop
606 // and varies predictably *inside* the loop. Evaluate the value it
607 // contains when the loop exits, if possible.
Dan Gohmanaf752342009-07-07 17:06:11 +0000608 const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
Andrew Trick57243da2013-10-25 21:35:56 +0000609 if (!SE->isLoopInvariant(ExitValue, L) ||
610 !isSafeToExpand(ExitValue, *SE))
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000611 continue;
Chris Lattner1f7648e2007-03-04 01:00:28 +0000612
Arnaud A. de Grandmaison87c473f2013-03-19 20:00:22 +0000613 // Computing the value outside of the loop brings no benefit if :
614 // - it is definitely used inside the loop in a way which can not be
615 // optimized away.
616 // - no use outside of the loop can take advantage of hoisting the
617 // computation out of the loop
618 if (ExitValue->getSCEVType()>=scMulExpr) {
619 unsigned NumHardInternalUses = 0;
620 unsigned NumSoftExternalUses = 0;
621 unsigned NumUses = 0;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000622 for (auto IB = Inst->user_begin(), IE = Inst->user_end();
623 IB != IE && NumUses <= 6; ++IB) {
Arnaud A. de Grandmaison87c473f2013-03-19 20:00:22 +0000624 Instruction *UseInstr = cast<Instruction>(*IB);
625 unsigned Opc = UseInstr->getOpcode();
626 NumUses++;
627 if (L->contains(UseInstr)) {
628 if (Opc == Instruction::Call || Opc == Instruction::Ret)
629 NumHardInternalUses++;
630 } else {
631 if (Opc == Instruction::PHI) {
632 // Do not count the Phi as a use. LCSSA may have inserted
633 // plenty of trivial ones.
634 NumUses--;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000635 for (auto PB = UseInstr->user_begin(),
636 PE = UseInstr->user_end();
637 PB != PE && NumUses <= 6; ++PB, ++NumUses) {
Arnaud A. de Grandmaison87c473f2013-03-19 20:00:22 +0000638 unsigned PhiOpc = cast<Instruction>(*PB)->getOpcode();
639 if (PhiOpc != Instruction::Call && PhiOpc != Instruction::Ret)
640 NumSoftExternalUses++;
641 }
642 continue;
643 }
644 if (Opc != Instruction::Call && Opc != Instruction::Ret)
645 NumSoftExternalUses++;
646 }
647 }
648 if (NumUses <= 6 && NumHardInternalUses && !NumSoftExternalUses)
649 continue;
650 }
651
Igor Laevsky4709c032015-08-10 18:23:58 +0000652 bool HighCost = Rewriter.isHighCostExpansion(ExitValue, L, Inst);
653 Value *ExitVal =
Sanjoy Dasb873cbe2015-10-13 07:17:38 +0000654 expandSCEVIfNeeded(Rewriter, ExitValue, L, Inst, PN->getType());
Dan Gohmanf84d42f2009-02-17 19:13:57 +0000655
David Greene0dd384c2010-01-05 01:27:06 +0000656 DEBUG(dbgs() << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal << '\n'
Chris Lattnerb25de3f2009-08-23 04:37:46 +0000657 << " LoopVal = " << *Inst << "\n");
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000658
Andrew Trick87716c92011-03-17 23:51:11 +0000659 if (!isValidRewrite(Inst, ExitVal)) {
660 DeadInsts.push_back(ExitVal);
661 continue;
662 }
Andrew Trick87716c92011-03-17 23:51:11 +0000663
Wei Mie2538b52015-05-28 21:49:07 +0000664 // Collect all the candidate PHINodes to be rewritten.
Sanjoy Dasde475902016-01-17 18:12:52 +0000665 RewritePhiSet.emplace_back(PN, i, ExitVal, HighCost);
Chris Lattnered30abf2007-03-03 22:48:48 +0000666 }
Chris Lattnered30abf2007-03-03 22:48:48 +0000667 }
668 }
Dan Gohman1a2abe52010-03-20 03:53:53 +0000669
Sanjoy Dasb873cbe2015-10-13 07:17:38 +0000670 bool LoopCanBeDel = canLoopBeDeleted(L, RewritePhiSet);
Wei Mie2538b52015-05-28 21:49:07 +0000671
672 // Transformation.
673 for (const RewritePhi &Phi : RewritePhiSet) {
674 PHINode *PN = Phi.PN;
675 Value *ExitVal = Phi.Val;
676
677 // Only do the rewrite when the ExitValue can be expanded cheaply.
678 // If LoopCanBeDel is true, rewrite exit value aggressively.
679 if (ReplaceExitValue == OnlyCheapRepl && !LoopCanBeDel && Phi.HighCost) {
680 DeadInsts.push_back(ExitVal);
681 continue;
682 }
683
684 Changed = true;
685 ++NumReplaced;
686 Instruction *Inst = cast<Instruction>(PN->getIncomingValue(Phi.Ith));
687 PN->setIncomingValue(Phi.Ith, ExitVal);
688
689 // If this instruction is dead now, delete it. Don't do it now to avoid
690 // invalidating iterators.
691 if (isInstructionTriviallyDead(Inst, TLI))
692 DeadInsts.push_back(Inst);
693
Sanjoy Dasde475902016-01-17 18:12:52 +0000694 // Replace PN with ExitVal if that is legal and does not break LCSSA.
695 if (PN->getNumIncomingValues() == 1 &&
696 LI->replacementPreservesLCSSAForm(PN, ExitVal)) {
Wei Mie2538b52015-05-28 21:49:07 +0000697 PN->replaceAllUsesWith(ExitVal);
698 PN->eraseFromParent();
699 }
700 }
701
Dan Gohman1a2abe52010-03-20 03:53:53 +0000702 // The insertion point instruction may have been deleted; clear it out
703 // so that the rewriter doesn't trip over it later.
704 Rewriter.clearInsertPoint();
Chris Lattnere61b67d2004-04-02 20:24:31 +0000705}
706
Chen Li5cde8382016-01-27 07:40:41 +0000707//===---------------------------------------------------------------------===//
708// rewriteFirstIterationLoopExitValues: Rewrite loop exit values if we know
709// they will exit at the first iteration.
710//===---------------------------------------------------------------------===//
711
712/// Check to see if this loop has loop invariant conditions which lead to loop
713/// exits. If so, we know that if the exit path is taken, it is at the first
714/// loop iteration. This lets us predict exit values of PHI nodes that live in
715/// loop header.
716void IndVarSimplify::rewriteFirstIterationLoopExitValues(Loop *L) {
717 // Verify the input to the pass is already in LCSSA form.
718 assert(L->isLCSSAForm(*DT));
719
720 SmallVector<BasicBlock *, 8> ExitBlocks;
721 L->getUniqueExitBlocks(ExitBlocks);
722 auto *LoopHeader = L->getHeader();
723 assert(LoopHeader && "Invalid loop");
724
725 for (auto *ExitBB : ExitBlocks) {
Chen Li5cde8382016-01-27 07:40:41 +0000726 // If there are no more PHI nodes in this exit block, then no more
727 // values defined inside the loop are used on this path.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000728 for (PHINode &PN : ExitBB->phis()) {
729 for (unsigned IncomingValIdx = 0, E = PN.getNumIncomingValues();
730 IncomingValIdx != E; ++IncomingValIdx) {
731 auto *IncomingBB = PN.getIncomingBlock(IncomingValIdx);
Chen Li5cde8382016-01-27 07:40:41 +0000732
733 // We currently only support loop exits from loop header. If the
734 // incoming block is not loop header, we need to recursively check
735 // all conditions starting from loop header are loop invariants.
736 // Additional support might be added in the future.
737 if (IncomingBB != LoopHeader)
738 continue;
739
740 // Get condition that leads to the exit path.
741 auto *TermInst = IncomingBB->getTerminator();
742
743 Value *Cond = nullptr;
744 if (auto *BI = dyn_cast<BranchInst>(TermInst)) {
745 // Must be a conditional branch, otherwise the block
746 // should not be in the loop.
747 Cond = BI->getCondition();
748 } else if (auto *SI = dyn_cast<SwitchInst>(TermInst))
749 Cond = SI->getCondition();
750 else
751 continue;
752
753 if (!L->isLoopInvariant(Cond))
754 continue;
755
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000756 auto *ExitVal = dyn_cast<PHINode>(PN.getIncomingValue(IncomingValIdx));
Chen Li5cde8382016-01-27 07:40:41 +0000757
758 // Only deal with PHIs.
759 if (!ExitVal)
760 continue;
761
762 // If ExitVal is a PHI on the loop header, then we know its
763 // value along this exit because the exit can only be taken
764 // on the first iteration.
765 auto *LoopPreheader = L->getLoopPreheader();
766 assert(LoopPreheader && "Invalid loop");
767 int PreheaderIdx = ExitVal->getBasicBlockIndex(LoopPreheader);
768 if (PreheaderIdx != -1) {
769 assert(ExitVal->getParent() == LoopHeader &&
770 "ExitVal must be in loop header");
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000771 PN.setIncomingValue(IncomingValIdx,
772 ExitVal->getIncomingValue(PreheaderIdx));
Chen Li5cde8382016-01-27 07:40:41 +0000773 }
774 }
775 }
776 }
777}
778
Sanjoy Das9119bf42015-09-20 06:58:03 +0000779/// Check whether it is possible to delete the loop after rewriting exit
780/// value. If it is possible, ignore ReplaceExitValue and do rewriting
781/// aggressively.
Sanjoy Dasb873cbe2015-10-13 07:17:38 +0000782bool IndVarSimplify::canLoopBeDeleted(
Wei Mie2538b52015-05-28 21:49:07 +0000783 Loop *L, SmallVector<RewritePhi, 8> &RewritePhiSet) {
Wei Mie2538b52015-05-28 21:49:07 +0000784 BasicBlock *Preheader = L->getLoopPreheader();
785 // If there is no preheader, the loop will not be deleted.
786 if (!Preheader)
787 return false;
788
789 // In LoopDeletion pass Loop can be deleted when ExitingBlocks.size() > 1.
790 // We obviate multiple ExitingBlocks case for simplicity.
791 // TODO: If we see testcase with multiple ExitingBlocks can be deleted
792 // after exit value rewriting, we can enhance the logic here.
793 SmallVector<BasicBlock *, 4> ExitingBlocks;
794 L->getExitingBlocks(ExitingBlocks);
795 SmallVector<BasicBlock *, 8> ExitBlocks;
796 L->getUniqueExitBlocks(ExitBlocks);
797 if (ExitBlocks.size() > 1 || ExitingBlocks.size() > 1)
798 return false;
799
800 BasicBlock *ExitBlock = ExitBlocks[0];
801 BasicBlock::iterator BI = ExitBlock->begin();
802 while (PHINode *P = dyn_cast<PHINode>(BI)) {
803 Value *Incoming = P->getIncomingValueForBlock(ExitingBlocks[0]);
804
805 // If the Incoming value of P is found in RewritePhiSet, we know it
806 // could be rewritten to use a loop invariant value in transformation
807 // phase later. Skip it in the loop invariant check below.
808 bool found = false;
809 for (const RewritePhi &Phi : RewritePhiSet) {
810 unsigned i = Phi.Ith;
811 if (Phi.PN == P && (Phi.PN)->getIncomingValue(i) == Incoming) {
812 found = true;
813 break;
814 }
815 }
816
817 Instruction *I;
818 if (!found && (I = dyn_cast<Instruction>(Incoming)))
819 if (!L->hasLoopInvariantOperands(I))
820 return false;
821
822 ++BI;
823 }
824
Sanjoy Das42e551b2015-12-08 23:52:58 +0000825 for (auto *BB : L->blocks())
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000826 if (llvm::any_of(*BB, [](Instruction &I) {
827 return I.mayHaveSideEffects();
828 }))
Sanjoy Das42e551b2015-12-08 23:52:58 +0000829 return false;
Wei Mie2538b52015-05-28 21:49:07 +0000830
831 return true;
832}
833
Andrew Trickcdc22972011-07-12 00:08:50 +0000834//===----------------------------------------------------------------------===//
Andrew Trickcdc22972011-07-12 00:08:50 +0000835// IV Widening - Extend the width of an IV to cover its widest uses.
836//===----------------------------------------------------------------------===//
837
Andrew Trickf44aadf2011-05-20 18:25:42 +0000838namespace {
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000839
Sanjoy Dase1e352d2015-09-20 18:42:50 +0000840// Collect information about induction variables that are used by sign/zero
841// extend operations. This information is recorded by CollectExtend and provides
842// the input to WidenIV.
843struct WideIVInfo {
Sanjoy Das7cc2cfe2015-09-20 18:42:53 +0000844 PHINode *NarrowIV = nullptr;
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000845
846 // Widest integer type created [sz]ext
847 Type *WidestNativeType = nullptr;
848
849 // Was a sext user seen before a zext?
850 bool IsSigned = false;
Sanjoy Dase1e352d2015-09-20 18:42:50 +0000851};
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000852
853} // end anonymous namespace
Andrew Trickf44aadf2011-05-20 18:25:42 +0000854
Sanjoy Das9119bf42015-09-20 06:58:03 +0000855/// Update information about the induction variable that is extended by this
856/// sign or zero extend operation. This is used to determine the final width of
857/// the IV before actually widening it.
Andrew Trickb6bc7832014-01-02 21:12:11 +0000858static void visitIVCast(CastInst *Cast, WideIVInfo &WI, ScalarEvolution *SE,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000859 const TargetTransformInfo *TTI) {
Andrew Trick3ec331e2011-08-10 03:46:27 +0000860 bool IsSigned = Cast->getOpcode() == Instruction::SExt;
861 if (!IsSigned && Cast->getOpcode() != Instruction::ZExt)
862 return;
863
Chris Lattner229907c2011-07-18 04:54:35 +0000864 Type *Ty = Cast->getType();
Andrew Trickf44aadf2011-05-20 18:25:42 +0000865 uint64_t Width = SE->getTypeSizeInBits(Ty);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000866 if (!Cast->getModule()->getDataLayout().isLegalInteger(Width))
Andrew Trickf44aadf2011-05-20 18:25:42 +0000867 return;
868
Sanjoy Das35025112016-08-13 00:58:31 +0000869 // Check that `Cast` actually extends the induction variable (we rely on this
870 // later). This takes care of cases where `Cast` is extending a truncation of
871 // the narrow induction variable, and thus can end up being narrower than the
872 // "narrow" induction variable.
873 uint64_t NarrowIVWidth = SE->getTypeSizeInBits(WI.NarrowIV->getType());
874 if (NarrowIVWidth >= Width)
875 return;
876
Jingyue Wu8a12cea2014-11-12 18:09:15 +0000877 // Cast is either an sext or zext up to this point.
878 // We should not widen an indvar if arithmetics on the wider indvar are more
879 // expensive than those on the narrower indvar. We check only the cost of ADD
880 // because at least an ADD is required to increment the induction variable. We
881 // could compute more comprehensively the cost of all instructions on the
882 // induction variable when necessary.
883 if (TTI &&
884 TTI->getArithmeticInstrCost(Instruction::Add, Ty) >
885 TTI->getArithmeticInstrCost(Instruction::Add,
886 Cast->getOperand(0)->getType())) {
887 return;
888 }
889
Andrew Trick69d44522011-06-21 03:22:38 +0000890 if (!WI.WidestNativeType) {
891 WI.WidestNativeType = SE->getEffectiveSCEVType(Ty);
892 WI.IsSigned = IsSigned;
Andrew Trickf44aadf2011-05-20 18:25:42 +0000893 return;
894 }
895
896 // We extend the IV to satisfy the sign of its first user, arbitrarily.
Andrew Trick69d44522011-06-21 03:22:38 +0000897 if (WI.IsSigned != IsSigned)
Andrew Trickf44aadf2011-05-20 18:25:42 +0000898 return;
899
Andrew Trick69d44522011-06-21 03:22:38 +0000900 if (Width > SE->getTypeSizeInBits(WI.WidestNativeType))
901 WI.WidestNativeType = SE->getEffectiveSCEVType(Ty);
Andrew Trickf44aadf2011-05-20 18:25:42 +0000902}
903
904namespace {
Andrew Trick22104482011-07-20 04:39:24 +0000905
Sanjoy Das9119bf42015-09-20 06:58:03 +0000906/// Record a link in the Narrow IV def-use chain along with the WideIV that
907/// computes the same value as the Narrow IV def. This avoids caching Use*
908/// pointers.
Andrew Trick22104482011-07-20 04:39:24 +0000909struct NarrowIVDefUse {
Sanjoy Das7cc2cfe2015-09-20 18:42:53 +0000910 Instruction *NarrowDef = nullptr;
911 Instruction *NarrowUse = nullptr;
912 Instruction *WideDef = nullptr;
Andrew Trick22104482011-07-20 04:39:24 +0000913
Sanjoy Das428db152015-09-20 01:52:18 +0000914 // True if the narrow def is never negative. Tracking this information lets
915 // us use a sign extension instead of a zero extension or vice versa, when
916 // profitable and legal.
Sanjoy Das7cc2cfe2015-09-20 18:42:53 +0000917 bool NeverNegative = false;
Sanjoy Das428db152015-09-20 01:52:18 +0000918
919 NarrowIVDefUse(Instruction *ND, Instruction *NU, Instruction *WD,
920 bool NeverNegative)
921 : NarrowDef(ND), NarrowUse(NU), WideDef(WD),
922 NeverNegative(NeverNegative) {}
Andrew Trick22104482011-07-20 04:39:24 +0000923};
924
Sanjoy Das9119bf42015-09-20 06:58:03 +0000925/// The goal of this transform is to remove sign and zero extends without
926/// creating any new induction variables. To do this, it creates a new phi of
927/// the wider type and redirects all users, either removing extends or inserting
928/// truncs whenever we stop propagating the type.
Andrew Trickf44aadf2011-05-20 18:25:42 +0000929class WidenIV {
Andrew Trick69d44522011-06-21 03:22:38 +0000930 // Parameters
Andrew Trickf44aadf2011-05-20 18:25:42 +0000931 PHINode *OrigPhi;
Chris Lattner229907c2011-07-18 04:54:35 +0000932 Type *WideType;
Andrew Trickf44aadf2011-05-20 18:25:42 +0000933
Andrew Trick69d44522011-06-21 03:22:38 +0000934 // Context
935 LoopInfo *LI;
936 Loop *L;
Andrew Trickf44aadf2011-05-20 18:25:42 +0000937 ScalarEvolution *SE;
Andrew Trick69d44522011-06-21 03:22:38 +0000938 DominatorTree *DT;
Andrew Trickf44aadf2011-05-20 18:25:42 +0000939
Artur Pilipenko5c6ef752016-10-19 19:43:54 +0000940 // Does the module have any calls to the llvm.experimental.guard intrinsic
941 // at all? If not we can avoid scanning instructions looking for guards.
942 bool HasGuards;
943
Andrew Trick69d44522011-06-21 03:22:38 +0000944 // Result
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000945 PHINode *WidePhi = nullptr;
946 Instruction *WideInc = nullptr;
947 const SCEV *WideIncExpr = nullptr;
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000948 SmallVectorImpl<WeakTrackingVH> &DeadInsts;
Andrew Trickf44aadf2011-05-20 18:25:42 +0000949
Evgeny Stupachenkodc8a2542016-09-28 23:39:39 +0000950 SmallPtrSet<Instruction *,16> Widened;
Andrew Trick22104482011-07-20 04:39:24 +0000951 SmallVector<NarrowIVDefUse, 8> NarrowIVUsers;
Andrew Trickf44aadf2011-05-20 18:25:42 +0000952
Evgeny Stupachenkodc8a2542016-09-28 23:39:39 +0000953 enum ExtendKind { ZeroExtended, SignExtended, Unknown };
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000954
Simon Pilgrim610ad9b2017-03-20 13:55:35 +0000955 // A map tracking the kind of extension used to widen each narrow IV
Evgeny Stupachenkodc8a2542016-09-28 23:39:39 +0000956 // and narrow IV user.
957 // Key: pointer to a narrow IV or IV user.
958 // Value: the kind of extension used to widen this Instruction.
959 DenseMap<AssertingVH<Instruction>, ExtendKind> ExtendKindMap;
960
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000961 using DefUserPair = std::pair<AssertingVH<Value>, AssertingVH<Instruction>>;
962
Artur Pilipenkof2d5dc52016-10-19 18:59:03 +0000963 // A map with control-dependent ranges for post increment IV uses. The key is
964 // a pair of IV def and a use of this def denoting the context. The value is
965 // a ConstantRange representing possible values of the def at the given
966 // context.
967 DenseMap<DefUserPair, ConstantRange> PostIncRangeInfos;
968
969 Optional<ConstantRange> getPostIncRangeInfo(Value *Def,
970 Instruction *UseI) {
971 DefUserPair Key(Def, UseI);
972 auto It = PostIncRangeInfos.find(Key);
973 return It == PostIncRangeInfos.end()
974 ? Optional<ConstantRange>(None)
975 : Optional<ConstantRange>(It->second);
976 }
977
978 void calculatePostIncRanges(PHINode *OrigPhi);
979 void calculatePostIncRange(Instruction *NarrowDef, Instruction *NarrowUser);
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000980
Artur Pilipenkof2d5dc52016-10-19 18:59:03 +0000981 void updatePostIncRangeInfo(Value *Def, Instruction *UseI, ConstantRange R) {
982 DefUserPair Key(Def, UseI);
983 auto It = PostIncRangeInfos.find(Key);
984 if (It == PostIncRangeInfos.end())
985 PostIncRangeInfos.insert({Key, R});
986 else
987 It->second = R.intersectWith(It->second);
988 }
989
Andrew Trickf44aadf2011-05-20 18:25:42 +0000990public:
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000991 WidenIV(const WideIVInfo &WI, LoopInfo *LInfo, ScalarEvolution *SEv,
992 DominatorTree *DTree, SmallVectorImpl<WeakTrackingVH> &DI,
993 bool HasGuards)
994 : OrigPhi(WI.NarrowIV), WideType(WI.WidestNativeType), LI(LInfo),
995 L(LI->getLoopFor(OrigPhi->getParent())), SE(SEv), DT(DTree),
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000996 HasGuards(HasGuards), DeadInsts(DI) {
Andrew Trickf44aadf2011-05-20 18:25:42 +0000997 assert(L->getHeader() == OrigPhi->getParent() && "Phi must be an IV");
Evgeny Stupachenkodc8a2542016-09-28 23:39:39 +0000998 ExtendKindMap[OrigPhi] = WI.IsSigned ? SignExtended : ZeroExtended;
Andrew Trickf44aadf2011-05-20 18:25:42 +0000999 }
1000
Sanjoy Dasb873cbe2015-10-13 07:17:38 +00001001 PHINode *createWideIV(SCEVExpander &Rewriter);
Andrew Trickf44aadf2011-05-20 18:25:42 +00001002
1003protected:
Sanjoy Das7360f302015-10-16 01:00:50 +00001004 Value *createExtendInst(Value *NarrowOper, Type *WideType, bool IsSigned,
1005 Instruction *Use);
Andrew Tricke0e30532011-09-28 01:35:36 +00001006
Sanjoy Das1fd184e2015-10-16 01:00:39 +00001007 Instruction *cloneIVUser(NarrowIVDefUse DU, const SCEVAddRecExpr *WideAR);
1008 Instruction *cloneArithmeticIVUser(NarrowIVDefUse DU,
1009 const SCEVAddRecExpr *WideAR);
1010 Instruction *cloneBitwiseIVUser(NarrowIVDefUse DU);
Andrew Trickf44aadf2011-05-20 18:25:42 +00001011
Evgeny Stupachenkodc8a2542016-09-28 23:39:39 +00001012 ExtendKind getExtendKind(Instruction *I);
Andrew Trick92905a12011-07-05 18:19:39 +00001013
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +00001014 using WidenedRecTy = std::pair<const SCEVAddRecExpr *, ExtendKind>;
Evgeny Stupachenkodc8a2542016-09-28 23:39:39 +00001015
1016 WidenedRecTy getWideRecurrence(NarrowIVDefUse DU);
1017
1018 WidenedRecTy getExtendedOperandRecurrence(NarrowIVDefUse DU);
Andrew Trickc7868bf02011-09-10 01:24:17 +00001019
Sanjoy Dasb873cbe2015-10-13 07:17:38 +00001020 const SCEV *getSCEVByOpCode(const SCEV *LHS, const SCEV *RHS,
Zinovy Nis0a36cba2014-08-21 08:25:45 +00001021 unsigned OpCode) const;
1022
Sanjoy Dasb873cbe2015-10-13 07:17:38 +00001023 Instruction *widenIVUse(NarrowIVDefUse DU, SCEVExpander &Rewriter);
Andrew Trick6d123092011-07-02 02:34:25 +00001024
Sanjoy Dasb873cbe2015-10-13 07:17:38 +00001025 bool widenLoopCompare(NarrowIVDefUse DU);
Chad Rosierbb99f402014-09-17 14:10:33 +00001026
Andrew Trick6d123092011-07-02 02:34:25 +00001027 void pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef);
Andrew Trickf44aadf2011-05-20 18:25:42 +00001028};
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +00001029
1030} // end anonymous namespace
Andrew Trickf44aadf2011-05-20 18:25:42 +00001031
Sanjoy Das9119bf42015-09-20 06:58:03 +00001032/// Perform a quick domtree based check for loop invariance assuming that V is
1033/// used within the loop. LoopInfo::isLoopInvariant() seems gratuitous for this
1034/// purpose.
Andrew Tricke0e30532011-09-28 01:35:36 +00001035static bool isLoopInvariant(Value *V, const Loop *L, const DominatorTree *DT) {
1036 Instruction *Inst = dyn_cast<Instruction>(V);
1037 if (!Inst)
1038 return true;
1039
1040 return DT->properlyDominates(Inst->getParent(), L->getHeader());
1041}
1042
Sanjoy Das7360f302015-10-16 01:00:50 +00001043Value *WidenIV::createExtendInst(Value *NarrowOper, Type *WideType,
1044 bool IsSigned, Instruction *Use) {
Andrew Tricke0e30532011-09-28 01:35:36 +00001045 // Set the debug location and conservative insertion point.
1046 IRBuilder<> Builder(Use);
1047 // Hoist the insertion point into loop preheaders as far as possible.
1048 for (const Loop *L = LI->getLoopFor(Use->getParent());
1049 L && L->getLoopPreheader() && isLoopInvariant(NarrowOper, L, DT);
1050 L = L->getParentLoop())
1051 Builder.SetInsertPoint(L->getLoopPreheader()->getTerminator());
1052
Andrew Trickeb3c36e2011-05-25 04:42:22 +00001053 return IsSigned ? Builder.CreateSExt(NarrowOper, WideType) :
1054 Builder.CreateZExt(NarrowOper, WideType);
Andrew Trickf44aadf2011-05-20 18:25:42 +00001055}
1056
Sanjoy Das9119bf42015-09-20 06:58:03 +00001057/// Instantiate a wide operation to replace a narrow operation. This only needs
1058/// to handle operations that can evaluation to SCEVAddRec. It can safely return
1059/// 0 for any operation we decide not to clone.
Sanjoy Das1fd184e2015-10-16 01:00:39 +00001060Instruction *WidenIV::cloneIVUser(NarrowIVDefUse DU,
1061 const SCEVAddRecExpr *WideAR) {
Andrew Trick22104482011-07-20 04:39:24 +00001062 unsigned Opcode = DU.NarrowUse->getOpcode();
Andrew Trickf44aadf2011-05-20 18:25:42 +00001063 switch (Opcode) {
1064 default:
Craig Topperf40110f2014-04-25 05:29:35 +00001065 return nullptr;
Andrew Trickf44aadf2011-05-20 18:25:42 +00001066 case Instruction::Add:
1067 case Instruction::Mul:
1068 case Instruction::UDiv:
1069 case Instruction::Sub:
Sanjoy Das1fd184e2015-10-16 01:00:39 +00001070 return cloneArithmeticIVUser(DU, WideAR);
1071
Andrew Trickf44aadf2011-05-20 18:25:42 +00001072 case Instruction::And:
1073 case Instruction::Or:
1074 case Instruction::Xor:
1075 case Instruction::Shl:
1076 case Instruction::LShr:
1077 case Instruction::AShr:
Sanjoy Das1fd184e2015-10-16 01:00:39 +00001078 return cloneBitwiseIVUser(DU);
Andrew Trickf44aadf2011-05-20 18:25:42 +00001079 }
Andrew Trickf44aadf2011-05-20 18:25:42 +00001080}
1081
Sanjoy Das1fd184e2015-10-16 01:00:39 +00001082Instruction *WidenIV::cloneBitwiseIVUser(NarrowIVDefUse DU) {
Sanjoy Das472840a2015-10-16 01:00:44 +00001083 Instruction *NarrowUse = DU.NarrowUse;
1084 Instruction *NarrowDef = DU.NarrowDef;
1085 Instruction *WideDef = DU.WideDef;
1086
1087 DEBUG(dbgs() << "Cloning bitwise IVUser: " << *NarrowUse << "\n");
Sanjoy Das1fd184e2015-10-16 01:00:39 +00001088
1089 // Replace NarrowDef operands with WideDef. Otherwise, we don't know anything
1090 // about the narrow operand yet so must insert a [sz]ext. It is probably loop
1091 // invariant and will be folded or hoisted. If it actually comes from a
1092 // widened IV, it should be removed during a future call to widenIVUse.
Evgeny Stupachenkodc8a2542016-09-28 23:39:39 +00001093 bool IsSigned = getExtendKind(NarrowDef) == SignExtended;
Sanjoy Das7360f302015-10-16 01:00:50 +00001094 Value *LHS = (NarrowUse->getOperand(0) == NarrowDef)
1095 ? WideDef
1096 : createExtendInst(NarrowUse->getOperand(0), WideType,
1097 IsSigned, NarrowUse);
1098 Value *RHS = (NarrowUse->getOperand(1) == NarrowDef)
1099 ? WideDef
1100 : createExtendInst(NarrowUse->getOperand(1), WideType,
1101 IsSigned, NarrowUse);
Sanjoy Das1fd184e2015-10-16 01:00:39 +00001102
Sanjoy Das472840a2015-10-16 01:00:44 +00001103 auto *NarrowBO = cast<BinaryOperator>(NarrowUse);
Sanjoy Das1fd184e2015-10-16 01:00:39 +00001104 auto *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(), LHS, RHS,
1105 NarrowBO->getName());
Sanjoy Das472840a2015-10-16 01:00:44 +00001106 IRBuilder<> Builder(NarrowUse);
Sanjoy Das1fd184e2015-10-16 01:00:39 +00001107 Builder.Insert(WideBO);
Sanjay Patel739f2ce2015-11-24 17:16:33 +00001108 WideBO->copyIRFlags(NarrowBO);
Sanjoy Das1fd184e2015-10-16 01:00:39 +00001109 return WideBO;
1110}
1111
1112Instruction *WidenIV::cloneArithmeticIVUser(NarrowIVDefUse DU,
1113 const SCEVAddRecExpr *WideAR) {
Sanjoy Das472840a2015-10-16 01:00:44 +00001114 Instruction *NarrowUse = DU.NarrowUse;
1115 Instruction *NarrowDef = DU.NarrowDef;
1116 Instruction *WideDef = DU.WideDef;
1117
1118 DEBUG(dbgs() << "Cloning arithmetic IVUser: " << *NarrowUse << "\n");
Sanjoy Das1fd184e2015-10-16 01:00:39 +00001119
Sanjoy Das37e87c22015-10-16 01:00:47 +00001120 unsigned IVOpIdx = (NarrowUse->getOperand(0) == NarrowDef) ? 0 : 1;
1121
1122 // We're trying to find X such that
1123 //
1124 // Widen(NarrowDef `op` NonIVNarrowDef) == WideAR == WideDef `op.wide` X
1125 //
1126 // We guess two solutions to X, sext(NonIVNarrowDef) and zext(NonIVNarrowDef),
1127 // and check using SCEV if any of them are correct.
1128
1129 // Returns true if extending NonIVNarrowDef according to `SignExt` is a
1130 // correct solution to X.
1131 auto GuessNonIVOperand = [&](bool SignExt) {
1132 const SCEV *WideLHS;
1133 const SCEV *WideRHS;
1134
1135 auto GetExtend = [this, SignExt](const SCEV *S, Type *Ty) {
1136 if (SignExt)
1137 return SE->getSignExtendExpr(S, Ty);
1138 return SE->getZeroExtendExpr(S, Ty);
1139 };
1140
1141 if (IVOpIdx == 0) {
1142 WideLHS = SE->getSCEV(WideDef);
1143 const SCEV *NarrowRHS = SE->getSCEV(NarrowUse->getOperand(1));
1144 WideRHS = GetExtend(NarrowRHS, WideType);
1145 } else {
1146 const SCEV *NarrowLHS = SE->getSCEV(NarrowUse->getOperand(0));
1147 WideLHS = GetExtend(NarrowLHS, WideType);
1148 WideRHS = SE->getSCEV(WideDef);
1149 }
1150
1151 // WideUse is "WideDef `op.wide` X" as described in the comment.
1152 const SCEV *WideUse = nullptr;
1153
1154 switch (NarrowUse->getOpcode()) {
1155 default:
1156 llvm_unreachable("No other possibility!");
1157
1158 case Instruction::Add:
1159 WideUse = SE->getAddExpr(WideLHS, WideRHS);
1160 break;
1161
1162 case Instruction::Mul:
1163 WideUse = SE->getMulExpr(WideLHS, WideRHS);
1164 break;
1165
1166 case Instruction::UDiv:
1167 WideUse = SE->getUDivExpr(WideLHS, WideRHS);
1168 break;
1169
1170 case Instruction::Sub:
1171 WideUse = SE->getMinusSCEV(WideLHS, WideRHS);
1172 break;
1173 }
1174
1175 return WideUse == WideAR;
1176 };
1177
Evgeny Stupachenkodc8a2542016-09-28 23:39:39 +00001178 bool SignExtend = getExtendKind(NarrowDef) == SignExtended;
Sanjoy Das37e87c22015-10-16 01:00:47 +00001179 if (!GuessNonIVOperand(SignExtend)) {
1180 SignExtend = !SignExtend;
1181 if (!GuessNonIVOperand(SignExtend))
1182 return nullptr;
1183 }
1184
1185 Value *LHS = (NarrowUse->getOperand(0) == NarrowDef)
1186 ? WideDef
Sanjoy Das7360f302015-10-16 01:00:50 +00001187 : createExtendInst(NarrowUse->getOperand(0), WideType,
1188 SignExtend, NarrowUse);
Sanjoy Das37e87c22015-10-16 01:00:47 +00001189 Value *RHS = (NarrowUse->getOperand(1) == NarrowDef)
1190 ? WideDef
Sanjoy Das7360f302015-10-16 01:00:50 +00001191 : createExtendInst(NarrowUse->getOperand(1), WideType,
1192 SignExtend, NarrowUse);
Sanjoy Das1fd184e2015-10-16 01:00:39 +00001193
Sanjoy Das472840a2015-10-16 01:00:44 +00001194 auto *NarrowBO = cast<BinaryOperator>(NarrowUse);
Sanjoy Das1fd184e2015-10-16 01:00:39 +00001195 auto *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(), LHS, RHS,
1196 NarrowBO->getName());
Sanjoy Das37e87c22015-10-16 01:00:47 +00001197
Sanjoy Das472840a2015-10-16 01:00:44 +00001198 IRBuilder<> Builder(NarrowUse);
Sanjoy Das1fd184e2015-10-16 01:00:39 +00001199 Builder.Insert(WideBO);
Sanjay Patel739f2ce2015-11-24 17:16:33 +00001200 WideBO->copyIRFlags(NarrowBO);
Sanjoy Das1fd184e2015-10-16 01:00:39 +00001201 return WideBO;
1202}
1203
Evgeny Stupachenkodc8a2542016-09-28 23:39:39 +00001204WidenIV::ExtendKind WidenIV::getExtendKind(Instruction *I) {
1205 auto It = ExtendKindMap.find(I);
1206 assert(It != ExtendKindMap.end() && "Instruction not yet extended!");
1207 return It->second;
1208}
1209
Sanjoy Dasb873cbe2015-10-13 07:17:38 +00001210const SCEV *WidenIV::getSCEVByOpCode(const SCEV *LHS, const SCEV *RHS,
Zinovy Nis0a36cba2014-08-21 08:25:45 +00001211 unsigned OpCode) const {
1212 if (OpCode == Instruction::Add)
1213 return SE->getAddExpr(LHS, RHS);
1214 if (OpCode == Instruction::Sub)
1215 return SE->getMinusSCEV(LHS, RHS);
1216 if (OpCode == Instruction::Mul)
1217 return SE->getMulExpr(LHS, RHS);
1218
1219 llvm_unreachable("Unsupported opcode.");
Zinovy Nis0a36cba2014-08-21 08:25:45 +00001220}
1221
Andrew Trickc7868bf02011-09-10 01:24:17 +00001222/// No-wrap operations can transfer sign extension of their result to their
1223/// operands. Generate the SCEV value for the widened operation without
1224/// actually modifying the IR yet. If the expression after extending the
Evgeny Stupachenkodc8a2542016-09-28 23:39:39 +00001225/// operands is an AddRec for this loop, return the AddRec and the kind of
1226/// extension used.
1227WidenIV::WidenedRecTy WidenIV::getExtendedOperandRecurrence(NarrowIVDefUse DU) {
Andrew Trickc7868bf02011-09-10 01:24:17 +00001228 // Handle the common case of add<nsw/nuw>
Zinovy Nis0a36cba2014-08-21 08:25:45 +00001229 const unsigned OpCode = DU.NarrowUse->getOpcode();
1230 // Only Add/Sub/Mul instructions supported yet.
1231 if (OpCode != Instruction::Add && OpCode != Instruction::Sub &&
1232 OpCode != Instruction::Mul)
Evgeny Stupachenkodc8a2542016-09-28 23:39:39 +00001233 return {nullptr, Unknown};
Andrew Trickc7868bf02011-09-10 01:24:17 +00001234
1235 // One operand (NarrowDef) has already been extended to WideDef. Now determine
1236 // if extending the other will lead to a recurrence.
Zinovy Nisccc3e372014-10-02 13:01:15 +00001237 const unsigned ExtendOperIdx =
1238 DU.NarrowUse->getOperand(0) == DU.NarrowDef ? 1 : 0;
Andrew Trickc7868bf02011-09-10 01:24:17 +00001239 assert(DU.NarrowUse->getOperand(1-ExtendOperIdx) == DU.NarrowDef && "bad DU");
1240
Craig Topperf40110f2014-04-25 05:29:35 +00001241 const SCEV *ExtendOperExpr = nullptr;
Andrew Trickc7868bf02011-09-10 01:24:17 +00001242 const OverflowingBinaryOperator *OBO =
1243 cast<OverflowingBinaryOperator>(DU.NarrowUse);
Evgeny Stupachenkodc8a2542016-09-28 23:39:39 +00001244 ExtendKind ExtKind = getExtendKind(DU.NarrowDef);
1245 if (ExtKind == SignExtended && OBO->hasNoSignedWrap())
Andrew Trickc7868bf02011-09-10 01:24:17 +00001246 ExtendOperExpr = SE->getSignExtendExpr(
1247 SE->getSCEV(DU.NarrowUse->getOperand(ExtendOperIdx)), WideType);
Evgeny Stupachenkodc8a2542016-09-28 23:39:39 +00001248 else if(ExtKind == ZeroExtended && OBO->hasNoUnsignedWrap())
Andrew Trickc7868bf02011-09-10 01:24:17 +00001249 ExtendOperExpr = SE->getZeroExtendExpr(
1250 SE->getSCEV(DU.NarrowUse->getOperand(ExtendOperIdx)), WideType);
1251 else
Evgeny Stupachenkodc8a2542016-09-28 23:39:39 +00001252 return {nullptr, Unknown};
Andrew Trickc7868bf02011-09-10 01:24:17 +00001253
Zinovy Nis0a36cba2014-08-21 08:25:45 +00001254 // When creating this SCEV expr, don't apply the current operations NSW or NUW
Andrew Trickd25089f2011-11-29 02:16:38 +00001255 // flags. This instruction may be guarded by control flow that the no-wrap
1256 // behavior depends on. Non-control-equivalent instructions can be mapped to
1257 // the same SCEV expression, and it would be incorrect to transfer NSW/NUW
1258 // semantics to those operations.
Zinovy Nisccc3e372014-10-02 13:01:15 +00001259 const SCEV *lhs = SE->getSCEV(DU.WideDef);
1260 const SCEV *rhs = ExtendOperExpr;
1261
1262 // Let's swap operands to the initial order for the case of non-commutative
1263 // operations, like SUB. See PR21014.
1264 if (ExtendOperIdx == 0)
1265 std::swap(lhs, rhs);
1266 const SCEVAddRecExpr *AddRec =
Sanjoy Dasb873cbe2015-10-13 07:17:38 +00001267 dyn_cast<SCEVAddRecExpr>(getSCEVByOpCode(lhs, rhs, OpCode));
Zinovy Nisccc3e372014-10-02 13:01:15 +00001268
Andrew Trickc7868bf02011-09-10 01:24:17 +00001269 if (!AddRec || AddRec->getLoop() != L)
Evgeny Stupachenkodc8a2542016-09-28 23:39:39 +00001270 return {nullptr, Unknown};
1271
1272 return {AddRec, ExtKind};
Andrew Trickc7868bf02011-09-10 01:24:17 +00001273}
1274
Sanjoy Das9119bf42015-09-20 06:58:03 +00001275/// Is this instruction potentially interesting for further simplification after
1276/// widening it's type? In other words, can the extend be safely hoisted out of
1277/// the loop with SCEV reducing the value to a recurrence on the same loop. If
Evgeny Stupachenkodc8a2542016-09-28 23:39:39 +00001278/// so, return the extended recurrence and the kind of extension used. Otherwise
1279/// return {nullptr, Unknown}.
1280WidenIV::WidenedRecTy WidenIV::getWideRecurrence(NarrowIVDefUse DU) {
1281 if (!SE->isSCEVable(DU.NarrowUse->getType()))
1282 return {nullptr, Unknown};
Andrew Trick92905a12011-07-05 18:19:39 +00001283
Evgeny Stupachenkodc8a2542016-09-28 23:39:39 +00001284 const SCEV *NarrowExpr = SE->getSCEV(DU.NarrowUse);
Sanjoy Dasff9eea22016-07-21 18:58:01 +00001285 if (SE->getTypeSizeInBits(NarrowExpr->getType()) >=
1286 SE->getTypeSizeInBits(WideType)) {
Andrew Trick92905a12011-07-05 18:19:39 +00001287 // NarrowUse implicitly widens its operand. e.g. a gep with a narrow
1288 // index. So don't follow this use.
Evgeny Stupachenkodc8a2542016-09-28 23:39:39 +00001289 return {nullptr, Unknown};
Andrew Trick92905a12011-07-05 18:19:39 +00001290 }
1291
Evgeny Stupachenkodc8a2542016-09-28 23:39:39 +00001292 const SCEV *WideExpr;
1293 ExtendKind ExtKind;
1294 if (DU.NeverNegative) {
1295 WideExpr = SE->getSignExtendExpr(NarrowExpr, WideType);
1296 if (isa<SCEVAddRecExpr>(WideExpr))
1297 ExtKind = SignExtended;
1298 else {
1299 WideExpr = SE->getZeroExtendExpr(NarrowExpr, WideType);
1300 ExtKind = ZeroExtended;
1301 }
1302 } else if (getExtendKind(DU.NarrowDef) == SignExtended) {
1303 WideExpr = SE->getSignExtendExpr(NarrowExpr, WideType);
1304 ExtKind = SignExtended;
1305 } else {
1306 WideExpr = SE->getZeroExtendExpr(NarrowExpr, WideType);
1307 ExtKind = ZeroExtended;
1308 }
Andrew Trick92905a12011-07-05 18:19:39 +00001309 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(WideExpr);
1310 if (!AddRec || AddRec->getLoop() != L)
Evgeny Stupachenkodc8a2542016-09-28 23:39:39 +00001311 return {nullptr, Unknown};
1312 return {AddRec, ExtKind};
Andrew Trick92905a12011-07-05 18:19:39 +00001313}
1314
Andrew Trick020dd892014-01-02 19:29:38 +00001315/// This IV user cannot be widen. Replace this use of the original narrow IV
1316/// with a truncation of the new wide IV to isolate and eliminate the narrow IV.
Sanjoy Das683bf072015-12-08 00:13:21 +00001317static void truncateIVUse(NarrowIVDefUse DU, DominatorTree *DT, LoopInfo *LI) {
Andrew Tricke4a18602014-01-07 06:59:12 +00001318 DEBUG(dbgs() << "INDVARS: Truncate IV " << *DU.WideDef
1319 << " for user " << *DU.NarrowUse << "\n");
Sanjoy Das683bf072015-12-08 00:13:21 +00001320 IRBuilder<> Builder(
1321 getInsertPointForUses(DU.NarrowUse, DU.NarrowDef, DT, LI));
Andrew Trick020dd892014-01-02 19:29:38 +00001322 Value *Trunc = Builder.CreateTrunc(DU.WideDef, DU.NarrowDef->getType());
1323 DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, Trunc);
1324}
1325
Chad Rosierbb99f402014-09-17 14:10:33 +00001326/// If the narrow use is a compare instruction, then widen the compare
1327// (and possibly the other operand). The extend operation is hoisted into the
1328// loop preheader as far as possible.
Sanjoy Dasb873cbe2015-10-13 07:17:38 +00001329bool WidenIV::widenLoopCompare(NarrowIVDefUse DU) {
Chad Rosierbb99f402014-09-17 14:10:33 +00001330 ICmpInst *Cmp = dyn_cast<ICmpInst>(DU.NarrowUse);
1331 if (!Cmp)
1332 return false;
1333
Sanjoy Dasf69d0e32015-09-18 21:21:02 +00001334 // We can legally widen the comparison in the following two cases:
1335 //
1336 // - The signedness of the IV extension and comparison match
1337 //
1338 // - The narrow IV is always positive (and thus its sign extension is equal
1339 // to its zero extension). For instance, let's say we're zero extending
1340 // %narrow for the following use
1341 //
1342 // icmp slt i32 %narrow, %val ... (A)
1343 //
1344 // and %narrow is always positive. Then
1345 //
1346 // (A) == icmp slt i32 sext(%narrow), sext(%val)
1347 // == icmp slt i32 zext(%narrow), sext(%val)
Evgeny Stupachenkodc8a2542016-09-28 23:39:39 +00001348 bool IsSigned = getExtendKind(DU.NarrowDef) == SignExtended;
Sanjoy Das428db152015-09-20 01:52:18 +00001349 if (!(DU.NeverNegative || IsSigned == Cmp->isSigned()))
Chad Rosier307b50b2014-09-17 16:35:09 +00001350 return false;
1351
Chad Rosierbb99f402014-09-17 14:10:33 +00001352 Value *Op = Cmp->getOperand(Cmp->getOperand(0) == DU.NarrowDef ? 1 : 0);
1353 unsigned CastWidth = SE->getTypeSizeInBits(Op->getType());
1354 unsigned IVWidth = SE->getTypeSizeInBits(WideType);
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +00001355 assert(CastWidth <= IVWidth && "Unexpected width while widening compare.");
Chad Rosierbb99f402014-09-17 14:10:33 +00001356
1357 // Widen the compare instruction.
Sanjoy Das683bf072015-12-08 00:13:21 +00001358 IRBuilder<> Builder(
1359 getInsertPointForUses(DU.NarrowUse, DU.NarrowDef, DT, LI));
Chad Rosierbb99f402014-09-17 14:10:33 +00001360 DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef);
1361
1362 // Widen the other operand of the compare, if necessary.
1363 if (CastWidth < IVWidth) {
Sanjoy Das7360f302015-10-16 01:00:50 +00001364 Value *ExtOp = createExtendInst(Op, WideType, Cmp->isSigned(), Cmp);
Chad Rosierbb99f402014-09-17 14:10:33 +00001365 DU.NarrowUse->replaceUsesOfWith(Op, ExtOp);
1366 }
1367 return true;
1368}
1369
Sanjoy Das9119bf42015-09-20 06:58:03 +00001370/// Determine whether an individual user of the narrow IV can be widened. If so,
1371/// return the wide clone of the user.
Sanjoy Dasb873cbe2015-10-13 07:17:38 +00001372Instruction *WidenIV::widenIVUse(NarrowIVDefUse DU, SCEVExpander &Rewriter) {
Evgeny Stupachenkodc8a2542016-09-28 23:39:39 +00001373 assert(ExtendKindMap.count(DU.NarrowDef) &&
1374 "Should already know the kind of extension used to widen NarrowDef");
Andrew Trickecdd6e42011-06-29 23:03:57 +00001375
Andrew Trick6d123092011-07-02 02:34:25 +00001376 // Stop traversing the def-use chain at inner-loop phis or post-loop phis.
Andrew Tricke4a18602014-01-07 06:59:12 +00001377 if (PHINode *UsePhi = dyn_cast<PHINode>(DU.NarrowUse)) {
1378 if (LI->getLoopFor(UsePhi->getParent()) != L) {
1379 // For LCSSA phis, sink the truncate outside the loop.
1380 // After SimplifyCFG most loop exit targets have a single predecessor.
1381 // Otherwise fall back to a truncate within the loop.
1382 if (UsePhi->getNumOperands() != 1)
Sanjoy Das683bf072015-12-08 00:13:21 +00001383 truncateIVUse(DU, DT, LI);
Andrew Tricke4a18602014-01-07 06:59:12 +00001384 else {
David Majnemer5d518382016-03-30 21:12:06 +00001385 // Widening the PHI requires us to insert a trunc. The logical place
1386 // for this trunc is in the same BB as the PHI. This is not possible if
1387 // the BB is terminated by a catchswitch.
1388 if (isa<CatchSwitchInst>(UsePhi->getParent()->getTerminator()))
1389 return nullptr;
1390
Andrew Tricke4a18602014-01-07 06:59:12 +00001391 PHINode *WidePhi =
1392 PHINode::Create(DU.WideDef->getType(), 1, UsePhi->getName() + ".wide",
1393 UsePhi);
1394 WidePhi->addIncoming(DU.WideDef, UsePhi->getIncomingBlock(0));
Duncan P. N. Exon Smith3a9c9e32015-10-13 18:26:00 +00001395 IRBuilder<> Builder(&*WidePhi->getParent()->getFirstInsertionPt());
Andrew Tricke4a18602014-01-07 06:59:12 +00001396 Value *Trunc = Builder.CreateTrunc(WidePhi, DU.NarrowDef->getType());
1397 UsePhi->replaceAllUsesWith(Trunc);
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001398 DeadInsts.emplace_back(UsePhi);
Andrew Tricke4a18602014-01-07 06:59:12 +00001399 DEBUG(dbgs() << "INDVARS: Widen lcssa phi " << *UsePhi
1400 << " to " << *WidePhi << "\n");
1401 }
Craig Topperf40110f2014-04-25 05:29:35 +00001402 return nullptr;
Andrew Tricke4a18602014-01-07 06:59:12 +00001403 }
Andrew Trick020dd892014-01-02 19:29:38 +00001404 }
Evgeny Stupachenkodc8a2542016-09-28 23:39:39 +00001405
1406 // This narrow use can be widened by a sext if it's non-negative or its narrow
1407 // def was widended by a sext. Same for zext.
1408 auto canWidenBySExt = [&]() {
1409 return DU.NeverNegative || getExtendKind(DU.NarrowDef) == SignExtended;
1410 };
1411 auto canWidenByZExt = [&]() {
1412 return DU.NeverNegative || getExtendKind(DU.NarrowDef) == ZeroExtended;
1413 };
1414
Andrew Trickf44aadf2011-05-20 18:25:42 +00001415 // Our raison d'etre! Eliminate sign and zero extension.
Evgeny Stupachenkodc8a2542016-09-28 23:39:39 +00001416 if ((isa<SExtInst>(DU.NarrowUse) && canWidenBySExt()) ||
1417 (isa<ZExtInst>(DU.NarrowUse) && canWidenByZExt())) {
Andrew Trick22104482011-07-20 04:39:24 +00001418 Value *NewDef = DU.WideDef;
1419 if (DU.NarrowUse->getType() != WideType) {
1420 unsigned CastWidth = SE->getTypeSizeInBits(DU.NarrowUse->getType());
Andrew Trickeb3c36e2011-05-25 04:42:22 +00001421 unsigned IVWidth = SE->getTypeSizeInBits(WideType);
1422 if (CastWidth < IVWidth) {
1423 // The cast isn't as wide as the IV, so insert a Trunc.
Andrew Trick22104482011-07-20 04:39:24 +00001424 IRBuilder<> Builder(DU.NarrowUse);
1425 NewDef = Builder.CreateTrunc(DU.WideDef, DU.NarrowUse->getType());
Andrew Trickeb3c36e2011-05-25 04:42:22 +00001426 }
1427 else {
1428 // A wider extend was hidden behind a narrower one. This may induce
1429 // another round of IV widening in which the intermediate IV becomes
1430 // dead. It should be very rare.
1431 DEBUG(dbgs() << "INDVARS: New IV " << *WidePhi
Andrew Trick22104482011-07-20 04:39:24 +00001432 << " not wide enough to subsume " << *DU.NarrowUse << "\n");
1433 DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef);
1434 NewDef = DU.NarrowUse;
Andrew Trickeb3c36e2011-05-25 04:42:22 +00001435 }
1436 }
Andrew Trick22104482011-07-20 04:39:24 +00001437 if (NewDef != DU.NarrowUse) {
1438 DEBUG(dbgs() << "INDVARS: eliminating " << *DU.NarrowUse
1439 << " replaced by " << *DU.WideDef << "\n");
Andrew Trickeb3c36e2011-05-25 04:42:22 +00001440 ++NumElimExt;
Andrew Trick22104482011-07-20 04:39:24 +00001441 DU.NarrowUse->replaceAllUsesWith(NewDef);
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001442 DeadInsts.emplace_back(DU.NarrowUse);
Andrew Trickeb3c36e2011-05-25 04:42:22 +00001443 }
Andrew Trick69d44522011-06-21 03:22:38 +00001444 // Now that the extend is gone, we want to expose it's uses for potential
1445 // further simplification. We don't need to directly inform SimplifyIVUsers
1446 // of the new users, because their parent IV will be processed later as a
1447 // new loop phi. If we preserved IVUsers analysis, we would also want to
1448 // push the uses of WideDef here.
Andrew Trickf44aadf2011-05-20 18:25:42 +00001449
1450 // No further widening is needed. The deceased [sz]ext had done it for us.
Craig Topperf40110f2014-04-25 05:29:35 +00001451 return nullptr;
Andrew Trickf44aadf2011-05-20 18:25:42 +00001452 }
Andrew Trick6d123092011-07-02 02:34:25 +00001453
1454 // Does this user itself evaluate to a recurrence after widening?
Wei Mid2948ce2016-11-15 17:34:52 +00001455 WidenedRecTy WideAddRec = getExtendedOperandRecurrence(DU);
Evgeny Stupachenkodc8a2542016-09-28 23:39:39 +00001456 if (!WideAddRec.first)
Wei Mid2948ce2016-11-15 17:34:52 +00001457 WideAddRec = getWideRecurrence(DU);
Chad Rosierbb99f402014-09-17 14:10:33 +00001458
Evgeny Stupachenkodc8a2542016-09-28 23:39:39 +00001459 assert((WideAddRec.first == nullptr) == (WideAddRec.second == Unknown));
1460 if (!WideAddRec.first) {
Chad Rosierbb99f402014-09-17 14:10:33 +00001461 // If use is a loop condition, try to promote the condition instead of
1462 // truncating the IV first.
Sanjoy Dasb873cbe2015-10-13 07:17:38 +00001463 if (widenLoopCompare(DU))
Chad Rosierbb99f402014-09-17 14:10:33 +00001464 return nullptr;
1465
Xin Tongee5cb652017-01-07 04:30:58 +00001466 // This user does not evaluate to a recurrence after widening, so don't
Andrew Trickf44aadf2011-05-20 18:25:42 +00001467 // follow it. Instead insert a Trunc to kill off the original use,
1468 // eventually isolating the original narrow IV so it can be removed.
Sanjoy Das683bf072015-12-08 00:13:21 +00001469 truncateIVUse(DU, DT, LI);
Craig Topperf40110f2014-04-25 05:29:35 +00001470 return nullptr;
Andrew Trickf44aadf2011-05-20 18:25:42 +00001471 }
Andrew Trick7da24172011-07-18 20:32:31 +00001472 // Assume block terminators cannot evaluate to a recurrence. We can't to
Andrew Trick6d123092011-07-02 02:34:25 +00001473 // insert a Trunc after a terminator if there happens to be a critical edge.
Andrew Trick22104482011-07-20 04:39:24 +00001474 assert(DU.NarrowUse != DU.NarrowUse->getParent()->getTerminator() &&
Andrew Trick6d123092011-07-02 02:34:25 +00001475 "SCEV is not expected to evaluate a block terminator");
Andrew Trickecdd6e42011-06-29 23:03:57 +00001476
Andrew Trick7fac79e2011-05-26 00:46:11 +00001477 // Reuse the IV increment that SCEVExpander created as long as it dominates
1478 // NarrowUse.
Craig Topperf40110f2014-04-25 05:29:35 +00001479 Instruction *WideUse = nullptr;
Evgeny Stupachenkodc8a2542016-09-28 23:39:39 +00001480 if (WideAddRec.first == WideIncExpr &&
1481 Rewriter.hoistIVInc(WideInc, DU.NarrowUse))
Andrew Trickf44aadf2011-05-20 18:25:42 +00001482 WideUse = WideInc;
Andrew Trickf44aadf2011-05-20 18:25:42 +00001483 else {
Evgeny Stupachenkodc8a2542016-09-28 23:39:39 +00001484 WideUse = cloneIVUser(DU, WideAddRec.first);
Andrew Trickf44aadf2011-05-20 18:25:42 +00001485 if (!WideUse)
Craig Topperf40110f2014-04-25 05:29:35 +00001486 return nullptr;
Andrew Trickf44aadf2011-05-20 18:25:42 +00001487 }
Andrew Trick6d123092011-07-02 02:34:25 +00001488 // Evaluation of WideAddRec ensured that the narrow expression could be
1489 // extended outside the loop without overflow. This suggests that the wide use
Andrew Trickf44aadf2011-05-20 18:25:42 +00001490 // evaluates to the same expression as the extended narrow use, but doesn't
1491 // absolutely guarantee it. Hence the following failsafe check. In rare cases
Andrew Trick69d44522011-06-21 03:22:38 +00001492 // where it fails, we simply throw away the newly created wide use.
Evgeny Stupachenkodc8a2542016-09-28 23:39:39 +00001493 if (WideAddRec.first != SE->getSCEV(WideUse)) {
Andrew Trickf44aadf2011-05-20 18:25:42 +00001494 DEBUG(dbgs() << "Wide use expression mismatch: " << *WideUse
Evgeny Stupachenkodc8a2542016-09-28 23:39:39 +00001495 << ": " << *SE->getSCEV(WideUse) << " != " << *WideAddRec.first << "\n");
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001496 DeadInsts.emplace_back(WideUse);
Craig Topperf40110f2014-04-25 05:29:35 +00001497 return nullptr;
Andrew Trickf44aadf2011-05-20 18:25:42 +00001498 }
1499
Evgeny Stupachenkodc8a2542016-09-28 23:39:39 +00001500 ExtendKindMap[DU.NarrowUse] = WideAddRec.second;
Andrew Trickf44aadf2011-05-20 18:25:42 +00001501 // Returning WideUse pushes it on the worklist.
1502 return WideUse;
1503}
1504
Sanjoy Das9119bf42015-09-20 06:58:03 +00001505/// Add eligible users of NarrowDef to NarrowIVUsers.
Andrew Trick6d123092011-07-02 02:34:25 +00001506void WidenIV::pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef) {
Sanjoy Das428db152015-09-20 01:52:18 +00001507 const SCEV *NarrowSCEV = SE->getSCEV(NarrowDef);
Artur Pilipenkof2d5dc52016-10-19 18:59:03 +00001508 bool NonNegativeDef =
Sanjoy Das428db152015-09-20 01:52:18 +00001509 SE->isKnownPredicate(ICmpInst::ICMP_SGE, NarrowSCEV,
Artur Pilipenkob78ad9d2016-08-22 13:12:07 +00001510 SE->getConstant(NarrowSCEV->getType(), 0));
Chandler Carruthcdf47882014-03-09 03:16:01 +00001511 for (User *U : NarrowDef->users()) {
1512 Instruction *NarrowUser = cast<Instruction>(U);
Andrew Trick6d123092011-07-02 02:34:25 +00001513
1514 // Handle data flow merges and bizarre phi cycles.
David Blaikie70573dc2014-11-19 07:49:26 +00001515 if (!Widened.insert(NarrowUser).second)
Andrew Trick6d123092011-07-02 02:34:25 +00001516 continue;
1517
Artur Pilipenkof2d5dc52016-10-19 18:59:03 +00001518 bool NonNegativeUse = false;
1519 if (!NonNegativeDef) {
1520 // We might have a control-dependent range information for this context.
1521 if (auto RangeInfo = getPostIncRangeInfo(NarrowDef, NarrowUser))
1522 NonNegativeUse = RangeInfo->getSignedMin().isNonNegative();
1523 }
1524
1525 NarrowIVUsers.emplace_back(NarrowDef, NarrowUser, WideDef,
1526 NonNegativeDef || NonNegativeUse);
Andrew Trick6d123092011-07-02 02:34:25 +00001527 }
1528}
1529
Sanjoy Das9119bf42015-09-20 06:58:03 +00001530/// Process a single induction variable. First use the SCEVExpander to create a
1531/// wide induction variable that evaluates to the same recurrence as the
1532/// original narrow IV. Then use a worklist to forward traverse the narrow IV's
Sanjoy Dasb873cbe2015-10-13 07:17:38 +00001533/// def-use chain. After widenIVUse has processed all interesting IV users, the
Sanjoy Das9119bf42015-09-20 06:58:03 +00001534/// narrow IV will be isolated for removal by DeleteDeadPHIs.
Andrew Trickf44aadf2011-05-20 18:25:42 +00001535///
1536/// It would be simpler to delete uses as they are processed, but we must avoid
1537/// invalidating SCEV expressions.
Sanjoy Dasb873cbe2015-10-13 07:17:38 +00001538PHINode *WidenIV::createWideIV(SCEVExpander &Rewriter) {
Andrew Trickf44aadf2011-05-20 18:25:42 +00001539 // Is this phi an induction variable?
1540 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(OrigPhi));
1541 if (!AddRec)
Craig Topperf40110f2014-04-25 05:29:35 +00001542 return nullptr;
Andrew Trickf44aadf2011-05-20 18:25:42 +00001543
1544 // Widen the induction variable expression.
Evgeny Stupachenkodc8a2542016-09-28 23:39:39 +00001545 const SCEV *WideIVExpr = getExtendKind(OrigPhi) == SignExtended
1546 ? SE->getSignExtendExpr(AddRec, WideType)
1547 : SE->getZeroExtendExpr(AddRec, WideType);
Andrew Trickf44aadf2011-05-20 18:25:42 +00001548
1549 assert(SE->getEffectiveSCEVType(WideIVExpr->getType()) == WideType &&
1550 "Expect the new IV expression to preserve its type");
1551
1552 // Can the IV be extended outside the loop without overflow?
1553 AddRec = dyn_cast<SCEVAddRecExpr>(WideIVExpr);
1554 if (!AddRec || AddRec->getLoop() != L)
Craig Topperf40110f2014-04-25 05:29:35 +00001555 return nullptr;
Andrew Trickf44aadf2011-05-20 18:25:42 +00001556
Andrew Trick69d44522011-06-21 03:22:38 +00001557 // An AddRec must have loop-invariant operands. Since this AddRec is
Andrew Trickf44aadf2011-05-20 18:25:42 +00001558 // materialized by a loop header phi, the expression cannot have any post-loop
1559 // operands, so they must dominate the loop header.
Sanjoy Das91e6ba62016-06-24 21:23:32 +00001560 assert(
1561 SE->properlyDominates(AddRec->getStart(), L->getHeader()) &&
1562 SE->properlyDominates(AddRec->getStepRecurrence(*SE), L->getHeader()) &&
1563 "Loop header phi recurrence inputs do not dominate the loop");
Andrew Trickf44aadf2011-05-20 18:25:42 +00001564
Artur Pilipenkof2d5dc52016-10-19 18:59:03 +00001565 // Iterate over IV uses (including transitive ones) looking for IV increments
1566 // of the form 'add nsw %iv, <const>'. For each increment and each use of
1567 // the increment calculate control-dependent range information basing on
1568 // dominating conditions inside of the loop (e.g. a range check inside of the
1569 // loop). Calculated ranges are stored in PostIncRangeInfos map.
1570 //
1571 // Control-dependent range information is later used to prove that a narrow
1572 // definition is not negative (see pushNarrowIVUsers). It's difficult to do
1573 // this on demand because when pushNarrowIVUsers needs this information some
1574 // of the dominating conditions might be already widened.
1575 if (UsePostIncrementRanges)
1576 calculatePostIncRanges(OrigPhi);
1577
Andrew Trickf44aadf2011-05-20 18:25:42 +00001578 // The rewriter provides a value for the desired IV expression. This may
1579 // either find an existing phi or materialize a new one. Either way, we
1580 // expect a well-formed cyclic phi-with-increments. i.e. any operand not part
1581 // of the phi-SCC dominates the loop entry.
Duncan P. N. Exon Smith3a9c9e32015-10-13 18:26:00 +00001582 Instruction *InsertPt = &L->getHeader()->front();
Andrew Trickf44aadf2011-05-20 18:25:42 +00001583 WidePhi = cast<PHINode>(Rewriter.expandCodeFor(AddRec, WideType, InsertPt));
1584
1585 // Remembering the WideIV increment generated by SCEVExpander allows
Sanjoy Dasb873cbe2015-10-13 07:17:38 +00001586 // widenIVUse to reuse it when widening the narrow IV's increment. We don't
Andrew Trickf44aadf2011-05-20 18:25:42 +00001587 // employ a general reuse mechanism because the call above is the only call to
1588 // SCEVExpander. Henceforth, we produce 1-to-1 narrow to wide uses.
Andrew Trick7fac79e2011-05-26 00:46:11 +00001589 if (BasicBlock *LatchBlock = L->getLoopLatch()) {
1590 WideInc =
1591 cast<Instruction>(WidePhi->getIncomingValueForBlock(LatchBlock));
1592 WideIncExpr = SE->getSCEV(WideInc);
Andrea Di Biagio824cabd2016-10-25 16:45:17 +00001593 // Propagate the debug location associated with the original loop increment
1594 // to the new (widened) increment.
1595 auto *OrigInc =
1596 cast<Instruction>(OrigPhi->getIncomingValueForBlock(LatchBlock));
1597 WideInc->setDebugLoc(OrigInc->getDebugLoc());
Andrew Trick7fac79e2011-05-26 00:46:11 +00001598 }
Andrew Trickf44aadf2011-05-20 18:25:42 +00001599
1600 DEBUG(dbgs() << "Wide IV: " << *WidePhi << "\n");
1601 ++NumWidened;
1602
1603 // Traverse the def-use chain using a worklist starting at the original IV.
Andrew Trick6d123092011-07-02 02:34:25 +00001604 assert(Widened.empty() && NarrowIVUsers.empty() && "expect initial state" );
Andrew Trickf44aadf2011-05-20 18:25:42 +00001605
Andrew Trick6d123092011-07-02 02:34:25 +00001606 Widened.insert(OrigPhi);
1607 pushNarrowIVUsers(OrigPhi, WidePhi);
1608
Andrew Trickf44aadf2011-05-20 18:25:42 +00001609 while (!NarrowIVUsers.empty()) {
Andrew Trick22104482011-07-20 04:39:24 +00001610 NarrowIVDefUse DU = NarrowIVUsers.pop_back_val();
Andrew Trickf44aadf2011-05-20 18:25:42 +00001611
Andrew Trick7fac79e2011-05-26 00:46:11 +00001612 // Process a def-use edge. This may replace the use, so don't hold a
1613 // use_iterator across it.
Sanjoy Dasb873cbe2015-10-13 07:17:38 +00001614 Instruction *WideUse = widenIVUse(DU, Rewriter);
Andrew Trickf44aadf2011-05-20 18:25:42 +00001615
Andrew Trick7fac79e2011-05-26 00:46:11 +00001616 // Follow all def-use edges from the previous narrow use.
Andrew Trick6d123092011-07-02 02:34:25 +00001617 if (WideUse)
Andrew Trick22104482011-07-20 04:39:24 +00001618 pushNarrowIVUsers(DU.NarrowUse, WideUse);
Andrew Trick6d123092011-07-02 02:34:25 +00001619
Sanjoy Dasb873cbe2015-10-13 07:17:38 +00001620 // widenIVUse may have removed the def-use edge.
Andrew Trick22104482011-07-20 04:39:24 +00001621 if (DU.NarrowDef->use_empty())
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001622 DeadInsts.emplace_back(DU.NarrowDef);
Andrew Trickf44aadf2011-05-20 18:25:42 +00001623 }
Adrian Prantlfbb6fbf2017-11-02 23:17:06 +00001624
1625 // Attach any debug information to the new PHI. Since OrigPhi and WidePHI
1626 // evaluate the same recurrence, we can just copy the debug info over.
1627 SmallVector<DbgValueInst *, 1> DbgValues;
1628 llvm::findDbgValues(DbgValues, OrigPhi);
1629 auto *MDPhi = MetadataAsValue::get(WidePhi->getContext(),
1630 ValueAsMetadata::get(WidePhi));
1631 for (auto &DbgValue : DbgValues)
1632 DbgValue->setOperand(0, MDPhi);
Andrew Trick69d44522011-06-21 03:22:38 +00001633 return WidePhi;
Andrew Trickf44aadf2011-05-20 18:25:42 +00001634}
1635
Artur Pilipenkof2d5dc52016-10-19 18:59:03 +00001636/// Calculates control-dependent range for the given def at the given context
1637/// by looking at dominating conditions inside of the loop
1638void WidenIV::calculatePostIncRange(Instruction *NarrowDef,
1639 Instruction *NarrowUser) {
1640 using namespace llvm::PatternMatch;
1641
1642 Value *NarrowDefLHS;
1643 const APInt *NarrowDefRHS;
1644 if (!match(NarrowDef, m_NSWAdd(m_Value(NarrowDefLHS),
1645 m_APInt(NarrowDefRHS))) ||
1646 !NarrowDefRHS->isNonNegative())
1647 return;
1648
1649 auto UpdateRangeFromCondition = [&] (Value *Condition,
1650 bool TrueDest) {
1651 CmpInst::Predicate Pred;
1652 Value *CmpRHS;
1653 if (!match(Condition, m_ICmp(Pred, m_Specific(NarrowDefLHS),
1654 m_Value(CmpRHS))))
1655 return;
1656
1657 CmpInst::Predicate P =
Simon Pilgrim610ad9b2017-03-20 13:55:35 +00001658 TrueDest ? Pred : CmpInst::getInversePredicate(Pred);
Artur Pilipenkof2d5dc52016-10-19 18:59:03 +00001659
1660 auto CmpRHSRange = SE->getSignedRange(SE->getSCEV(CmpRHS));
1661 auto CmpConstrainedLHSRange =
1662 ConstantRange::makeAllowedICmpRegion(P, CmpRHSRange);
1663 auto NarrowDefRange =
1664 CmpConstrainedLHSRange.addWithNoSignedWrap(*NarrowDefRHS);
1665
1666 updatePostIncRangeInfo(NarrowDef, NarrowUser, NarrowDefRange);
1667 };
1668
Artur Pilipenko5c6ef752016-10-19 19:43:54 +00001669 auto UpdateRangeFromGuards = [&](Instruction *Ctx) {
1670 if (!HasGuards)
1671 return;
1672
1673 for (Instruction &I : make_range(Ctx->getIterator().getReverse(),
1674 Ctx->getParent()->rend())) {
1675 Value *C = nullptr;
1676 if (match(&I, m_Intrinsic<Intrinsic::experimental_guard>(m_Value(C))))
1677 UpdateRangeFromCondition(C, /*TrueDest=*/true);
1678 }
1679 };
1680
1681 UpdateRangeFromGuards(NarrowUser);
1682
Artur Pilipenkof2d5dc52016-10-19 18:59:03 +00001683 BasicBlock *NarrowUserBB = NarrowUser->getParent();
Simon Pilgrim610ad9b2017-03-20 13:55:35 +00001684 // If NarrowUserBB is statically unreachable asking dominator queries may
Simon Pilgrim7d18a702016-11-20 13:19:49 +00001685 // yield surprising results. (e.g. the block may not have a dom tree node)
Artur Pilipenkof2d5dc52016-10-19 18:59:03 +00001686 if (!DT->isReachableFromEntry(NarrowUserBB))
1687 return;
1688
1689 for (auto *DTB = (*DT)[NarrowUserBB]->getIDom();
1690 L->contains(DTB->getBlock());
1691 DTB = DTB->getIDom()) {
1692 auto *BB = DTB->getBlock();
1693 auto *TI = BB->getTerminator();
Artur Pilipenko5c6ef752016-10-19 19:43:54 +00001694 UpdateRangeFromGuards(TI);
Artur Pilipenkof2d5dc52016-10-19 18:59:03 +00001695
1696 auto *BI = dyn_cast<BranchInst>(TI);
1697 if (!BI || !BI->isConditional())
1698 continue;
1699
1700 auto *TrueSuccessor = BI->getSuccessor(0);
1701 auto *FalseSuccessor = BI->getSuccessor(1);
1702
1703 auto DominatesNarrowUser = [this, NarrowUser] (BasicBlockEdge BBE) {
1704 return BBE.isSingleEdge() &&
1705 DT->dominates(BBE, NarrowUser->getParent());
1706 };
1707
1708 if (DominatesNarrowUser(BasicBlockEdge(BB, TrueSuccessor)))
1709 UpdateRangeFromCondition(BI->getCondition(), /*TrueDest=*/true);
1710
1711 if (DominatesNarrowUser(BasicBlockEdge(BB, FalseSuccessor)))
1712 UpdateRangeFromCondition(BI->getCondition(), /*TrueDest=*/false);
1713 }
1714}
1715
1716/// Calculates PostIncRangeInfos map for the given IV
1717void WidenIV::calculatePostIncRanges(PHINode *OrigPhi) {
1718 SmallPtrSet<Instruction *, 16> Visited;
1719 SmallVector<Instruction *, 6> Worklist;
1720 Worklist.push_back(OrigPhi);
1721 Visited.insert(OrigPhi);
1722
1723 while (!Worklist.empty()) {
1724 Instruction *NarrowDef = Worklist.pop_back_val();
1725
1726 for (Use &U : NarrowDef->uses()) {
1727 auto *NarrowUser = cast<Instruction>(U.getUser());
1728
1729 // Don't go looking outside the current loop.
1730 auto *NarrowUserLoop = (*LI)[NarrowUser->getParent()];
1731 if (!NarrowUserLoop || !L->contains(NarrowUserLoop))
1732 continue;
1733
1734 if (!Visited.insert(NarrowUser).second)
1735 continue;
1736
1737 Worklist.push_back(NarrowUser);
1738
1739 calculatePostIncRange(NarrowDef, NarrowUser);
1740 }
1741 }
1742}
1743
Andrew Trickcdc22972011-07-12 00:08:50 +00001744//===----------------------------------------------------------------------===//
Andrew Trickb6bc7832014-01-02 21:12:11 +00001745// Live IV Reduction - Minimize IVs live across the loop.
1746//===----------------------------------------------------------------------===//
1747
Andrew Trickb6bc7832014-01-02 21:12:11 +00001748//===----------------------------------------------------------------------===//
Andrew Trickcdc22972011-07-12 00:08:50 +00001749// Simplification of IV users based on SCEV evaluation.
1750//===----------------------------------------------------------------------===//
1751
Andrew Trickb6bc7832014-01-02 21:12:11 +00001752namespace {
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +00001753
Sanjoy Dase1e352d2015-09-20 18:42:50 +00001754class IndVarSimplifyVisitor : public IVVisitor {
1755 ScalarEvolution *SE;
1756 const TargetTransformInfo *TTI;
1757 PHINode *IVPhi;
Andrew Trickb6bc7832014-01-02 21:12:11 +00001758
Sanjoy Dase1e352d2015-09-20 18:42:50 +00001759public:
1760 WideIVInfo WI;
Andrew Trickb6bc7832014-01-02 21:12:11 +00001761
Sanjoy Dase1e352d2015-09-20 18:42:50 +00001762 IndVarSimplifyVisitor(PHINode *IV, ScalarEvolution *SCEV,
1763 const TargetTransformInfo *TTI,
1764 const DominatorTree *DTree)
1765 : SE(SCEV), TTI(TTI), IVPhi(IV) {
1766 DT = DTree;
1767 WI.NarrowIV = IVPhi;
Sanjoy Dase1e352d2015-09-20 18:42:50 +00001768 }
Andrew Trickb6bc7832014-01-02 21:12:11 +00001769
Sanjoy Dase1e352d2015-09-20 18:42:50 +00001770 // Implement the interface used by simplifyUsersOfIV.
1771 void visitCast(CastInst *Cast) override { visitIVCast(Cast, WI, SE, TTI); }
1772};
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +00001773
1774} // end anonymous namespace
Andrew Trick81683ed2011-05-12 00:04:28 +00001775
Sanjoy Das9119bf42015-09-20 06:58:03 +00001776/// Iteratively perform simplification on a worklist of IV users. Each
1777/// successive simplification may push more users which may themselves be
1778/// candidates for simplification.
Andrew Trick69d44522011-06-21 03:22:38 +00001779///
Andrew Trick3ec331e2011-08-10 03:46:27 +00001780/// Sign/Zero extend elimination is interleaved with IV simplification.
Sanjoy Dasb873cbe2015-10-13 07:17:38 +00001781void IndVarSimplify::simplifyAndExtend(Loop *L,
Andrew Trick3ec331e2011-08-10 03:46:27 +00001782 SCEVExpander &Rewriter,
Justin Bogner843fb202015-12-15 19:40:57 +00001783 LoopInfo *LI) {
Andrew Trickd50861c2011-10-15 01:38:14 +00001784 SmallVector<WideIVInfo, 8> WideIVs;
Andrew Trick8a3c39c2011-06-28 02:49:20 +00001785
Artur Pilipenko5c6ef752016-10-19 19:43:54 +00001786 auto *GuardDecl = L->getBlocks()[0]->getModule()->getFunction(
1787 Intrinsic::getName(Intrinsic::experimental_guard));
1788 bool HasGuards = GuardDecl && !GuardDecl->use_empty();
1789
Andrew Trick69d44522011-06-21 03:22:38 +00001790 SmallVector<PHINode*, 8> LoopPhis;
1791 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
1792 LoopPhis.push_back(cast<PHINode>(I));
1793 }
Andrew Trick8a3c39c2011-06-28 02:49:20 +00001794 // Each round of simplification iterates through the SimplifyIVUsers worklist
1795 // for all current phis, then determines whether any IVs can be
1796 // widened. Widening adds new phis to LoopPhis, inducing another round of
1797 // simplification on the wide IVs.
Andrew Trick69d44522011-06-21 03:22:38 +00001798 while (!LoopPhis.empty()) {
Andrew Trick8a3c39c2011-06-28 02:49:20 +00001799 // Evaluate as many IV expressions as possible before widening any IVs. This
Andrew Trick4426f5b2011-06-28 16:45:04 +00001800 // forces SCEV to set no-wrap flags before evaluating sign/zero
Andrew Trick8a3c39c2011-06-28 02:49:20 +00001801 // extension. The first time SCEV attempts to normalize sign/zero extension,
1802 // the result becomes final. So for the most predictable results, we delay
1803 // evaluation of sign/zero extend evaluation until needed, and avoid running
Sanjoy Dasb873cbe2015-10-13 07:17:38 +00001804 // other SCEV based analysis prior to simplifyAndExtend.
Andrew Trick8a3c39c2011-06-28 02:49:20 +00001805 do {
1806 PHINode *CurrIV = LoopPhis.pop_back_val();
Andrew Trick69d44522011-06-21 03:22:38 +00001807
Andrew Trick8a3c39c2011-06-28 02:49:20 +00001808 // Information about sign/zero extensions of CurrIV.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001809 IndVarSimplifyVisitor Visitor(CurrIV, SE, TTI, DT);
Andrew Trick69d44522011-06-21 03:22:38 +00001810
Hongbin Zhengd36f20302017-10-12 02:54:11 +00001811 Changed |=
1812 simplifyUsersOfIV(CurrIV, SE, DT, LI, DeadInsts, Rewriter, &Visitor);
Andrew Trick69d44522011-06-21 03:22:38 +00001813
Andrew Trickb6bc7832014-01-02 21:12:11 +00001814 if (Visitor.WI.WidestNativeType) {
1815 WideIVs.push_back(Visitor.WI);
Andrew Trick69d44522011-06-21 03:22:38 +00001816 }
Andrew Trick8a3c39c2011-06-28 02:49:20 +00001817 } while(!LoopPhis.empty());
1818
Andrew Trickd50861c2011-10-15 01:38:14 +00001819 for (; !WideIVs.empty(); WideIVs.pop_back()) {
Artur Pilipenko5c6ef752016-10-19 19:43:54 +00001820 WidenIV Widener(WideIVs.back(), LI, SE, DT, DeadInsts, HasGuards);
Sanjoy Dasb873cbe2015-10-13 07:17:38 +00001821 if (PHINode *WidePhi = Widener.createWideIV(Rewriter)) {
Andrew Trick69d44522011-06-21 03:22:38 +00001822 Changed = true;
1823 LoopPhis.push_back(WidePhi);
1824 }
1825 }
1826 }
1827}
1828
Andrew Trickcdc22972011-07-12 00:08:50 +00001829//===----------------------------------------------------------------------===//
Sanjoy Dasb873cbe2015-10-13 07:17:38 +00001830// linearFunctionTestReplace and its kin. Rewrite the loop exit condition.
Andrew Trickcdc22972011-07-12 00:08:50 +00001831//===----------------------------------------------------------------------===//
1832
Sanjoy Das9119bf42015-09-20 06:58:03 +00001833/// Return true if this loop's backedge taken count expression can be safely and
1834/// cheaply expanded into an instruction sequence that can be used by
Sanjoy Dasb873cbe2015-10-13 07:17:38 +00001835/// linearFunctionTestReplace.
Andrew Trickc2c79c92011-11-02 17:19:57 +00001836///
1837/// TODO: This fails for pointer-type loop counters with greater than one byte
1838/// strides, consequently preventing LFTR from running. For the purpose of LFTR
1839/// we could skip this check in the case that the LFTR loop counter (chosen by
1840/// FindLoopCounter) is also pointer type. Instead, we could directly convert
1841/// the loop test to an inequality test by checking the target data's alignment
1842/// of element types (given that the initial pointer value originates from or is
1843/// used by ABI constrained operation, as opposed to inttoptr/ptrtoint).
1844/// However, we don't yet have a strong motivation for converting loop tests
1845/// into inequality tests.
Sanjoy Das2e6bb3b2015-04-14 03:20:28 +00001846static bool canExpandBackedgeTakenCount(Loop *L, ScalarEvolution *SE,
1847 SCEVExpander &Rewriter) {
Andrew Trickcdc22972011-07-12 00:08:50 +00001848 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
1849 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount) ||
1850 BackedgeTakenCount->isZero())
1851 return false;
1852
1853 if (!L->getExitingBlock())
1854 return false;
1855
1856 // Can't rewrite non-branch yet.
Sanjoy Das2e6bb3b2015-04-14 03:20:28 +00001857 if (!isa<BranchInst>(L->getExitingBlock()->getTerminator()))
Andrew Trickcdc22972011-07-12 00:08:50 +00001858 return false;
1859
Sanjoy Das2e6bb3b2015-04-14 03:20:28 +00001860 if (Rewriter.isHighCostExpansion(BackedgeTakenCount, L))
Andrew Tricka27d8b12011-07-18 18:21:35 +00001861 return false;
1862
Andrew Trickcdc22972011-07-12 00:08:50 +00001863 return true;
1864}
1865
Sanjoy Das9119bf42015-09-20 06:58:03 +00001866/// Return the loop header phi IFF IncV adds a loop invariant value to the phi.
Andrew Trick7da24172011-07-18 20:32:31 +00001867static PHINode *getLoopPhiForCounter(Value *IncV, Loop *L, DominatorTree *DT) {
1868 Instruction *IncI = dyn_cast<Instruction>(IncV);
1869 if (!IncI)
Craig Topperf40110f2014-04-25 05:29:35 +00001870 return nullptr;
Andrew Trick7da24172011-07-18 20:32:31 +00001871
1872 switch (IncI->getOpcode()) {
1873 case Instruction::Add:
1874 case Instruction::Sub:
1875 break;
1876 case Instruction::GetElementPtr:
1877 // An IV counter must preserve its type.
1878 if (IncI->getNumOperands() == 2)
1879 break;
Galina Kistanova55344ab2017-06-03 05:19:10 +00001880 LLVM_FALLTHROUGH;
Andrew Trick7da24172011-07-18 20:32:31 +00001881 default:
Craig Topperf40110f2014-04-25 05:29:35 +00001882 return nullptr;
Andrew Trick7da24172011-07-18 20:32:31 +00001883 }
1884
1885 PHINode *Phi = dyn_cast<PHINode>(IncI->getOperand(0));
1886 if (Phi && Phi->getParent() == L->getHeader()) {
1887 if (isLoopInvariant(IncI->getOperand(1), L, DT))
1888 return Phi;
Craig Topperf40110f2014-04-25 05:29:35 +00001889 return nullptr;
Andrew Trick7da24172011-07-18 20:32:31 +00001890 }
1891 if (IncI->getOpcode() == Instruction::GetElementPtr)
Craig Topperf40110f2014-04-25 05:29:35 +00001892 return nullptr;
Andrew Trick7da24172011-07-18 20:32:31 +00001893
1894 // Allow add/sub to be commuted.
1895 Phi = dyn_cast<PHINode>(IncI->getOperand(1));
1896 if (Phi && Phi->getParent() == L->getHeader()) {
1897 if (isLoopInvariant(IncI->getOperand(0), L, DT))
1898 return Phi;
1899 }
Craig Topperf40110f2014-04-25 05:29:35 +00001900 return nullptr;
Andrew Trick7da24172011-07-18 20:32:31 +00001901}
1902
Andrew Trickc0872662012-07-18 04:35:10 +00001903/// Return the compare guarding the loop latch, or NULL for unrecognized tests.
1904static ICmpInst *getLoopTest(Loop *L) {
Andrew Trick7da24172011-07-18 20:32:31 +00001905 assert(L->getExitingBlock() && "expected loop exit");
1906
1907 BasicBlock *LatchBlock = L->getLoopLatch();
1908 // Don't bother with LFTR if the loop is not properly simplified.
1909 if (!LatchBlock)
Craig Topperf40110f2014-04-25 05:29:35 +00001910 return nullptr;
Andrew Trick7da24172011-07-18 20:32:31 +00001911
1912 BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator());
1913 assert(BI && "expected exit branch");
1914
Andrew Trickc0872662012-07-18 04:35:10 +00001915 return dyn_cast<ICmpInst>(BI->getCondition());
1916}
1917
Sanjoy Dasb873cbe2015-10-13 07:17:38 +00001918/// linearFunctionTestReplace policy. Return true unless we can show that the
Sanjoy Das9119bf42015-09-20 06:58:03 +00001919/// current exit test is already sufficiently canonical.
Andrew Trickc0872662012-07-18 04:35:10 +00001920static bool needsLFTR(Loop *L, DominatorTree *DT) {
Andrew Trick7da24172011-07-18 20:32:31 +00001921 // Do LFTR to simplify the exit condition to an ICMP.
Andrew Trickc0872662012-07-18 04:35:10 +00001922 ICmpInst *Cond = getLoopTest(L);
Andrew Trick7da24172011-07-18 20:32:31 +00001923 if (!Cond)
1924 return true;
1925
1926 // Do LFTR to simplify the exit ICMP to EQ/NE
1927 ICmpInst::Predicate Pred = Cond->getPredicate();
1928 if (Pred != ICmpInst::ICMP_NE && Pred != ICmpInst::ICMP_EQ)
1929 return true;
1930
1931 // Look for a loop invariant RHS
1932 Value *LHS = Cond->getOperand(0);
1933 Value *RHS = Cond->getOperand(1);
1934 if (!isLoopInvariant(RHS, L, DT)) {
1935 if (!isLoopInvariant(LHS, L, DT))
1936 return true;
1937 std::swap(LHS, RHS);
1938 }
1939 // Look for a simple IV counter LHS
1940 PHINode *Phi = dyn_cast<PHINode>(LHS);
1941 if (!Phi)
1942 Phi = getLoopPhiForCounter(LHS, L, DT);
1943
1944 if (!Phi)
1945 return true;
1946
Jakub Staszake076cac2012-10-04 19:08:30 +00001947 // Do LFTR if PHI node is defined in the loop, but is *not* a counter.
Jakub Staszakf8a81292012-10-03 23:59:47 +00001948 int Idx = Phi->getBasicBlockIndex(L->getLoopLatch());
1949 if (Idx < 0)
1950 return true;
Jakub Staszake076cac2012-10-04 19:08:30 +00001951
1952 // Do LFTR if the exit condition's IV is *not* a simple counter.
Jakub Staszakf8a81292012-10-03 23:59:47 +00001953 Value *IncV = Phi->getIncomingValue(Idx);
Andrew Trick7da24172011-07-18 20:32:31 +00001954 return Phi != getLoopPhiForCounter(IncV, L, DT);
1955}
1956
Andrew Trickc0872662012-07-18 04:35:10 +00001957/// Recursive helper for hasConcreteDef(). Unfortunately, this currently boils
1958/// down to checking that all operands are constant and listing instructions
1959/// that may hide undef.
Craig Topper71b7b682014-08-21 05:55:13 +00001960static bool hasConcreteDefImpl(Value *V, SmallPtrSetImpl<Value*> &Visited,
Andrew Trickc0872662012-07-18 04:35:10 +00001961 unsigned Depth) {
1962 if (isa<Constant>(V))
1963 return !isa<UndefValue>(V);
1964
1965 if (Depth >= 6)
1966 return false;
1967
1968 // Conservatively handle non-constant non-instructions. For example, Arguments
1969 // may be undef.
1970 Instruction *I = dyn_cast<Instruction>(V);
1971 if (!I)
1972 return false;
1973
1974 // Load and return values may be undef.
1975 if(I->mayReadFromMemory() || isa<CallInst>(I) || isa<InvokeInst>(I))
1976 return false;
1977
1978 // Optimistically handle other instructions.
Sanjoy Das42e551b2015-12-08 23:52:58 +00001979 for (Value *Op : I->operands()) {
1980 if (!Visited.insert(Op).second)
Andrew Trickc0872662012-07-18 04:35:10 +00001981 continue;
Sanjoy Das42e551b2015-12-08 23:52:58 +00001982 if (!hasConcreteDefImpl(Op, Visited, Depth+1))
Andrew Trickc0872662012-07-18 04:35:10 +00001983 return false;
1984 }
1985 return true;
1986}
1987
1988/// Return true if the given value is concrete. We must prove that undef can
1989/// never reach it.
1990///
1991/// TODO: If we decide that this is a good approach to checking for undef, we
1992/// may factor it into a common location.
1993static bool hasConcreteDef(Value *V) {
1994 SmallPtrSet<Value*, 8> Visited;
1995 Visited.insert(V);
1996 return hasConcreteDefImpl(V, Visited, 0);
1997}
1998
Sanjoy Das9119bf42015-09-20 06:58:03 +00001999/// Return true if this IV has any uses other than the (soon to be rewritten)
2000/// loop exit test.
Andrew Trick7da24172011-07-18 20:32:31 +00002001static bool AlmostDeadIV(PHINode *Phi, BasicBlock *LatchBlock, Value *Cond) {
2002 int LatchIdx = Phi->getBasicBlockIndex(LatchBlock);
2003 Value *IncV = Phi->getIncomingValue(LatchIdx);
2004
Chandler Carruthcdf47882014-03-09 03:16:01 +00002005 for (User *U : Phi->users())
2006 if (U != Cond && U != IncV) return false;
Andrew Trick7da24172011-07-18 20:32:31 +00002007
Chandler Carruthcdf47882014-03-09 03:16:01 +00002008 for (User *U : IncV->users())
2009 if (U != Cond && U != Phi) return false;
Andrew Trick7da24172011-07-18 20:32:31 +00002010 return true;
2011}
2012
Sanjoy Das9119bf42015-09-20 06:58:03 +00002013/// Find an affine IV in canonical form.
Andrew Trick7da24172011-07-18 20:32:31 +00002014///
Andrew Trickc2c79c92011-11-02 17:19:57 +00002015/// BECount may be an i8* pointer type. The pointer difference is already
2016/// valid count without scaling the address stride, so it remains a pointer
2017/// expression as far as SCEV is concerned.
2018///
Andrew Trickc0872662012-07-18 04:35:10 +00002019/// Currently only valid for LFTR. See the comments on hasConcreteDef below.
2020///
Andrew Trick7da24172011-07-18 20:32:31 +00002021/// FIXME: Accept -1 stride and set IVLimit = IVInit - BECount
2022///
2023/// FIXME: Accept non-unit stride as long as SCEV can reduce BECount * Stride.
2024/// This is difficult in general for SCEV because of potential overflow. But we
2025/// could at least handle constant BECounts.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002026static PHINode *FindLoopCounter(Loop *L, const SCEV *BECount,
2027 ScalarEvolution *SE, DominatorTree *DT) {
Andrew Trick7da24172011-07-18 20:32:31 +00002028 uint64_t BCWidth = SE->getTypeSizeInBits(BECount->getType());
2029
2030 Value *Cond =
2031 cast<BranchInst>(L->getExitingBlock()->getTerminator())->getCondition();
2032
2033 // Loop over all of the PHI nodes, looking for a simple counter.
Craig Topperf40110f2014-04-25 05:29:35 +00002034 PHINode *BestPhi = nullptr;
2035 const SCEV *BestInit = nullptr;
Andrew Trick7da24172011-07-18 20:32:31 +00002036 BasicBlock *LatchBlock = L->getLoopLatch();
2037 assert(LatchBlock && "needsLFTR should guarantee a loop latch");
Sanjoy Dascddde582016-01-27 17:05:09 +00002038 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
Andrew Trick7da24172011-07-18 20:32:31 +00002039
2040 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
2041 PHINode *Phi = cast<PHINode>(I);
2042 if (!SE->isSCEVable(Phi->getType()))
2043 continue;
2044
Andrew Trickc2c79c92011-11-02 17:19:57 +00002045 // Avoid comparing an integer IV against a pointer Limit.
2046 if (BECount->getType()->isPointerTy() && !Phi->getType()->isPointerTy())
2047 continue;
2048
Andrew Trick7da24172011-07-18 20:32:31 +00002049 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Phi));
2050 if (!AR || AR->getLoop() != L || !AR->isAffine())
2051 continue;
2052
2053 // AR may be a pointer type, while BECount is an integer type.
2054 // AR may be wider than BECount. With eq/ne tests overflow is immaterial.
2055 // AR may not be a narrower type, or we may never exit.
2056 uint64_t PhiWidth = SE->getTypeSizeInBits(AR->getType());
Sanjoy Dascddde582016-01-27 17:05:09 +00002057 if (PhiWidth < BCWidth || !DL.isLegalInteger(PhiWidth))
Andrew Trick7da24172011-07-18 20:32:31 +00002058 continue;
2059
2060 const SCEV *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*SE));
2061 if (!Step || !Step->isOne())
2062 continue;
2063
2064 int LatchIdx = Phi->getBasicBlockIndex(LatchBlock);
2065 Value *IncV = Phi->getIncomingValue(LatchIdx);
2066 if (getLoopPhiForCounter(IncV, L, DT) != Phi)
2067 continue;
2068
Andrew Trickc0872662012-07-18 04:35:10 +00002069 // Avoid reusing a potentially undef value to compute other values that may
2070 // have originally had a concrete definition.
2071 if (!hasConcreteDef(Phi)) {
2072 // We explicitly allow unknown phis as long as they are already used by
2073 // the loop test. In this case we assume that performing LFTR could not
2074 // increase the number of undef users.
2075 if (ICmpInst *Cond = getLoopTest(L)) {
Sanjoy Das91e6ba62016-06-24 21:23:32 +00002076 if (Phi != getLoopPhiForCounter(Cond->getOperand(0), L, DT) &&
2077 Phi != getLoopPhiForCounter(Cond->getOperand(1), L, DT)) {
Andrew Trickc0872662012-07-18 04:35:10 +00002078 continue;
2079 }
2080 }
2081 }
Andrew Trick7da24172011-07-18 20:32:31 +00002082 const SCEV *Init = AR->getStart();
2083
2084 if (BestPhi && !AlmostDeadIV(BestPhi, LatchBlock, Cond)) {
2085 // Don't force a live loop counter if another IV can be used.
2086 if (AlmostDeadIV(Phi, LatchBlock, Cond))
2087 continue;
2088
2089 // Prefer to count-from-zero. This is a more "canonical" counter form. It
2090 // also prefers integer to pointer IVs.
2091 if (BestInit->isZero() != Init->isZero()) {
2092 if (BestInit->isZero())
2093 continue;
2094 }
2095 // If two IVs both count from zero or both count from nonzero then the
2096 // narrower is likely a dead phi that has been widened. Use the wider phi
2097 // to allow the other to be eliminated.
Andrew Trick0d07dfc2012-07-18 04:35:13 +00002098 else if (PhiWidth <= SE->getTypeSizeInBits(BestPhi->getType()))
Andrew Trick7da24172011-07-18 20:32:31 +00002099 continue;
2100 }
2101 BestPhi = Phi;
2102 BestInit = Init;
2103 }
2104 return BestPhi;
2105}
2106
Sanjoy Dasb873cbe2015-10-13 07:17:38 +00002107/// Help linearFunctionTestReplace by generating a value that holds the RHS of
Sanjoy Das9119bf42015-09-20 06:58:03 +00002108/// the new loop test.
Andrew Trickc2c79c92011-11-02 17:19:57 +00002109static Value *genLoopLimit(PHINode *IndVar, const SCEV *IVCount, Loop *L,
Chandler Carruth7ec50852012-11-01 08:07:29 +00002110 SCEVExpander &Rewriter, ScalarEvolution *SE) {
Andrew Trickc2c79c92011-11-02 17:19:57 +00002111 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(IndVar));
2112 assert(AR && AR->getLoop() == L && AR->isAffine() && "bad loop counter");
2113 const SCEV *IVInit = AR->getStart();
2114
2115 // IVInit may be a pointer while IVCount is an integer when FindLoopCounter
2116 // finds a valid pointer IV. Sign extend BECount in order to materialize a
2117 // GEP. Avoid running SCEVExpander on a new pointer value, instead reusing
2118 // the existing GEPs whenever possible.
Sanjoy Das91e6ba62016-06-24 21:23:32 +00002119 if (IndVar->getType()->isPointerTy() && !IVCount->getType()->isPointerTy()) {
Juergen Ributzkad04d0962013-10-24 05:29:56 +00002120 // IVOffset will be the new GEP offset that is interpreted by GEP as a
2121 // signed value. IVCount on the other hand represents the loop trip count,
2122 // which is an unsigned value. FindLoopCounter only allows induction
2123 // variables that have a positive unit stride of one. This means we don't
2124 // have to handle the case of negative offsets (yet) and just need to zero
2125 // extend IVCount.
Andrew Trickc2c79c92011-11-02 17:19:57 +00002126 Type *OfsTy = SE->getEffectiveSCEVType(IVInit->getType());
Juergen Ributzkad04d0962013-10-24 05:29:56 +00002127 const SCEV *IVOffset = SE->getTruncateOrZeroExtend(IVCount, OfsTy);
Andrew Trickc2c79c92011-11-02 17:19:57 +00002128
2129 // Expand the code for the iteration count.
2130 assert(SE->isLoopInvariant(IVOffset, L) &&
2131 "Computed iteration count is not loop invariant!");
2132 BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator());
2133 Value *GEPOffset = Rewriter.expandCodeFor(IVOffset, OfsTy, BI);
2134
2135 Value *GEPBase = IndVar->getIncomingValueForBlock(L->getLoopPreheader());
2136 assert(AR->getStart() == SE->getSCEV(GEPBase) && "bad loop counter");
2137 // We could handle pointer IVs other than i8*, but we need to compensate for
2138 // gep index scaling. See canExpandBackedgeTakenCount comments.
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00002139 assert(SE->getSizeOfExpr(IntegerType::getInt64Ty(IndVar->getContext()),
Sanjoy Das91e6ba62016-06-24 21:23:32 +00002140 cast<PointerType>(GEPBase->getType())
2141 ->getElementType())->isOne() &&
2142 "unit stride pointer IV must be i8*");
Andrew Trickc2c79c92011-11-02 17:19:57 +00002143
2144 IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
David Blaikie93c54442015-04-03 19:41:44 +00002145 return Builder.CreateGEP(nullptr, GEPBase, GEPOffset, "lftr.limit");
Sanjoy Das91e6ba62016-06-24 21:23:32 +00002146 } else {
Andrew Trickc2c79c92011-11-02 17:19:57 +00002147 // In any other case, convert both IVInit and IVCount to integers before
Xin Tong02b13972017-01-10 03:13:52 +00002148 // comparing. This may result in SCEV expansion of pointers, but in practice
Andrew Trickc2c79c92011-11-02 17:19:57 +00002149 // SCEV will fold the pointer arithmetic away as such:
2150 // BECount = (IVEnd - IVInit - 1) => IVLimit = IVInit (postinc).
2151 //
2152 // Valid Cases: (1) both integers is most common; (2) both may be pointers
Andrew Trickada23562013-10-24 00:43:38 +00002153 // for simple memset-style loops.
2154 //
2155 // IVInit integer and IVCount pointer would only occur if a canonical IV
2156 // were generated on top of case #2, which is not expected.
Andrew Trickc2c79c92011-11-02 17:19:57 +00002157
Craig Topperf40110f2014-04-25 05:29:35 +00002158 const SCEV *IVLimit = nullptr;
Andrew Trickc2c79c92011-11-02 17:19:57 +00002159 // For unit stride, IVCount = Start + BECount with 2's complement overflow.
2160 // For non-zero Start, compute IVCount here.
2161 if (AR->getStart()->isZero())
2162 IVLimit = IVCount;
2163 else {
2164 assert(AR->getStepRecurrence(*SE)->isOne() && "only handles unit stride");
2165 const SCEV *IVInit = AR->getStart();
2166
2167 // For integer IVs, truncate the IV before computing IVInit + BECount.
2168 if (SE->getTypeSizeInBits(IVInit->getType())
2169 > SE->getTypeSizeInBits(IVCount->getType()))
2170 IVInit = SE->getTruncateExpr(IVInit, IVCount->getType());
2171
2172 IVLimit = SE->getAddExpr(IVInit, IVCount);
2173 }
2174 // Expand the code for the iteration count.
2175 BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator());
2176 IRBuilder<> Builder(BI);
2177 assert(SE->isLoopInvariant(IVLimit, L) &&
2178 "Computed iteration count is not loop invariant!");
2179 // Ensure that we generate the same type as IndVar, or a smaller integer
2180 // type. In the presence of null pointer values, we have an integer type
2181 // SCEV expression (IVInit) for a pointer type IV value (IndVar).
2182 Type *LimitTy = IVCount->getType()->isPointerTy() ?
2183 IndVar->getType() : IVCount->getType();
2184 return Rewriter.expandCodeFor(IVLimit, LimitTy, BI);
2185 }
2186}
2187
Sanjoy Das9119bf42015-09-20 06:58:03 +00002188/// This method rewrites the exit condition of the loop to be a canonical !=
2189/// comparison against the incremented loop induction variable. This pass is
2190/// able to rewrite the exit tests of any loop where the SCEV analysis can
2191/// determine a loop-invariant trip count of the loop, which is actually a much
2192/// broader range than just linear tests.
Andrew Trick7da24172011-07-18 20:32:31 +00002193Value *IndVarSimplify::
Sanjoy Dasb873cbe2015-10-13 07:17:38 +00002194linearFunctionTestReplace(Loop *L,
Andrew Trickcdc22972011-07-12 00:08:50 +00002195 const SCEV *BackedgeTakenCount,
2196 PHINode *IndVar,
2197 SCEVExpander &Rewriter) {
Sanjoy Das2e6bb3b2015-04-14 03:20:28 +00002198 assert(canExpandBackedgeTakenCount(L, SE, Rewriter) && "precondition");
Andrew Trickcdc22972011-07-12 00:08:50 +00002199
Andrew Trick2b718482013-07-12 22:08:44 +00002200 // Initialize CmpIndVar and IVCount to their preincremented values.
2201 Value *CmpIndVar = IndVar;
2202 const SCEV *IVCount = BackedgeTakenCount;
Andrew Trick7da24172011-07-18 20:32:31 +00002203
Sanjoy Das85cd1322017-02-20 23:37:11 +00002204 assert(L->getLoopLatch() && "Loop no longer in simplified form?");
2205
Andrew Trickc2c79c92011-11-02 17:19:57 +00002206 // If the exiting block is the same as the backedge block, we prefer to
2207 // compare against the post-incremented value, otherwise we must compare
2208 // against the preincremented value.
Andrew Trickcdc22972011-07-12 00:08:50 +00002209 if (L->getExitingBlock() == L->getLoopLatch()) {
Sanjoy Das2d380312015-03-02 21:41:07 +00002210 // Add one to the "backedge-taken" count to get the trip count.
2211 // This addition may overflow, which is valid as long as the comparison is
2212 // truncated to BackedgeTakenCount->getType().
2213 IVCount = SE->getAddExpr(BackedgeTakenCount,
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002214 SE->getOne(BackedgeTakenCount->getType()));
Andrew Trickcdc22972011-07-12 00:08:50 +00002215 // The BackedgeTaken expression contains the number of times that the
2216 // backedge branches to the loop header. This is one less than the
2217 // number of times the loop executes, so use the incremented indvar.
Sanjoy Das2d380312015-03-02 21:41:07 +00002218 CmpIndVar = IndVar->getIncomingValueForBlock(L->getExitingBlock());
Andrew Trickcdc22972011-07-12 00:08:50 +00002219 }
2220
Chandler Carruth7ec50852012-11-01 08:07:29 +00002221 Value *ExitCnt = genLoopLimit(IndVar, IVCount, L, Rewriter, SE);
Sanjoy Das91e6ba62016-06-24 21:23:32 +00002222 assert(ExitCnt->getType()->isPointerTy() ==
2223 IndVar->getType()->isPointerTy() &&
2224 "genLoopLimit missed a cast");
Andrew Trickcdc22972011-07-12 00:08:50 +00002225
2226 // Insert a new icmp_ne or icmp_eq instruction before the branch.
Andrew Trickc2c79c92011-11-02 17:19:57 +00002227 BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator());
Andrew Trick7da24172011-07-18 20:32:31 +00002228 ICmpInst::Predicate P;
Andrew Trickcdc22972011-07-12 00:08:50 +00002229 if (L->contains(BI->getSuccessor(0)))
Andrew Trick7da24172011-07-18 20:32:31 +00002230 P = ICmpInst::ICMP_NE;
Andrew Trickcdc22972011-07-12 00:08:50 +00002231 else
Andrew Trick7da24172011-07-18 20:32:31 +00002232 P = ICmpInst::ICMP_EQ;
Andrew Trickcdc22972011-07-12 00:08:50 +00002233
2234 DEBUG(dbgs() << "INDVARS: Rewriting loop exit condition to:\n"
2235 << " LHS:" << *CmpIndVar << '\n'
2236 << " op:\t"
Andrew Trick7da24172011-07-18 20:32:31 +00002237 << (P == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
2238 << " RHS:\t" << *ExitCnt << "\n"
Andrew Trickc2c79c92011-11-02 17:19:57 +00002239 << " IVCount:\t" << *IVCount << "\n");
Andrew Trickcdc22972011-07-12 00:08:50 +00002240
Andrew Tricka1e41182013-07-12 22:08:48 +00002241 IRBuilder<> Builder(BI);
2242
Andrea Di Biagio9bcb0642016-10-26 10:28:32 +00002243 // The new loop exit condition should reuse the debug location of the
2244 // original loop exit condition.
2245 if (auto *Cond = dyn_cast<Instruction>(BI->getCondition()))
2246 Builder.SetCurrentDebugLocation(Cond->getDebugLoc());
2247
Andrew Trick2b718482013-07-12 22:08:44 +00002248 // LFTR can ignore IV overflow and truncate to the width of
2249 // BECount. This avoids materializing the add(zext(add)) expression.
Andrew Tricka1e41182013-07-12 22:08:48 +00002250 unsigned CmpIndVarSize = SE->getTypeSizeInBits(CmpIndVar->getType());
2251 unsigned ExitCntSize = SE->getTypeSizeInBits(ExitCnt->getType());
2252 if (CmpIndVarSize > ExitCntSize) {
2253 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(SE->getSCEV(IndVar));
2254 const SCEV *ARStart = AR->getStart();
2255 const SCEV *ARStep = AR->getStepRecurrence(*SE);
2256 // For constant IVCount, avoid truncation.
2257 if (isa<SCEVConstant>(ARStart) && isa<SCEVConstant>(IVCount)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002258 const APInt &Start = cast<SCEVConstant>(ARStart)->getAPInt();
2259 APInt Count = cast<SCEVConstant>(IVCount)->getAPInt();
Andrew Tricka1e41182013-07-12 22:08:48 +00002260 // Note that the post-inc value of BackedgeTakenCount may have overflowed
2261 // above such that IVCount is now zero.
2262 if (IVCount != BackedgeTakenCount && Count == 0) {
2263 Count = APInt::getMaxValue(Count.getBitWidth()).zext(CmpIndVarSize);
2264 ++Count;
2265 }
2266 else
2267 Count = Count.zext(CmpIndVarSize);
2268 APInt NewLimit;
2269 if (cast<SCEVConstant>(ARStep)->getValue()->isNegative())
2270 NewLimit = Start - Count;
2271 else
2272 NewLimit = Start + Count;
2273 ExitCnt = ConstantInt::get(CmpIndVar->getType(), NewLimit);
Andrew Trick7da24172011-07-18 20:32:31 +00002274
Andrew Tricka1e41182013-07-12 22:08:48 +00002275 DEBUG(dbgs() << " Widen RHS:\t" << *ExitCnt << "\n");
2276 } else {
Ehsan Amiridbcfea92016-08-11 21:31:40 +00002277 // We try to extend trip count first. If that doesn't work we truncate IV.
2278 // Zext(trunc(IV)) == IV implies equivalence of the following two:
2279 // Trunc(IV) == ExitCnt and IV == zext(ExitCnt). Similarly for sext. If
2280 // one of the two holds, extend the trip count, otherwise we truncate IV.
2281 bool Extended = false;
2282 const SCEV *IV = SE->getSCEV(CmpIndVar);
2283 const SCEV *ZExtTrunc =
2284 SE->getZeroExtendExpr(SE->getTruncateExpr(SE->getSCEV(CmpIndVar),
2285 ExitCnt->getType()),
2286 CmpIndVar->getType());
Ehsan Amirib9fcc2b2016-08-11 13:51:20 +00002287
Ehsan Amiridbcfea92016-08-11 21:31:40 +00002288 if (ZExtTrunc == IV) {
2289 Extended = true;
2290 ExitCnt = Builder.CreateZExt(ExitCnt, IndVar->getType(),
2291 "wide.trip.count");
2292 } else {
2293 const SCEV *SExtTrunc =
2294 SE->getSignExtendExpr(SE->getTruncateExpr(SE->getSCEV(CmpIndVar),
2295 ExitCnt->getType()),
2296 CmpIndVar->getType());
2297 if (SExtTrunc == IV) {
2298 Extended = true;
2299 ExitCnt = Builder.CreateSExt(ExitCnt, IndVar->getType(),
2300 "wide.trip.count");
2301 }
2302 }
2303
2304 if (!Extended)
Ehsan Amirib9fcc2b2016-08-11 13:51:20 +00002305 CmpIndVar = Builder.CreateTrunc(CmpIndVar, ExitCnt->getType(),
2306 "lftr.wideiv");
Andrew Tricka1e41182013-07-12 22:08:48 +00002307 }
2308 }
Andrew Trick7da24172011-07-18 20:32:31 +00002309 Value *Cond = Builder.CreateICmp(P, CmpIndVar, ExitCnt, "exitcond");
Andrew Trickcdc22972011-07-12 00:08:50 +00002310 Value *OrigCond = BI->getCondition();
2311 // It's tempting to use replaceAllUsesWith here to fully replace the old
2312 // comparison, but that's not immediately safe, since users of the old
2313 // comparison may not be dominated by the new comparison. Instead, just
2314 // update the branch to use the new comparison; in the common case this
2315 // will make old comparison dead.
2316 BI->setCondition(Cond);
2317 DeadInsts.push_back(OrigCond);
2318
2319 ++NumLFTR;
2320 Changed = true;
2321 return Cond;
2322}
2323
2324//===----------------------------------------------------------------------===//
Sanjoy Dasb873cbe2015-10-13 07:17:38 +00002325// sinkUnusedInvariants. A late subpass to cleanup loop preheaders.
Andrew Trickcdc22972011-07-12 00:08:50 +00002326//===----------------------------------------------------------------------===//
2327
2328/// If there's a single exit block, sink any loop-invariant values that
2329/// were defined in the preheader but not used inside the loop into the
2330/// exit block to reduce register pressure in the loop.
Sanjoy Dasb873cbe2015-10-13 07:17:38 +00002331void IndVarSimplify::sinkUnusedInvariants(Loop *L) {
Andrew Trickcdc22972011-07-12 00:08:50 +00002332 BasicBlock *ExitBlock = L->getExitBlock();
2333 if (!ExitBlock) return;
2334
2335 BasicBlock *Preheader = L->getLoopPreheader();
2336 if (!Preheader) return;
2337
Duncan P. N. Exon Smith362d12042016-08-17 01:54:41 +00002338 BasicBlock::iterator InsertPt = ExitBlock->getFirstInsertionPt();
Duncan P. N. Exon Smith3a9c9e32015-10-13 18:26:00 +00002339 BasicBlock::iterator I(Preheader->getTerminator());
Andrew Trickcdc22972011-07-12 00:08:50 +00002340 while (I != Preheader->begin()) {
2341 --I;
2342 // New instructions were inserted at the end of the preheader.
2343 if (isa<PHINode>(I))
2344 break;
2345
2346 // Don't move instructions which might have side effects, since the side
2347 // effects need to complete before instructions inside the loop. Also don't
2348 // move instructions which might read memory, since the loop may modify
2349 // memory. Note that it's okay if the instruction might have undefined
2350 // behavior: LoopSimplify guarantees that the preheader dominates the exit
2351 // block.
2352 if (I->mayHaveSideEffects() || I->mayReadFromMemory())
2353 continue;
2354
2355 // Skip debug info intrinsics.
2356 if (isa<DbgInfoIntrinsic>(I))
2357 continue;
2358
David Majnemerba275f92015-08-19 19:54:02 +00002359 // Skip eh pad instructions.
2360 if (I->isEHPad())
Bill Wendlingeed1e892011-08-26 20:40:15 +00002361 continue;
2362
Eli Friedman73beaf72011-10-27 01:33:51 +00002363 // Don't sink alloca: we never want to sink static alloca's out of the
2364 // entry block, and correctly sinking dynamic alloca's requires
2365 // checks for stacksave/stackrestore intrinsics.
2366 // FIXME: Refactor this check somehow?
2367 if (isa<AllocaInst>(I))
2368 continue;
Andrew Trickcdc22972011-07-12 00:08:50 +00002369
2370 // Determine if there is a use in or before the loop (direct or
2371 // otherwise).
2372 bool UsedInLoop = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00002373 for (Use &U : I->uses()) {
2374 Instruction *User = cast<Instruction>(U.getUser());
2375 BasicBlock *UseBB = User->getParent();
2376 if (PHINode *P = dyn_cast<PHINode>(User)) {
Andrew Trickcdc22972011-07-12 00:08:50 +00002377 unsigned i =
Chandler Carruthcdf47882014-03-09 03:16:01 +00002378 PHINode::getIncomingValueNumForOperand(U.getOperandNo());
Andrew Trickcdc22972011-07-12 00:08:50 +00002379 UseBB = P->getIncomingBlock(i);
2380 }
2381 if (UseBB == Preheader || L->contains(UseBB)) {
2382 UsedInLoop = true;
2383 break;
2384 }
2385 }
2386
2387 // If there is, the def must remain in the preheader.
2388 if (UsedInLoop)
2389 continue;
2390
2391 // Otherwise, sink it to the exit block.
Duncan P. N. Exon Smith3a9c9e32015-10-13 18:26:00 +00002392 Instruction *ToMove = &*I;
Andrew Trickcdc22972011-07-12 00:08:50 +00002393 bool Done = false;
2394
2395 if (I != Preheader->begin()) {
2396 // Skip debug info intrinsics.
2397 do {
2398 --I;
2399 } while (isa<DbgInfoIntrinsic>(I) && I != Preheader->begin());
2400
2401 if (isa<DbgInfoIntrinsic>(I) && I == Preheader->begin())
2402 Done = true;
2403 } else {
2404 Done = true;
2405 }
2406
Duncan P. N. Exon Smith362d12042016-08-17 01:54:41 +00002407 ToMove->moveBefore(*ExitBlock, InsertPt);
Andrew Trickcdc22972011-07-12 00:08:50 +00002408 if (Done) break;
Duncan P. N. Exon Smith362d12042016-08-17 01:54:41 +00002409 InsertPt = ToMove->getIterator();
Andrew Trickcdc22972011-07-12 00:08:50 +00002410 }
2411}
2412
2413//===----------------------------------------------------------------------===//
2414// IndVarSimplify driver. Manage several subpasses of IV simplification.
2415//===----------------------------------------------------------------------===//
2416
Sanjoy Das496f2742016-05-29 21:42:00 +00002417bool IndVarSimplify::run(Loop *L) {
Sanjoy Das3e5ce2b2016-05-30 01:37:39 +00002418 // We need (and expect!) the incoming loop to be in LCSSA.
Igor Laevsky04423cf2016-10-11 13:37:22 +00002419 assert(L->isRecursivelyLCSSAForm(*DT, *LI) &&
2420 "LCSSA required to run indvars!");
Sanjoy Das3e5ce2b2016-05-30 01:37:39 +00002421
Dan Gohmanf3aea7a2010-06-18 01:35:11 +00002422 // If LoopSimplify form is not available, stay out of trouble. Some notes:
2423 // - LSR currently only supports LoopSimplify-form loops. Indvars'
2424 // canonicalization can be a pessimization without LSR to "clean up"
2425 // afterwards.
2426 // - We depend on having a preheader; in particular,
2427 // Loop::getCanonicalInductionVariable only supports loops with preheaders,
2428 // and we're in trouble if we can't find the induction variable even when
2429 // we've manually inserted one.
Sanjoy Das85cd1322017-02-20 23:37:11 +00002430 // - LFTR relies on having a single backedge.
Dan Gohmanf3aea7a2010-06-18 01:35:11 +00002431 if (!L->isLoopSimplifyForm())
2432 return false;
2433
Dan Gohman0a40ad92009-04-16 03:18:22 +00002434 // If there are any floating-point recurrences, attempt to
Dan Gohman43300342009-02-17 20:49:49 +00002435 // transform them to use integer recurrences.
Sanjoy Dasb873cbe2015-10-13 07:17:38 +00002436 rewriteNonIntegerIVs(L);
Dan Gohman43300342009-02-17 20:49:49 +00002437
Dan Gohmanaf752342009-07-07 17:06:11 +00002438 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
Chris Lattner1f7648e2007-03-04 01:00:28 +00002439
Dan Gohmandaafbe62009-06-26 22:53:46 +00002440 // Create a rewriter object which we'll use to transform the code with.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002441 SCEVExpander Rewriter(*SE, DL, "indvars");
Andrew Trickf9201c52011-10-11 02:28:51 +00002442#ifndef NDEBUG
2443 Rewriter.setDebugType(DEBUG_TYPE);
2444#endif
Andrew Trick163b4a72011-06-27 23:17:44 +00002445
2446 // Eliminate redundant IV users.
Andrew Trick8a3c39c2011-06-28 02:49:20 +00002447 //
2448 // Simplification works best when run before other consumers of SCEV. We
2449 // attempt to avoid evaluating SCEVs for sign/zero extend operations until
2450 // other expressions involving loop IVs have been evaluated. This helps SCEV
Andrew Trick4426f5b2011-06-28 16:45:04 +00002451 // set no-wrap flags before normalizing sign/zero extension.
Andrew Trickf47d0af2012-03-22 17:10:11 +00002452 Rewriter.disableCanonicalMode();
Justin Bogner843fb202015-12-15 19:40:57 +00002453 simplifyAndExtend(L, Rewriter, LI);
Andrew Trick1abe2962011-05-04 02:10:13 +00002454
Chris Lattnere61b67d2004-04-02 20:24:31 +00002455 // Check to see if this loop has a computable loop-invariant execution count.
2456 // If so, this means that we can compute the final value of any expressions
2457 // that are recurrent in the loop, and substitute the exit values from the
2458 // loop into any instructions outside of the loop that use the final values of
2459 // the current expressions.
Chris Lattner0b18c1d2002-05-10 15:38:35 +00002460 //
Wei Mie2538b52015-05-28 21:49:07 +00002461 if (ReplaceExitValue != NeverRepl &&
2462 !isa<SCEVCouldNotCompute>(BackedgeTakenCount))
Sanjoy Dasb873cbe2015-10-13 07:17:38 +00002463 rewriteLoopExitValues(L, Rewriter);
Chris Lattner476e6df2001-12-03 17:28:42 +00002464
Andrew Trick9ea55dc2011-07-16 01:06:48 +00002465 // Eliminate redundant IV cycles.
Andrew Trickf47d0af2012-03-22 17:10:11 +00002466 NumElimIV += Rewriter.replaceCongruentIVs(L, DT, DeadInsts);
Andrew Trick32390552011-07-06 20:50:43 +00002467
Dan Gohmaneb6be652009-02-12 22:19:27 +00002468 // If we have a trip count expression, rewrite the loop's exit condition
2469 // using it. We can currently only handle loops with a single exit.
Serguei Katkov38414b52017-06-09 06:11:59 +00002470 if (!DisableLFTR && canExpandBackedgeTakenCount(L, SE, Rewriter) &&
2471 needsLFTR(L, DT)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002472 PHINode *IndVar = FindLoopCounter(L, BackedgeTakenCount, SE, DT);
Andrew Trick25553ab2012-03-24 00:51:17 +00002473 if (IndVar) {
2474 // Check preconditions for proper SCEVExpander operation. SCEV does not
2475 // express SCEVExpander's dependencies, such as LoopSimplify. Instead any
2476 // pass that uses the SCEVExpander must do it. This does not work well for
Andrew Trickb70d9782014-01-07 01:02:52 +00002477 // loop passes because SCEVExpander makes assumptions about all loops,
2478 // while LoopPassManager only forces the current loop to be simplified.
Andrew Trick25553ab2012-03-24 00:51:17 +00002479 //
2480 // FIXME: SCEV expansion has no way to bail out, so the caller must
2481 // explicitly check any assumptions made by SCEV. Brittle.
2482 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(BackedgeTakenCount);
2483 if (!AR || AR->getLoop()->getLoopPreheader())
Sanjoy Dasb873cbe2015-10-13 07:17:38 +00002484 (void)linearFunctionTestReplace(L, BackedgeTakenCount, IndVar,
Andrew Trick25553ab2012-03-24 00:51:17 +00002485 Rewriter);
2486 }
Chris Lattnerc1a682d2004-04-22 14:59:40 +00002487 }
Andrew Trick87716c92011-03-17 23:51:11 +00002488 // Clear the rewriter cache, because values that are in the rewriter's cache
2489 // can be deleted in the loop below, causing the AssertingVH in the cache to
2490 // trigger.
2491 Rewriter.clear();
2492
2493 // Now that we're done iterating through lists, clean up any instructions
2494 // which are now dead.
Duncan P. N. Exon Smith817ac8f2015-06-24 22:23:21 +00002495 while (!DeadInsts.empty())
2496 if (Instruction *Inst =
2497 dyn_cast_or_null<Instruction>(DeadInsts.pop_back_val()))
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00002498 RecursivelyDeleteTriviallyDeadInstructions(Inst, TLI);
Andrew Trick87716c92011-03-17 23:51:11 +00002499
Dan Gohmandaafbe62009-06-26 22:53:46 +00002500 // The Rewriter may not be used from this point on.
Torok Edwin26895b52009-05-24 20:08:21 +00002501
Dan Gohmand76d71a2009-05-12 02:17:14 +00002502 // Loop-invariant instructions in the preheader that aren't used in the
2503 // loop may be sunk below the loop to reduce register pressure.
Sanjoy Dasb873cbe2015-10-13 07:17:38 +00002504 sinkUnusedInvariants(L);
Dan Gohmand76d71a2009-05-12 02:17:14 +00002505
Chen Li5cde8382016-01-27 07:40:41 +00002506 // rewriteFirstIterationLoopExitValues does not rely on the computation of
2507 // trip count and therefore can further simplify exit values in addition to
2508 // rewriteLoopExitValues.
2509 rewriteFirstIterationLoopExitValues(L);
2510
Dan Gohmand76d71a2009-05-12 02:17:14 +00002511 // Clean up dead instructions.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00002512 Changed |= DeleteDeadPHIs(L->getHeader(), TLI);
Sanjoy Das683bf072015-12-08 00:13:21 +00002513
Dan Gohmand76d71a2009-05-12 02:17:14 +00002514 // Check a post-condition.
Igor Laevsky04423cf2016-10-11 13:37:22 +00002515 assert(L->isRecursivelyLCSSAForm(*DT, *LI) &&
2516 "Indvars did not preserve LCSSA!");
Andrew Trick494c5492011-07-18 18:44:20 +00002517
2518 // Verify that LFTR, and any other change have not interfered with SCEV's
2519 // ability to compute trip count.
2520#ifndef NDEBUG
Andrew Trickf47d0af2012-03-22 17:10:11 +00002521 if (VerifyIndvars && !isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
Andrew Trick494c5492011-07-18 18:44:20 +00002522 SE->forgetLoop(L);
2523 const SCEV *NewBECount = SE->getBackedgeTakenCount(L);
2524 if (SE->getTypeSizeInBits(BackedgeTakenCount->getType()) <
2525 SE->getTypeSizeInBits(NewBECount->getType()))
2526 NewBECount = SE->getTruncateOrNoop(NewBECount,
2527 BackedgeTakenCount->getType());
2528 else
2529 BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount,
2530 NewBECount->getType());
2531 assert(BackedgeTakenCount == NewBECount && "indvars must preserve SCEV");
2532 }
2533#endif
2534
Devang Patel2ac57e12007-03-07 06:39:01 +00002535 return Changed;
Chris Lattner476e6df2001-12-03 17:28:42 +00002536}
Sanjoy Das496f2742016-05-29 21:42:00 +00002537
Chandler Carruth410eaeb2017-01-11 06:23:21 +00002538PreservedAnalyses IndVarSimplifyPass::run(Loop &L, LoopAnalysisManager &AM,
2539 LoopStandardAnalysisResults &AR,
2540 LPMUpdater &) {
Sanjoy Das4d4339d2016-06-05 18:01:19 +00002541 Function *F = L.getHeader()->getParent();
2542 const DataLayout &DL = F->getParent()->getDataLayout();
2543
Chandler Carruth410eaeb2017-01-11 06:23:21 +00002544 IndVarSimplify IVS(&AR.LI, &AR.SE, &AR.DT, DL, &AR.TLI, &AR.TTI);
Sanjoy Das4d4339d2016-06-05 18:01:19 +00002545 if (!IVS.run(&L))
2546 return PreservedAnalyses::all();
2547
Chandler Carruthca68a3e2017-01-15 06:32:49 +00002548 auto PA = getLoopPassPreservedAnalyses();
2549 PA.preserveSet<CFGAnalyses>();
2550 return PA;
Sanjoy Das4d4339d2016-06-05 18:01:19 +00002551}
2552
Sanjoy Das496f2742016-05-29 21:42:00 +00002553namespace {
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +00002554
Sanjoy Das496f2742016-05-29 21:42:00 +00002555struct IndVarSimplifyLegacyPass : public LoopPass {
2556 static char ID; // Pass identification, replacement for typeid
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +00002557
Sanjoy Das496f2742016-05-29 21:42:00 +00002558 IndVarSimplifyLegacyPass() : LoopPass(ID) {
2559 initializeIndVarSimplifyLegacyPassPass(*PassRegistry::getPassRegistry());
2560 }
2561
2562 bool runOnLoop(Loop *L, LPPassManager &LPM) override {
2563 if (skipLoop(L))
2564 return false;
2565
2566 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2567 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
2568 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2569 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
2570 auto *TLI = TLIP ? &TLIP->getTLI() : nullptr;
2571 auto *TTIP = getAnalysisIfAvailable<TargetTransformInfoWrapperPass>();
2572 auto *TTI = TTIP ? &TTIP->getTTI(*L->getHeader()->getParent()) : nullptr;
2573 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
2574
2575 IndVarSimplify IVS(LI, SE, DT, DL, TLI, TTI);
2576 return IVS.run(L);
2577 }
2578
2579 void getAnalysisUsage(AnalysisUsage &AU) const override {
2580 AU.setPreservesCFG();
2581 getLoopAnalysisUsage(AU);
2582 }
2583};
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +00002584
2585} // end anonymous namespace
Sanjoy Das496f2742016-05-29 21:42:00 +00002586
2587char IndVarSimplifyLegacyPass::ID = 0;
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +00002588
Sanjoy Das496f2742016-05-29 21:42:00 +00002589INITIALIZE_PASS_BEGIN(IndVarSimplifyLegacyPass, "indvars",
2590 "Induction Variable Simplification", false, false)
2591INITIALIZE_PASS_DEPENDENCY(LoopPass)
2592INITIALIZE_PASS_END(IndVarSimplifyLegacyPass, "indvars",
2593 "Induction Variable Simplification", false, false)
2594
2595Pass *llvm::createIndVarSimplifyPass() {
2596 return new IndVarSimplifyLegacyPass();
2597}