1*9880d681SAndroid Build Coastguard Worker //===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
2*9880d681SAndroid Build Coastguard Worker //
3*9880d681SAndroid Build Coastguard Worker // The LLVM Compiler Infrastructure
4*9880d681SAndroid Build Coastguard Worker //
5*9880d681SAndroid Build Coastguard Worker // This file is distributed under the University of Illinois Open Source
6*9880d681SAndroid Build Coastguard Worker // License. See LICENSE.TXT for details.
7*9880d681SAndroid Build Coastguard Worker //
8*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
9*9880d681SAndroid Build Coastguard Worker //
10*9880d681SAndroid Build Coastguard Worker // This transformation analyzes and transforms the induction variables (and
11*9880d681SAndroid Build Coastguard Worker // computations derived from them) into simpler forms suitable for subsequent
12*9880d681SAndroid Build Coastguard Worker // analysis and transformation.
13*9880d681SAndroid Build Coastguard Worker //
14*9880d681SAndroid Build Coastguard Worker // If the trip count of a loop is computable, this pass also makes the following
15*9880d681SAndroid Build Coastguard Worker // changes:
16*9880d681SAndroid Build Coastguard Worker // 1. The exit condition for the loop is canonicalized to compare the
17*9880d681SAndroid Build Coastguard Worker // induction value against the exit value. This turns loops like:
18*9880d681SAndroid Build Coastguard Worker // 'for (i = 7; i*i < 1000; ++i)' into 'for (i = 0; i != 25; ++i)'
19*9880d681SAndroid Build Coastguard Worker // 2. Any use outside of the loop of an expression derived from the indvar
20*9880d681SAndroid Build Coastguard Worker // is changed to compute the derived value outside of the loop, eliminating
21*9880d681SAndroid Build Coastguard Worker // the dependence on the exit value of the induction variable. If the only
22*9880d681SAndroid Build Coastguard Worker // purpose of the loop is to compute the exit value of some derived
23*9880d681SAndroid Build Coastguard Worker // expression, this transformation will make the loop dead.
24*9880d681SAndroid Build Coastguard Worker //
25*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
26*9880d681SAndroid Build Coastguard Worker
27*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Scalar/IndVarSimplify.h"
28*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Scalar.h"
29*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/SmallVector.h"
30*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/Statistic.h"
31*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/GlobalsModRef.h"
32*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/LoopInfo.h"
33*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/LoopPass.h"
34*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/LoopPassManager.h"
35*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/ScalarEvolutionExpander.h"
36*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
37*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/TargetLibraryInfo.h"
38*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/TargetTransformInfo.h"
39*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/BasicBlock.h"
40*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/CFG.h"
41*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Constants.h"
42*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/DataLayout.h"
43*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Dominators.h"
44*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Instructions.h"
45*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/IntrinsicInst.h"
46*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/LLVMContext.h"
47*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/PatternMatch.h"
48*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Type.h"
49*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/CommandLine.h"
50*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/Debug.h"
51*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/raw_ostream.h"
52*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Utils/BasicBlockUtils.h"
53*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Utils/Local.h"
54*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Utils/LoopUtils.h"
55*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Utils/SimplifyIndVar.h"
56*9880d681SAndroid Build Coastguard Worker using namespace llvm;
57*9880d681SAndroid Build Coastguard Worker
58*9880d681SAndroid Build Coastguard Worker #define DEBUG_TYPE "indvars"
59*9880d681SAndroid Build Coastguard Worker
60*9880d681SAndroid Build Coastguard Worker STATISTIC(NumWidened , "Number of indvars widened");
61*9880d681SAndroid Build Coastguard Worker STATISTIC(NumReplaced , "Number of exit values replaced");
62*9880d681SAndroid Build Coastguard Worker STATISTIC(NumLFTR , "Number of loop exit tests replaced");
63*9880d681SAndroid Build Coastguard Worker STATISTIC(NumElimExt , "Number of IV sign/zero extends eliminated");
64*9880d681SAndroid Build Coastguard Worker STATISTIC(NumElimIV , "Number of congruent IVs eliminated");
65*9880d681SAndroid Build Coastguard Worker
66*9880d681SAndroid Build Coastguard Worker // Trip count verification can be enabled by default under NDEBUG if we
67*9880d681SAndroid Build Coastguard Worker // implement a strong expression equivalence checker in SCEV. Until then, we
68*9880d681SAndroid Build Coastguard Worker // use the verify-indvars flag, which may assert in some cases.
69*9880d681SAndroid Build Coastguard Worker static cl::opt<bool> VerifyIndvars(
70*9880d681SAndroid Build Coastguard Worker "verify-indvars", cl::Hidden,
71*9880d681SAndroid Build Coastguard Worker cl::desc("Verify the ScalarEvolution result after running indvars"));
72*9880d681SAndroid Build Coastguard Worker
73*9880d681SAndroid Build Coastguard Worker enum ReplaceExitVal { NeverRepl, OnlyCheapRepl, AlwaysRepl };
74*9880d681SAndroid Build Coastguard Worker
75*9880d681SAndroid Build Coastguard Worker static cl::opt<ReplaceExitVal> ReplaceExitValue(
76*9880d681SAndroid Build Coastguard Worker "replexitval", cl::Hidden, cl::init(OnlyCheapRepl),
77*9880d681SAndroid Build Coastguard Worker cl::desc("Choose the strategy to replace exit value in IndVarSimplify"),
78*9880d681SAndroid Build Coastguard Worker cl::values(clEnumValN(NeverRepl, "never", "never replace exit value"),
79*9880d681SAndroid Build Coastguard Worker clEnumValN(OnlyCheapRepl, "cheap",
80*9880d681SAndroid Build Coastguard Worker "only replace exit value when the cost is cheap"),
81*9880d681SAndroid Build Coastguard Worker clEnumValN(AlwaysRepl, "always",
82*9880d681SAndroid Build Coastguard Worker "always replace exit value whenever possible"),
83*9880d681SAndroid Build Coastguard Worker clEnumValEnd));
84*9880d681SAndroid Build Coastguard Worker
85*9880d681SAndroid Build Coastguard Worker namespace {
86*9880d681SAndroid Build Coastguard Worker struct RewritePhi;
87*9880d681SAndroid Build Coastguard Worker
88*9880d681SAndroid Build Coastguard Worker class IndVarSimplify {
89*9880d681SAndroid Build Coastguard Worker LoopInfo *LI;
90*9880d681SAndroid Build Coastguard Worker ScalarEvolution *SE;
91*9880d681SAndroid Build Coastguard Worker DominatorTree *DT;
92*9880d681SAndroid Build Coastguard Worker const DataLayout &DL;
93*9880d681SAndroid Build Coastguard Worker TargetLibraryInfo *TLI;
94*9880d681SAndroid Build Coastguard Worker const TargetTransformInfo *TTI;
95*9880d681SAndroid Build Coastguard Worker
96*9880d681SAndroid Build Coastguard Worker SmallVector<WeakVH, 16> DeadInsts;
97*9880d681SAndroid Build Coastguard Worker bool Changed = false;
98*9880d681SAndroid Build Coastguard Worker
99*9880d681SAndroid Build Coastguard Worker bool isValidRewrite(Value *FromVal, Value *ToVal);
100*9880d681SAndroid Build Coastguard Worker
101*9880d681SAndroid Build Coastguard Worker void handleFloatingPointIV(Loop *L, PHINode *PH);
102*9880d681SAndroid Build Coastguard Worker void rewriteNonIntegerIVs(Loop *L);
103*9880d681SAndroid Build Coastguard Worker
104*9880d681SAndroid Build Coastguard Worker void simplifyAndExtend(Loop *L, SCEVExpander &Rewriter, LoopInfo *LI);
105*9880d681SAndroid Build Coastguard Worker
106*9880d681SAndroid Build Coastguard Worker bool canLoopBeDeleted(Loop *L, SmallVector<RewritePhi, 8> &RewritePhiSet);
107*9880d681SAndroid Build Coastguard Worker void rewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter);
108*9880d681SAndroid Build Coastguard Worker void rewriteFirstIterationLoopExitValues(Loop *L);
109*9880d681SAndroid Build Coastguard Worker
110*9880d681SAndroid Build Coastguard Worker Value *linearFunctionTestReplace(Loop *L, const SCEV *BackedgeTakenCount,
111*9880d681SAndroid Build Coastguard Worker PHINode *IndVar, SCEVExpander &Rewriter);
112*9880d681SAndroid Build Coastguard Worker
113*9880d681SAndroid Build Coastguard Worker void sinkUnusedInvariants(Loop *L);
114*9880d681SAndroid Build Coastguard Worker
115*9880d681SAndroid Build Coastguard Worker Value *expandSCEVIfNeeded(SCEVExpander &Rewriter, const SCEV *S, Loop *L,
116*9880d681SAndroid Build Coastguard Worker Instruction *InsertPt, Type *Ty);
117*9880d681SAndroid Build Coastguard Worker
118*9880d681SAndroid Build Coastguard Worker public:
IndVarSimplify(LoopInfo * LI,ScalarEvolution * SE,DominatorTree * DT,const DataLayout & DL,TargetLibraryInfo * TLI,TargetTransformInfo * TTI)119*9880d681SAndroid Build Coastguard Worker IndVarSimplify(LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT,
120*9880d681SAndroid Build Coastguard Worker const DataLayout &DL, TargetLibraryInfo *TLI,
121*9880d681SAndroid Build Coastguard Worker TargetTransformInfo *TTI)
122*9880d681SAndroid Build Coastguard Worker : LI(LI), SE(SE), DT(DT), DL(DL), TLI(TLI), TTI(TTI) {}
123*9880d681SAndroid Build Coastguard Worker
124*9880d681SAndroid Build Coastguard Worker bool run(Loop *L);
125*9880d681SAndroid Build Coastguard Worker };
126*9880d681SAndroid Build Coastguard Worker }
127*9880d681SAndroid Build Coastguard Worker
128*9880d681SAndroid Build Coastguard Worker /// Return true if the SCEV expansion generated by the rewriter can replace the
129*9880d681SAndroid Build Coastguard Worker /// original value. SCEV guarantees that it produces the same value, but the way
130*9880d681SAndroid Build Coastguard Worker /// it is produced may be illegal IR. Ideally, this function will only be
131*9880d681SAndroid Build Coastguard Worker /// called for verification.
isValidRewrite(Value * FromVal,Value * ToVal)132*9880d681SAndroid Build Coastguard Worker bool IndVarSimplify::isValidRewrite(Value *FromVal, Value *ToVal) {
133*9880d681SAndroid Build Coastguard Worker // If an SCEV expression subsumed multiple pointers, its expansion could
134*9880d681SAndroid Build Coastguard Worker // reassociate the GEP changing the base pointer. This is illegal because the
135*9880d681SAndroid Build Coastguard Worker // final address produced by a GEP chain must be inbounds relative to its
136*9880d681SAndroid Build Coastguard Worker // underlying object. Otherwise basic alias analysis, among other things,
137*9880d681SAndroid Build Coastguard Worker // could fail in a dangerous way. Ultimately, SCEV will be improved to avoid
138*9880d681SAndroid Build Coastguard Worker // producing an expression involving multiple pointers. Until then, we must
139*9880d681SAndroid Build Coastguard Worker // bail out here.
140*9880d681SAndroid Build Coastguard Worker //
141*9880d681SAndroid Build Coastguard Worker // Retrieve the pointer operand of the GEP. Don't use GetUnderlyingObject
142*9880d681SAndroid Build Coastguard Worker // because it understands lcssa phis while SCEV does not.
143*9880d681SAndroid Build Coastguard Worker Value *FromPtr = FromVal;
144*9880d681SAndroid Build Coastguard Worker Value *ToPtr = ToVal;
145*9880d681SAndroid Build Coastguard Worker if (auto *GEP = dyn_cast<GEPOperator>(FromVal)) {
146*9880d681SAndroid Build Coastguard Worker FromPtr = GEP->getPointerOperand();
147*9880d681SAndroid Build Coastguard Worker }
148*9880d681SAndroid Build Coastguard Worker if (auto *GEP = dyn_cast<GEPOperator>(ToVal)) {
149*9880d681SAndroid Build Coastguard Worker ToPtr = GEP->getPointerOperand();
150*9880d681SAndroid Build Coastguard Worker }
151*9880d681SAndroid Build Coastguard Worker if (FromPtr != FromVal || ToPtr != ToVal) {
152*9880d681SAndroid Build Coastguard Worker // Quickly check the common case
153*9880d681SAndroid Build Coastguard Worker if (FromPtr == ToPtr)
154*9880d681SAndroid Build Coastguard Worker return true;
155*9880d681SAndroid Build Coastguard Worker
156*9880d681SAndroid Build Coastguard Worker // SCEV may have rewritten an expression that produces the GEP's pointer
157*9880d681SAndroid Build Coastguard Worker // operand. That's ok as long as the pointer operand has the same base
158*9880d681SAndroid Build Coastguard Worker // pointer. Unlike GetUnderlyingObject(), getPointerBase() will find the
159*9880d681SAndroid Build Coastguard Worker // base of a recurrence. This handles the case in which SCEV expansion
160*9880d681SAndroid Build Coastguard Worker // converts a pointer type recurrence into a nonrecurrent pointer base
161*9880d681SAndroid Build Coastguard Worker // indexed by an integer recurrence.
162*9880d681SAndroid Build Coastguard Worker
163*9880d681SAndroid Build Coastguard Worker // If the GEP base pointer is a vector of pointers, abort.
164*9880d681SAndroid Build Coastguard Worker if (!FromPtr->getType()->isPointerTy() || !ToPtr->getType()->isPointerTy())
165*9880d681SAndroid Build Coastguard Worker return false;
166*9880d681SAndroid Build Coastguard Worker
167*9880d681SAndroid Build Coastguard Worker const SCEV *FromBase = SE->getPointerBase(SE->getSCEV(FromPtr));
168*9880d681SAndroid Build Coastguard Worker const SCEV *ToBase = SE->getPointerBase(SE->getSCEV(ToPtr));
169*9880d681SAndroid Build Coastguard Worker if (FromBase == ToBase)
170*9880d681SAndroid Build Coastguard Worker return true;
171*9880d681SAndroid Build Coastguard Worker
172*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "INDVARS: GEP rewrite bail out "
173*9880d681SAndroid Build Coastguard Worker << *FromBase << " != " << *ToBase << "\n");
174*9880d681SAndroid Build Coastguard Worker
175*9880d681SAndroid Build Coastguard Worker return false;
176*9880d681SAndroid Build Coastguard Worker }
177*9880d681SAndroid Build Coastguard Worker return true;
178*9880d681SAndroid Build Coastguard Worker }
179*9880d681SAndroid Build Coastguard Worker
180*9880d681SAndroid Build Coastguard Worker /// Determine the insertion point for this user. By default, insert immediately
181*9880d681SAndroid Build Coastguard Worker /// before the user. SCEVExpander or LICM will hoist loop invariants out of the
182*9880d681SAndroid Build Coastguard Worker /// loop. For PHI nodes, there may be multiple uses, so compute the nearest
183*9880d681SAndroid Build Coastguard Worker /// common dominator for the incoming blocks.
getInsertPointForUses(Instruction * User,Value * Def,DominatorTree * DT,LoopInfo * LI)184*9880d681SAndroid Build Coastguard Worker static Instruction *getInsertPointForUses(Instruction *User, Value *Def,
185*9880d681SAndroid Build Coastguard Worker DominatorTree *DT, LoopInfo *LI) {
186*9880d681SAndroid Build Coastguard Worker PHINode *PHI = dyn_cast<PHINode>(User);
187*9880d681SAndroid Build Coastguard Worker if (!PHI)
188*9880d681SAndroid Build Coastguard Worker return User;
189*9880d681SAndroid Build Coastguard Worker
190*9880d681SAndroid Build Coastguard Worker Instruction *InsertPt = nullptr;
191*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i) {
192*9880d681SAndroid Build Coastguard Worker if (PHI->getIncomingValue(i) != Def)
193*9880d681SAndroid Build Coastguard Worker continue;
194*9880d681SAndroid Build Coastguard Worker
195*9880d681SAndroid Build Coastguard Worker BasicBlock *InsertBB = PHI->getIncomingBlock(i);
196*9880d681SAndroid Build Coastguard Worker if (!InsertPt) {
197*9880d681SAndroid Build Coastguard Worker InsertPt = InsertBB->getTerminator();
198*9880d681SAndroid Build Coastguard Worker continue;
199*9880d681SAndroid Build Coastguard Worker }
200*9880d681SAndroid Build Coastguard Worker InsertBB = DT->findNearestCommonDominator(InsertPt->getParent(), InsertBB);
201*9880d681SAndroid Build Coastguard Worker InsertPt = InsertBB->getTerminator();
202*9880d681SAndroid Build Coastguard Worker }
203*9880d681SAndroid Build Coastguard Worker assert(InsertPt && "Missing phi operand");
204*9880d681SAndroid Build Coastguard Worker
205*9880d681SAndroid Build Coastguard Worker auto *DefI = dyn_cast<Instruction>(Def);
206*9880d681SAndroid Build Coastguard Worker if (!DefI)
207*9880d681SAndroid Build Coastguard Worker return InsertPt;
208*9880d681SAndroid Build Coastguard Worker
209*9880d681SAndroid Build Coastguard Worker assert(DT->dominates(DefI, InsertPt) && "def does not dominate all uses");
210*9880d681SAndroid Build Coastguard Worker
211*9880d681SAndroid Build Coastguard Worker auto *L = LI->getLoopFor(DefI->getParent());
212*9880d681SAndroid Build Coastguard Worker assert(!L || L->contains(LI->getLoopFor(InsertPt->getParent())));
213*9880d681SAndroid Build Coastguard Worker
214*9880d681SAndroid Build Coastguard Worker for (auto *DTN = (*DT)[InsertPt->getParent()]; DTN; DTN = DTN->getIDom())
215*9880d681SAndroid Build Coastguard Worker if (LI->getLoopFor(DTN->getBlock()) == L)
216*9880d681SAndroid Build Coastguard Worker return DTN->getBlock()->getTerminator();
217*9880d681SAndroid Build Coastguard Worker
218*9880d681SAndroid Build Coastguard Worker llvm_unreachable("DefI dominates InsertPt!");
219*9880d681SAndroid Build Coastguard Worker }
220*9880d681SAndroid Build Coastguard Worker
221*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
222*9880d681SAndroid Build Coastguard Worker // rewriteNonIntegerIVs and helpers. Prefer integer IVs.
223*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
224*9880d681SAndroid Build Coastguard Worker
225*9880d681SAndroid Build Coastguard Worker /// Convert APF to an integer, if possible.
ConvertToSInt(const APFloat & APF,int64_t & IntVal)226*9880d681SAndroid Build Coastguard Worker static bool ConvertToSInt(const APFloat &APF, int64_t &IntVal) {
227*9880d681SAndroid Build Coastguard Worker bool isExact = false;
228*9880d681SAndroid Build Coastguard Worker // See if we can convert this to an int64_t
229*9880d681SAndroid Build Coastguard Worker uint64_t UIntVal;
230*9880d681SAndroid Build Coastguard Worker if (APF.convertToInteger(&UIntVal, 64, true, APFloat::rmTowardZero,
231*9880d681SAndroid Build Coastguard Worker &isExact) != APFloat::opOK || !isExact)
232*9880d681SAndroid Build Coastguard Worker return false;
233*9880d681SAndroid Build Coastguard Worker IntVal = UIntVal;
234*9880d681SAndroid Build Coastguard Worker return true;
235*9880d681SAndroid Build Coastguard Worker }
236*9880d681SAndroid Build Coastguard Worker
237*9880d681SAndroid Build Coastguard Worker /// If the loop has floating induction variable then insert corresponding
238*9880d681SAndroid Build Coastguard Worker /// integer induction variable if possible.
239*9880d681SAndroid Build Coastguard Worker /// For example,
240*9880d681SAndroid Build Coastguard Worker /// for(double i = 0; i < 10000; ++i)
241*9880d681SAndroid Build Coastguard Worker /// bar(i)
242*9880d681SAndroid Build Coastguard Worker /// is converted into
243*9880d681SAndroid Build Coastguard Worker /// for(int i = 0; i < 10000; ++i)
244*9880d681SAndroid Build Coastguard Worker /// bar((double)i);
245*9880d681SAndroid Build Coastguard Worker ///
handleFloatingPointIV(Loop * L,PHINode * PN)246*9880d681SAndroid Build Coastguard Worker void IndVarSimplify::handleFloatingPointIV(Loop *L, PHINode *PN) {
247*9880d681SAndroid Build Coastguard Worker unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
248*9880d681SAndroid Build Coastguard Worker unsigned BackEdge = IncomingEdge^1;
249*9880d681SAndroid Build Coastguard Worker
250*9880d681SAndroid Build Coastguard Worker // Check incoming value.
251*9880d681SAndroid Build Coastguard Worker auto *InitValueVal = dyn_cast<ConstantFP>(PN->getIncomingValue(IncomingEdge));
252*9880d681SAndroid Build Coastguard Worker
253*9880d681SAndroid Build Coastguard Worker int64_t InitValue;
254*9880d681SAndroid Build Coastguard Worker if (!InitValueVal || !ConvertToSInt(InitValueVal->getValueAPF(), InitValue))
255*9880d681SAndroid Build Coastguard Worker return;
256*9880d681SAndroid Build Coastguard Worker
257*9880d681SAndroid Build Coastguard Worker // Check IV increment. Reject this PN if increment operation is not
258*9880d681SAndroid Build Coastguard Worker // an add or increment value can not be represented by an integer.
259*9880d681SAndroid Build Coastguard Worker auto *Incr = dyn_cast<BinaryOperator>(PN->getIncomingValue(BackEdge));
260*9880d681SAndroid Build Coastguard Worker if (Incr == nullptr || Incr->getOpcode() != Instruction::FAdd) return;
261*9880d681SAndroid Build Coastguard Worker
262*9880d681SAndroid Build Coastguard Worker // If this is not an add of the PHI with a constantfp, or if the constant fp
263*9880d681SAndroid Build Coastguard Worker // is not an integer, bail out.
264*9880d681SAndroid Build Coastguard Worker ConstantFP *IncValueVal = dyn_cast<ConstantFP>(Incr->getOperand(1));
265*9880d681SAndroid Build Coastguard Worker int64_t IncValue;
266*9880d681SAndroid Build Coastguard Worker if (IncValueVal == nullptr || Incr->getOperand(0) != PN ||
267*9880d681SAndroid Build Coastguard Worker !ConvertToSInt(IncValueVal->getValueAPF(), IncValue))
268*9880d681SAndroid Build Coastguard Worker return;
269*9880d681SAndroid Build Coastguard Worker
270*9880d681SAndroid Build Coastguard Worker // Check Incr uses. One user is PN and the other user is an exit condition
271*9880d681SAndroid Build Coastguard Worker // used by the conditional terminator.
272*9880d681SAndroid Build Coastguard Worker Value::user_iterator IncrUse = Incr->user_begin();
273*9880d681SAndroid Build Coastguard Worker Instruction *U1 = cast<Instruction>(*IncrUse++);
274*9880d681SAndroid Build Coastguard Worker if (IncrUse == Incr->user_end()) return;
275*9880d681SAndroid Build Coastguard Worker Instruction *U2 = cast<Instruction>(*IncrUse++);
276*9880d681SAndroid Build Coastguard Worker if (IncrUse != Incr->user_end()) return;
277*9880d681SAndroid Build Coastguard Worker
278*9880d681SAndroid Build Coastguard Worker // Find exit condition, which is an fcmp. If it doesn't exist, or if it isn't
279*9880d681SAndroid Build Coastguard Worker // only used by a branch, we can't transform it.
280*9880d681SAndroid Build Coastguard Worker FCmpInst *Compare = dyn_cast<FCmpInst>(U1);
281*9880d681SAndroid Build Coastguard Worker if (!Compare)
282*9880d681SAndroid Build Coastguard Worker Compare = dyn_cast<FCmpInst>(U2);
283*9880d681SAndroid Build Coastguard Worker if (!Compare || !Compare->hasOneUse() ||
284*9880d681SAndroid Build Coastguard Worker !isa<BranchInst>(Compare->user_back()))
285*9880d681SAndroid Build Coastguard Worker return;
286*9880d681SAndroid Build Coastguard Worker
287*9880d681SAndroid Build Coastguard Worker BranchInst *TheBr = cast<BranchInst>(Compare->user_back());
288*9880d681SAndroid Build Coastguard Worker
289*9880d681SAndroid Build Coastguard Worker // We need to verify that the branch actually controls the iteration count
290*9880d681SAndroid Build Coastguard Worker // of the loop. If not, the new IV can overflow and no one will notice.
291*9880d681SAndroid Build Coastguard Worker // The branch block must be in the loop and one of the successors must be out
292*9880d681SAndroid Build Coastguard Worker // of the loop.
293*9880d681SAndroid Build Coastguard Worker assert(TheBr->isConditional() && "Can't use fcmp if not conditional");
294*9880d681SAndroid Build Coastguard Worker if (!L->contains(TheBr->getParent()) ||
295*9880d681SAndroid Build Coastguard Worker (L->contains(TheBr->getSuccessor(0)) &&
296*9880d681SAndroid Build Coastguard Worker L->contains(TheBr->getSuccessor(1))))
297*9880d681SAndroid Build Coastguard Worker return;
298*9880d681SAndroid Build Coastguard Worker
299*9880d681SAndroid Build Coastguard Worker
300*9880d681SAndroid Build Coastguard Worker // If it isn't a comparison with an integer-as-fp (the exit value), we can't
301*9880d681SAndroid Build Coastguard Worker // transform it.
302*9880d681SAndroid Build Coastguard Worker ConstantFP *ExitValueVal = dyn_cast<ConstantFP>(Compare->getOperand(1));
303*9880d681SAndroid Build Coastguard Worker int64_t ExitValue;
304*9880d681SAndroid Build Coastguard Worker if (ExitValueVal == nullptr ||
305*9880d681SAndroid Build Coastguard Worker !ConvertToSInt(ExitValueVal->getValueAPF(), ExitValue))
306*9880d681SAndroid Build Coastguard Worker return;
307*9880d681SAndroid Build Coastguard Worker
308*9880d681SAndroid Build Coastguard Worker // Find new predicate for integer comparison.
309*9880d681SAndroid Build Coastguard Worker CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
310*9880d681SAndroid Build Coastguard Worker switch (Compare->getPredicate()) {
311*9880d681SAndroid Build Coastguard Worker default: return; // Unknown comparison.
312*9880d681SAndroid Build Coastguard Worker case CmpInst::FCMP_OEQ:
313*9880d681SAndroid Build Coastguard Worker case CmpInst::FCMP_UEQ: NewPred = CmpInst::ICMP_EQ; break;
314*9880d681SAndroid Build Coastguard Worker case CmpInst::FCMP_ONE:
315*9880d681SAndroid Build Coastguard Worker case CmpInst::FCMP_UNE: NewPred = CmpInst::ICMP_NE; break;
316*9880d681SAndroid Build Coastguard Worker case CmpInst::FCMP_OGT:
317*9880d681SAndroid Build Coastguard Worker case CmpInst::FCMP_UGT: NewPred = CmpInst::ICMP_SGT; break;
318*9880d681SAndroid Build Coastguard Worker case CmpInst::FCMP_OGE:
319*9880d681SAndroid Build Coastguard Worker case CmpInst::FCMP_UGE: NewPred = CmpInst::ICMP_SGE; break;
320*9880d681SAndroid Build Coastguard Worker case CmpInst::FCMP_OLT:
321*9880d681SAndroid Build Coastguard Worker case CmpInst::FCMP_ULT: NewPred = CmpInst::ICMP_SLT; break;
322*9880d681SAndroid Build Coastguard Worker case CmpInst::FCMP_OLE:
323*9880d681SAndroid Build Coastguard Worker case CmpInst::FCMP_ULE: NewPred = CmpInst::ICMP_SLE; break;
324*9880d681SAndroid Build Coastguard Worker }
325*9880d681SAndroid Build Coastguard Worker
326*9880d681SAndroid Build Coastguard Worker // We convert the floating point induction variable to a signed i32 value if
327*9880d681SAndroid Build Coastguard Worker // we can. This is only safe if the comparison will not overflow in a way
328*9880d681SAndroid Build Coastguard Worker // that won't be trapped by the integer equivalent operations. Check for this
329*9880d681SAndroid Build Coastguard Worker // now.
330*9880d681SAndroid Build Coastguard Worker // TODO: We could use i64 if it is native and the range requires it.
331*9880d681SAndroid Build Coastguard Worker
332*9880d681SAndroid Build Coastguard Worker // The start/stride/exit values must all fit in signed i32.
333*9880d681SAndroid Build Coastguard Worker if (!isInt<32>(InitValue) || !isInt<32>(IncValue) || !isInt<32>(ExitValue))
334*9880d681SAndroid Build Coastguard Worker return;
335*9880d681SAndroid Build Coastguard Worker
336*9880d681SAndroid Build Coastguard Worker // If not actually striding (add x, 0.0), avoid touching the code.
337*9880d681SAndroid Build Coastguard Worker if (IncValue == 0)
338*9880d681SAndroid Build Coastguard Worker return;
339*9880d681SAndroid Build Coastguard Worker
340*9880d681SAndroid Build Coastguard Worker // Positive and negative strides have different safety conditions.
341*9880d681SAndroid Build Coastguard Worker if (IncValue > 0) {
342*9880d681SAndroid Build Coastguard Worker // If we have a positive stride, we require the init to be less than the
343*9880d681SAndroid Build Coastguard Worker // exit value.
344*9880d681SAndroid Build Coastguard Worker if (InitValue >= ExitValue)
345*9880d681SAndroid Build Coastguard Worker return;
346*9880d681SAndroid Build Coastguard Worker
347*9880d681SAndroid Build Coastguard Worker uint32_t Range = uint32_t(ExitValue-InitValue);
348*9880d681SAndroid Build Coastguard Worker // Check for infinite loop, either:
349*9880d681SAndroid Build Coastguard Worker // while (i <= Exit) or until (i > Exit)
350*9880d681SAndroid Build Coastguard Worker if (NewPred == CmpInst::ICMP_SLE || NewPred == CmpInst::ICMP_SGT) {
351*9880d681SAndroid Build Coastguard Worker if (++Range == 0) return; // Range overflows.
352*9880d681SAndroid Build Coastguard Worker }
353*9880d681SAndroid Build Coastguard Worker
354*9880d681SAndroid Build Coastguard Worker unsigned Leftover = Range % uint32_t(IncValue);
355*9880d681SAndroid Build Coastguard Worker
356*9880d681SAndroid Build Coastguard Worker // If this is an equality comparison, we require that the strided value
357*9880d681SAndroid Build Coastguard Worker // exactly land on the exit value, otherwise the IV condition will wrap
358*9880d681SAndroid Build Coastguard Worker // around and do things the fp IV wouldn't.
359*9880d681SAndroid Build Coastguard Worker if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
360*9880d681SAndroid Build Coastguard Worker Leftover != 0)
361*9880d681SAndroid Build Coastguard Worker return;
362*9880d681SAndroid Build Coastguard Worker
363*9880d681SAndroid Build Coastguard Worker // If the stride would wrap around the i32 before exiting, we can't
364*9880d681SAndroid Build Coastguard Worker // transform the IV.
365*9880d681SAndroid Build Coastguard Worker if (Leftover != 0 && int32_t(ExitValue+IncValue) < ExitValue)
366*9880d681SAndroid Build Coastguard Worker return;
367*9880d681SAndroid Build Coastguard Worker
368*9880d681SAndroid Build Coastguard Worker } else {
369*9880d681SAndroid Build Coastguard Worker // If we have a negative stride, we require the init to be greater than the
370*9880d681SAndroid Build Coastguard Worker // exit value.
371*9880d681SAndroid Build Coastguard Worker if (InitValue <= ExitValue)
372*9880d681SAndroid Build Coastguard Worker return;
373*9880d681SAndroid Build Coastguard Worker
374*9880d681SAndroid Build Coastguard Worker uint32_t Range = uint32_t(InitValue-ExitValue);
375*9880d681SAndroid Build Coastguard Worker // Check for infinite loop, either:
376*9880d681SAndroid Build Coastguard Worker // while (i >= Exit) or until (i < Exit)
377*9880d681SAndroid Build Coastguard Worker if (NewPred == CmpInst::ICMP_SGE || NewPred == CmpInst::ICMP_SLT) {
378*9880d681SAndroid Build Coastguard Worker if (++Range == 0) return; // Range overflows.
379*9880d681SAndroid Build Coastguard Worker }
380*9880d681SAndroid Build Coastguard Worker
381*9880d681SAndroid Build Coastguard Worker unsigned Leftover = Range % uint32_t(-IncValue);
382*9880d681SAndroid Build Coastguard Worker
383*9880d681SAndroid Build Coastguard Worker // If this is an equality comparison, we require that the strided value
384*9880d681SAndroid Build Coastguard Worker // exactly land on the exit value, otherwise the IV condition will wrap
385*9880d681SAndroid Build Coastguard Worker // around and do things the fp IV wouldn't.
386*9880d681SAndroid Build Coastguard Worker if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
387*9880d681SAndroid Build Coastguard Worker Leftover != 0)
388*9880d681SAndroid Build Coastguard Worker return;
389*9880d681SAndroid Build Coastguard Worker
390*9880d681SAndroid Build Coastguard Worker // If the stride would wrap around the i32 before exiting, we can't
391*9880d681SAndroid Build Coastguard Worker // transform the IV.
392*9880d681SAndroid Build Coastguard Worker if (Leftover != 0 && int32_t(ExitValue+IncValue) > ExitValue)
393*9880d681SAndroid Build Coastguard Worker return;
394*9880d681SAndroid Build Coastguard Worker }
395*9880d681SAndroid Build Coastguard Worker
396*9880d681SAndroid Build Coastguard Worker IntegerType *Int32Ty = Type::getInt32Ty(PN->getContext());
397*9880d681SAndroid Build Coastguard Worker
398*9880d681SAndroid Build Coastguard Worker // Insert new integer induction variable.
399*9880d681SAndroid Build Coastguard Worker PHINode *NewPHI = PHINode::Create(Int32Ty, 2, PN->getName()+".int", PN);
400*9880d681SAndroid Build Coastguard Worker NewPHI->addIncoming(ConstantInt::get(Int32Ty, InitValue),
401*9880d681SAndroid Build Coastguard Worker PN->getIncomingBlock(IncomingEdge));
402*9880d681SAndroid Build Coastguard Worker
403*9880d681SAndroid Build Coastguard Worker Value *NewAdd =
404*9880d681SAndroid Build Coastguard Worker BinaryOperator::CreateAdd(NewPHI, ConstantInt::get(Int32Ty, IncValue),
405*9880d681SAndroid Build Coastguard Worker Incr->getName()+".int", Incr);
406*9880d681SAndroid Build Coastguard Worker NewPHI->addIncoming(NewAdd, PN->getIncomingBlock(BackEdge));
407*9880d681SAndroid Build Coastguard Worker
408*9880d681SAndroid Build Coastguard Worker ICmpInst *NewCompare = new ICmpInst(TheBr, NewPred, NewAdd,
409*9880d681SAndroid Build Coastguard Worker ConstantInt::get(Int32Ty, ExitValue),
410*9880d681SAndroid Build Coastguard Worker Compare->getName());
411*9880d681SAndroid Build Coastguard Worker
412*9880d681SAndroid Build Coastguard Worker // In the following deletions, PN may become dead and may be deleted.
413*9880d681SAndroid Build Coastguard Worker // Use a WeakVH to observe whether this happens.
414*9880d681SAndroid Build Coastguard Worker WeakVH WeakPH = PN;
415*9880d681SAndroid Build Coastguard Worker
416*9880d681SAndroid Build Coastguard Worker // Delete the old floating point exit comparison. The branch starts using the
417*9880d681SAndroid Build Coastguard Worker // new comparison.
418*9880d681SAndroid Build Coastguard Worker NewCompare->takeName(Compare);
419*9880d681SAndroid Build Coastguard Worker Compare->replaceAllUsesWith(NewCompare);
420*9880d681SAndroid Build Coastguard Worker RecursivelyDeleteTriviallyDeadInstructions(Compare, TLI);
421*9880d681SAndroid Build Coastguard Worker
422*9880d681SAndroid Build Coastguard Worker // Delete the old floating point increment.
423*9880d681SAndroid Build Coastguard Worker Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
424*9880d681SAndroid Build Coastguard Worker RecursivelyDeleteTriviallyDeadInstructions(Incr, TLI);
425*9880d681SAndroid Build Coastguard Worker
426*9880d681SAndroid Build Coastguard Worker // If the FP induction variable still has uses, this is because something else
427*9880d681SAndroid Build Coastguard Worker // in the loop uses its value. In order to canonicalize the induction
428*9880d681SAndroid Build Coastguard Worker // variable, we chose to eliminate the IV and rewrite it in terms of an
429*9880d681SAndroid Build Coastguard Worker // int->fp cast.
430*9880d681SAndroid Build Coastguard Worker //
431*9880d681SAndroid Build Coastguard Worker // We give preference to sitofp over uitofp because it is faster on most
432*9880d681SAndroid Build Coastguard Worker // platforms.
433*9880d681SAndroid Build Coastguard Worker if (WeakPH) {
434*9880d681SAndroid Build Coastguard Worker Value *Conv = new SIToFPInst(NewPHI, PN->getType(), "indvar.conv",
435*9880d681SAndroid Build Coastguard Worker &*PN->getParent()->getFirstInsertionPt());
436*9880d681SAndroid Build Coastguard Worker PN->replaceAllUsesWith(Conv);
437*9880d681SAndroid Build Coastguard Worker RecursivelyDeleteTriviallyDeadInstructions(PN, TLI);
438*9880d681SAndroid Build Coastguard Worker }
439*9880d681SAndroid Build Coastguard Worker Changed = true;
440*9880d681SAndroid Build Coastguard Worker }
441*9880d681SAndroid Build Coastguard Worker
rewriteNonIntegerIVs(Loop * L)442*9880d681SAndroid Build Coastguard Worker void IndVarSimplify::rewriteNonIntegerIVs(Loop *L) {
443*9880d681SAndroid Build Coastguard Worker // First step. Check to see if there are any floating-point recurrences.
444*9880d681SAndroid Build Coastguard Worker // If there are, change them into integer recurrences, permitting analysis by
445*9880d681SAndroid Build Coastguard Worker // the SCEV routines.
446*9880d681SAndroid Build Coastguard Worker //
447*9880d681SAndroid Build Coastguard Worker BasicBlock *Header = L->getHeader();
448*9880d681SAndroid Build Coastguard Worker
449*9880d681SAndroid Build Coastguard Worker SmallVector<WeakVH, 8> PHIs;
450*9880d681SAndroid Build Coastguard Worker for (BasicBlock::iterator I = Header->begin();
451*9880d681SAndroid Build Coastguard Worker PHINode *PN = dyn_cast<PHINode>(I); ++I)
452*9880d681SAndroid Build Coastguard Worker PHIs.push_back(PN);
453*9880d681SAndroid Build Coastguard Worker
454*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
455*9880d681SAndroid Build Coastguard Worker if (PHINode *PN = dyn_cast_or_null<PHINode>(&*PHIs[i]))
456*9880d681SAndroid Build Coastguard Worker handleFloatingPointIV(L, PN);
457*9880d681SAndroid Build Coastguard Worker
458*9880d681SAndroid Build Coastguard Worker // If the loop previously had floating-point IV, ScalarEvolution
459*9880d681SAndroid Build Coastguard Worker // may not have been able to compute a trip count. Now that we've done some
460*9880d681SAndroid Build Coastguard Worker // re-writing, the trip count may be computable.
461*9880d681SAndroid Build Coastguard Worker if (Changed)
462*9880d681SAndroid Build Coastguard Worker SE->forgetLoop(L);
463*9880d681SAndroid Build Coastguard Worker }
464*9880d681SAndroid Build Coastguard Worker
465*9880d681SAndroid Build Coastguard Worker namespace {
466*9880d681SAndroid Build Coastguard Worker // Collect information about PHI nodes which can be transformed in
467*9880d681SAndroid Build Coastguard Worker // rewriteLoopExitValues.
468*9880d681SAndroid Build Coastguard Worker struct RewritePhi {
469*9880d681SAndroid Build Coastguard Worker PHINode *PN;
470*9880d681SAndroid Build Coastguard Worker unsigned Ith; // Ith incoming value.
471*9880d681SAndroid Build Coastguard Worker Value *Val; // Exit value after expansion.
472*9880d681SAndroid Build Coastguard Worker bool HighCost; // High Cost when expansion.
473*9880d681SAndroid Build Coastguard Worker
RewritePhi__anoncba0d73c0211::RewritePhi474*9880d681SAndroid Build Coastguard Worker RewritePhi(PHINode *P, unsigned I, Value *V, bool H)
475*9880d681SAndroid Build Coastguard Worker : PN(P), Ith(I), Val(V), HighCost(H) {}
476*9880d681SAndroid Build Coastguard Worker };
477*9880d681SAndroid Build Coastguard Worker }
478*9880d681SAndroid Build Coastguard Worker
expandSCEVIfNeeded(SCEVExpander & Rewriter,const SCEV * S,Loop * L,Instruction * InsertPt,Type * ResultTy)479*9880d681SAndroid Build Coastguard Worker Value *IndVarSimplify::expandSCEVIfNeeded(SCEVExpander &Rewriter, const SCEV *S,
480*9880d681SAndroid Build Coastguard Worker Loop *L, Instruction *InsertPt,
481*9880d681SAndroid Build Coastguard Worker Type *ResultTy) {
482*9880d681SAndroid Build Coastguard Worker // Before expanding S into an expensive LLVM expression, see if we can use an
483*9880d681SAndroid Build Coastguard Worker // already existing value as the expansion for S.
484*9880d681SAndroid Build Coastguard Worker if (Value *ExistingValue = Rewriter.findExistingExpansion(S, InsertPt, L))
485*9880d681SAndroid Build Coastguard Worker if (ExistingValue->getType() == ResultTy)
486*9880d681SAndroid Build Coastguard Worker return ExistingValue;
487*9880d681SAndroid Build Coastguard Worker
488*9880d681SAndroid Build Coastguard Worker // We didn't find anything, fall back to using SCEVExpander.
489*9880d681SAndroid Build Coastguard Worker return Rewriter.expandCodeFor(S, ResultTy, InsertPt);
490*9880d681SAndroid Build Coastguard Worker }
491*9880d681SAndroid Build Coastguard Worker
492*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
493*9880d681SAndroid Build Coastguard Worker // rewriteLoopExitValues - Optimize IV users outside the loop.
494*9880d681SAndroid Build Coastguard Worker // As a side effect, reduces the amount of IV processing within the loop.
495*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
496*9880d681SAndroid Build Coastguard Worker
497*9880d681SAndroid Build Coastguard Worker /// Check to see if this loop has a computable loop-invariant execution count.
498*9880d681SAndroid Build Coastguard Worker /// If so, this means that we can compute the final value of any expressions
499*9880d681SAndroid Build Coastguard Worker /// that are recurrent in the loop, and substitute the exit values from the loop
500*9880d681SAndroid Build Coastguard Worker /// into any instructions outside of the loop that use the final values of the
501*9880d681SAndroid Build Coastguard Worker /// current expressions.
502*9880d681SAndroid Build Coastguard Worker ///
503*9880d681SAndroid Build Coastguard Worker /// This is mostly redundant with the regular IndVarSimplify activities that
504*9880d681SAndroid Build Coastguard Worker /// happen later, except that it's more powerful in some cases, because it's
505*9880d681SAndroid Build Coastguard Worker /// able to brute-force evaluate arbitrary instructions as long as they have
506*9880d681SAndroid Build Coastguard Worker /// constant operands at the beginning of the loop.
rewriteLoopExitValues(Loop * L,SCEVExpander & Rewriter)507*9880d681SAndroid Build Coastguard Worker void IndVarSimplify::rewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter) {
508*9880d681SAndroid Build Coastguard Worker // Check a pre-condition.
509*9880d681SAndroid Build Coastguard Worker assert(L->isRecursivelyLCSSAForm(*DT) && "Indvars did not preserve LCSSA!");
510*9880d681SAndroid Build Coastguard Worker
511*9880d681SAndroid Build Coastguard Worker SmallVector<BasicBlock*, 8> ExitBlocks;
512*9880d681SAndroid Build Coastguard Worker L->getUniqueExitBlocks(ExitBlocks);
513*9880d681SAndroid Build Coastguard Worker
514*9880d681SAndroid Build Coastguard Worker SmallVector<RewritePhi, 8> RewritePhiSet;
515*9880d681SAndroid Build Coastguard Worker // Find all values that are computed inside the loop, but used outside of it.
516*9880d681SAndroid Build Coastguard Worker // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
517*9880d681SAndroid Build Coastguard Worker // the exit blocks of the loop to find them.
518*9880d681SAndroid Build Coastguard Worker for (BasicBlock *ExitBB : ExitBlocks) {
519*9880d681SAndroid Build Coastguard Worker // If there are no PHI nodes in this exit block, then no values defined
520*9880d681SAndroid Build Coastguard Worker // inside the loop are used on this path, skip it.
521*9880d681SAndroid Build Coastguard Worker PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
522*9880d681SAndroid Build Coastguard Worker if (!PN) continue;
523*9880d681SAndroid Build Coastguard Worker
524*9880d681SAndroid Build Coastguard Worker unsigned NumPreds = PN->getNumIncomingValues();
525*9880d681SAndroid Build Coastguard Worker
526*9880d681SAndroid Build Coastguard Worker // Iterate over all of the PHI nodes.
527*9880d681SAndroid Build Coastguard Worker BasicBlock::iterator BBI = ExitBB->begin();
528*9880d681SAndroid Build Coastguard Worker while ((PN = dyn_cast<PHINode>(BBI++))) {
529*9880d681SAndroid Build Coastguard Worker if (PN->use_empty())
530*9880d681SAndroid Build Coastguard Worker continue; // dead use, don't replace it
531*9880d681SAndroid Build Coastguard Worker
532*9880d681SAndroid Build Coastguard Worker if (!SE->isSCEVable(PN->getType()))
533*9880d681SAndroid Build Coastguard Worker continue;
534*9880d681SAndroid Build Coastguard Worker
535*9880d681SAndroid Build Coastguard Worker // It's necessary to tell ScalarEvolution about this explicitly so that
536*9880d681SAndroid Build Coastguard Worker // it can walk the def-use list and forget all SCEVs, as it may not be
537*9880d681SAndroid Build Coastguard Worker // watching the PHI itself. Once the new exit value is in place, there
538*9880d681SAndroid Build Coastguard Worker // may not be a def-use connection between the loop and every instruction
539*9880d681SAndroid Build Coastguard Worker // which got a SCEVAddRecExpr for that loop.
540*9880d681SAndroid Build Coastguard Worker SE->forgetValue(PN);
541*9880d681SAndroid Build Coastguard Worker
542*9880d681SAndroid Build Coastguard Worker // Iterate over all of the values in all the PHI nodes.
543*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0; i != NumPreds; ++i) {
544*9880d681SAndroid Build Coastguard Worker // If the value being merged in is not integer or is not defined
545*9880d681SAndroid Build Coastguard Worker // in the loop, skip it.
546*9880d681SAndroid Build Coastguard Worker Value *InVal = PN->getIncomingValue(i);
547*9880d681SAndroid Build Coastguard Worker if (!isa<Instruction>(InVal))
548*9880d681SAndroid Build Coastguard Worker continue;
549*9880d681SAndroid Build Coastguard Worker
550*9880d681SAndroid Build Coastguard Worker // If this pred is for a subloop, not L itself, skip it.
551*9880d681SAndroid Build Coastguard Worker if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
552*9880d681SAndroid Build Coastguard Worker continue; // The Block is in a subloop, skip it.
553*9880d681SAndroid Build Coastguard Worker
554*9880d681SAndroid Build Coastguard Worker // Check that InVal is defined in the loop.
555*9880d681SAndroid Build Coastguard Worker Instruction *Inst = cast<Instruction>(InVal);
556*9880d681SAndroid Build Coastguard Worker if (!L->contains(Inst))
557*9880d681SAndroid Build Coastguard Worker continue;
558*9880d681SAndroid Build Coastguard Worker
559*9880d681SAndroid Build Coastguard Worker // Okay, this instruction has a user outside of the current loop
560*9880d681SAndroid Build Coastguard Worker // and varies predictably *inside* the loop. Evaluate the value it
561*9880d681SAndroid Build Coastguard Worker // contains when the loop exits, if possible.
562*9880d681SAndroid Build Coastguard Worker const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
563*9880d681SAndroid Build Coastguard Worker if (!SE->isLoopInvariant(ExitValue, L) ||
564*9880d681SAndroid Build Coastguard Worker !isSafeToExpand(ExitValue, *SE))
565*9880d681SAndroid Build Coastguard Worker continue;
566*9880d681SAndroid Build Coastguard Worker
567*9880d681SAndroid Build Coastguard Worker // Computing the value outside of the loop brings no benefit if :
568*9880d681SAndroid Build Coastguard Worker // - it is definitely used inside the loop in a way which can not be
569*9880d681SAndroid Build Coastguard Worker // optimized away.
570*9880d681SAndroid Build Coastguard Worker // - no use outside of the loop can take advantage of hoisting the
571*9880d681SAndroid Build Coastguard Worker // computation out of the loop
572*9880d681SAndroid Build Coastguard Worker if (ExitValue->getSCEVType()>=scMulExpr) {
573*9880d681SAndroid Build Coastguard Worker unsigned NumHardInternalUses = 0;
574*9880d681SAndroid Build Coastguard Worker unsigned NumSoftExternalUses = 0;
575*9880d681SAndroid Build Coastguard Worker unsigned NumUses = 0;
576*9880d681SAndroid Build Coastguard Worker for (auto IB = Inst->user_begin(), IE = Inst->user_end();
577*9880d681SAndroid Build Coastguard Worker IB != IE && NumUses <= 6; ++IB) {
578*9880d681SAndroid Build Coastguard Worker Instruction *UseInstr = cast<Instruction>(*IB);
579*9880d681SAndroid Build Coastguard Worker unsigned Opc = UseInstr->getOpcode();
580*9880d681SAndroid Build Coastguard Worker NumUses++;
581*9880d681SAndroid Build Coastguard Worker if (L->contains(UseInstr)) {
582*9880d681SAndroid Build Coastguard Worker if (Opc == Instruction::Call || Opc == Instruction::Ret)
583*9880d681SAndroid Build Coastguard Worker NumHardInternalUses++;
584*9880d681SAndroid Build Coastguard Worker } else {
585*9880d681SAndroid Build Coastguard Worker if (Opc == Instruction::PHI) {
586*9880d681SAndroid Build Coastguard Worker // Do not count the Phi as a use. LCSSA may have inserted
587*9880d681SAndroid Build Coastguard Worker // plenty of trivial ones.
588*9880d681SAndroid Build Coastguard Worker NumUses--;
589*9880d681SAndroid Build Coastguard Worker for (auto PB = UseInstr->user_begin(),
590*9880d681SAndroid Build Coastguard Worker PE = UseInstr->user_end();
591*9880d681SAndroid Build Coastguard Worker PB != PE && NumUses <= 6; ++PB, ++NumUses) {
592*9880d681SAndroid Build Coastguard Worker unsigned PhiOpc = cast<Instruction>(*PB)->getOpcode();
593*9880d681SAndroid Build Coastguard Worker if (PhiOpc != Instruction::Call && PhiOpc != Instruction::Ret)
594*9880d681SAndroid Build Coastguard Worker NumSoftExternalUses++;
595*9880d681SAndroid Build Coastguard Worker }
596*9880d681SAndroid Build Coastguard Worker continue;
597*9880d681SAndroid Build Coastguard Worker }
598*9880d681SAndroid Build Coastguard Worker if (Opc != Instruction::Call && Opc != Instruction::Ret)
599*9880d681SAndroid Build Coastguard Worker NumSoftExternalUses++;
600*9880d681SAndroid Build Coastguard Worker }
601*9880d681SAndroid Build Coastguard Worker }
602*9880d681SAndroid Build Coastguard Worker if (NumUses <= 6 && NumHardInternalUses && !NumSoftExternalUses)
603*9880d681SAndroid Build Coastguard Worker continue;
604*9880d681SAndroid Build Coastguard Worker }
605*9880d681SAndroid Build Coastguard Worker
606*9880d681SAndroid Build Coastguard Worker bool HighCost = Rewriter.isHighCostExpansion(ExitValue, L, Inst);
607*9880d681SAndroid Build Coastguard Worker Value *ExitVal =
608*9880d681SAndroid Build Coastguard Worker expandSCEVIfNeeded(Rewriter, ExitValue, L, Inst, PN->getType());
609*9880d681SAndroid Build Coastguard Worker
610*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal << '\n'
611*9880d681SAndroid Build Coastguard Worker << " LoopVal = " << *Inst << "\n");
612*9880d681SAndroid Build Coastguard Worker
613*9880d681SAndroid Build Coastguard Worker if (!isValidRewrite(Inst, ExitVal)) {
614*9880d681SAndroid Build Coastguard Worker DeadInsts.push_back(ExitVal);
615*9880d681SAndroid Build Coastguard Worker continue;
616*9880d681SAndroid Build Coastguard Worker }
617*9880d681SAndroid Build Coastguard Worker
618*9880d681SAndroid Build Coastguard Worker // Collect all the candidate PHINodes to be rewritten.
619*9880d681SAndroid Build Coastguard Worker RewritePhiSet.emplace_back(PN, i, ExitVal, HighCost);
620*9880d681SAndroid Build Coastguard Worker }
621*9880d681SAndroid Build Coastguard Worker }
622*9880d681SAndroid Build Coastguard Worker }
623*9880d681SAndroid Build Coastguard Worker
624*9880d681SAndroid Build Coastguard Worker bool LoopCanBeDel = canLoopBeDeleted(L, RewritePhiSet);
625*9880d681SAndroid Build Coastguard Worker
626*9880d681SAndroid Build Coastguard Worker // Transformation.
627*9880d681SAndroid Build Coastguard Worker for (const RewritePhi &Phi : RewritePhiSet) {
628*9880d681SAndroid Build Coastguard Worker PHINode *PN = Phi.PN;
629*9880d681SAndroid Build Coastguard Worker Value *ExitVal = Phi.Val;
630*9880d681SAndroid Build Coastguard Worker
631*9880d681SAndroid Build Coastguard Worker // Only do the rewrite when the ExitValue can be expanded cheaply.
632*9880d681SAndroid Build Coastguard Worker // If LoopCanBeDel is true, rewrite exit value aggressively.
633*9880d681SAndroid Build Coastguard Worker if (ReplaceExitValue == OnlyCheapRepl && !LoopCanBeDel && Phi.HighCost) {
634*9880d681SAndroid Build Coastguard Worker DeadInsts.push_back(ExitVal);
635*9880d681SAndroid Build Coastguard Worker continue;
636*9880d681SAndroid Build Coastguard Worker }
637*9880d681SAndroid Build Coastguard Worker
638*9880d681SAndroid Build Coastguard Worker Changed = true;
639*9880d681SAndroid Build Coastguard Worker ++NumReplaced;
640*9880d681SAndroid Build Coastguard Worker Instruction *Inst = cast<Instruction>(PN->getIncomingValue(Phi.Ith));
641*9880d681SAndroid Build Coastguard Worker PN->setIncomingValue(Phi.Ith, ExitVal);
642*9880d681SAndroid Build Coastguard Worker
643*9880d681SAndroid Build Coastguard Worker // If this instruction is dead now, delete it. Don't do it now to avoid
644*9880d681SAndroid Build Coastguard Worker // invalidating iterators.
645*9880d681SAndroid Build Coastguard Worker if (isInstructionTriviallyDead(Inst, TLI))
646*9880d681SAndroid Build Coastguard Worker DeadInsts.push_back(Inst);
647*9880d681SAndroid Build Coastguard Worker
648*9880d681SAndroid Build Coastguard Worker // Replace PN with ExitVal if that is legal and does not break LCSSA.
649*9880d681SAndroid Build Coastguard Worker if (PN->getNumIncomingValues() == 1 &&
650*9880d681SAndroid Build Coastguard Worker LI->replacementPreservesLCSSAForm(PN, ExitVal)) {
651*9880d681SAndroid Build Coastguard Worker PN->replaceAllUsesWith(ExitVal);
652*9880d681SAndroid Build Coastguard Worker PN->eraseFromParent();
653*9880d681SAndroid Build Coastguard Worker }
654*9880d681SAndroid Build Coastguard Worker }
655*9880d681SAndroid Build Coastguard Worker
656*9880d681SAndroid Build Coastguard Worker // The insertion point instruction may have been deleted; clear it out
657*9880d681SAndroid Build Coastguard Worker // so that the rewriter doesn't trip over it later.
658*9880d681SAndroid Build Coastguard Worker Rewriter.clearInsertPoint();
659*9880d681SAndroid Build Coastguard Worker }
660*9880d681SAndroid Build Coastguard Worker
661*9880d681SAndroid Build Coastguard Worker //===---------------------------------------------------------------------===//
662*9880d681SAndroid Build Coastguard Worker // rewriteFirstIterationLoopExitValues: Rewrite loop exit values if we know
663*9880d681SAndroid Build Coastguard Worker // they will exit at the first iteration.
664*9880d681SAndroid Build Coastguard Worker //===---------------------------------------------------------------------===//
665*9880d681SAndroid Build Coastguard Worker
666*9880d681SAndroid Build Coastguard Worker /// Check to see if this loop has loop invariant conditions which lead to loop
667*9880d681SAndroid Build Coastguard Worker /// exits. If so, we know that if the exit path is taken, it is at the first
668*9880d681SAndroid Build Coastguard Worker /// loop iteration. This lets us predict exit values of PHI nodes that live in
669*9880d681SAndroid Build Coastguard Worker /// loop header.
rewriteFirstIterationLoopExitValues(Loop * L)670*9880d681SAndroid Build Coastguard Worker void IndVarSimplify::rewriteFirstIterationLoopExitValues(Loop *L) {
671*9880d681SAndroid Build Coastguard Worker // Verify the input to the pass is already in LCSSA form.
672*9880d681SAndroid Build Coastguard Worker assert(L->isLCSSAForm(*DT));
673*9880d681SAndroid Build Coastguard Worker
674*9880d681SAndroid Build Coastguard Worker SmallVector<BasicBlock *, 8> ExitBlocks;
675*9880d681SAndroid Build Coastguard Worker L->getUniqueExitBlocks(ExitBlocks);
676*9880d681SAndroid Build Coastguard Worker auto *LoopHeader = L->getHeader();
677*9880d681SAndroid Build Coastguard Worker assert(LoopHeader && "Invalid loop");
678*9880d681SAndroid Build Coastguard Worker
679*9880d681SAndroid Build Coastguard Worker for (auto *ExitBB : ExitBlocks) {
680*9880d681SAndroid Build Coastguard Worker BasicBlock::iterator BBI = ExitBB->begin();
681*9880d681SAndroid Build Coastguard Worker // If there are no more PHI nodes in this exit block, then no more
682*9880d681SAndroid Build Coastguard Worker // values defined inside the loop are used on this path.
683*9880d681SAndroid Build Coastguard Worker while (auto *PN = dyn_cast<PHINode>(BBI++)) {
684*9880d681SAndroid Build Coastguard Worker for (unsigned IncomingValIdx = 0, E = PN->getNumIncomingValues();
685*9880d681SAndroid Build Coastguard Worker IncomingValIdx != E; ++IncomingValIdx) {
686*9880d681SAndroid Build Coastguard Worker auto *IncomingBB = PN->getIncomingBlock(IncomingValIdx);
687*9880d681SAndroid Build Coastguard Worker
688*9880d681SAndroid Build Coastguard Worker // We currently only support loop exits from loop header. If the
689*9880d681SAndroid Build Coastguard Worker // incoming block is not loop header, we need to recursively check
690*9880d681SAndroid Build Coastguard Worker // all conditions starting from loop header are loop invariants.
691*9880d681SAndroid Build Coastguard Worker // Additional support might be added in the future.
692*9880d681SAndroid Build Coastguard Worker if (IncomingBB != LoopHeader)
693*9880d681SAndroid Build Coastguard Worker continue;
694*9880d681SAndroid Build Coastguard Worker
695*9880d681SAndroid Build Coastguard Worker // Get condition that leads to the exit path.
696*9880d681SAndroid Build Coastguard Worker auto *TermInst = IncomingBB->getTerminator();
697*9880d681SAndroid Build Coastguard Worker
698*9880d681SAndroid Build Coastguard Worker Value *Cond = nullptr;
699*9880d681SAndroid Build Coastguard Worker if (auto *BI = dyn_cast<BranchInst>(TermInst)) {
700*9880d681SAndroid Build Coastguard Worker // Must be a conditional branch, otherwise the block
701*9880d681SAndroid Build Coastguard Worker // should not be in the loop.
702*9880d681SAndroid Build Coastguard Worker Cond = BI->getCondition();
703*9880d681SAndroid Build Coastguard Worker } else if (auto *SI = dyn_cast<SwitchInst>(TermInst))
704*9880d681SAndroid Build Coastguard Worker Cond = SI->getCondition();
705*9880d681SAndroid Build Coastguard Worker else
706*9880d681SAndroid Build Coastguard Worker continue;
707*9880d681SAndroid Build Coastguard Worker
708*9880d681SAndroid Build Coastguard Worker if (!L->isLoopInvariant(Cond))
709*9880d681SAndroid Build Coastguard Worker continue;
710*9880d681SAndroid Build Coastguard Worker
711*9880d681SAndroid Build Coastguard Worker auto *ExitVal =
712*9880d681SAndroid Build Coastguard Worker dyn_cast<PHINode>(PN->getIncomingValue(IncomingValIdx));
713*9880d681SAndroid Build Coastguard Worker
714*9880d681SAndroid Build Coastguard Worker // Only deal with PHIs.
715*9880d681SAndroid Build Coastguard Worker if (!ExitVal)
716*9880d681SAndroid Build Coastguard Worker continue;
717*9880d681SAndroid Build Coastguard Worker
718*9880d681SAndroid Build Coastguard Worker // If ExitVal is a PHI on the loop header, then we know its
719*9880d681SAndroid Build Coastguard Worker // value along this exit because the exit can only be taken
720*9880d681SAndroid Build Coastguard Worker // on the first iteration.
721*9880d681SAndroid Build Coastguard Worker auto *LoopPreheader = L->getLoopPreheader();
722*9880d681SAndroid Build Coastguard Worker assert(LoopPreheader && "Invalid loop");
723*9880d681SAndroid Build Coastguard Worker int PreheaderIdx = ExitVal->getBasicBlockIndex(LoopPreheader);
724*9880d681SAndroid Build Coastguard Worker if (PreheaderIdx != -1) {
725*9880d681SAndroid Build Coastguard Worker assert(ExitVal->getParent() == LoopHeader &&
726*9880d681SAndroid Build Coastguard Worker "ExitVal must be in loop header");
727*9880d681SAndroid Build Coastguard Worker PN->setIncomingValue(IncomingValIdx,
728*9880d681SAndroid Build Coastguard Worker ExitVal->getIncomingValue(PreheaderIdx));
729*9880d681SAndroid Build Coastguard Worker }
730*9880d681SAndroid Build Coastguard Worker }
731*9880d681SAndroid Build Coastguard Worker }
732*9880d681SAndroid Build Coastguard Worker }
733*9880d681SAndroid Build Coastguard Worker }
734*9880d681SAndroid Build Coastguard Worker
735*9880d681SAndroid Build Coastguard Worker /// Check whether it is possible to delete the loop after rewriting exit
736*9880d681SAndroid Build Coastguard Worker /// value. If it is possible, ignore ReplaceExitValue and do rewriting
737*9880d681SAndroid Build Coastguard Worker /// aggressively.
canLoopBeDeleted(Loop * L,SmallVector<RewritePhi,8> & RewritePhiSet)738*9880d681SAndroid Build Coastguard Worker bool IndVarSimplify::canLoopBeDeleted(
739*9880d681SAndroid Build Coastguard Worker Loop *L, SmallVector<RewritePhi, 8> &RewritePhiSet) {
740*9880d681SAndroid Build Coastguard Worker
741*9880d681SAndroid Build Coastguard Worker BasicBlock *Preheader = L->getLoopPreheader();
742*9880d681SAndroid Build Coastguard Worker // If there is no preheader, the loop will not be deleted.
743*9880d681SAndroid Build Coastguard Worker if (!Preheader)
744*9880d681SAndroid Build Coastguard Worker return false;
745*9880d681SAndroid Build Coastguard Worker
746*9880d681SAndroid Build Coastguard Worker // In LoopDeletion pass Loop can be deleted when ExitingBlocks.size() > 1.
747*9880d681SAndroid Build Coastguard Worker // We obviate multiple ExitingBlocks case for simplicity.
748*9880d681SAndroid Build Coastguard Worker // TODO: If we see testcase with multiple ExitingBlocks can be deleted
749*9880d681SAndroid Build Coastguard Worker // after exit value rewriting, we can enhance the logic here.
750*9880d681SAndroid Build Coastguard Worker SmallVector<BasicBlock *, 4> ExitingBlocks;
751*9880d681SAndroid Build Coastguard Worker L->getExitingBlocks(ExitingBlocks);
752*9880d681SAndroid Build Coastguard Worker SmallVector<BasicBlock *, 8> ExitBlocks;
753*9880d681SAndroid Build Coastguard Worker L->getUniqueExitBlocks(ExitBlocks);
754*9880d681SAndroid Build Coastguard Worker if (ExitBlocks.size() > 1 || ExitingBlocks.size() > 1)
755*9880d681SAndroid Build Coastguard Worker return false;
756*9880d681SAndroid Build Coastguard Worker
757*9880d681SAndroid Build Coastguard Worker BasicBlock *ExitBlock = ExitBlocks[0];
758*9880d681SAndroid Build Coastguard Worker BasicBlock::iterator BI = ExitBlock->begin();
759*9880d681SAndroid Build Coastguard Worker while (PHINode *P = dyn_cast<PHINode>(BI)) {
760*9880d681SAndroid Build Coastguard Worker Value *Incoming = P->getIncomingValueForBlock(ExitingBlocks[0]);
761*9880d681SAndroid Build Coastguard Worker
762*9880d681SAndroid Build Coastguard Worker // If the Incoming value of P is found in RewritePhiSet, we know it
763*9880d681SAndroid Build Coastguard Worker // could be rewritten to use a loop invariant value in transformation
764*9880d681SAndroid Build Coastguard Worker // phase later. Skip it in the loop invariant check below.
765*9880d681SAndroid Build Coastguard Worker bool found = false;
766*9880d681SAndroid Build Coastguard Worker for (const RewritePhi &Phi : RewritePhiSet) {
767*9880d681SAndroid Build Coastguard Worker unsigned i = Phi.Ith;
768*9880d681SAndroid Build Coastguard Worker if (Phi.PN == P && (Phi.PN)->getIncomingValue(i) == Incoming) {
769*9880d681SAndroid Build Coastguard Worker found = true;
770*9880d681SAndroid Build Coastguard Worker break;
771*9880d681SAndroid Build Coastguard Worker }
772*9880d681SAndroid Build Coastguard Worker }
773*9880d681SAndroid Build Coastguard Worker
774*9880d681SAndroid Build Coastguard Worker Instruction *I;
775*9880d681SAndroid Build Coastguard Worker if (!found && (I = dyn_cast<Instruction>(Incoming)))
776*9880d681SAndroid Build Coastguard Worker if (!L->hasLoopInvariantOperands(I))
777*9880d681SAndroid Build Coastguard Worker return false;
778*9880d681SAndroid Build Coastguard Worker
779*9880d681SAndroid Build Coastguard Worker ++BI;
780*9880d681SAndroid Build Coastguard Worker }
781*9880d681SAndroid Build Coastguard Worker
782*9880d681SAndroid Build Coastguard Worker for (auto *BB : L->blocks())
783*9880d681SAndroid Build Coastguard Worker if (any_of(*BB, [](Instruction &I) { return I.mayHaveSideEffects(); }))
784*9880d681SAndroid Build Coastguard Worker return false;
785*9880d681SAndroid Build Coastguard Worker
786*9880d681SAndroid Build Coastguard Worker return true;
787*9880d681SAndroid Build Coastguard Worker }
788*9880d681SAndroid Build Coastguard Worker
789*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
790*9880d681SAndroid Build Coastguard Worker // IV Widening - Extend the width of an IV to cover its widest uses.
791*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
792*9880d681SAndroid Build Coastguard Worker
793*9880d681SAndroid Build Coastguard Worker namespace {
794*9880d681SAndroid Build Coastguard Worker // Collect information about induction variables that are used by sign/zero
795*9880d681SAndroid Build Coastguard Worker // extend operations. This information is recorded by CollectExtend and provides
796*9880d681SAndroid Build Coastguard Worker // the input to WidenIV.
797*9880d681SAndroid Build Coastguard Worker struct WideIVInfo {
798*9880d681SAndroid Build Coastguard Worker PHINode *NarrowIV = nullptr;
799*9880d681SAndroid Build Coastguard Worker Type *WidestNativeType = nullptr; // Widest integer type created [sz]ext
800*9880d681SAndroid Build Coastguard Worker bool IsSigned = false; // Was a sext user seen before a zext?
801*9880d681SAndroid Build Coastguard Worker };
802*9880d681SAndroid Build Coastguard Worker }
803*9880d681SAndroid Build Coastguard Worker
804*9880d681SAndroid Build Coastguard Worker /// Update information about the induction variable that is extended by this
805*9880d681SAndroid Build Coastguard Worker /// sign or zero extend operation. This is used to determine the final width of
806*9880d681SAndroid Build Coastguard Worker /// the IV before actually widening it.
visitIVCast(CastInst * Cast,WideIVInfo & WI,ScalarEvolution * SE,const TargetTransformInfo * TTI)807*9880d681SAndroid Build Coastguard Worker static void visitIVCast(CastInst *Cast, WideIVInfo &WI, ScalarEvolution *SE,
808*9880d681SAndroid Build Coastguard Worker const TargetTransformInfo *TTI) {
809*9880d681SAndroid Build Coastguard Worker bool IsSigned = Cast->getOpcode() == Instruction::SExt;
810*9880d681SAndroid Build Coastguard Worker if (!IsSigned && Cast->getOpcode() != Instruction::ZExt)
811*9880d681SAndroid Build Coastguard Worker return;
812*9880d681SAndroid Build Coastguard Worker
813*9880d681SAndroid Build Coastguard Worker Type *Ty = Cast->getType();
814*9880d681SAndroid Build Coastguard Worker uint64_t Width = SE->getTypeSizeInBits(Ty);
815*9880d681SAndroid Build Coastguard Worker if (!Cast->getModule()->getDataLayout().isLegalInteger(Width))
816*9880d681SAndroid Build Coastguard Worker return;
817*9880d681SAndroid Build Coastguard Worker
818*9880d681SAndroid Build Coastguard Worker // Cast is either an sext or zext up to this point.
819*9880d681SAndroid Build Coastguard Worker // We should not widen an indvar if arithmetics on the wider indvar are more
820*9880d681SAndroid Build Coastguard Worker // expensive than those on the narrower indvar. We check only the cost of ADD
821*9880d681SAndroid Build Coastguard Worker // because at least an ADD is required to increment the induction variable. We
822*9880d681SAndroid Build Coastguard Worker // could compute more comprehensively the cost of all instructions on the
823*9880d681SAndroid Build Coastguard Worker // induction variable when necessary.
824*9880d681SAndroid Build Coastguard Worker if (TTI &&
825*9880d681SAndroid Build Coastguard Worker TTI->getArithmeticInstrCost(Instruction::Add, Ty) >
826*9880d681SAndroid Build Coastguard Worker TTI->getArithmeticInstrCost(Instruction::Add,
827*9880d681SAndroid Build Coastguard Worker Cast->getOperand(0)->getType())) {
828*9880d681SAndroid Build Coastguard Worker return;
829*9880d681SAndroid Build Coastguard Worker }
830*9880d681SAndroid Build Coastguard Worker
831*9880d681SAndroid Build Coastguard Worker if (!WI.WidestNativeType) {
832*9880d681SAndroid Build Coastguard Worker WI.WidestNativeType = SE->getEffectiveSCEVType(Ty);
833*9880d681SAndroid Build Coastguard Worker WI.IsSigned = IsSigned;
834*9880d681SAndroid Build Coastguard Worker return;
835*9880d681SAndroid Build Coastguard Worker }
836*9880d681SAndroid Build Coastguard Worker
837*9880d681SAndroid Build Coastguard Worker // We extend the IV to satisfy the sign of its first user, arbitrarily.
838*9880d681SAndroid Build Coastguard Worker if (WI.IsSigned != IsSigned)
839*9880d681SAndroid Build Coastguard Worker return;
840*9880d681SAndroid Build Coastguard Worker
841*9880d681SAndroid Build Coastguard Worker if (Width > SE->getTypeSizeInBits(WI.WidestNativeType))
842*9880d681SAndroid Build Coastguard Worker WI.WidestNativeType = SE->getEffectiveSCEVType(Ty);
843*9880d681SAndroid Build Coastguard Worker }
844*9880d681SAndroid Build Coastguard Worker
845*9880d681SAndroid Build Coastguard Worker namespace {
846*9880d681SAndroid Build Coastguard Worker
847*9880d681SAndroid Build Coastguard Worker /// Record a link in the Narrow IV def-use chain along with the WideIV that
848*9880d681SAndroid Build Coastguard Worker /// computes the same value as the Narrow IV def. This avoids caching Use*
849*9880d681SAndroid Build Coastguard Worker /// pointers.
850*9880d681SAndroid Build Coastguard Worker struct NarrowIVDefUse {
851*9880d681SAndroid Build Coastguard Worker Instruction *NarrowDef = nullptr;
852*9880d681SAndroid Build Coastguard Worker Instruction *NarrowUse = nullptr;
853*9880d681SAndroid Build Coastguard Worker Instruction *WideDef = nullptr;
854*9880d681SAndroid Build Coastguard Worker
855*9880d681SAndroid Build Coastguard Worker // True if the narrow def is never negative. Tracking this information lets
856*9880d681SAndroid Build Coastguard Worker // us use a sign extension instead of a zero extension or vice versa, when
857*9880d681SAndroid Build Coastguard Worker // profitable and legal.
858*9880d681SAndroid Build Coastguard Worker bool NeverNegative = false;
859*9880d681SAndroid Build Coastguard Worker
NarrowIVDefUse__anoncba0d73c0511::NarrowIVDefUse860*9880d681SAndroid Build Coastguard Worker NarrowIVDefUse(Instruction *ND, Instruction *NU, Instruction *WD,
861*9880d681SAndroid Build Coastguard Worker bool NeverNegative)
862*9880d681SAndroid Build Coastguard Worker : NarrowDef(ND), NarrowUse(NU), WideDef(WD),
863*9880d681SAndroid Build Coastguard Worker NeverNegative(NeverNegative) {}
864*9880d681SAndroid Build Coastguard Worker };
865*9880d681SAndroid Build Coastguard Worker
866*9880d681SAndroid Build Coastguard Worker /// The goal of this transform is to remove sign and zero extends without
867*9880d681SAndroid Build Coastguard Worker /// creating any new induction variables. To do this, it creates a new phi of
868*9880d681SAndroid Build Coastguard Worker /// the wider type and redirects all users, either removing extends or inserting
869*9880d681SAndroid Build Coastguard Worker /// truncs whenever we stop propagating the type.
870*9880d681SAndroid Build Coastguard Worker ///
871*9880d681SAndroid Build Coastguard Worker class WidenIV {
872*9880d681SAndroid Build Coastguard Worker // Parameters
873*9880d681SAndroid Build Coastguard Worker PHINode *OrigPhi;
874*9880d681SAndroid Build Coastguard Worker Type *WideType;
875*9880d681SAndroid Build Coastguard Worker bool IsSigned;
876*9880d681SAndroid Build Coastguard Worker
877*9880d681SAndroid Build Coastguard Worker // Context
878*9880d681SAndroid Build Coastguard Worker LoopInfo *LI;
879*9880d681SAndroid Build Coastguard Worker Loop *L;
880*9880d681SAndroid Build Coastguard Worker ScalarEvolution *SE;
881*9880d681SAndroid Build Coastguard Worker DominatorTree *DT;
882*9880d681SAndroid Build Coastguard Worker
883*9880d681SAndroid Build Coastguard Worker // Result
884*9880d681SAndroid Build Coastguard Worker PHINode *WidePhi;
885*9880d681SAndroid Build Coastguard Worker Instruction *WideInc;
886*9880d681SAndroid Build Coastguard Worker const SCEV *WideIncExpr;
887*9880d681SAndroid Build Coastguard Worker SmallVectorImpl<WeakVH> &DeadInsts;
888*9880d681SAndroid Build Coastguard Worker
889*9880d681SAndroid Build Coastguard Worker SmallPtrSet<Instruction*,16> Widened;
890*9880d681SAndroid Build Coastguard Worker SmallVector<NarrowIVDefUse, 8> NarrowIVUsers;
891*9880d681SAndroid Build Coastguard Worker
892*9880d681SAndroid Build Coastguard Worker public:
WidenIV(const WideIVInfo & WI,LoopInfo * LInfo,ScalarEvolution * SEv,DominatorTree * DTree,SmallVectorImpl<WeakVH> & DI)893*9880d681SAndroid Build Coastguard Worker WidenIV(const WideIVInfo &WI, LoopInfo *LInfo,
894*9880d681SAndroid Build Coastguard Worker ScalarEvolution *SEv, DominatorTree *DTree,
895*9880d681SAndroid Build Coastguard Worker SmallVectorImpl<WeakVH> &DI) :
896*9880d681SAndroid Build Coastguard Worker OrigPhi(WI.NarrowIV),
897*9880d681SAndroid Build Coastguard Worker WideType(WI.WidestNativeType),
898*9880d681SAndroid Build Coastguard Worker IsSigned(WI.IsSigned),
899*9880d681SAndroid Build Coastguard Worker LI(LInfo),
900*9880d681SAndroid Build Coastguard Worker L(LI->getLoopFor(OrigPhi->getParent())),
901*9880d681SAndroid Build Coastguard Worker SE(SEv),
902*9880d681SAndroid Build Coastguard Worker DT(DTree),
903*9880d681SAndroid Build Coastguard Worker WidePhi(nullptr),
904*9880d681SAndroid Build Coastguard Worker WideInc(nullptr),
905*9880d681SAndroid Build Coastguard Worker WideIncExpr(nullptr),
906*9880d681SAndroid Build Coastguard Worker DeadInsts(DI) {
907*9880d681SAndroid Build Coastguard Worker assert(L->getHeader() == OrigPhi->getParent() && "Phi must be an IV");
908*9880d681SAndroid Build Coastguard Worker }
909*9880d681SAndroid Build Coastguard Worker
910*9880d681SAndroid Build Coastguard Worker PHINode *createWideIV(SCEVExpander &Rewriter);
911*9880d681SAndroid Build Coastguard Worker
912*9880d681SAndroid Build Coastguard Worker protected:
913*9880d681SAndroid Build Coastguard Worker Value *createExtendInst(Value *NarrowOper, Type *WideType, bool IsSigned,
914*9880d681SAndroid Build Coastguard Worker Instruction *Use);
915*9880d681SAndroid Build Coastguard Worker
916*9880d681SAndroid Build Coastguard Worker Instruction *cloneIVUser(NarrowIVDefUse DU, const SCEVAddRecExpr *WideAR);
917*9880d681SAndroid Build Coastguard Worker Instruction *cloneArithmeticIVUser(NarrowIVDefUse DU,
918*9880d681SAndroid Build Coastguard Worker const SCEVAddRecExpr *WideAR);
919*9880d681SAndroid Build Coastguard Worker Instruction *cloneBitwiseIVUser(NarrowIVDefUse DU);
920*9880d681SAndroid Build Coastguard Worker
921*9880d681SAndroid Build Coastguard Worker const SCEVAddRecExpr *getWideRecurrence(Instruction *NarrowUse);
922*9880d681SAndroid Build Coastguard Worker
923*9880d681SAndroid Build Coastguard Worker const SCEVAddRecExpr* getExtendedOperandRecurrence(NarrowIVDefUse DU);
924*9880d681SAndroid Build Coastguard Worker
925*9880d681SAndroid Build Coastguard Worker const SCEV *getSCEVByOpCode(const SCEV *LHS, const SCEV *RHS,
926*9880d681SAndroid Build Coastguard Worker unsigned OpCode) const;
927*9880d681SAndroid Build Coastguard Worker
928*9880d681SAndroid Build Coastguard Worker Instruction *widenIVUse(NarrowIVDefUse DU, SCEVExpander &Rewriter);
929*9880d681SAndroid Build Coastguard Worker
930*9880d681SAndroid Build Coastguard Worker bool widenLoopCompare(NarrowIVDefUse DU);
931*9880d681SAndroid Build Coastguard Worker
932*9880d681SAndroid Build Coastguard Worker void pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef);
933*9880d681SAndroid Build Coastguard Worker };
934*9880d681SAndroid Build Coastguard Worker } // anonymous namespace
935*9880d681SAndroid Build Coastguard Worker
936*9880d681SAndroid Build Coastguard Worker /// Perform a quick domtree based check for loop invariance assuming that V is
937*9880d681SAndroid Build Coastguard Worker /// used within the loop. LoopInfo::isLoopInvariant() seems gratuitous for this
938*9880d681SAndroid Build Coastguard Worker /// purpose.
isLoopInvariant(Value * V,const Loop * L,const DominatorTree * DT)939*9880d681SAndroid Build Coastguard Worker static bool isLoopInvariant(Value *V, const Loop *L, const DominatorTree *DT) {
940*9880d681SAndroid Build Coastguard Worker Instruction *Inst = dyn_cast<Instruction>(V);
941*9880d681SAndroid Build Coastguard Worker if (!Inst)
942*9880d681SAndroid Build Coastguard Worker return true;
943*9880d681SAndroid Build Coastguard Worker
944*9880d681SAndroid Build Coastguard Worker return DT->properlyDominates(Inst->getParent(), L->getHeader());
945*9880d681SAndroid Build Coastguard Worker }
946*9880d681SAndroid Build Coastguard Worker
createExtendInst(Value * NarrowOper,Type * WideType,bool IsSigned,Instruction * Use)947*9880d681SAndroid Build Coastguard Worker Value *WidenIV::createExtendInst(Value *NarrowOper, Type *WideType,
948*9880d681SAndroid Build Coastguard Worker bool IsSigned, Instruction *Use) {
949*9880d681SAndroid Build Coastguard Worker // Set the debug location and conservative insertion point.
950*9880d681SAndroid Build Coastguard Worker IRBuilder<> Builder(Use);
951*9880d681SAndroid Build Coastguard Worker // Hoist the insertion point into loop preheaders as far as possible.
952*9880d681SAndroid Build Coastguard Worker for (const Loop *L = LI->getLoopFor(Use->getParent());
953*9880d681SAndroid Build Coastguard Worker L && L->getLoopPreheader() && isLoopInvariant(NarrowOper, L, DT);
954*9880d681SAndroid Build Coastguard Worker L = L->getParentLoop())
955*9880d681SAndroid Build Coastguard Worker Builder.SetInsertPoint(L->getLoopPreheader()->getTerminator());
956*9880d681SAndroid Build Coastguard Worker
957*9880d681SAndroid Build Coastguard Worker return IsSigned ? Builder.CreateSExt(NarrowOper, WideType) :
958*9880d681SAndroid Build Coastguard Worker Builder.CreateZExt(NarrowOper, WideType);
959*9880d681SAndroid Build Coastguard Worker }
960*9880d681SAndroid Build Coastguard Worker
961*9880d681SAndroid Build Coastguard Worker /// Instantiate a wide operation to replace a narrow operation. This only needs
962*9880d681SAndroid Build Coastguard Worker /// to handle operations that can evaluation to SCEVAddRec. It can safely return
963*9880d681SAndroid Build Coastguard Worker /// 0 for any operation we decide not to clone.
cloneIVUser(NarrowIVDefUse DU,const SCEVAddRecExpr * WideAR)964*9880d681SAndroid Build Coastguard Worker Instruction *WidenIV::cloneIVUser(NarrowIVDefUse DU,
965*9880d681SAndroid Build Coastguard Worker const SCEVAddRecExpr *WideAR) {
966*9880d681SAndroid Build Coastguard Worker unsigned Opcode = DU.NarrowUse->getOpcode();
967*9880d681SAndroid Build Coastguard Worker switch (Opcode) {
968*9880d681SAndroid Build Coastguard Worker default:
969*9880d681SAndroid Build Coastguard Worker return nullptr;
970*9880d681SAndroid Build Coastguard Worker case Instruction::Add:
971*9880d681SAndroid Build Coastguard Worker case Instruction::Mul:
972*9880d681SAndroid Build Coastguard Worker case Instruction::UDiv:
973*9880d681SAndroid Build Coastguard Worker case Instruction::Sub:
974*9880d681SAndroid Build Coastguard Worker return cloneArithmeticIVUser(DU, WideAR);
975*9880d681SAndroid Build Coastguard Worker
976*9880d681SAndroid Build Coastguard Worker case Instruction::And:
977*9880d681SAndroid Build Coastguard Worker case Instruction::Or:
978*9880d681SAndroid Build Coastguard Worker case Instruction::Xor:
979*9880d681SAndroid Build Coastguard Worker case Instruction::Shl:
980*9880d681SAndroid Build Coastguard Worker case Instruction::LShr:
981*9880d681SAndroid Build Coastguard Worker case Instruction::AShr:
982*9880d681SAndroid Build Coastguard Worker return cloneBitwiseIVUser(DU);
983*9880d681SAndroid Build Coastguard Worker }
984*9880d681SAndroid Build Coastguard Worker }
985*9880d681SAndroid Build Coastguard Worker
cloneBitwiseIVUser(NarrowIVDefUse DU)986*9880d681SAndroid Build Coastguard Worker Instruction *WidenIV::cloneBitwiseIVUser(NarrowIVDefUse DU) {
987*9880d681SAndroid Build Coastguard Worker Instruction *NarrowUse = DU.NarrowUse;
988*9880d681SAndroid Build Coastguard Worker Instruction *NarrowDef = DU.NarrowDef;
989*9880d681SAndroid Build Coastguard Worker Instruction *WideDef = DU.WideDef;
990*9880d681SAndroid Build Coastguard Worker
991*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "Cloning bitwise IVUser: " << *NarrowUse << "\n");
992*9880d681SAndroid Build Coastguard Worker
993*9880d681SAndroid Build Coastguard Worker // Replace NarrowDef operands with WideDef. Otherwise, we don't know anything
994*9880d681SAndroid Build Coastguard Worker // about the narrow operand yet so must insert a [sz]ext. It is probably loop
995*9880d681SAndroid Build Coastguard Worker // invariant and will be folded or hoisted. If it actually comes from a
996*9880d681SAndroid Build Coastguard Worker // widened IV, it should be removed during a future call to widenIVUse.
997*9880d681SAndroid Build Coastguard Worker Value *LHS = (NarrowUse->getOperand(0) == NarrowDef)
998*9880d681SAndroid Build Coastguard Worker ? WideDef
999*9880d681SAndroid Build Coastguard Worker : createExtendInst(NarrowUse->getOperand(0), WideType,
1000*9880d681SAndroid Build Coastguard Worker IsSigned, NarrowUse);
1001*9880d681SAndroid Build Coastguard Worker Value *RHS = (NarrowUse->getOperand(1) == NarrowDef)
1002*9880d681SAndroid Build Coastguard Worker ? WideDef
1003*9880d681SAndroid Build Coastguard Worker : createExtendInst(NarrowUse->getOperand(1), WideType,
1004*9880d681SAndroid Build Coastguard Worker IsSigned, NarrowUse);
1005*9880d681SAndroid Build Coastguard Worker
1006*9880d681SAndroid Build Coastguard Worker auto *NarrowBO = cast<BinaryOperator>(NarrowUse);
1007*9880d681SAndroid Build Coastguard Worker auto *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(), LHS, RHS,
1008*9880d681SAndroid Build Coastguard Worker NarrowBO->getName());
1009*9880d681SAndroid Build Coastguard Worker IRBuilder<> Builder(NarrowUse);
1010*9880d681SAndroid Build Coastguard Worker Builder.Insert(WideBO);
1011*9880d681SAndroid Build Coastguard Worker WideBO->copyIRFlags(NarrowBO);
1012*9880d681SAndroid Build Coastguard Worker return WideBO;
1013*9880d681SAndroid Build Coastguard Worker }
1014*9880d681SAndroid Build Coastguard Worker
cloneArithmeticIVUser(NarrowIVDefUse DU,const SCEVAddRecExpr * WideAR)1015*9880d681SAndroid Build Coastguard Worker Instruction *WidenIV::cloneArithmeticIVUser(NarrowIVDefUse DU,
1016*9880d681SAndroid Build Coastguard Worker const SCEVAddRecExpr *WideAR) {
1017*9880d681SAndroid Build Coastguard Worker Instruction *NarrowUse = DU.NarrowUse;
1018*9880d681SAndroid Build Coastguard Worker Instruction *NarrowDef = DU.NarrowDef;
1019*9880d681SAndroid Build Coastguard Worker Instruction *WideDef = DU.WideDef;
1020*9880d681SAndroid Build Coastguard Worker
1021*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "Cloning arithmetic IVUser: " << *NarrowUse << "\n");
1022*9880d681SAndroid Build Coastguard Worker
1023*9880d681SAndroid Build Coastguard Worker unsigned IVOpIdx = (NarrowUse->getOperand(0) == NarrowDef) ? 0 : 1;
1024*9880d681SAndroid Build Coastguard Worker
1025*9880d681SAndroid Build Coastguard Worker // We're trying to find X such that
1026*9880d681SAndroid Build Coastguard Worker //
1027*9880d681SAndroid Build Coastguard Worker // Widen(NarrowDef `op` NonIVNarrowDef) == WideAR == WideDef `op.wide` X
1028*9880d681SAndroid Build Coastguard Worker //
1029*9880d681SAndroid Build Coastguard Worker // We guess two solutions to X, sext(NonIVNarrowDef) and zext(NonIVNarrowDef),
1030*9880d681SAndroid Build Coastguard Worker // and check using SCEV if any of them are correct.
1031*9880d681SAndroid Build Coastguard Worker
1032*9880d681SAndroid Build Coastguard Worker // Returns true if extending NonIVNarrowDef according to `SignExt` is a
1033*9880d681SAndroid Build Coastguard Worker // correct solution to X.
1034*9880d681SAndroid Build Coastguard Worker auto GuessNonIVOperand = [&](bool SignExt) {
1035*9880d681SAndroid Build Coastguard Worker const SCEV *WideLHS;
1036*9880d681SAndroid Build Coastguard Worker const SCEV *WideRHS;
1037*9880d681SAndroid Build Coastguard Worker
1038*9880d681SAndroid Build Coastguard Worker auto GetExtend = [this, SignExt](const SCEV *S, Type *Ty) {
1039*9880d681SAndroid Build Coastguard Worker if (SignExt)
1040*9880d681SAndroid Build Coastguard Worker return SE->getSignExtendExpr(S, Ty);
1041*9880d681SAndroid Build Coastguard Worker return SE->getZeroExtendExpr(S, Ty);
1042*9880d681SAndroid Build Coastguard Worker };
1043*9880d681SAndroid Build Coastguard Worker
1044*9880d681SAndroid Build Coastguard Worker if (IVOpIdx == 0) {
1045*9880d681SAndroid Build Coastguard Worker WideLHS = SE->getSCEV(WideDef);
1046*9880d681SAndroid Build Coastguard Worker const SCEV *NarrowRHS = SE->getSCEV(NarrowUse->getOperand(1));
1047*9880d681SAndroid Build Coastguard Worker WideRHS = GetExtend(NarrowRHS, WideType);
1048*9880d681SAndroid Build Coastguard Worker } else {
1049*9880d681SAndroid Build Coastguard Worker const SCEV *NarrowLHS = SE->getSCEV(NarrowUse->getOperand(0));
1050*9880d681SAndroid Build Coastguard Worker WideLHS = GetExtend(NarrowLHS, WideType);
1051*9880d681SAndroid Build Coastguard Worker WideRHS = SE->getSCEV(WideDef);
1052*9880d681SAndroid Build Coastguard Worker }
1053*9880d681SAndroid Build Coastguard Worker
1054*9880d681SAndroid Build Coastguard Worker // WideUse is "WideDef `op.wide` X" as described in the comment.
1055*9880d681SAndroid Build Coastguard Worker const SCEV *WideUse = nullptr;
1056*9880d681SAndroid Build Coastguard Worker
1057*9880d681SAndroid Build Coastguard Worker switch (NarrowUse->getOpcode()) {
1058*9880d681SAndroid Build Coastguard Worker default:
1059*9880d681SAndroid Build Coastguard Worker llvm_unreachable("No other possibility!");
1060*9880d681SAndroid Build Coastguard Worker
1061*9880d681SAndroid Build Coastguard Worker case Instruction::Add:
1062*9880d681SAndroid Build Coastguard Worker WideUse = SE->getAddExpr(WideLHS, WideRHS);
1063*9880d681SAndroid Build Coastguard Worker break;
1064*9880d681SAndroid Build Coastguard Worker
1065*9880d681SAndroid Build Coastguard Worker case Instruction::Mul:
1066*9880d681SAndroid Build Coastguard Worker WideUse = SE->getMulExpr(WideLHS, WideRHS);
1067*9880d681SAndroid Build Coastguard Worker break;
1068*9880d681SAndroid Build Coastguard Worker
1069*9880d681SAndroid Build Coastguard Worker case Instruction::UDiv:
1070*9880d681SAndroid Build Coastguard Worker WideUse = SE->getUDivExpr(WideLHS, WideRHS);
1071*9880d681SAndroid Build Coastguard Worker break;
1072*9880d681SAndroid Build Coastguard Worker
1073*9880d681SAndroid Build Coastguard Worker case Instruction::Sub:
1074*9880d681SAndroid Build Coastguard Worker WideUse = SE->getMinusSCEV(WideLHS, WideRHS);
1075*9880d681SAndroid Build Coastguard Worker break;
1076*9880d681SAndroid Build Coastguard Worker }
1077*9880d681SAndroid Build Coastguard Worker
1078*9880d681SAndroid Build Coastguard Worker return WideUse == WideAR;
1079*9880d681SAndroid Build Coastguard Worker };
1080*9880d681SAndroid Build Coastguard Worker
1081*9880d681SAndroid Build Coastguard Worker bool SignExtend = IsSigned;
1082*9880d681SAndroid Build Coastguard Worker if (!GuessNonIVOperand(SignExtend)) {
1083*9880d681SAndroid Build Coastguard Worker SignExtend = !SignExtend;
1084*9880d681SAndroid Build Coastguard Worker if (!GuessNonIVOperand(SignExtend))
1085*9880d681SAndroid Build Coastguard Worker return nullptr;
1086*9880d681SAndroid Build Coastguard Worker }
1087*9880d681SAndroid Build Coastguard Worker
1088*9880d681SAndroid Build Coastguard Worker Value *LHS = (NarrowUse->getOperand(0) == NarrowDef)
1089*9880d681SAndroid Build Coastguard Worker ? WideDef
1090*9880d681SAndroid Build Coastguard Worker : createExtendInst(NarrowUse->getOperand(0), WideType,
1091*9880d681SAndroid Build Coastguard Worker SignExtend, NarrowUse);
1092*9880d681SAndroid Build Coastguard Worker Value *RHS = (NarrowUse->getOperand(1) == NarrowDef)
1093*9880d681SAndroid Build Coastguard Worker ? WideDef
1094*9880d681SAndroid Build Coastguard Worker : createExtendInst(NarrowUse->getOperand(1), WideType,
1095*9880d681SAndroid Build Coastguard Worker SignExtend, NarrowUse);
1096*9880d681SAndroid Build Coastguard Worker
1097*9880d681SAndroid Build Coastguard Worker auto *NarrowBO = cast<BinaryOperator>(NarrowUse);
1098*9880d681SAndroid Build Coastguard Worker auto *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(), LHS, RHS,
1099*9880d681SAndroid Build Coastguard Worker NarrowBO->getName());
1100*9880d681SAndroid Build Coastguard Worker
1101*9880d681SAndroid Build Coastguard Worker IRBuilder<> Builder(NarrowUse);
1102*9880d681SAndroid Build Coastguard Worker Builder.Insert(WideBO);
1103*9880d681SAndroid Build Coastguard Worker WideBO->copyIRFlags(NarrowBO);
1104*9880d681SAndroid Build Coastguard Worker return WideBO;
1105*9880d681SAndroid Build Coastguard Worker }
1106*9880d681SAndroid Build Coastguard Worker
getSCEVByOpCode(const SCEV * LHS,const SCEV * RHS,unsigned OpCode) const1107*9880d681SAndroid Build Coastguard Worker const SCEV *WidenIV::getSCEVByOpCode(const SCEV *LHS, const SCEV *RHS,
1108*9880d681SAndroid Build Coastguard Worker unsigned OpCode) const {
1109*9880d681SAndroid Build Coastguard Worker if (OpCode == Instruction::Add)
1110*9880d681SAndroid Build Coastguard Worker return SE->getAddExpr(LHS, RHS);
1111*9880d681SAndroid Build Coastguard Worker if (OpCode == Instruction::Sub)
1112*9880d681SAndroid Build Coastguard Worker return SE->getMinusSCEV(LHS, RHS);
1113*9880d681SAndroid Build Coastguard Worker if (OpCode == Instruction::Mul)
1114*9880d681SAndroid Build Coastguard Worker return SE->getMulExpr(LHS, RHS);
1115*9880d681SAndroid Build Coastguard Worker
1116*9880d681SAndroid Build Coastguard Worker llvm_unreachable("Unsupported opcode.");
1117*9880d681SAndroid Build Coastguard Worker }
1118*9880d681SAndroid Build Coastguard Worker
1119*9880d681SAndroid Build Coastguard Worker /// No-wrap operations can transfer sign extension of their result to their
1120*9880d681SAndroid Build Coastguard Worker /// operands. Generate the SCEV value for the widened operation without
1121*9880d681SAndroid Build Coastguard Worker /// actually modifying the IR yet. If the expression after extending the
1122*9880d681SAndroid Build Coastguard Worker /// operands is an AddRec for this loop, return it.
getExtendedOperandRecurrence(NarrowIVDefUse DU)1123*9880d681SAndroid Build Coastguard Worker const SCEVAddRecExpr* WidenIV::getExtendedOperandRecurrence(NarrowIVDefUse DU) {
1124*9880d681SAndroid Build Coastguard Worker
1125*9880d681SAndroid Build Coastguard Worker // Handle the common case of add<nsw/nuw>
1126*9880d681SAndroid Build Coastguard Worker const unsigned OpCode = DU.NarrowUse->getOpcode();
1127*9880d681SAndroid Build Coastguard Worker // Only Add/Sub/Mul instructions supported yet.
1128*9880d681SAndroid Build Coastguard Worker if (OpCode != Instruction::Add && OpCode != Instruction::Sub &&
1129*9880d681SAndroid Build Coastguard Worker OpCode != Instruction::Mul)
1130*9880d681SAndroid Build Coastguard Worker return nullptr;
1131*9880d681SAndroid Build Coastguard Worker
1132*9880d681SAndroid Build Coastguard Worker // One operand (NarrowDef) has already been extended to WideDef. Now determine
1133*9880d681SAndroid Build Coastguard Worker // if extending the other will lead to a recurrence.
1134*9880d681SAndroid Build Coastguard Worker const unsigned ExtendOperIdx =
1135*9880d681SAndroid Build Coastguard Worker DU.NarrowUse->getOperand(0) == DU.NarrowDef ? 1 : 0;
1136*9880d681SAndroid Build Coastguard Worker assert(DU.NarrowUse->getOperand(1-ExtendOperIdx) == DU.NarrowDef && "bad DU");
1137*9880d681SAndroid Build Coastguard Worker
1138*9880d681SAndroid Build Coastguard Worker const SCEV *ExtendOperExpr = nullptr;
1139*9880d681SAndroid Build Coastguard Worker const OverflowingBinaryOperator *OBO =
1140*9880d681SAndroid Build Coastguard Worker cast<OverflowingBinaryOperator>(DU.NarrowUse);
1141*9880d681SAndroid Build Coastguard Worker if (IsSigned && OBO->hasNoSignedWrap())
1142*9880d681SAndroid Build Coastguard Worker ExtendOperExpr = SE->getSignExtendExpr(
1143*9880d681SAndroid Build Coastguard Worker SE->getSCEV(DU.NarrowUse->getOperand(ExtendOperIdx)), WideType);
1144*9880d681SAndroid Build Coastguard Worker else if(!IsSigned && OBO->hasNoUnsignedWrap())
1145*9880d681SAndroid Build Coastguard Worker ExtendOperExpr = SE->getZeroExtendExpr(
1146*9880d681SAndroid Build Coastguard Worker SE->getSCEV(DU.NarrowUse->getOperand(ExtendOperIdx)), WideType);
1147*9880d681SAndroid Build Coastguard Worker else
1148*9880d681SAndroid Build Coastguard Worker return nullptr;
1149*9880d681SAndroid Build Coastguard Worker
1150*9880d681SAndroid Build Coastguard Worker // When creating this SCEV expr, don't apply the current operations NSW or NUW
1151*9880d681SAndroid Build Coastguard Worker // flags. This instruction may be guarded by control flow that the no-wrap
1152*9880d681SAndroid Build Coastguard Worker // behavior depends on. Non-control-equivalent instructions can be mapped to
1153*9880d681SAndroid Build Coastguard Worker // the same SCEV expression, and it would be incorrect to transfer NSW/NUW
1154*9880d681SAndroid Build Coastguard Worker // semantics to those operations.
1155*9880d681SAndroid Build Coastguard Worker const SCEV *lhs = SE->getSCEV(DU.WideDef);
1156*9880d681SAndroid Build Coastguard Worker const SCEV *rhs = ExtendOperExpr;
1157*9880d681SAndroid Build Coastguard Worker
1158*9880d681SAndroid Build Coastguard Worker // Let's swap operands to the initial order for the case of non-commutative
1159*9880d681SAndroid Build Coastguard Worker // operations, like SUB. See PR21014.
1160*9880d681SAndroid Build Coastguard Worker if (ExtendOperIdx == 0)
1161*9880d681SAndroid Build Coastguard Worker std::swap(lhs, rhs);
1162*9880d681SAndroid Build Coastguard Worker const SCEVAddRecExpr *AddRec =
1163*9880d681SAndroid Build Coastguard Worker dyn_cast<SCEVAddRecExpr>(getSCEVByOpCode(lhs, rhs, OpCode));
1164*9880d681SAndroid Build Coastguard Worker
1165*9880d681SAndroid Build Coastguard Worker if (!AddRec || AddRec->getLoop() != L)
1166*9880d681SAndroid Build Coastguard Worker return nullptr;
1167*9880d681SAndroid Build Coastguard Worker return AddRec;
1168*9880d681SAndroid Build Coastguard Worker }
1169*9880d681SAndroid Build Coastguard Worker
1170*9880d681SAndroid Build Coastguard Worker /// Is this instruction potentially interesting for further simplification after
1171*9880d681SAndroid Build Coastguard Worker /// widening it's type? In other words, can the extend be safely hoisted out of
1172*9880d681SAndroid Build Coastguard Worker /// the loop with SCEV reducing the value to a recurrence on the same loop. If
1173*9880d681SAndroid Build Coastguard Worker /// so, return the sign or zero extended recurrence. Otherwise return NULL.
getWideRecurrence(Instruction * NarrowUse)1174*9880d681SAndroid Build Coastguard Worker const SCEVAddRecExpr *WidenIV::getWideRecurrence(Instruction *NarrowUse) {
1175*9880d681SAndroid Build Coastguard Worker if (!SE->isSCEVable(NarrowUse->getType()))
1176*9880d681SAndroid Build Coastguard Worker return nullptr;
1177*9880d681SAndroid Build Coastguard Worker
1178*9880d681SAndroid Build Coastguard Worker const SCEV *NarrowExpr = SE->getSCEV(NarrowUse);
1179*9880d681SAndroid Build Coastguard Worker if (SE->getTypeSizeInBits(NarrowExpr->getType())
1180*9880d681SAndroid Build Coastguard Worker >= SE->getTypeSizeInBits(WideType)) {
1181*9880d681SAndroid Build Coastguard Worker // NarrowUse implicitly widens its operand. e.g. a gep with a narrow
1182*9880d681SAndroid Build Coastguard Worker // index. So don't follow this use.
1183*9880d681SAndroid Build Coastguard Worker return nullptr;
1184*9880d681SAndroid Build Coastguard Worker }
1185*9880d681SAndroid Build Coastguard Worker
1186*9880d681SAndroid Build Coastguard Worker const SCEV *WideExpr = IsSigned ?
1187*9880d681SAndroid Build Coastguard Worker SE->getSignExtendExpr(NarrowExpr, WideType) :
1188*9880d681SAndroid Build Coastguard Worker SE->getZeroExtendExpr(NarrowExpr, WideType);
1189*9880d681SAndroid Build Coastguard Worker const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(WideExpr);
1190*9880d681SAndroid Build Coastguard Worker if (!AddRec || AddRec->getLoop() != L)
1191*9880d681SAndroid Build Coastguard Worker return nullptr;
1192*9880d681SAndroid Build Coastguard Worker return AddRec;
1193*9880d681SAndroid Build Coastguard Worker }
1194*9880d681SAndroid Build Coastguard Worker
1195*9880d681SAndroid Build Coastguard Worker /// This IV user cannot be widen. Replace this use of the original narrow IV
1196*9880d681SAndroid Build Coastguard Worker /// with a truncation of the new wide IV to isolate and eliminate the narrow IV.
truncateIVUse(NarrowIVDefUse DU,DominatorTree * DT,LoopInfo * LI)1197*9880d681SAndroid Build Coastguard Worker static void truncateIVUse(NarrowIVDefUse DU, DominatorTree *DT, LoopInfo *LI) {
1198*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "INDVARS: Truncate IV " << *DU.WideDef
1199*9880d681SAndroid Build Coastguard Worker << " for user " << *DU.NarrowUse << "\n");
1200*9880d681SAndroid Build Coastguard Worker IRBuilder<> Builder(
1201*9880d681SAndroid Build Coastguard Worker getInsertPointForUses(DU.NarrowUse, DU.NarrowDef, DT, LI));
1202*9880d681SAndroid Build Coastguard Worker Value *Trunc = Builder.CreateTrunc(DU.WideDef, DU.NarrowDef->getType());
1203*9880d681SAndroid Build Coastguard Worker DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, Trunc);
1204*9880d681SAndroid Build Coastguard Worker }
1205*9880d681SAndroid Build Coastguard Worker
1206*9880d681SAndroid Build Coastguard Worker /// If the narrow use is a compare instruction, then widen the compare
1207*9880d681SAndroid Build Coastguard Worker // (and possibly the other operand). The extend operation is hoisted into the
1208*9880d681SAndroid Build Coastguard Worker // loop preheader as far as possible.
widenLoopCompare(NarrowIVDefUse DU)1209*9880d681SAndroid Build Coastguard Worker bool WidenIV::widenLoopCompare(NarrowIVDefUse DU) {
1210*9880d681SAndroid Build Coastguard Worker ICmpInst *Cmp = dyn_cast<ICmpInst>(DU.NarrowUse);
1211*9880d681SAndroid Build Coastguard Worker if (!Cmp)
1212*9880d681SAndroid Build Coastguard Worker return false;
1213*9880d681SAndroid Build Coastguard Worker
1214*9880d681SAndroid Build Coastguard Worker // We can legally widen the comparison in the following two cases:
1215*9880d681SAndroid Build Coastguard Worker //
1216*9880d681SAndroid Build Coastguard Worker // - The signedness of the IV extension and comparison match
1217*9880d681SAndroid Build Coastguard Worker //
1218*9880d681SAndroid Build Coastguard Worker // - The narrow IV is always positive (and thus its sign extension is equal
1219*9880d681SAndroid Build Coastguard Worker // to its zero extension). For instance, let's say we're zero extending
1220*9880d681SAndroid Build Coastguard Worker // %narrow for the following use
1221*9880d681SAndroid Build Coastguard Worker //
1222*9880d681SAndroid Build Coastguard Worker // icmp slt i32 %narrow, %val ... (A)
1223*9880d681SAndroid Build Coastguard Worker //
1224*9880d681SAndroid Build Coastguard Worker // and %narrow is always positive. Then
1225*9880d681SAndroid Build Coastguard Worker //
1226*9880d681SAndroid Build Coastguard Worker // (A) == icmp slt i32 sext(%narrow), sext(%val)
1227*9880d681SAndroid Build Coastguard Worker // == icmp slt i32 zext(%narrow), sext(%val)
1228*9880d681SAndroid Build Coastguard Worker
1229*9880d681SAndroid Build Coastguard Worker if (!(DU.NeverNegative || IsSigned == Cmp->isSigned()))
1230*9880d681SAndroid Build Coastguard Worker return false;
1231*9880d681SAndroid Build Coastguard Worker
1232*9880d681SAndroid Build Coastguard Worker Value *Op = Cmp->getOperand(Cmp->getOperand(0) == DU.NarrowDef ? 1 : 0);
1233*9880d681SAndroid Build Coastguard Worker unsigned CastWidth = SE->getTypeSizeInBits(Op->getType());
1234*9880d681SAndroid Build Coastguard Worker unsigned IVWidth = SE->getTypeSizeInBits(WideType);
1235*9880d681SAndroid Build Coastguard Worker assert (CastWidth <= IVWidth && "Unexpected width while widening compare.");
1236*9880d681SAndroid Build Coastguard Worker
1237*9880d681SAndroid Build Coastguard Worker // Widen the compare instruction.
1238*9880d681SAndroid Build Coastguard Worker IRBuilder<> Builder(
1239*9880d681SAndroid Build Coastguard Worker getInsertPointForUses(DU.NarrowUse, DU.NarrowDef, DT, LI));
1240*9880d681SAndroid Build Coastguard Worker DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef);
1241*9880d681SAndroid Build Coastguard Worker
1242*9880d681SAndroid Build Coastguard Worker // Widen the other operand of the compare, if necessary.
1243*9880d681SAndroid Build Coastguard Worker if (CastWidth < IVWidth) {
1244*9880d681SAndroid Build Coastguard Worker Value *ExtOp = createExtendInst(Op, WideType, Cmp->isSigned(), Cmp);
1245*9880d681SAndroid Build Coastguard Worker DU.NarrowUse->replaceUsesOfWith(Op, ExtOp);
1246*9880d681SAndroid Build Coastguard Worker }
1247*9880d681SAndroid Build Coastguard Worker return true;
1248*9880d681SAndroid Build Coastguard Worker }
1249*9880d681SAndroid Build Coastguard Worker
1250*9880d681SAndroid Build Coastguard Worker /// Determine whether an individual user of the narrow IV can be widened. If so,
1251*9880d681SAndroid Build Coastguard Worker /// return the wide clone of the user.
widenIVUse(NarrowIVDefUse DU,SCEVExpander & Rewriter)1252*9880d681SAndroid Build Coastguard Worker Instruction *WidenIV::widenIVUse(NarrowIVDefUse DU, SCEVExpander &Rewriter) {
1253*9880d681SAndroid Build Coastguard Worker
1254*9880d681SAndroid Build Coastguard Worker // Stop traversing the def-use chain at inner-loop phis or post-loop phis.
1255*9880d681SAndroid Build Coastguard Worker if (PHINode *UsePhi = dyn_cast<PHINode>(DU.NarrowUse)) {
1256*9880d681SAndroid Build Coastguard Worker if (LI->getLoopFor(UsePhi->getParent()) != L) {
1257*9880d681SAndroid Build Coastguard Worker // For LCSSA phis, sink the truncate outside the loop.
1258*9880d681SAndroid Build Coastguard Worker // After SimplifyCFG most loop exit targets have a single predecessor.
1259*9880d681SAndroid Build Coastguard Worker // Otherwise fall back to a truncate within the loop.
1260*9880d681SAndroid Build Coastguard Worker if (UsePhi->getNumOperands() != 1)
1261*9880d681SAndroid Build Coastguard Worker truncateIVUse(DU, DT, LI);
1262*9880d681SAndroid Build Coastguard Worker else {
1263*9880d681SAndroid Build Coastguard Worker // Widening the PHI requires us to insert a trunc. The logical place
1264*9880d681SAndroid Build Coastguard Worker // for this trunc is in the same BB as the PHI. This is not possible if
1265*9880d681SAndroid Build Coastguard Worker // the BB is terminated by a catchswitch.
1266*9880d681SAndroid Build Coastguard Worker if (isa<CatchSwitchInst>(UsePhi->getParent()->getTerminator()))
1267*9880d681SAndroid Build Coastguard Worker return nullptr;
1268*9880d681SAndroid Build Coastguard Worker
1269*9880d681SAndroid Build Coastguard Worker PHINode *WidePhi =
1270*9880d681SAndroid Build Coastguard Worker PHINode::Create(DU.WideDef->getType(), 1, UsePhi->getName() + ".wide",
1271*9880d681SAndroid Build Coastguard Worker UsePhi);
1272*9880d681SAndroid Build Coastguard Worker WidePhi->addIncoming(DU.WideDef, UsePhi->getIncomingBlock(0));
1273*9880d681SAndroid Build Coastguard Worker IRBuilder<> Builder(&*WidePhi->getParent()->getFirstInsertionPt());
1274*9880d681SAndroid Build Coastguard Worker Value *Trunc = Builder.CreateTrunc(WidePhi, DU.NarrowDef->getType());
1275*9880d681SAndroid Build Coastguard Worker UsePhi->replaceAllUsesWith(Trunc);
1276*9880d681SAndroid Build Coastguard Worker DeadInsts.emplace_back(UsePhi);
1277*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "INDVARS: Widen lcssa phi " << *UsePhi
1278*9880d681SAndroid Build Coastguard Worker << " to " << *WidePhi << "\n");
1279*9880d681SAndroid Build Coastguard Worker }
1280*9880d681SAndroid Build Coastguard Worker return nullptr;
1281*9880d681SAndroid Build Coastguard Worker }
1282*9880d681SAndroid Build Coastguard Worker }
1283*9880d681SAndroid Build Coastguard Worker // Our raison d'etre! Eliminate sign and zero extension.
1284*9880d681SAndroid Build Coastguard Worker if (IsSigned ? isa<SExtInst>(DU.NarrowUse) : isa<ZExtInst>(DU.NarrowUse)) {
1285*9880d681SAndroid Build Coastguard Worker Value *NewDef = DU.WideDef;
1286*9880d681SAndroid Build Coastguard Worker if (DU.NarrowUse->getType() != WideType) {
1287*9880d681SAndroid Build Coastguard Worker unsigned CastWidth = SE->getTypeSizeInBits(DU.NarrowUse->getType());
1288*9880d681SAndroid Build Coastguard Worker unsigned IVWidth = SE->getTypeSizeInBits(WideType);
1289*9880d681SAndroid Build Coastguard Worker if (CastWidth < IVWidth) {
1290*9880d681SAndroid Build Coastguard Worker // The cast isn't as wide as the IV, so insert a Trunc.
1291*9880d681SAndroid Build Coastguard Worker IRBuilder<> Builder(DU.NarrowUse);
1292*9880d681SAndroid Build Coastguard Worker NewDef = Builder.CreateTrunc(DU.WideDef, DU.NarrowUse->getType());
1293*9880d681SAndroid Build Coastguard Worker }
1294*9880d681SAndroid Build Coastguard Worker else {
1295*9880d681SAndroid Build Coastguard Worker // A wider extend was hidden behind a narrower one. This may induce
1296*9880d681SAndroid Build Coastguard Worker // another round of IV widening in which the intermediate IV becomes
1297*9880d681SAndroid Build Coastguard Worker // dead. It should be very rare.
1298*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "INDVARS: New IV " << *WidePhi
1299*9880d681SAndroid Build Coastguard Worker << " not wide enough to subsume " << *DU.NarrowUse << "\n");
1300*9880d681SAndroid Build Coastguard Worker DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef);
1301*9880d681SAndroid Build Coastguard Worker NewDef = DU.NarrowUse;
1302*9880d681SAndroid Build Coastguard Worker }
1303*9880d681SAndroid Build Coastguard Worker }
1304*9880d681SAndroid Build Coastguard Worker if (NewDef != DU.NarrowUse) {
1305*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "INDVARS: eliminating " << *DU.NarrowUse
1306*9880d681SAndroid Build Coastguard Worker << " replaced by " << *DU.WideDef << "\n");
1307*9880d681SAndroid Build Coastguard Worker ++NumElimExt;
1308*9880d681SAndroid Build Coastguard Worker DU.NarrowUse->replaceAllUsesWith(NewDef);
1309*9880d681SAndroid Build Coastguard Worker DeadInsts.emplace_back(DU.NarrowUse);
1310*9880d681SAndroid Build Coastguard Worker }
1311*9880d681SAndroid Build Coastguard Worker // Now that the extend is gone, we want to expose it's uses for potential
1312*9880d681SAndroid Build Coastguard Worker // further simplification. We don't need to directly inform SimplifyIVUsers
1313*9880d681SAndroid Build Coastguard Worker // of the new users, because their parent IV will be processed later as a
1314*9880d681SAndroid Build Coastguard Worker // new loop phi. If we preserved IVUsers analysis, we would also want to
1315*9880d681SAndroid Build Coastguard Worker // push the uses of WideDef here.
1316*9880d681SAndroid Build Coastguard Worker
1317*9880d681SAndroid Build Coastguard Worker // No further widening is needed. The deceased [sz]ext had done it for us.
1318*9880d681SAndroid Build Coastguard Worker return nullptr;
1319*9880d681SAndroid Build Coastguard Worker }
1320*9880d681SAndroid Build Coastguard Worker
1321*9880d681SAndroid Build Coastguard Worker // Does this user itself evaluate to a recurrence after widening?
1322*9880d681SAndroid Build Coastguard Worker const SCEVAddRecExpr *WideAddRec = getWideRecurrence(DU.NarrowUse);
1323*9880d681SAndroid Build Coastguard Worker if (!WideAddRec)
1324*9880d681SAndroid Build Coastguard Worker WideAddRec = getExtendedOperandRecurrence(DU);
1325*9880d681SAndroid Build Coastguard Worker
1326*9880d681SAndroid Build Coastguard Worker if (!WideAddRec) {
1327*9880d681SAndroid Build Coastguard Worker // If use is a loop condition, try to promote the condition instead of
1328*9880d681SAndroid Build Coastguard Worker // truncating the IV first.
1329*9880d681SAndroid Build Coastguard Worker if (widenLoopCompare(DU))
1330*9880d681SAndroid Build Coastguard Worker return nullptr;
1331*9880d681SAndroid Build Coastguard Worker
1332*9880d681SAndroid Build Coastguard Worker // This user does not evaluate to a recurence after widening, so don't
1333*9880d681SAndroid Build Coastguard Worker // follow it. Instead insert a Trunc to kill off the original use,
1334*9880d681SAndroid Build Coastguard Worker // eventually isolating the original narrow IV so it can be removed.
1335*9880d681SAndroid Build Coastguard Worker truncateIVUse(DU, DT, LI);
1336*9880d681SAndroid Build Coastguard Worker return nullptr;
1337*9880d681SAndroid Build Coastguard Worker }
1338*9880d681SAndroid Build Coastguard Worker // Assume block terminators cannot evaluate to a recurrence. We can't to
1339*9880d681SAndroid Build Coastguard Worker // insert a Trunc after a terminator if there happens to be a critical edge.
1340*9880d681SAndroid Build Coastguard Worker assert(DU.NarrowUse != DU.NarrowUse->getParent()->getTerminator() &&
1341*9880d681SAndroid Build Coastguard Worker "SCEV is not expected to evaluate a block terminator");
1342*9880d681SAndroid Build Coastguard Worker
1343*9880d681SAndroid Build Coastguard Worker // Reuse the IV increment that SCEVExpander created as long as it dominates
1344*9880d681SAndroid Build Coastguard Worker // NarrowUse.
1345*9880d681SAndroid Build Coastguard Worker Instruction *WideUse = nullptr;
1346*9880d681SAndroid Build Coastguard Worker if (WideAddRec == WideIncExpr && Rewriter.hoistIVInc(WideInc, DU.NarrowUse))
1347*9880d681SAndroid Build Coastguard Worker WideUse = WideInc;
1348*9880d681SAndroid Build Coastguard Worker else {
1349*9880d681SAndroid Build Coastguard Worker WideUse = cloneIVUser(DU, WideAddRec);
1350*9880d681SAndroid Build Coastguard Worker if (!WideUse)
1351*9880d681SAndroid Build Coastguard Worker return nullptr;
1352*9880d681SAndroid Build Coastguard Worker }
1353*9880d681SAndroid Build Coastguard Worker // Evaluation of WideAddRec ensured that the narrow expression could be
1354*9880d681SAndroid Build Coastguard Worker // extended outside the loop without overflow. This suggests that the wide use
1355*9880d681SAndroid Build Coastguard Worker // evaluates to the same expression as the extended narrow use, but doesn't
1356*9880d681SAndroid Build Coastguard Worker // absolutely guarantee it. Hence the following failsafe check. In rare cases
1357*9880d681SAndroid Build Coastguard Worker // where it fails, we simply throw away the newly created wide use.
1358*9880d681SAndroid Build Coastguard Worker if (WideAddRec != SE->getSCEV(WideUse)) {
1359*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "Wide use expression mismatch: " << *WideUse
1360*9880d681SAndroid Build Coastguard Worker << ": " << *SE->getSCEV(WideUse) << " != " << *WideAddRec << "\n");
1361*9880d681SAndroid Build Coastguard Worker DeadInsts.emplace_back(WideUse);
1362*9880d681SAndroid Build Coastguard Worker return nullptr;
1363*9880d681SAndroid Build Coastguard Worker }
1364*9880d681SAndroid Build Coastguard Worker
1365*9880d681SAndroid Build Coastguard Worker // Returning WideUse pushes it on the worklist.
1366*9880d681SAndroid Build Coastguard Worker return WideUse;
1367*9880d681SAndroid Build Coastguard Worker }
1368*9880d681SAndroid Build Coastguard Worker
1369*9880d681SAndroid Build Coastguard Worker /// Add eligible users of NarrowDef to NarrowIVUsers.
1370*9880d681SAndroid Build Coastguard Worker ///
pushNarrowIVUsers(Instruction * NarrowDef,Instruction * WideDef)1371*9880d681SAndroid Build Coastguard Worker void WidenIV::pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef) {
1372*9880d681SAndroid Build Coastguard Worker const SCEV *NarrowSCEV = SE->getSCEV(NarrowDef);
1373*9880d681SAndroid Build Coastguard Worker bool NeverNegative =
1374*9880d681SAndroid Build Coastguard Worker SE->isKnownPredicate(ICmpInst::ICMP_SGE, NarrowSCEV,
1375*9880d681SAndroid Build Coastguard Worker SE->getConstant(NarrowSCEV->getType(), 0));
1376*9880d681SAndroid Build Coastguard Worker for (User *U : NarrowDef->users()) {
1377*9880d681SAndroid Build Coastguard Worker Instruction *NarrowUser = cast<Instruction>(U);
1378*9880d681SAndroid Build Coastguard Worker
1379*9880d681SAndroid Build Coastguard Worker // Handle data flow merges and bizarre phi cycles.
1380*9880d681SAndroid Build Coastguard Worker if (!Widened.insert(NarrowUser).second)
1381*9880d681SAndroid Build Coastguard Worker continue;
1382*9880d681SAndroid Build Coastguard Worker
1383*9880d681SAndroid Build Coastguard Worker NarrowIVUsers.emplace_back(NarrowDef, NarrowUser, WideDef, NeverNegative);
1384*9880d681SAndroid Build Coastguard Worker }
1385*9880d681SAndroid Build Coastguard Worker }
1386*9880d681SAndroid Build Coastguard Worker
1387*9880d681SAndroid Build Coastguard Worker /// Process a single induction variable. First use the SCEVExpander to create a
1388*9880d681SAndroid Build Coastguard Worker /// wide induction variable that evaluates to the same recurrence as the
1389*9880d681SAndroid Build Coastguard Worker /// original narrow IV. Then use a worklist to forward traverse the narrow IV's
1390*9880d681SAndroid Build Coastguard Worker /// def-use chain. After widenIVUse has processed all interesting IV users, the
1391*9880d681SAndroid Build Coastguard Worker /// narrow IV will be isolated for removal by DeleteDeadPHIs.
1392*9880d681SAndroid Build Coastguard Worker ///
1393*9880d681SAndroid Build Coastguard Worker /// It would be simpler to delete uses as they are processed, but we must avoid
1394*9880d681SAndroid Build Coastguard Worker /// invalidating SCEV expressions.
1395*9880d681SAndroid Build Coastguard Worker ///
createWideIV(SCEVExpander & Rewriter)1396*9880d681SAndroid Build Coastguard Worker PHINode *WidenIV::createWideIV(SCEVExpander &Rewriter) {
1397*9880d681SAndroid Build Coastguard Worker // Is this phi an induction variable?
1398*9880d681SAndroid Build Coastguard Worker const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(OrigPhi));
1399*9880d681SAndroid Build Coastguard Worker if (!AddRec)
1400*9880d681SAndroid Build Coastguard Worker return nullptr;
1401*9880d681SAndroid Build Coastguard Worker
1402*9880d681SAndroid Build Coastguard Worker // Widen the induction variable expression.
1403*9880d681SAndroid Build Coastguard Worker const SCEV *WideIVExpr = IsSigned ?
1404*9880d681SAndroid Build Coastguard Worker SE->getSignExtendExpr(AddRec, WideType) :
1405*9880d681SAndroid Build Coastguard Worker SE->getZeroExtendExpr(AddRec, WideType);
1406*9880d681SAndroid Build Coastguard Worker
1407*9880d681SAndroid Build Coastguard Worker assert(SE->getEffectiveSCEVType(WideIVExpr->getType()) == WideType &&
1408*9880d681SAndroid Build Coastguard Worker "Expect the new IV expression to preserve its type");
1409*9880d681SAndroid Build Coastguard Worker
1410*9880d681SAndroid Build Coastguard Worker // Can the IV be extended outside the loop without overflow?
1411*9880d681SAndroid Build Coastguard Worker AddRec = dyn_cast<SCEVAddRecExpr>(WideIVExpr);
1412*9880d681SAndroid Build Coastguard Worker if (!AddRec || AddRec->getLoop() != L)
1413*9880d681SAndroid Build Coastguard Worker return nullptr;
1414*9880d681SAndroid Build Coastguard Worker
1415*9880d681SAndroid Build Coastguard Worker // An AddRec must have loop-invariant operands. Since this AddRec is
1416*9880d681SAndroid Build Coastguard Worker // materialized by a loop header phi, the expression cannot have any post-loop
1417*9880d681SAndroid Build Coastguard Worker // operands, so they must dominate the loop header.
1418*9880d681SAndroid Build Coastguard Worker assert(
1419*9880d681SAndroid Build Coastguard Worker SE->properlyDominates(AddRec->getStart(), L->getHeader()) &&
1420*9880d681SAndroid Build Coastguard Worker SE->properlyDominates(AddRec->getStepRecurrence(*SE), L->getHeader()) &&
1421*9880d681SAndroid Build Coastguard Worker "Loop header phi recurrence inputs do not dominate the loop");
1422*9880d681SAndroid Build Coastguard Worker
1423*9880d681SAndroid Build Coastguard Worker // The rewriter provides a value for the desired IV expression. This may
1424*9880d681SAndroid Build Coastguard Worker // either find an existing phi or materialize a new one. Either way, we
1425*9880d681SAndroid Build Coastguard Worker // expect a well-formed cyclic phi-with-increments. i.e. any operand not part
1426*9880d681SAndroid Build Coastguard Worker // of the phi-SCC dominates the loop entry.
1427*9880d681SAndroid Build Coastguard Worker Instruction *InsertPt = &L->getHeader()->front();
1428*9880d681SAndroid Build Coastguard Worker WidePhi = cast<PHINode>(Rewriter.expandCodeFor(AddRec, WideType, InsertPt));
1429*9880d681SAndroid Build Coastguard Worker
1430*9880d681SAndroid Build Coastguard Worker // Remembering the WideIV increment generated by SCEVExpander allows
1431*9880d681SAndroid Build Coastguard Worker // widenIVUse to reuse it when widening the narrow IV's increment. We don't
1432*9880d681SAndroid Build Coastguard Worker // employ a general reuse mechanism because the call above is the only call to
1433*9880d681SAndroid Build Coastguard Worker // SCEVExpander. Henceforth, we produce 1-to-1 narrow to wide uses.
1434*9880d681SAndroid Build Coastguard Worker if (BasicBlock *LatchBlock = L->getLoopLatch()) {
1435*9880d681SAndroid Build Coastguard Worker WideInc =
1436*9880d681SAndroid Build Coastguard Worker cast<Instruction>(WidePhi->getIncomingValueForBlock(LatchBlock));
1437*9880d681SAndroid Build Coastguard Worker WideIncExpr = SE->getSCEV(WideInc);
1438*9880d681SAndroid Build Coastguard Worker }
1439*9880d681SAndroid Build Coastguard Worker
1440*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "Wide IV: " << *WidePhi << "\n");
1441*9880d681SAndroid Build Coastguard Worker ++NumWidened;
1442*9880d681SAndroid Build Coastguard Worker
1443*9880d681SAndroid Build Coastguard Worker // Traverse the def-use chain using a worklist starting at the original IV.
1444*9880d681SAndroid Build Coastguard Worker assert(Widened.empty() && NarrowIVUsers.empty() && "expect initial state" );
1445*9880d681SAndroid Build Coastguard Worker
1446*9880d681SAndroid Build Coastguard Worker Widened.insert(OrigPhi);
1447*9880d681SAndroid Build Coastguard Worker pushNarrowIVUsers(OrigPhi, WidePhi);
1448*9880d681SAndroid Build Coastguard Worker
1449*9880d681SAndroid Build Coastguard Worker while (!NarrowIVUsers.empty()) {
1450*9880d681SAndroid Build Coastguard Worker NarrowIVDefUse DU = NarrowIVUsers.pop_back_val();
1451*9880d681SAndroid Build Coastguard Worker
1452*9880d681SAndroid Build Coastguard Worker // Process a def-use edge. This may replace the use, so don't hold a
1453*9880d681SAndroid Build Coastguard Worker // use_iterator across it.
1454*9880d681SAndroid Build Coastguard Worker Instruction *WideUse = widenIVUse(DU, Rewriter);
1455*9880d681SAndroid Build Coastguard Worker
1456*9880d681SAndroid Build Coastguard Worker // Follow all def-use edges from the previous narrow use.
1457*9880d681SAndroid Build Coastguard Worker if (WideUse)
1458*9880d681SAndroid Build Coastguard Worker pushNarrowIVUsers(DU.NarrowUse, WideUse);
1459*9880d681SAndroid Build Coastguard Worker
1460*9880d681SAndroid Build Coastguard Worker // widenIVUse may have removed the def-use edge.
1461*9880d681SAndroid Build Coastguard Worker if (DU.NarrowDef->use_empty())
1462*9880d681SAndroid Build Coastguard Worker DeadInsts.emplace_back(DU.NarrowDef);
1463*9880d681SAndroid Build Coastguard Worker }
1464*9880d681SAndroid Build Coastguard Worker return WidePhi;
1465*9880d681SAndroid Build Coastguard Worker }
1466*9880d681SAndroid Build Coastguard Worker
1467*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
1468*9880d681SAndroid Build Coastguard Worker // Live IV Reduction - Minimize IVs live across the loop.
1469*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
1470*9880d681SAndroid Build Coastguard Worker
1471*9880d681SAndroid Build Coastguard Worker
1472*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
1473*9880d681SAndroid Build Coastguard Worker // Simplification of IV users based on SCEV evaluation.
1474*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
1475*9880d681SAndroid Build Coastguard Worker
1476*9880d681SAndroid Build Coastguard Worker namespace {
1477*9880d681SAndroid Build Coastguard Worker class IndVarSimplifyVisitor : public IVVisitor {
1478*9880d681SAndroid Build Coastguard Worker ScalarEvolution *SE;
1479*9880d681SAndroid Build Coastguard Worker const TargetTransformInfo *TTI;
1480*9880d681SAndroid Build Coastguard Worker PHINode *IVPhi;
1481*9880d681SAndroid Build Coastguard Worker
1482*9880d681SAndroid Build Coastguard Worker public:
1483*9880d681SAndroid Build Coastguard Worker WideIVInfo WI;
1484*9880d681SAndroid Build Coastguard Worker
IndVarSimplifyVisitor(PHINode * IV,ScalarEvolution * SCEV,const TargetTransformInfo * TTI,const DominatorTree * DTree)1485*9880d681SAndroid Build Coastguard Worker IndVarSimplifyVisitor(PHINode *IV, ScalarEvolution *SCEV,
1486*9880d681SAndroid Build Coastguard Worker const TargetTransformInfo *TTI,
1487*9880d681SAndroid Build Coastguard Worker const DominatorTree *DTree)
1488*9880d681SAndroid Build Coastguard Worker : SE(SCEV), TTI(TTI), IVPhi(IV) {
1489*9880d681SAndroid Build Coastguard Worker DT = DTree;
1490*9880d681SAndroid Build Coastguard Worker WI.NarrowIV = IVPhi;
1491*9880d681SAndroid Build Coastguard Worker }
1492*9880d681SAndroid Build Coastguard Worker
1493*9880d681SAndroid Build Coastguard Worker // Implement the interface used by simplifyUsersOfIV.
visitCast(CastInst * Cast)1494*9880d681SAndroid Build Coastguard Worker void visitCast(CastInst *Cast) override { visitIVCast(Cast, WI, SE, TTI); }
1495*9880d681SAndroid Build Coastguard Worker };
1496*9880d681SAndroid Build Coastguard Worker }
1497*9880d681SAndroid Build Coastguard Worker
1498*9880d681SAndroid Build Coastguard Worker /// Iteratively perform simplification on a worklist of IV users. Each
1499*9880d681SAndroid Build Coastguard Worker /// successive simplification may push more users which may themselves be
1500*9880d681SAndroid Build Coastguard Worker /// candidates for simplification.
1501*9880d681SAndroid Build Coastguard Worker ///
1502*9880d681SAndroid Build Coastguard Worker /// Sign/Zero extend elimination is interleaved with IV simplification.
1503*9880d681SAndroid Build Coastguard Worker ///
simplifyAndExtend(Loop * L,SCEVExpander & Rewriter,LoopInfo * LI)1504*9880d681SAndroid Build Coastguard Worker void IndVarSimplify::simplifyAndExtend(Loop *L,
1505*9880d681SAndroid Build Coastguard Worker SCEVExpander &Rewriter,
1506*9880d681SAndroid Build Coastguard Worker LoopInfo *LI) {
1507*9880d681SAndroid Build Coastguard Worker SmallVector<WideIVInfo, 8> WideIVs;
1508*9880d681SAndroid Build Coastguard Worker
1509*9880d681SAndroid Build Coastguard Worker SmallVector<PHINode*, 8> LoopPhis;
1510*9880d681SAndroid Build Coastguard Worker for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
1511*9880d681SAndroid Build Coastguard Worker LoopPhis.push_back(cast<PHINode>(I));
1512*9880d681SAndroid Build Coastguard Worker }
1513*9880d681SAndroid Build Coastguard Worker // Each round of simplification iterates through the SimplifyIVUsers worklist
1514*9880d681SAndroid Build Coastguard Worker // for all current phis, then determines whether any IVs can be
1515*9880d681SAndroid Build Coastguard Worker // widened. Widening adds new phis to LoopPhis, inducing another round of
1516*9880d681SAndroid Build Coastguard Worker // simplification on the wide IVs.
1517*9880d681SAndroid Build Coastguard Worker while (!LoopPhis.empty()) {
1518*9880d681SAndroid Build Coastguard Worker // Evaluate as many IV expressions as possible before widening any IVs. This
1519*9880d681SAndroid Build Coastguard Worker // forces SCEV to set no-wrap flags before evaluating sign/zero
1520*9880d681SAndroid Build Coastguard Worker // extension. The first time SCEV attempts to normalize sign/zero extension,
1521*9880d681SAndroid Build Coastguard Worker // the result becomes final. So for the most predictable results, we delay
1522*9880d681SAndroid Build Coastguard Worker // evaluation of sign/zero extend evaluation until needed, and avoid running
1523*9880d681SAndroid Build Coastguard Worker // other SCEV based analysis prior to simplifyAndExtend.
1524*9880d681SAndroid Build Coastguard Worker do {
1525*9880d681SAndroid Build Coastguard Worker PHINode *CurrIV = LoopPhis.pop_back_val();
1526*9880d681SAndroid Build Coastguard Worker
1527*9880d681SAndroid Build Coastguard Worker // Information about sign/zero extensions of CurrIV.
1528*9880d681SAndroid Build Coastguard Worker IndVarSimplifyVisitor Visitor(CurrIV, SE, TTI, DT);
1529*9880d681SAndroid Build Coastguard Worker
1530*9880d681SAndroid Build Coastguard Worker Changed |= simplifyUsersOfIV(CurrIV, SE, DT, LI, DeadInsts, &Visitor);
1531*9880d681SAndroid Build Coastguard Worker
1532*9880d681SAndroid Build Coastguard Worker if (Visitor.WI.WidestNativeType) {
1533*9880d681SAndroid Build Coastguard Worker WideIVs.push_back(Visitor.WI);
1534*9880d681SAndroid Build Coastguard Worker }
1535*9880d681SAndroid Build Coastguard Worker } while(!LoopPhis.empty());
1536*9880d681SAndroid Build Coastguard Worker
1537*9880d681SAndroid Build Coastguard Worker for (; !WideIVs.empty(); WideIVs.pop_back()) {
1538*9880d681SAndroid Build Coastguard Worker WidenIV Widener(WideIVs.back(), LI, SE, DT, DeadInsts);
1539*9880d681SAndroid Build Coastguard Worker if (PHINode *WidePhi = Widener.createWideIV(Rewriter)) {
1540*9880d681SAndroid Build Coastguard Worker Changed = true;
1541*9880d681SAndroid Build Coastguard Worker LoopPhis.push_back(WidePhi);
1542*9880d681SAndroid Build Coastguard Worker }
1543*9880d681SAndroid Build Coastguard Worker }
1544*9880d681SAndroid Build Coastguard Worker }
1545*9880d681SAndroid Build Coastguard Worker }
1546*9880d681SAndroid Build Coastguard Worker
1547*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
1548*9880d681SAndroid Build Coastguard Worker // linearFunctionTestReplace and its kin. Rewrite the loop exit condition.
1549*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
1550*9880d681SAndroid Build Coastguard Worker
1551*9880d681SAndroid Build Coastguard Worker /// Return true if this loop's backedge taken count expression can be safely and
1552*9880d681SAndroid Build Coastguard Worker /// cheaply expanded into an instruction sequence that can be used by
1553*9880d681SAndroid Build Coastguard Worker /// linearFunctionTestReplace.
1554*9880d681SAndroid Build Coastguard Worker ///
1555*9880d681SAndroid Build Coastguard Worker /// TODO: This fails for pointer-type loop counters with greater than one byte
1556*9880d681SAndroid Build Coastguard Worker /// strides, consequently preventing LFTR from running. For the purpose of LFTR
1557*9880d681SAndroid Build Coastguard Worker /// we could skip this check in the case that the LFTR loop counter (chosen by
1558*9880d681SAndroid Build Coastguard Worker /// FindLoopCounter) is also pointer type. Instead, we could directly convert
1559*9880d681SAndroid Build Coastguard Worker /// the loop test to an inequality test by checking the target data's alignment
1560*9880d681SAndroid Build Coastguard Worker /// of element types (given that the initial pointer value originates from or is
1561*9880d681SAndroid Build Coastguard Worker /// used by ABI constrained operation, as opposed to inttoptr/ptrtoint).
1562*9880d681SAndroid Build Coastguard Worker /// However, we don't yet have a strong motivation for converting loop tests
1563*9880d681SAndroid Build Coastguard Worker /// into inequality tests.
canExpandBackedgeTakenCount(Loop * L,ScalarEvolution * SE,SCEVExpander & Rewriter)1564*9880d681SAndroid Build Coastguard Worker static bool canExpandBackedgeTakenCount(Loop *L, ScalarEvolution *SE,
1565*9880d681SAndroid Build Coastguard Worker SCEVExpander &Rewriter) {
1566*9880d681SAndroid Build Coastguard Worker const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
1567*9880d681SAndroid Build Coastguard Worker if (isa<SCEVCouldNotCompute>(BackedgeTakenCount) ||
1568*9880d681SAndroid Build Coastguard Worker BackedgeTakenCount->isZero())
1569*9880d681SAndroid Build Coastguard Worker return false;
1570*9880d681SAndroid Build Coastguard Worker
1571*9880d681SAndroid Build Coastguard Worker if (!L->getExitingBlock())
1572*9880d681SAndroid Build Coastguard Worker return false;
1573*9880d681SAndroid Build Coastguard Worker
1574*9880d681SAndroid Build Coastguard Worker // Can't rewrite non-branch yet.
1575*9880d681SAndroid Build Coastguard Worker if (!isa<BranchInst>(L->getExitingBlock()->getTerminator()))
1576*9880d681SAndroid Build Coastguard Worker return false;
1577*9880d681SAndroid Build Coastguard Worker
1578*9880d681SAndroid Build Coastguard Worker if (Rewriter.isHighCostExpansion(BackedgeTakenCount, L))
1579*9880d681SAndroid Build Coastguard Worker return false;
1580*9880d681SAndroid Build Coastguard Worker
1581*9880d681SAndroid Build Coastguard Worker return true;
1582*9880d681SAndroid Build Coastguard Worker }
1583*9880d681SAndroid Build Coastguard Worker
1584*9880d681SAndroid Build Coastguard Worker /// Return the loop header phi IFF IncV adds a loop invariant value to the phi.
getLoopPhiForCounter(Value * IncV,Loop * L,DominatorTree * DT)1585*9880d681SAndroid Build Coastguard Worker static PHINode *getLoopPhiForCounter(Value *IncV, Loop *L, DominatorTree *DT) {
1586*9880d681SAndroid Build Coastguard Worker Instruction *IncI = dyn_cast<Instruction>(IncV);
1587*9880d681SAndroid Build Coastguard Worker if (!IncI)
1588*9880d681SAndroid Build Coastguard Worker return nullptr;
1589*9880d681SAndroid Build Coastguard Worker
1590*9880d681SAndroid Build Coastguard Worker switch (IncI->getOpcode()) {
1591*9880d681SAndroid Build Coastguard Worker case Instruction::Add:
1592*9880d681SAndroid Build Coastguard Worker case Instruction::Sub:
1593*9880d681SAndroid Build Coastguard Worker break;
1594*9880d681SAndroid Build Coastguard Worker case Instruction::GetElementPtr:
1595*9880d681SAndroid Build Coastguard Worker // An IV counter must preserve its type.
1596*9880d681SAndroid Build Coastguard Worker if (IncI->getNumOperands() == 2)
1597*9880d681SAndroid Build Coastguard Worker break;
1598*9880d681SAndroid Build Coastguard Worker default:
1599*9880d681SAndroid Build Coastguard Worker return nullptr;
1600*9880d681SAndroid Build Coastguard Worker }
1601*9880d681SAndroid Build Coastguard Worker
1602*9880d681SAndroid Build Coastguard Worker PHINode *Phi = dyn_cast<PHINode>(IncI->getOperand(0));
1603*9880d681SAndroid Build Coastguard Worker if (Phi && Phi->getParent() == L->getHeader()) {
1604*9880d681SAndroid Build Coastguard Worker if (isLoopInvariant(IncI->getOperand(1), L, DT))
1605*9880d681SAndroid Build Coastguard Worker return Phi;
1606*9880d681SAndroid Build Coastguard Worker return nullptr;
1607*9880d681SAndroid Build Coastguard Worker }
1608*9880d681SAndroid Build Coastguard Worker if (IncI->getOpcode() == Instruction::GetElementPtr)
1609*9880d681SAndroid Build Coastguard Worker return nullptr;
1610*9880d681SAndroid Build Coastguard Worker
1611*9880d681SAndroid Build Coastguard Worker // Allow add/sub to be commuted.
1612*9880d681SAndroid Build Coastguard Worker Phi = dyn_cast<PHINode>(IncI->getOperand(1));
1613*9880d681SAndroid Build Coastguard Worker if (Phi && Phi->getParent() == L->getHeader()) {
1614*9880d681SAndroid Build Coastguard Worker if (isLoopInvariant(IncI->getOperand(0), L, DT))
1615*9880d681SAndroid Build Coastguard Worker return Phi;
1616*9880d681SAndroid Build Coastguard Worker }
1617*9880d681SAndroid Build Coastguard Worker return nullptr;
1618*9880d681SAndroid Build Coastguard Worker }
1619*9880d681SAndroid Build Coastguard Worker
1620*9880d681SAndroid Build Coastguard Worker /// Return the compare guarding the loop latch, or NULL for unrecognized tests.
getLoopTest(Loop * L)1621*9880d681SAndroid Build Coastguard Worker static ICmpInst *getLoopTest(Loop *L) {
1622*9880d681SAndroid Build Coastguard Worker assert(L->getExitingBlock() && "expected loop exit");
1623*9880d681SAndroid Build Coastguard Worker
1624*9880d681SAndroid Build Coastguard Worker BasicBlock *LatchBlock = L->getLoopLatch();
1625*9880d681SAndroid Build Coastguard Worker // Don't bother with LFTR if the loop is not properly simplified.
1626*9880d681SAndroid Build Coastguard Worker if (!LatchBlock)
1627*9880d681SAndroid Build Coastguard Worker return nullptr;
1628*9880d681SAndroid Build Coastguard Worker
1629*9880d681SAndroid Build Coastguard Worker BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator());
1630*9880d681SAndroid Build Coastguard Worker assert(BI && "expected exit branch");
1631*9880d681SAndroid Build Coastguard Worker
1632*9880d681SAndroid Build Coastguard Worker return dyn_cast<ICmpInst>(BI->getCondition());
1633*9880d681SAndroid Build Coastguard Worker }
1634*9880d681SAndroid Build Coastguard Worker
1635*9880d681SAndroid Build Coastguard Worker /// linearFunctionTestReplace policy. Return true unless we can show that the
1636*9880d681SAndroid Build Coastguard Worker /// current exit test is already sufficiently canonical.
needsLFTR(Loop * L,DominatorTree * DT)1637*9880d681SAndroid Build Coastguard Worker static bool needsLFTR(Loop *L, DominatorTree *DT) {
1638*9880d681SAndroid Build Coastguard Worker // Do LFTR to simplify the exit condition to an ICMP.
1639*9880d681SAndroid Build Coastguard Worker ICmpInst *Cond = getLoopTest(L);
1640*9880d681SAndroid Build Coastguard Worker if (!Cond)
1641*9880d681SAndroid Build Coastguard Worker return true;
1642*9880d681SAndroid Build Coastguard Worker
1643*9880d681SAndroid Build Coastguard Worker // Do LFTR to simplify the exit ICMP to EQ/NE
1644*9880d681SAndroid Build Coastguard Worker ICmpInst::Predicate Pred = Cond->getPredicate();
1645*9880d681SAndroid Build Coastguard Worker if (Pred != ICmpInst::ICMP_NE && Pred != ICmpInst::ICMP_EQ)
1646*9880d681SAndroid Build Coastguard Worker return true;
1647*9880d681SAndroid Build Coastguard Worker
1648*9880d681SAndroid Build Coastguard Worker // Look for a loop invariant RHS
1649*9880d681SAndroid Build Coastguard Worker Value *LHS = Cond->getOperand(0);
1650*9880d681SAndroid Build Coastguard Worker Value *RHS = Cond->getOperand(1);
1651*9880d681SAndroid Build Coastguard Worker if (!isLoopInvariant(RHS, L, DT)) {
1652*9880d681SAndroid Build Coastguard Worker if (!isLoopInvariant(LHS, L, DT))
1653*9880d681SAndroid Build Coastguard Worker return true;
1654*9880d681SAndroid Build Coastguard Worker std::swap(LHS, RHS);
1655*9880d681SAndroid Build Coastguard Worker }
1656*9880d681SAndroid Build Coastguard Worker // Look for a simple IV counter LHS
1657*9880d681SAndroid Build Coastguard Worker PHINode *Phi = dyn_cast<PHINode>(LHS);
1658*9880d681SAndroid Build Coastguard Worker if (!Phi)
1659*9880d681SAndroid Build Coastguard Worker Phi = getLoopPhiForCounter(LHS, L, DT);
1660*9880d681SAndroid Build Coastguard Worker
1661*9880d681SAndroid Build Coastguard Worker if (!Phi)
1662*9880d681SAndroid Build Coastguard Worker return true;
1663*9880d681SAndroid Build Coastguard Worker
1664*9880d681SAndroid Build Coastguard Worker // Do LFTR if PHI node is defined in the loop, but is *not* a counter.
1665*9880d681SAndroid Build Coastguard Worker int Idx = Phi->getBasicBlockIndex(L->getLoopLatch());
1666*9880d681SAndroid Build Coastguard Worker if (Idx < 0)
1667*9880d681SAndroid Build Coastguard Worker return true;
1668*9880d681SAndroid Build Coastguard Worker
1669*9880d681SAndroid Build Coastguard Worker // Do LFTR if the exit condition's IV is *not* a simple counter.
1670*9880d681SAndroid Build Coastguard Worker Value *IncV = Phi->getIncomingValue(Idx);
1671*9880d681SAndroid Build Coastguard Worker return Phi != getLoopPhiForCounter(IncV, L, DT);
1672*9880d681SAndroid Build Coastguard Worker }
1673*9880d681SAndroid Build Coastguard Worker
1674*9880d681SAndroid Build Coastguard Worker /// Recursive helper for hasConcreteDef(). Unfortunately, this currently boils
1675*9880d681SAndroid Build Coastguard Worker /// down to checking that all operands are constant and listing instructions
1676*9880d681SAndroid Build Coastguard Worker /// that may hide undef.
hasConcreteDefImpl(Value * V,SmallPtrSetImpl<Value * > & Visited,unsigned Depth)1677*9880d681SAndroid Build Coastguard Worker static bool hasConcreteDefImpl(Value *V, SmallPtrSetImpl<Value*> &Visited,
1678*9880d681SAndroid Build Coastguard Worker unsigned Depth) {
1679*9880d681SAndroid Build Coastguard Worker if (isa<Constant>(V))
1680*9880d681SAndroid Build Coastguard Worker return !isa<UndefValue>(V);
1681*9880d681SAndroid Build Coastguard Worker
1682*9880d681SAndroid Build Coastguard Worker if (Depth >= 6)
1683*9880d681SAndroid Build Coastguard Worker return false;
1684*9880d681SAndroid Build Coastguard Worker
1685*9880d681SAndroid Build Coastguard Worker // Conservatively handle non-constant non-instructions. For example, Arguments
1686*9880d681SAndroid Build Coastguard Worker // may be undef.
1687*9880d681SAndroid Build Coastguard Worker Instruction *I = dyn_cast<Instruction>(V);
1688*9880d681SAndroid Build Coastguard Worker if (!I)
1689*9880d681SAndroid Build Coastguard Worker return false;
1690*9880d681SAndroid Build Coastguard Worker
1691*9880d681SAndroid Build Coastguard Worker // Load and return values may be undef.
1692*9880d681SAndroid Build Coastguard Worker if(I->mayReadFromMemory() || isa<CallInst>(I) || isa<InvokeInst>(I))
1693*9880d681SAndroid Build Coastguard Worker return false;
1694*9880d681SAndroid Build Coastguard Worker
1695*9880d681SAndroid Build Coastguard Worker // Optimistically handle other instructions.
1696*9880d681SAndroid Build Coastguard Worker for (Value *Op : I->operands()) {
1697*9880d681SAndroid Build Coastguard Worker if (!Visited.insert(Op).second)
1698*9880d681SAndroid Build Coastguard Worker continue;
1699*9880d681SAndroid Build Coastguard Worker if (!hasConcreteDefImpl(Op, Visited, Depth+1))
1700*9880d681SAndroid Build Coastguard Worker return false;
1701*9880d681SAndroid Build Coastguard Worker }
1702*9880d681SAndroid Build Coastguard Worker return true;
1703*9880d681SAndroid Build Coastguard Worker }
1704*9880d681SAndroid Build Coastguard Worker
1705*9880d681SAndroid Build Coastguard Worker /// Return true if the given value is concrete. We must prove that undef can
1706*9880d681SAndroid Build Coastguard Worker /// never reach it.
1707*9880d681SAndroid Build Coastguard Worker ///
1708*9880d681SAndroid Build Coastguard Worker /// TODO: If we decide that this is a good approach to checking for undef, we
1709*9880d681SAndroid Build Coastguard Worker /// may factor it into a common location.
hasConcreteDef(Value * V)1710*9880d681SAndroid Build Coastguard Worker static bool hasConcreteDef(Value *V) {
1711*9880d681SAndroid Build Coastguard Worker SmallPtrSet<Value*, 8> Visited;
1712*9880d681SAndroid Build Coastguard Worker Visited.insert(V);
1713*9880d681SAndroid Build Coastguard Worker return hasConcreteDefImpl(V, Visited, 0);
1714*9880d681SAndroid Build Coastguard Worker }
1715*9880d681SAndroid Build Coastguard Worker
1716*9880d681SAndroid Build Coastguard Worker /// Return true if this IV has any uses other than the (soon to be rewritten)
1717*9880d681SAndroid Build Coastguard Worker /// loop exit test.
AlmostDeadIV(PHINode * Phi,BasicBlock * LatchBlock,Value * Cond)1718*9880d681SAndroid Build Coastguard Worker static bool AlmostDeadIV(PHINode *Phi, BasicBlock *LatchBlock, Value *Cond) {
1719*9880d681SAndroid Build Coastguard Worker int LatchIdx = Phi->getBasicBlockIndex(LatchBlock);
1720*9880d681SAndroid Build Coastguard Worker Value *IncV = Phi->getIncomingValue(LatchIdx);
1721*9880d681SAndroid Build Coastguard Worker
1722*9880d681SAndroid Build Coastguard Worker for (User *U : Phi->users())
1723*9880d681SAndroid Build Coastguard Worker if (U != Cond && U != IncV) return false;
1724*9880d681SAndroid Build Coastguard Worker
1725*9880d681SAndroid Build Coastguard Worker for (User *U : IncV->users())
1726*9880d681SAndroid Build Coastguard Worker if (U != Cond && U != Phi) return false;
1727*9880d681SAndroid Build Coastguard Worker return true;
1728*9880d681SAndroid Build Coastguard Worker }
1729*9880d681SAndroid Build Coastguard Worker
1730*9880d681SAndroid Build Coastguard Worker /// Find an affine IV in canonical form.
1731*9880d681SAndroid Build Coastguard Worker ///
1732*9880d681SAndroid Build Coastguard Worker /// BECount may be an i8* pointer type. The pointer difference is already
1733*9880d681SAndroid Build Coastguard Worker /// valid count without scaling the address stride, so it remains a pointer
1734*9880d681SAndroid Build Coastguard Worker /// expression as far as SCEV is concerned.
1735*9880d681SAndroid Build Coastguard Worker ///
1736*9880d681SAndroid Build Coastguard Worker /// Currently only valid for LFTR. See the comments on hasConcreteDef below.
1737*9880d681SAndroid Build Coastguard Worker ///
1738*9880d681SAndroid Build Coastguard Worker /// FIXME: Accept -1 stride and set IVLimit = IVInit - BECount
1739*9880d681SAndroid Build Coastguard Worker ///
1740*9880d681SAndroid Build Coastguard Worker /// FIXME: Accept non-unit stride as long as SCEV can reduce BECount * Stride.
1741*9880d681SAndroid Build Coastguard Worker /// This is difficult in general for SCEV because of potential overflow. But we
1742*9880d681SAndroid Build Coastguard Worker /// could at least handle constant BECounts.
FindLoopCounter(Loop * L,const SCEV * BECount,ScalarEvolution * SE,DominatorTree * DT)1743*9880d681SAndroid Build Coastguard Worker static PHINode *FindLoopCounter(Loop *L, const SCEV *BECount,
1744*9880d681SAndroid Build Coastguard Worker ScalarEvolution *SE, DominatorTree *DT) {
1745*9880d681SAndroid Build Coastguard Worker uint64_t BCWidth = SE->getTypeSizeInBits(BECount->getType());
1746*9880d681SAndroid Build Coastguard Worker
1747*9880d681SAndroid Build Coastguard Worker Value *Cond =
1748*9880d681SAndroid Build Coastguard Worker cast<BranchInst>(L->getExitingBlock()->getTerminator())->getCondition();
1749*9880d681SAndroid Build Coastguard Worker
1750*9880d681SAndroid Build Coastguard Worker // Loop over all of the PHI nodes, looking for a simple counter.
1751*9880d681SAndroid Build Coastguard Worker PHINode *BestPhi = nullptr;
1752*9880d681SAndroid Build Coastguard Worker const SCEV *BestInit = nullptr;
1753*9880d681SAndroid Build Coastguard Worker BasicBlock *LatchBlock = L->getLoopLatch();
1754*9880d681SAndroid Build Coastguard Worker assert(LatchBlock && "needsLFTR should guarantee a loop latch");
1755*9880d681SAndroid Build Coastguard Worker const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
1756*9880d681SAndroid Build Coastguard Worker
1757*9880d681SAndroid Build Coastguard Worker for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
1758*9880d681SAndroid Build Coastguard Worker PHINode *Phi = cast<PHINode>(I);
1759*9880d681SAndroid Build Coastguard Worker if (!SE->isSCEVable(Phi->getType()))
1760*9880d681SAndroid Build Coastguard Worker continue;
1761*9880d681SAndroid Build Coastguard Worker
1762*9880d681SAndroid Build Coastguard Worker // Avoid comparing an integer IV against a pointer Limit.
1763*9880d681SAndroid Build Coastguard Worker if (BECount->getType()->isPointerTy() && !Phi->getType()->isPointerTy())
1764*9880d681SAndroid Build Coastguard Worker continue;
1765*9880d681SAndroid Build Coastguard Worker
1766*9880d681SAndroid Build Coastguard Worker const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Phi));
1767*9880d681SAndroid Build Coastguard Worker if (!AR || AR->getLoop() != L || !AR->isAffine())
1768*9880d681SAndroid Build Coastguard Worker continue;
1769*9880d681SAndroid Build Coastguard Worker
1770*9880d681SAndroid Build Coastguard Worker // AR may be a pointer type, while BECount is an integer type.
1771*9880d681SAndroid Build Coastguard Worker // AR may be wider than BECount. With eq/ne tests overflow is immaterial.
1772*9880d681SAndroid Build Coastguard Worker // AR may not be a narrower type, or we may never exit.
1773*9880d681SAndroid Build Coastguard Worker uint64_t PhiWidth = SE->getTypeSizeInBits(AR->getType());
1774*9880d681SAndroid Build Coastguard Worker if (PhiWidth < BCWidth || !DL.isLegalInteger(PhiWidth))
1775*9880d681SAndroid Build Coastguard Worker continue;
1776*9880d681SAndroid Build Coastguard Worker
1777*9880d681SAndroid Build Coastguard Worker const SCEV *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*SE));
1778*9880d681SAndroid Build Coastguard Worker if (!Step || !Step->isOne())
1779*9880d681SAndroid Build Coastguard Worker continue;
1780*9880d681SAndroid Build Coastguard Worker
1781*9880d681SAndroid Build Coastguard Worker int LatchIdx = Phi->getBasicBlockIndex(LatchBlock);
1782*9880d681SAndroid Build Coastguard Worker Value *IncV = Phi->getIncomingValue(LatchIdx);
1783*9880d681SAndroid Build Coastguard Worker if (getLoopPhiForCounter(IncV, L, DT) != Phi)
1784*9880d681SAndroid Build Coastguard Worker continue;
1785*9880d681SAndroid Build Coastguard Worker
1786*9880d681SAndroid Build Coastguard Worker // Avoid reusing a potentially undef value to compute other values that may
1787*9880d681SAndroid Build Coastguard Worker // have originally had a concrete definition.
1788*9880d681SAndroid Build Coastguard Worker if (!hasConcreteDef(Phi)) {
1789*9880d681SAndroid Build Coastguard Worker // We explicitly allow unknown phis as long as they are already used by
1790*9880d681SAndroid Build Coastguard Worker // the loop test. In this case we assume that performing LFTR could not
1791*9880d681SAndroid Build Coastguard Worker // increase the number of undef users.
1792*9880d681SAndroid Build Coastguard Worker if (ICmpInst *Cond = getLoopTest(L)) {
1793*9880d681SAndroid Build Coastguard Worker if (Phi != getLoopPhiForCounter(Cond->getOperand(0), L, DT) &&
1794*9880d681SAndroid Build Coastguard Worker Phi != getLoopPhiForCounter(Cond->getOperand(1), L, DT)) {
1795*9880d681SAndroid Build Coastguard Worker continue;
1796*9880d681SAndroid Build Coastguard Worker }
1797*9880d681SAndroid Build Coastguard Worker }
1798*9880d681SAndroid Build Coastguard Worker }
1799*9880d681SAndroid Build Coastguard Worker const SCEV *Init = AR->getStart();
1800*9880d681SAndroid Build Coastguard Worker
1801*9880d681SAndroid Build Coastguard Worker if (BestPhi && !AlmostDeadIV(BestPhi, LatchBlock, Cond)) {
1802*9880d681SAndroid Build Coastguard Worker // Don't force a live loop counter if another IV can be used.
1803*9880d681SAndroid Build Coastguard Worker if (AlmostDeadIV(Phi, LatchBlock, Cond))
1804*9880d681SAndroid Build Coastguard Worker continue;
1805*9880d681SAndroid Build Coastguard Worker
1806*9880d681SAndroid Build Coastguard Worker // Prefer to count-from-zero. This is a more "canonical" counter form. It
1807*9880d681SAndroid Build Coastguard Worker // also prefers integer to pointer IVs.
1808*9880d681SAndroid Build Coastguard Worker if (BestInit->isZero() != Init->isZero()) {
1809*9880d681SAndroid Build Coastguard Worker if (BestInit->isZero())
1810*9880d681SAndroid Build Coastguard Worker continue;
1811*9880d681SAndroid Build Coastguard Worker }
1812*9880d681SAndroid Build Coastguard Worker // If two IVs both count from zero or both count from nonzero then the
1813*9880d681SAndroid Build Coastguard Worker // narrower is likely a dead phi that has been widened. Use the wider phi
1814*9880d681SAndroid Build Coastguard Worker // to allow the other to be eliminated.
1815*9880d681SAndroid Build Coastguard Worker else if (PhiWidth <= SE->getTypeSizeInBits(BestPhi->getType()))
1816*9880d681SAndroid Build Coastguard Worker continue;
1817*9880d681SAndroid Build Coastguard Worker }
1818*9880d681SAndroid Build Coastguard Worker BestPhi = Phi;
1819*9880d681SAndroid Build Coastguard Worker BestInit = Init;
1820*9880d681SAndroid Build Coastguard Worker }
1821*9880d681SAndroid Build Coastguard Worker return BestPhi;
1822*9880d681SAndroid Build Coastguard Worker }
1823*9880d681SAndroid Build Coastguard Worker
1824*9880d681SAndroid Build Coastguard Worker /// Help linearFunctionTestReplace by generating a value that holds the RHS of
1825*9880d681SAndroid Build Coastguard Worker /// the new loop test.
genLoopLimit(PHINode * IndVar,const SCEV * IVCount,Loop * L,SCEVExpander & Rewriter,ScalarEvolution * SE)1826*9880d681SAndroid Build Coastguard Worker static Value *genLoopLimit(PHINode *IndVar, const SCEV *IVCount, Loop *L,
1827*9880d681SAndroid Build Coastguard Worker SCEVExpander &Rewriter, ScalarEvolution *SE) {
1828*9880d681SAndroid Build Coastguard Worker const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(IndVar));
1829*9880d681SAndroid Build Coastguard Worker assert(AR && AR->getLoop() == L && AR->isAffine() && "bad loop counter");
1830*9880d681SAndroid Build Coastguard Worker const SCEV *IVInit = AR->getStart();
1831*9880d681SAndroid Build Coastguard Worker
1832*9880d681SAndroid Build Coastguard Worker // IVInit may be a pointer while IVCount is an integer when FindLoopCounter
1833*9880d681SAndroid Build Coastguard Worker // finds a valid pointer IV. Sign extend BECount in order to materialize a
1834*9880d681SAndroid Build Coastguard Worker // GEP. Avoid running SCEVExpander on a new pointer value, instead reusing
1835*9880d681SAndroid Build Coastguard Worker // the existing GEPs whenever possible.
1836*9880d681SAndroid Build Coastguard Worker if (IndVar->getType()->isPointerTy() && !IVCount->getType()->isPointerTy()) {
1837*9880d681SAndroid Build Coastguard Worker // IVOffset will be the new GEP offset that is interpreted by GEP as a
1838*9880d681SAndroid Build Coastguard Worker // signed value. IVCount on the other hand represents the loop trip count,
1839*9880d681SAndroid Build Coastguard Worker // which is an unsigned value. FindLoopCounter only allows induction
1840*9880d681SAndroid Build Coastguard Worker // variables that have a positive unit stride of one. This means we don't
1841*9880d681SAndroid Build Coastguard Worker // have to handle the case of negative offsets (yet) and just need to zero
1842*9880d681SAndroid Build Coastguard Worker // extend IVCount.
1843*9880d681SAndroid Build Coastguard Worker Type *OfsTy = SE->getEffectiveSCEVType(IVInit->getType());
1844*9880d681SAndroid Build Coastguard Worker const SCEV *IVOffset = SE->getTruncateOrZeroExtend(IVCount, OfsTy);
1845*9880d681SAndroid Build Coastguard Worker
1846*9880d681SAndroid Build Coastguard Worker // Expand the code for the iteration count.
1847*9880d681SAndroid Build Coastguard Worker assert(SE->isLoopInvariant(IVOffset, L) &&
1848*9880d681SAndroid Build Coastguard Worker "Computed iteration count is not loop invariant!");
1849*9880d681SAndroid Build Coastguard Worker BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator());
1850*9880d681SAndroid Build Coastguard Worker Value *GEPOffset = Rewriter.expandCodeFor(IVOffset, OfsTy, BI);
1851*9880d681SAndroid Build Coastguard Worker
1852*9880d681SAndroid Build Coastguard Worker Value *GEPBase = IndVar->getIncomingValueForBlock(L->getLoopPreheader());
1853*9880d681SAndroid Build Coastguard Worker assert(AR->getStart() == SE->getSCEV(GEPBase) && "bad loop counter");
1854*9880d681SAndroid Build Coastguard Worker // We could handle pointer IVs other than i8*, but we need to compensate for
1855*9880d681SAndroid Build Coastguard Worker // gep index scaling. See canExpandBackedgeTakenCount comments.
1856*9880d681SAndroid Build Coastguard Worker assert(SE->getSizeOfExpr(IntegerType::getInt64Ty(IndVar->getContext()),
1857*9880d681SAndroid Build Coastguard Worker cast<PointerType>(GEPBase->getType())
1858*9880d681SAndroid Build Coastguard Worker ->getElementType())->isOne() &&
1859*9880d681SAndroid Build Coastguard Worker "unit stride pointer IV must be i8*");
1860*9880d681SAndroid Build Coastguard Worker
1861*9880d681SAndroid Build Coastguard Worker IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
1862*9880d681SAndroid Build Coastguard Worker return Builder.CreateGEP(nullptr, GEPBase, GEPOffset, "lftr.limit");
1863*9880d681SAndroid Build Coastguard Worker } else {
1864*9880d681SAndroid Build Coastguard Worker // In any other case, convert both IVInit and IVCount to integers before
1865*9880d681SAndroid Build Coastguard Worker // comparing. This may result in SCEV expension of pointers, but in practice
1866*9880d681SAndroid Build Coastguard Worker // SCEV will fold the pointer arithmetic away as such:
1867*9880d681SAndroid Build Coastguard Worker // BECount = (IVEnd - IVInit - 1) => IVLimit = IVInit (postinc).
1868*9880d681SAndroid Build Coastguard Worker //
1869*9880d681SAndroid Build Coastguard Worker // Valid Cases: (1) both integers is most common; (2) both may be pointers
1870*9880d681SAndroid Build Coastguard Worker // for simple memset-style loops.
1871*9880d681SAndroid Build Coastguard Worker //
1872*9880d681SAndroid Build Coastguard Worker // IVInit integer and IVCount pointer would only occur if a canonical IV
1873*9880d681SAndroid Build Coastguard Worker // were generated on top of case #2, which is not expected.
1874*9880d681SAndroid Build Coastguard Worker
1875*9880d681SAndroid Build Coastguard Worker const SCEV *IVLimit = nullptr;
1876*9880d681SAndroid Build Coastguard Worker // For unit stride, IVCount = Start + BECount with 2's complement overflow.
1877*9880d681SAndroid Build Coastguard Worker // For non-zero Start, compute IVCount here.
1878*9880d681SAndroid Build Coastguard Worker if (AR->getStart()->isZero())
1879*9880d681SAndroid Build Coastguard Worker IVLimit = IVCount;
1880*9880d681SAndroid Build Coastguard Worker else {
1881*9880d681SAndroid Build Coastguard Worker assert(AR->getStepRecurrence(*SE)->isOne() && "only handles unit stride");
1882*9880d681SAndroid Build Coastguard Worker const SCEV *IVInit = AR->getStart();
1883*9880d681SAndroid Build Coastguard Worker
1884*9880d681SAndroid Build Coastguard Worker // For integer IVs, truncate the IV before computing IVInit + BECount.
1885*9880d681SAndroid Build Coastguard Worker if (SE->getTypeSizeInBits(IVInit->getType())
1886*9880d681SAndroid Build Coastguard Worker > SE->getTypeSizeInBits(IVCount->getType()))
1887*9880d681SAndroid Build Coastguard Worker IVInit = SE->getTruncateExpr(IVInit, IVCount->getType());
1888*9880d681SAndroid Build Coastguard Worker
1889*9880d681SAndroid Build Coastguard Worker IVLimit = SE->getAddExpr(IVInit, IVCount);
1890*9880d681SAndroid Build Coastguard Worker }
1891*9880d681SAndroid Build Coastguard Worker // Expand the code for the iteration count.
1892*9880d681SAndroid Build Coastguard Worker BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator());
1893*9880d681SAndroid Build Coastguard Worker IRBuilder<> Builder(BI);
1894*9880d681SAndroid Build Coastguard Worker assert(SE->isLoopInvariant(IVLimit, L) &&
1895*9880d681SAndroid Build Coastguard Worker "Computed iteration count is not loop invariant!");
1896*9880d681SAndroid Build Coastguard Worker // Ensure that we generate the same type as IndVar, or a smaller integer
1897*9880d681SAndroid Build Coastguard Worker // type. In the presence of null pointer values, we have an integer type
1898*9880d681SAndroid Build Coastguard Worker // SCEV expression (IVInit) for a pointer type IV value (IndVar).
1899*9880d681SAndroid Build Coastguard Worker Type *LimitTy = IVCount->getType()->isPointerTy() ?
1900*9880d681SAndroid Build Coastguard Worker IndVar->getType() : IVCount->getType();
1901*9880d681SAndroid Build Coastguard Worker return Rewriter.expandCodeFor(IVLimit, LimitTy, BI);
1902*9880d681SAndroid Build Coastguard Worker }
1903*9880d681SAndroid Build Coastguard Worker }
1904*9880d681SAndroid Build Coastguard Worker
1905*9880d681SAndroid Build Coastguard Worker /// This method rewrites the exit condition of the loop to be a canonical !=
1906*9880d681SAndroid Build Coastguard Worker /// comparison against the incremented loop induction variable. This pass is
1907*9880d681SAndroid Build Coastguard Worker /// able to rewrite the exit tests of any loop where the SCEV analysis can
1908*9880d681SAndroid Build Coastguard Worker /// determine a loop-invariant trip count of the loop, which is actually a much
1909*9880d681SAndroid Build Coastguard Worker /// broader range than just linear tests.
1910*9880d681SAndroid Build Coastguard Worker Value *IndVarSimplify::
linearFunctionTestReplace(Loop * L,const SCEV * BackedgeTakenCount,PHINode * IndVar,SCEVExpander & Rewriter)1911*9880d681SAndroid Build Coastguard Worker linearFunctionTestReplace(Loop *L,
1912*9880d681SAndroid Build Coastguard Worker const SCEV *BackedgeTakenCount,
1913*9880d681SAndroid Build Coastguard Worker PHINode *IndVar,
1914*9880d681SAndroid Build Coastguard Worker SCEVExpander &Rewriter) {
1915*9880d681SAndroid Build Coastguard Worker assert(canExpandBackedgeTakenCount(L, SE, Rewriter) && "precondition");
1916*9880d681SAndroid Build Coastguard Worker
1917*9880d681SAndroid Build Coastguard Worker // Initialize CmpIndVar and IVCount to their preincremented values.
1918*9880d681SAndroid Build Coastguard Worker Value *CmpIndVar = IndVar;
1919*9880d681SAndroid Build Coastguard Worker const SCEV *IVCount = BackedgeTakenCount;
1920*9880d681SAndroid Build Coastguard Worker
1921*9880d681SAndroid Build Coastguard Worker // If the exiting block is the same as the backedge block, we prefer to
1922*9880d681SAndroid Build Coastguard Worker // compare against the post-incremented value, otherwise we must compare
1923*9880d681SAndroid Build Coastguard Worker // against the preincremented value.
1924*9880d681SAndroid Build Coastguard Worker if (L->getExitingBlock() == L->getLoopLatch()) {
1925*9880d681SAndroid Build Coastguard Worker // Add one to the "backedge-taken" count to get the trip count.
1926*9880d681SAndroid Build Coastguard Worker // This addition may overflow, which is valid as long as the comparison is
1927*9880d681SAndroid Build Coastguard Worker // truncated to BackedgeTakenCount->getType().
1928*9880d681SAndroid Build Coastguard Worker IVCount = SE->getAddExpr(BackedgeTakenCount,
1929*9880d681SAndroid Build Coastguard Worker SE->getOne(BackedgeTakenCount->getType()));
1930*9880d681SAndroid Build Coastguard Worker // The BackedgeTaken expression contains the number of times that the
1931*9880d681SAndroid Build Coastguard Worker // backedge branches to the loop header. This is one less than the
1932*9880d681SAndroid Build Coastguard Worker // number of times the loop executes, so use the incremented indvar.
1933*9880d681SAndroid Build Coastguard Worker CmpIndVar = IndVar->getIncomingValueForBlock(L->getExitingBlock());
1934*9880d681SAndroid Build Coastguard Worker }
1935*9880d681SAndroid Build Coastguard Worker
1936*9880d681SAndroid Build Coastguard Worker Value *ExitCnt = genLoopLimit(IndVar, IVCount, L, Rewriter, SE);
1937*9880d681SAndroid Build Coastguard Worker assert(ExitCnt->getType()->isPointerTy() ==
1938*9880d681SAndroid Build Coastguard Worker IndVar->getType()->isPointerTy() &&
1939*9880d681SAndroid Build Coastguard Worker "genLoopLimit missed a cast");
1940*9880d681SAndroid Build Coastguard Worker
1941*9880d681SAndroid Build Coastguard Worker // Insert a new icmp_ne or icmp_eq instruction before the branch.
1942*9880d681SAndroid Build Coastguard Worker BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator());
1943*9880d681SAndroid Build Coastguard Worker ICmpInst::Predicate P;
1944*9880d681SAndroid Build Coastguard Worker if (L->contains(BI->getSuccessor(0)))
1945*9880d681SAndroid Build Coastguard Worker P = ICmpInst::ICMP_NE;
1946*9880d681SAndroid Build Coastguard Worker else
1947*9880d681SAndroid Build Coastguard Worker P = ICmpInst::ICMP_EQ;
1948*9880d681SAndroid Build Coastguard Worker
1949*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "INDVARS: Rewriting loop exit condition to:\n"
1950*9880d681SAndroid Build Coastguard Worker << " LHS:" << *CmpIndVar << '\n'
1951*9880d681SAndroid Build Coastguard Worker << " op:\t"
1952*9880d681SAndroid Build Coastguard Worker << (P == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
1953*9880d681SAndroid Build Coastguard Worker << " RHS:\t" << *ExitCnt << "\n"
1954*9880d681SAndroid Build Coastguard Worker << " IVCount:\t" << *IVCount << "\n");
1955*9880d681SAndroid Build Coastguard Worker
1956*9880d681SAndroid Build Coastguard Worker IRBuilder<> Builder(BI);
1957*9880d681SAndroid Build Coastguard Worker
1958*9880d681SAndroid Build Coastguard Worker // LFTR can ignore IV overflow and truncate to the width of
1959*9880d681SAndroid Build Coastguard Worker // BECount. This avoids materializing the add(zext(add)) expression.
1960*9880d681SAndroid Build Coastguard Worker unsigned CmpIndVarSize = SE->getTypeSizeInBits(CmpIndVar->getType());
1961*9880d681SAndroid Build Coastguard Worker unsigned ExitCntSize = SE->getTypeSizeInBits(ExitCnt->getType());
1962*9880d681SAndroid Build Coastguard Worker if (CmpIndVarSize > ExitCntSize) {
1963*9880d681SAndroid Build Coastguard Worker const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(SE->getSCEV(IndVar));
1964*9880d681SAndroid Build Coastguard Worker const SCEV *ARStart = AR->getStart();
1965*9880d681SAndroid Build Coastguard Worker const SCEV *ARStep = AR->getStepRecurrence(*SE);
1966*9880d681SAndroid Build Coastguard Worker // For constant IVCount, avoid truncation.
1967*9880d681SAndroid Build Coastguard Worker if (isa<SCEVConstant>(ARStart) && isa<SCEVConstant>(IVCount)) {
1968*9880d681SAndroid Build Coastguard Worker const APInt &Start = cast<SCEVConstant>(ARStart)->getAPInt();
1969*9880d681SAndroid Build Coastguard Worker APInt Count = cast<SCEVConstant>(IVCount)->getAPInt();
1970*9880d681SAndroid Build Coastguard Worker // Note that the post-inc value of BackedgeTakenCount may have overflowed
1971*9880d681SAndroid Build Coastguard Worker // above such that IVCount is now zero.
1972*9880d681SAndroid Build Coastguard Worker if (IVCount != BackedgeTakenCount && Count == 0) {
1973*9880d681SAndroid Build Coastguard Worker Count = APInt::getMaxValue(Count.getBitWidth()).zext(CmpIndVarSize);
1974*9880d681SAndroid Build Coastguard Worker ++Count;
1975*9880d681SAndroid Build Coastguard Worker }
1976*9880d681SAndroid Build Coastguard Worker else
1977*9880d681SAndroid Build Coastguard Worker Count = Count.zext(CmpIndVarSize);
1978*9880d681SAndroid Build Coastguard Worker APInt NewLimit;
1979*9880d681SAndroid Build Coastguard Worker if (cast<SCEVConstant>(ARStep)->getValue()->isNegative())
1980*9880d681SAndroid Build Coastguard Worker NewLimit = Start - Count;
1981*9880d681SAndroid Build Coastguard Worker else
1982*9880d681SAndroid Build Coastguard Worker NewLimit = Start + Count;
1983*9880d681SAndroid Build Coastguard Worker ExitCnt = ConstantInt::get(CmpIndVar->getType(), NewLimit);
1984*9880d681SAndroid Build Coastguard Worker
1985*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << " Widen RHS:\t" << *ExitCnt << "\n");
1986*9880d681SAndroid Build Coastguard Worker } else {
1987*9880d681SAndroid Build Coastguard Worker CmpIndVar = Builder.CreateTrunc(CmpIndVar, ExitCnt->getType(),
1988*9880d681SAndroid Build Coastguard Worker "lftr.wideiv");
1989*9880d681SAndroid Build Coastguard Worker }
1990*9880d681SAndroid Build Coastguard Worker }
1991*9880d681SAndroid Build Coastguard Worker Value *Cond = Builder.CreateICmp(P, CmpIndVar, ExitCnt, "exitcond");
1992*9880d681SAndroid Build Coastguard Worker Value *OrigCond = BI->getCondition();
1993*9880d681SAndroid Build Coastguard Worker // It's tempting to use replaceAllUsesWith here to fully replace the old
1994*9880d681SAndroid Build Coastguard Worker // comparison, but that's not immediately safe, since users of the old
1995*9880d681SAndroid Build Coastguard Worker // comparison may not be dominated by the new comparison. Instead, just
1996*9880d681SAndroid Build Coastguard Worker // update the branch to use the new comparison; in the common case this
1997*9880d681SAndroid Build Coastguard Worker // will make old comparison dead.
1998*9880d681SAndroid Build Coastguard Worker BI->setCondition(Cond);
1999*9880d681SAndroid Build Coastguard Worker DeadInsts.push_back(OrigCond);
2000*9880d681SAndroid Build Coastguard Worker
2001*9880d681SAndroid Build Coastguard Worker ++NumLFTR;
2002*9880d681SAndroid Build Coastguard Worker Changed = true;
2003*9880d681SAndroid Build Coastguard Worker return Cond;
2004*9880d681SAndroid Build Coastguard Worker }
2005*9880d681SAndroid Build Coastguard Worker
2006*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
2007*9880d681SAndroid Build Coastguard Worker // sinkUnusedInvariants. A late subpass to cleanup loop preheaders.
2008*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
2009*9880d681SAndroid Build Coastguard Worker
2010*9880d681SAndroid Build Coastguard Worker /// If there's a single exit block, sink any loop-invariant values that
2011*9880d681SAndroid Build Coastguard Worker /// were defined in the preheader but not used inside the loop into the
2012*9880d681SAndroid Build Coastguard Worker /// exit block to reduce register pressure in the loop.
sinkUnusedInvariants(Loop * L)2013*9880d681SAndroid Build Coastguard Worker void IndVarSimplify::sinkUnusedInvariants(Loop *L) {
2014*9880d681SAndroid Build Coastguard Worker BasicBlock *ExitBlock = L->getExitBlock();
2015*9880d681SAndroid Build Coastguard Worker if (!ExitBlock) return;
2016*9880d681SAndroid Build Coastguard Worker
2017*9880d681SAndroid Build Coastguard Worker BasicBlock *Preheader = L->getLoopPreheader();
2018*9880d681SAndroid Build Coastguard Worker if (!Preheader) return;
2019*9880d681SAndroid Build Coastguard Worker
2020*9880d681SAndroid Build Coastguard Worker Instruction *InsertPt = &*ExitBlock->getFirstInsertionPt();
2021*9880d681SAndroid Build Coastguard Worker BasicBlock::iterator I(Preheader->getTerminator());
2022*9880d681SAndroid Build Coastguard Worker while (I != Preheader->begin()) {
2023*9880d681SAndroid Build Coastguard Worker --I;
2024*9880d681SAndroid Build Coastguard Worker // New instructions were inserted at the end of the preheader.
2025*9880d681SAndroid Build Coastguard Worker if (isa<PHINode>(I))
2026*9880d681SAndroid Build Coastguard Worker break;
2027*9880d681SAndroid Build Coastguard Worker
2028*9880d681SAndroid Build Coastguard Worker // Don't move instructions which might have side effects, since the side
2029*9880d681SAndroid Build Coastguard Worker // effects need to complete before instructions inside the loop. Also don't
2030*9880d681SAndroid Build Coastguard Worker // move instructions which might read memory, since the loop may modify
2031*9880d681SAndroid Build Coastguard Worker // memory. Note that it's okay if the instruction might have undefined
2032*9880d681SAndroid Build Coastguard Worker // behavior: LoopSimplify guarantees that the preheader dominates the exit
2033*9880d681SAndroid Build Coastguard Worker // block.
2034*9880d681SAndroid Build Coastguard Worker if (I->mayHaveSideEffects() || I->mayReadFromMemory())
2035*9880d681SAndroid Build Coastguard Worker continue;
2036*9880d681SAndroid Build Coastguard Worker
2037*9880d681SAndroid Build Coastguard Worker // Skip debug info intrinsics.
2038*9880d681SAndroid Build Coastguard Worker if (isa<DbgInfoIntrinsic>(I))
2039*9880d681SAndroid Build Coastguard Worker continue;
2040*9880d681SAndroid Build Coastguard Worker
2041*9880d681SAndroid Build Coastguard Worker // Skip eh pad instructions.
2042*9880d681SAndroid Build Coastguard Worker if (I->isEHPad())
2043*9880d681SAndroid Build Coastguard Worker continue;
2044*9880d681SAndroid Build Coastguard Worker
2045*9880d681SAndroid Build Coastguard Worker // Don't sink alloca: we never want to sink static alloca's out of the
2046*9880d681SAndroid Build Coastguard Worker // entry block, and correctly sinking dynamic alloca's requires
2047*9880d681SAndroid Build Coastguard Worker // checks for stacksave/stackrestore intrinsics.
2048*9880d681SAndroid Build Coastguard Worker // FIXME: Refactor this check somehow?
2049*9880d681SAndroid Build Coastguard Worker if (isa<AllocaInst>(I))
2050*9880d681SAndroid Build Coastguard Worker continue;
2051*9880d681SAndroid Build Coastguard Worker
2052*9880d681SAndroid Build Coastguard Worker // Determine if there is a use in or before the loop (direct or
2053*9880d681SAndroid Build Coastguard Worker // otherwise).
2054*9880d681SAndroid Build Coastguard Worker bool UsedInLoop = false;
2055*9880d681SAndroid Build Coastguard Worker for (Use &U : I->uses()) {
2056*9880d681SAndroid Build Coastguard Worker Instruction *User = cast<Instruction>(U.getUser());
2057*9880d681SAndroid Build Coastguard Worker BasicBlock *UseBB = User->getParent();
2058*9880d681SAndroid Build Coastguard Worker if (PHINode *P = dyn_cast<PHINode>(User)) {
2059*9880d681SAndroid Build Coastguard Worker unsigned i =
2060*9880d681SAndroid Build Coastguard Worker PHINode::getIncomingValueNumForOperand(U.getOperandNo());
2061*9880d681SAndroid Build Coastguard Worker UseBB = P->getIncomingBlock(i);
2062*9880d681SAndroid Build Coastguard Worker }
2063*9880d681SAndroid Build Coastguard Worker if (UseBB == Preheader || L->contains(UseBB)) {
2064*9880d681SAndroid Build Coastguard Worker UsedInLoop = true;
2065*9880d681SAndroid Build Coastguard Worker break;
2066*9880d681SAndroid Build Coastguard Worker }
2067*9880d681SAndroid Build Coastguard Worker }
2068*9880d681SAndroid Build Coastguard Worker
2069*9880d681SAndroid Build Coastguard Worker // If there is, the def must remain in the preheader.
2070*9880d681SAndroid Build Coastguard Worker if (UsedInLoop)
2071*9880d681SAndroid Build Coastguard Worker continue;
2072*9880d681SAndroid Build Coastguard Worker
2073*9880d681SAndroid Build Coastguard Worker // Otherwise, sink it to the exit block.
2074*9880d681SAndroid Build Coastguard Worker Instruction *ToMove = &*I;
2075*9880d681SAndroid Build Coastguard Worker bool Done = false;
2076*9880d681SAndroid Build Coastguard Worker
2077*9880d681SAndroid Build Coastguard Worker if (I != Preheader->begin()) {
2078*9880d681SAndroid Build Coastguard Worker // Skip debug info intrinsics.
2079*9880d681SAndroid Build Coastguard Worker do {
2080*9880d681SAndroid Build Coastguard Worker --I;
2081*9880d681SAndroid Build Coastguard Worker } while (isa<DbgInfoIntrinsic>(I) && I != Preheader->begin());
2082*9880d681SAndroid Build Coastguard Worker
2083*9880d681SAndroid Build Coastguard Worker if (isa<DbgInfoIntrinsic>(I) && I == Preheader->begin())
2084*9880d681SAndroid Build Coastguard Worker Done = true;
2085*9880d681SAndroid Build Coastguard Worker } else {
2086*9880d681SAndroid Build Coastguard Worker Done = true;
2087*9880d681SAndroid Build Coastguard Worker }
2088*9880d681SAndroid Build Coastguard Worker
2089*9880d681SAndroid Build Coastguard Worker ToMove->moveBefore(InsertPt);
2090*9880d681SAndroid Build Coastguard Worker if (Done) break;
2091*9880d681SAndroid Build Coastguard Worker InsertPt = ToMove;
2092*9880d681SAndroid Build Coastguard Worker }
2093*9880d681SAndroid Build Coastguard Worker }
2094*9880d681SAndroid Build Coastguard Worker
2095*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
2096*9880d681SAndroid Build Coastguard Worker // IndVarSimplify driver. Manage several subpasses of IV simplification.
2097*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
2098*9880d681SAndroid Build Coastguard Worker
run(Loop * L)2099*9880d681SAndroid Build Coastguard Worker bool IndVarSimplify::run(Loop *L) {
2100*9880d681SAndroid Build Coastguard Worker // We need (and expect!) the incoming loop to be in LCSSA.
2101*9880d681SAndroid Build Coastguard Worker assert(L->isRecursivelyLCSSAForm(*DT) && "LCSSA required to run indvars!");
2102*9880d681SAndroid Build Coastguard Worker
2103*9880d681SAndroid Build Coastguard Worker // If LoopSimplify form is not available, stay out of trouble. Some notes:
2104*9880d681SAndroid Build Coastguard Worker // - LSR currently only supports LoopSimplify-form loops. Indvars'
2105*9880d681SAndroid Build Coastguard Worker // canonicalization can be a pessimization without LSR to "clean up"
2106*9880d681SAndroid Build Coastguard Worker // afterwards.
2107*9880d681SAndroid Build Coastguard Worker // - We depend on having a preheader; in particular,
2108*9880d681SAndroid Build Coastguard Worker // Loop::getCanonicalInductionVariable only supports loops with preheaders,
2109*9880d681SAndroid Build Coastguard Worker // and we're in trouble if we can't find the induction variable even when
2110*9880d681SAndroid Build Coastguard Worker // we've manually inserted one.
2111*9880d681SAndroid Build Coastguard Worker if (!L->isLoopSimplifyForm())
2112*9880d681SAndroid Build Coastguard Worker return false;
2113*9880d681SAndroid Build Coastguard Worker
2114*9880d681SAndroid Build Coastguard Worker // If there are any floating-point recurrences, attempt to
2115*9880d681SAndroid Build Coastguard Worker // transform them to use integer recurrences.
2116*9880d681SAndroid Build Coastguard Worker rewriteNonIntegerIVs(L);
2117*9880d681SAndroid Build Coastguard Worker
2118*9880d681SAndroid Build Coastguard Worker const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
2119*9880d681SAndroid Build Coastguard Worker
2120*9880d681SAndroid Build Coastguard Worker // Create a rewriter object which we'll use to transform the code with.
2121*9880d681SAndroid Build Coastguard Worker SCEVExpander Rewriter(*SE, DL, "indvars");
2122*9880d681SAndroid Build Coastguard Worker #ifndef NDEBUG
2123*9880d681SAndroid Build Coastguard Worker Rewriter.setDebugType(DEBUG_TYPE);
2124*9880d681SAndroid Build Coastguard Worker #endif
2125*9880d681SAndroid Build Coastguard Worker
2126*9880d681SAndroid Build Coastguard Worker // Eliminate redundant IV users.
2127*9880d681SAndroid Build Coastguard Worker //
2128*9880d681SAndroid Build Coastguard Worker // Simplification works best when run before other consumers of SCEV. We
2129*9880d681SAndroid Build Coastguard Worker // attempt to avoid evaluating SCEVs for sign/zero extend operations until
2130*9880d681SAndroid Build Coastguard Worker // other expressions involving loop IVs have been evaluated. This helps SCEV
2131*9880d681SAndroid Build Coastguard Worker // set no-wrap flags before normalizing sign/zero extension.
2132*9880d681SAndroid Build Coastguard Worker Rewriter.disableCanonicalMode();
2133*9880d681SAndroid Build Coastguard Worker simplifyAndExtend(L, Rewriter, LI);
2134*9880d681SAndroid Build Coastguard Worker
2135*9880d681SAndroid Build Coastguard Worker // Check to see if this loop has a computable loop-invariant execution count.
2136*9880d681SAndroid Build Coastguard Worker // If so, this means that we can compute the final value of any expressions
2137*9880d681SAndroid Build Coastguard Worker // that are recurrent in the loop, and substitute the exit values from the
2138*9880d681SAndroid Build Coastguard Worker // loop into any instructions outside of the loop that use the final values of
2139*9880d681SAndroid Build Coastguard Worker // the current expressions.
2140*9880d681SAndroid Build Coastguard Worker //
2141*9880d681SAndroid Build Coastguard Worker if (ReplaceExitValue != NeverRepl &&
2142*9880d681SAndroid Build Coastguard Worker !isa<SCEVCouldNotCompute>(BackedgeTakenCount))
2143*9880d681SAndroid Build Coastguard Worker rewriteLoopExitValues(L, Rewriter);
2144*9880d681SAndroid Build Coastguard Worker
2145*9880d681SAndroid Build Coastguard Worker // Eliminate redundant IV cycles.
2146*9880d681SAndroid Build Coastguard Worker NumElimIV += Rewriter.replaceCongruentIVs(L, DT, DeadInsts);
2147*9880d681SAndroid Build Coastguard Worker
2148*9880d681SAndroid Build Coastguard Worker // If we have a trip count expression, rewrite the loop's exit condition
2149*9880d681SAndroid Build Coastguard Worker // using it. We can currently only handle loops with a single exit.
2150*9880d681SAndroid Build Coastguard Worker if (canExpandBackedgeTakenCount(L, SE, Rewriter) && needsLFTR(L, DT)) {
2151*9880d681SAndroid Build Coastguard Worker PHINode *IndVar = FindLoopCounter(L, BackedgeTakenCount, SE, DT);
2152*9880d681SAndroid Build Coastguard Worker if (IndVar) {
2153*9880d681SAndroid Build Coastguard Worker // Check preconditions for proper SCEVExpander operation. SCEV does not
2154*9880d681SAndroid Build Coastguard Worker // express SCEVExpander's dependencies, such as LoopSimplify. Instead any
2155*9880d681SAndroid Build Coastguard Worker // pass that uses the SCEVExpander must do it. This does not work well for
2156*9880d681SAndroid Build Coastguard Worker // loop passes because SCEVExpander makes assumptions about all loops,
2157*9880d681SAndroid Build Coastguard Worker // while LoopPassManager only forces the current loop to be simplified.
2158*9880d681SAndroid Build Coastguard Worker //
2159*9880d681SAndroid Build Coastguard Worker // FIXME: SCEV expansion has no way to bail out, so the caller must
2160*9880d681SAndroid Build Coastguard Worker // explicitly check any assumptions made by SCEV. Brittle.
2161*9880d681SAndroid Build Coastguard Worker const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(BackedgeTakenCount);
2162*9880d681SAndroid Build Coastguard Worker if (!AR || AR->getLoop()->getLoopPreheader())
2163*9880d681SAndroid Build Coastguard Worker (void)linearFunctionTestReplace(L, BackedgeTakenCount, IndVar,
2164*9880d681SAndroid Build Coastguard Worker Rewriter);
2165*9880d681SAndroid Build Coastguard Worker }
2166*9880d681SAndroid Build Coastguard Worker }
2167*9880d681SAndroid Build Coastguard Worker // Clear the rewriter cache, because values that are in the rewriter's cache
2168*9880d681SAndroid Build Coastguard Worker // can be deleted in the loop below, causing the AssertingVH in the cache to
2169*9880d681SAndroid Build Coastguard Worker // trigger.
2170*9880d681SAndroid Build Coastguard Worker Rewriter.clear();
2171*9880d681SAndroid Build Coastguard Worker
2172*9880d681SAndroid Build Coastguard Worker // Now that we're done iterating through lists, clean up any instructions
2173*9880d681SAndroid Build Coastguard Worker // which are now dead.
2174*9880d681SAndroid Build Coastguard Worker while (!DeadInsts.empty())
2175*9880d681SAndroid Build Coastguard Worker if (Instruction *Inst =
2176*9880d681SAndroid Build Coastguard Worker dyn_cast_or_null<Instruction>(DeadInsts.pop_back_val()))
2177*9880d681SAndroid Build Coastguard Worker RecursivelyDeleteTriviallyDeadInstructions(Inst, TLI);
2178*9880d681SAndroid Build Coastguard Worker
2179*9880d681SAndroid Build Coastguard Worker // The Rewriter may not be used from this point on.
2180*9880d681SAndroid Build Coastguard Worker
2181*9880d681SAndroid Build Coastguard Worker // Loop-invariant instructions in the preheader that aren't used in the
2182*9880d681SAndroid Build Coastguard Worker // loop may be sunk below the loop to reduce register pressure.
2183*9880d681SAndroid Build Coastguard Worker sinkUnusedInvariants(L);
2184*9880d681SAndroid Build Coastguard Worker
2185*9880d681SAndroid Build Coastguard Worker // rewriteFirstIterationLoopExitValues does not rely on the computation of
2186*9880d681SAndroid Build Coastguard Worker // trip count and therefore can further simplify exit values in addition to
2187*9880d681SAndroid Build Coastguard Worker // rewriteLoopExitValues.
2188*9880d681SAndroid Build Coastguard Worker rewriteFirstIterationLoopExitValues(L);
2189*9880d681SAndroid Build Coastguard Worker
2190*9880d681SAndroid Build Coastguard Worker // Clean up dead instructions.
2191*9880d681SAndroid Build Coastguard Worker Changed |= DeleteDeadPHIs(L->getHeader(), TLI);
2192*9880d681SAndroid Build Coastguard Worker
2193*9880d681SAndroid Build Coastguard Worker // Check a post-condition.
2194*9880d681SAndroid Build Coastguard Worker assert(L->isRecursivelyLCSSAForm(*DT) && "Indvars did not preserve LCSSA!");
2195*9880d681SAndroid Build Coastguard Worker
2196*9880d681SAndroid Build Coastguard Worker // Verify that LFTR, and any other change have not interfered with SCEV's
2197*9880d681SAndroid Build Coastguard Worker // ability to compute trip count.
2198*9880d681SAndroid Build Coastguard Worker #ifndef NDEBUG
2199*9880d681SAndroid Build Coastguard Worker if (VerifyIndvars && !isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
2200*9880d681SAndroid Build Coastguard Worker SE->forgetLoop(L);
2201*9880d681SAndroid Build Coastguard Worker const SCEV *NewBECount = SE->getBackedgeTakenCount(L);
2202*9880d681SAndroid Build Coastguard Worker if (SE->getTypeSizeInBits(BackedgeTakenCount->getType()) <
2203*9880d681SAndroid Build Coastguard Worker SE->getTypeSizeInBits(NewBECount->getType()))
2204*9880d681SAndroid Build Coastguard Worker NewBECount = SE->getTruncateOrNoop(NewBECount,
2205*9880d681SAndroid Build Coastguard Worker BackedgeTakenCount->getType());
2206*9880d681SAndroid Build Coastguard Worker else
2207*9880d681SAndroid Build Coastguard Worker BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount,
2208*9880d681SAndroid Build Coastguard Worker NewBECount->getType());
2209*9880d681SAndroid Build Coastguard Worker assert(BackedgeTakenCount == NewBECount && "indvars must preserve SCEV");
2210*9880d681SAndroid Build Coastguard Worker }
2211*9880d681SAndroid Build Coastguard Worker #endif
2212*9880d681SAndroid Build Coastguard Worker
2213*9880d681SAndroid Build Coastguard Worker return Changed;
2214*9880d681SAndroid Build Coastguard Worker }
2215*9880d681SAndroid Build Coastguard Worker
run(Loop & L,AnalysisManager<Loop> & AM)2216*9880d681SAndroid Build Coastguard Worker PreservedAnalyses IndVarSimplifyPass::run(Loop &L, AnalysisManager<Loop> &AM) {
2217*9880d681SAndroid Build Coastguard Worker auto &FAM = AM.getResult<FunctionAnalysisManagerLoopProxy>(L).getManager();
2218*9880d681SAndroid Build Coastguard Worker Function *F = L.getHeader()->getParent();
2219*9880d681SAndroid Build Coastguard Worker const DataLayout &DL = F->getParent()->getDataLayout();
2220*9880d681SAndroid Build Coastguard Worker
2221*9880d681SAndroid Build Coastguard Worker auto *LI = FAM.getCachedResult<LoopAnalysis>(*F);
2222*9880d681SAndroid Build Coastguard Worker auto *SE = FAM.getCachedResult<ScalarEvolutionAnalysis>(*F);
2223*9880d681SAndroid Build Coastguard Worker auto *DT = FAM.getCachedResult<DominatorTreeAnalysis>(*F);
2224*9880d681SAndroid Build Coastguard Worker
2225*9880d681SAndroid Build Coastguard Worker assert((LI && SE && DT) &&
2226*9880d681SAndroid Build Coastguard Worker "Analyses required for indvarsimplify not available!");
2227*9880d681SAndroid Build Coastguard Worker
2228*9880d681SAndroid Build Coastguard Worker // Optional analyses.
2229*9880d681SAndroid Build Coastguard Worker auto *TTI = FAM.getCachedResult<TargetIRAnalysis>(*F);
2230*9880d681SAndroid Build Coastguard Worker auto *TLI = FAM.getCachedResult<TargetLibraryAnalysis>(*F);
2231*9880d681SAndroid Build Coastguard Worker
2232*9880d681SAndroid Build Coastguard Worker IndVarSimplify IVS(LI, SE, DT, DL, TLI, TTI);
2233*9880d681SAndroid Build Coastguard Worker if (!IVS.run(&L))
2234*9880d681SAndroid Build Coastguard Worker return PreservedAnalyses::all();
2235*9880d681SAndroid Build Coastguard Worker
2236*9880d681SAndroid Build Coastguard Worker // FIXME: This should also 'preserve the CFG'.
2237*9880d681SAndroid Build Coastguard Worker return getLoopPassPreservedAnalyses();
2238*9880d681SAndroid Build Coastguard Worker }
2239*9880d681SAndroid Build Coastguard Worker
2240*9880d681SAndroid Build Coastguard Worker namespace {
2241*9880d681SAndroid Build Coastguard Worker struct IndVarSimplifyLegacyPass : public LoopPass {
2242*9880d681SAndroid Build Coastguard Worker static char ID; // Pass identification, replacement for typeid
IndVarSimplifyLegacyPass__anoncba0d73c0911::IndVarSimplifyLegacyPass2243*9880d681SAndroid Build Coastguard Worker IndVarSimplifyLegacyPass() : LoopPass(ID) {
2244*9880d681SAndroid Build Coastguard Worker initializeIndVarSimplifyLegacyPassPass(*PassRegistry::getPassRegistry());
2245*9880d681SAndroid Build Coastguard Worker }
2246*9880d681SAndroid Build Coastguard Worker
runOnLoop__anoncba0d73c0911::IndVarSimplifyLegacyPass2247*9880d681SAndroid Build Coastguard Worker bool runOnLoop(Loop *L, LPPassManager &LPM) override {
2248*9880d681SAndroid Build Coastguard Worker if (skipLoop(L))
2249*9880d681SAndroid Build Coastguard Worker return false;
2250*9880d681SAndroid Build Coastguard Worker
2251*9880d681SAndroid Build Coastguard Worker auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2252*9880d681SAndroid Build Coastguard Worker auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
2253*9880d681SAndroid Build Coastguard Worker auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2254*9880d681SAndroid Build Coastguard Worker auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
2255*9880d681SAndroid Build Coastguard Worker auto *TLI = TLIP ? &TLIP->getTLI() : nullptr;
2256*9880d681SAndroid Build Coastguard Worker auto *TTIP = getAnalysisIfAvailable<TargetTransformInfoWrapperPass>();
2257*9880d681SAndroid Build Coastguard Worker auto *TTI = TTIP ? &TTIP->getTTI(*L->getHeader()->getParent()) : nullptr;
2258*9880d681SAndroid Build Coastguard Worker const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
2259*9880d681SAndroid Build Coastguard Worker
2260*9880d681SAndroid Build Coastguard Worker IndVarSimplify IVS(LI, SE, DT, DL, TLI, TTI);
2261*9880d681SAndroid Build Coastguard Worker return IVS.run(L);
2262*9880d681SAndroid Build Coastguard Worker }
2263*9880d681SAndroid Build Coastguard Worker
getAnalysisUsage__anoncba0d73c0911::IndVarSimplifyLegacyPass2264*9880d681SAndroid Build Coastguard Worker void getAnalysisUsage(AnalysisUsage &AU) const override {
2265*9880d681SAndroid Build Coastguard Worker AU.setPreservesCFG();
2266*9880d681SAndroid Build Coastguard Worker getLoopAnalysisUsage(AU);
2267*9880d681SAndroid Build Coastguard Worker }
2268*9880d681SAndroid Build Coastguard Worker };
2269*9880d681SAndroid Build Coastguard Worker }
2270*9880d681SAndroid Build Coastguard Worker
2271*9880d681SAndroid Build Coastguard Worker char IndVarSimplifyLegacyPass::ID = 0;
2272*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_BEGIN(IndVarSimplifyLegacyPass, "indvars",
2273*9880d681SAndroid Build Coastguard Worker "Induction Variable Simplification", false, false)
INITIALIZE_PASS_DEPENDENCY(LoopPass)2274*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(LoopPass)
2275*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_END(IndVarSimplifyLegacyPass, "indvars",
2276*9880d681SAndroid Build Coastguard Worker "Induction Variable Simplification", false, false)
2277*9880d681SAndroid Build Coastguard Worker
2278*9880d681SAndroid Build Coastguard Worker Pass *llvm::createIndVarSimplifyPass() {
2279*9880d681SAndroid Build Coastguard Worker return new IndVarSimplifyLegacyPass();
2280*9880d681SAndroid Build Coastguard Worker }
2281