xref: /freebsd-src/contrib/llvm-project/llvm/lib/Transforms/Scalar/LoopFlatten.cpp (revision 04eeddc0aa8e0a417a16eaf9d7d095207f4a8623)
1e8d8bef9SDimitry Andric //===- LoopFlatten.cpp - Loop flattening pass------------------------------===//
2e8d8bef9SDimitry Andric //
3e8d8bef9SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e8d8bef9SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e8d8bef9SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e8d8bef9SDimitry Andric //
7e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===//
8e8d8bef9SDimitry Andric //
9e8d8bef9SDimitry Andric // This pass flattens pairs nested loops into a single loop.
10e8d8bef9SDimitry Andric //
11e8d8bef9SDimitry Andric // The intention is to optimise loop nests like this, which together access an
12e8d8bef9SDimitry Andric // array linearly:
13*04eeddc0SDimitry Andric //
14e8d8bef9SDimitry Andric //   for (int i = 0; i < N; ++i)
15e8d8bef9SDimitry Andric //     for (int j = 0; j < M; ++j)
16e8d8bef9SDimitry Andric //       f(A[i*M+j]);
17*04eeddc0SDimitry Andric //
18e8d8bef9SDimitry Andric // into one loop:
19*04eeddc0SDimitry Andric //
20e8d8bef9SDimitry Andric //   for (int i = 0; i < (N*M); ++i)
21e8d8bef9SDimitry Andric //     f(A[i]);
22e8d8bef9SDimitry Andric //
23e8d8bef9SDimitry Andric // It can also flatten loops where the induction variables are not used in the
24e8d8bef9SDimitry Andric // loop. This is only worth doing if the induction variables are only used in an
25e8d8bef9SDimitry Andric // expression like i*M+j. If they had any other uses, we would have to insert a
26e8d8bef9SDimitry Andric // div/mod to reconstruct the original values, so this wouldn't be profitable.
27e8d8bef9SDimitry Andric //
28*04eeddc0SDimitry Andric // We also need to prove that N*M will not overflow. The preferred solution is
29*04eeddc0SDimitry Andric // to widen the IV, which avoids overflow checks, so that is tried first. If
30*04eeddc0SDimitry Andric // the IV cannot be widened, then we try to determine that this new tripcount
31*04eeddc0SDimitry Andric // expression won't overflow.
32*04eeddc0SDimitry Andric //
33*04eeddc0SDimitry Andric // Q: Does LoopFlatten use SCEV?
34*04eeddc0SDimitry Andric // Short answer: Yes and no.
35*04eeddc0SDimitry Andric //
36*04eeddc0SDimitry Andric // Long answer:
37*04eeddc0SDimitry Andric // For this transformation to be valid, we require all uses of the induction
38*04eeddc0SDimitry Andric // variables to be linear expressions of the form i*M+j. The different Loop
39*04eeddc0SDimitry Andric // APIs are used to get some loop components like the induction variable,
40*04eeddc0SDimitry Andric // compare statement, etc. In addition, we do some pattern matching to find the
41*04eeddc0SDimitry Andric // linear expressions and other loop components like the loop increment. The
42*04eeddc0SDimitry Andric // latter are examples of expressions that do use the induction variable, but
43*04eeddc0SDimitry Andric // are safe to ignore when we check all uses to be of the form i*M+j. We keep
44*04eeddc0SDimitry Andric // track of all of this in bookkeeping struct FlattenInfo.
45*04eeddc0SDimitry Andric // We assume the loops to be canonical, i.e. starting at 0 and increment with
46*04eeddc0SDimitry Andric // 1. This makes RHS of the compare the loop tripcount (with the right
47*04eeddc0SDimitry Andric // predicate). We use SCEV to then sanity check that this tripcount matches
48*04eeddc0SDimitry Andric // with the tripcount as computed by SCEV.
49e8d8bef9SDimitry Andric //
50e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===//
51e8d8bef9SDimitry Andric 
52e8d8bef9SDimitry Andric #include "llvm/Transforms/Scalar/LoopFlatten.h"
53349cc55cSDimitry Andric 
54349cc55cSDimitry Andric #include "llvm/ADT/Statistic.h"
55e8d8bef9SDimitry Andric #include "llvm/Analysis/AssumptionCache.h"
56e8d8bef9SDimitry Andric #include "llvm/Analysis/LoopInfo.h"
57*04eeddc0SDimitry Andric #include "llvm/Analysis/MemorySSAUpdater.h"
58e8d8bef9SDimitry Andric #include "llvm/Analysis/OptimizationRemarkEmitter.h"
59e8d8bef9SDimitry Andric #include "llvm/Analysis/ScalarEvolution.h"
60e8d8bef9SDimitry Andric #include "llvm/Analysis/TargetTransformInfo.h"
61e8d8bef9SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
62e8d8bef9SDimitry Andric #include "llvm/IR/Dominators.h"
63e8d8bef9SDimitry Andric #include "llvm/IR/Function.h"
64e8d8bef9SDimitry Andric #include "llvm/IR/IRBuilder.h"
65e8d8bef9SDimitry Andric #include "llvm/IR/Module.h"
66e8d8bef9SDimitry Andric #include "llvm/IR/PatternMatch.h"
67e8d8bef9SDimitry Andric #include "llvm/IR/Verifier.h"
68e8d8bef9SDimitry Andric #include "llvm/InitializePasses.h"
69e8d8bef9SDimitry Andric #include "llvm/Pass.h"
70e8d8bef9SDimitry Andric #include "llvm/Support/Debug.h"
71e8d8bef9SDimitry Andric #include "llvm/Support/raw_ostream.h"
72e8d8bef9SDimitry Andric #include "llvm/Transforms/Scalar.h"
73e8d8bef9SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
74e8d8bef9SDimitry Andric #include "llvm/Transforms/Utils/LoopUtils.h"
75e8d8bef9SDimitry Andric #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
76e8d8bef9SDimitry Andric #include "llvm/Transforms/Utils/SimplifyIndVar.h"
77e8d8bef9SDimitry Andric 
78e8d8bef9SDimitry Andric using namespace llvm;
79e8d8bef9SDimitry Andric using namespace llvm::PatternMatch;
80e8d8bef9SDimitry Andric 
81349cc55cSDimitry Andric #define DEBUG_TYPE "loop-flatten"
82349cc55cSDimitry Andric 
83349cc55cSDimitry Andric STATISTIC(NumFlattened, "Number of loops flattened");
84349cc55cSDimitry Andric 
85e8d8bef9SDimitry Andric static cl::opt<unsigned> RepeatedInstructionThreshold(
86e8d8bef9SDimitry Andric     "loop-flatten-cost-threshold", cl::Hidden, cl::init(2),
87e8d8bef9SDimitry Andric     cl::desc("Limit on the cost of instructions that can be repeated due to "
88e8d8bef9SDimitry Andric              "loop flattening"));
89e8d8bef9SDimitry Andric 
90e8d8bef9SDimitry Andric static cl::opt<bool>
91e8d8bef9SDimitry Andric     AssumeNoOverflow("loop-flatten-assume-no-overflow", cl::Hidden,
92e8d8bef9SDimitry Andric                      cl::init(false),
93e8d8bef9SDimitry Andric                      cl::desc("Assume that the product of the two iteration "
94fe6060f1SDimitry Andric                               "trip counts will never overflow"));
95e8d8bef9SDimitry Andric 
96e8d8bef9SDimitry Andric static cl::opt<bool>
97*04eeddc0SDimitry Andric     WidenIV("loop-flatten-widen-iv", cl::Hidden, cl::init(true),
98e8d8bef9SDimitry Andric             cl::desc("Widen the loop induction variables, if possible, so "
99e8d8bef9SDimitry Andric                      "overflow checks won't reject flattening"));
100e8d8bef9SDimitry Andric 
101*04eeddc0SDimitry Andric // We require all uses of both induction variables to match this pattern:
102*04eeddc0SDimitry Andric //
103*04eeddc0SDimitry Andric //   (OuterPHI * InnerTripCount) + InnerPHI
104*04eeddc0SDimitry Andric //
105*04eeddc0SDimitry Andric // I.e., it needs to be a linear expression of the induction variables and the
106*04eeddc0SDimitry Andric // inner loop trip count. We keep track of all different expressions on which
107*04eeddc0SDimitry Andric // checks will be performed in this bookkeeping struct.
108*04eeddc0SDimitry Andric //
109e8d8bef9SDimitry Andric struct FlattenInfo {
110*04eeddc0SDimitry Andric   Loop *OuterLoop = nullptr;  // The loop pair to be flattened.
111e8d8bef9SDimitry Andric   Loop *InnerLoop = nullptr;
112*04eeddc0SDimitry Andric 
113*04eeddc0SDimitry Andric   PHINode *InnerInductionPHI = nullptr; // These PHINodes correspond to loop
114*04eeddc0SDimitry Andric   PHINode *OuterInductionPHI = nullptr; // induction variables, which are
115*04eeddc0SDimitry Andric                                         // expected to start at zero and
116*04eeddc0SDimitry Andric                                         // increment by one on each loop.
117*04eeddc0SDimitry Andric 
118*04eeddc0SDimitry Andric   Value *InnerTripCount = nullptr; // The product of these two tripcounts
119*04eeddc0SDimitry Andric   Value *OuterTripCount = nullptr; // will be the new flattened loop
120*04eeddc0SDimitry Andric                                    // tripcount. Also used to recognise a
121*04eeddc0SDimitry Andric                                    // linear expression that will be replaced.
122*04eeddc0SDimitry Andric 
123*04eeddc0SDimitry Andric   SmallPtrSet<Value *, 4> LinearIVUses;  // Contains the linear expressions
124*04eeddc0SDimitry Andric                                          // of the form i*M+j that will be
125*04eeddc0SDimitry Andric                                          // replaced.
126*04eeddc0SDimitry Andric 
127*04eeddc0SDimitry Andric   BinaryOperator *InnerIncrement = nullptr;  // Uses of induction variables in
128*04eeddc0SDimitry Andric   BinaryOperator *OuterIncrement = nullptr;  // loop control statements that
129*04eeddc0SDimitry Andric   BranchInst *InnerBranch = nullptr;         // are safe to ignore.
130*04eeddc0SDimitry Andric 
131*04eeddc0SDimitry Andric   BranchInst *OuterBranch = nullptr; // The instruction that needs to be
132*04eeddc0SDimitry Andric                                      // updated with new tripcount.
133*04eeddc0SDimitry Andric 
134e8d8bef9SDimitry Andric   SmallPtrSet<PHINode *, 4> InnerPHIsToTransform;
135e8d8bef9SDimitry Andric 
136*04eeddc0SDimitry Andric   bool Widened = false; // Whether this holds the flatten info before or after
137*04eeddc0SDimitry Andric                         // widening.
138e8d8bef9SDimitry Andric 
139*04eeddc0SDimitry Andric   PHINode *NarrowInnerInductionPHI = nullptr; // Holds the old/narrow induction
140*04eeddc0SDimitry Andric   PHINode *NarrowOuterInductionPHI = nullptr; // phis, i.e. the Phis before IV
141*04eeddc0SDimitry Andric                                               // has been apllied. Used to skip
142*04eeddc0SDimitry Andric                                               // checks on phi nodes.
143349cc55cSDimitry Andric 
144e8d8bef9SDimitry Andric   FlattenInfo(Loop *OL, Loop *IL) : OuterLoop(OL), InnerLoop(IL){};
145349cc55cSDimitry Andric 
146349cc55cSDimitry Andric   bool isNarrowInductionPhi(PHINode *Phi) {
147349cc55cSDimitry Andric     // This can't be the narrow phi if we haven't widened the IV first.
148349cc55cSDimitry Andric     if (!Widened)
149349cc55cSDimitry Andric       return false;
150349cc55cSDimitry Andric     return NarrowInnerInductionPHI == Phi || NarrowOuterInductionPHI == Phi;
151349cc55cSDimitry Andric   }
152*04eeddc0SDimitry Andric   bool isInnerLoopIncrement(User *U) {
153*04eeddc0SDimitry Andric     return InnerIncrement == U;
154*04eeddc0SDimitry Andric   }
155*04eeddc0SDimitry Andric   bool isOuterLoopIncrement(User *U) {
156*04eeddc0SDimitry Andric     return OuterIncrement == U;
157*04eeddc0SDimitry Andric   }
158*04eeddc0SDimitry Andric   bool isInnerLoopTest(User *U) {
159*04eeddc0SDimitry Andric     return InnerBranch->getCondition() == U;
160*04eeddc0SDimitry Andric   }
161*04eeddc0SDimitry Andric 
162*04eeddc0SDimitry Andric   bool checkOuterInductionPhiUsers(SmallPtrSet<Value *, 4> &ValidOuterPHIUses) {
163*04eeddc0SDimitry Andric     for (User *U : OuterInductionPHI->users()) {
164*04eeddc0SDimitry Andric       if (isOuterLoopIncrement(U))
165*04eeddc0SDimitry Andric         continue;
166*04eeddc0SDimitry Andric 
167*04eeddc0SDimitry Andric       auto IsValidOuterPHIUses = [&] (User *U) -> bool {
168*04eeddc0SDimitry Andric         LLVM_DEBUG(dbgs() << "Found use of outer induction variable: "; U->dump());
169*04eeddc0SDimitry Andric         if (!ValidOuterPHIUses.count(U)) {
170*04eeddc0SDimitry Andric           LLVM_DEBUG(dbgs() << "Did not match expected pattern, bailing\n");
171*04eeddc0SDimitry Andric           return false;
172*04eeddc0SDimitry Andric         }
173*04eeddc0SDimitry Andric         LLVM_DEBUG(dbgs() << "Use is optimisable\n");
174*04eeddc0SDimitry Andric         return true;
175*04eeddc0SDimitry Andric       };
176*04eeddc0SDimitry Andric 
177*04eeddc0SDimitry Andric       if (auto *V = dyn_cast<TruncInst>(U)) {
178*04eeddc0SDimitry Andric         for (auto *K : V->users()) {
179*04eeddc0SDimitry Andric           if (!IsValidOuterPHIUses(K))
180*04eeddc0SDimitry Andric             return false;
181*04eeddc0SDimitry Andric         }
182*04eeddc0SDimitry Andric         continue;
183*04eeddc0SDimitry Andric       }
184*04eeddc0SDimitry Andric 
185*04eeddc0SDimitry Andric       if (!IsValidOuterPHIUses(U))
186*04eeddc0SDimitry Andric         return false;
187*04eeddc0SDimitry Andric     }
188*04eeddc0SDimitry Andric     return true;
189*04eeddc0SDimitry Andric   }
190*04eeddc0SDimitry Andric 
191*04eeddc0SDimitry Andric   bool matchLinearIVUser(User *U, Value *InnerTripCount,
192*04eeddc0SDimitry Andric                          SmallPtrSet<Value *, 4> &ValidOuterPHIUses) {
193*04eeddc0SDimitry Andric     LLVM_DEBUG(dbgs() << "Found use of inner induction variable: "; U->dump());
194*04eeddc0SDimitry Andric     Value *MatchedMul = nullptr;
195*04eeddc0SDimitry Andric     Value *MatchedItCount = nullptr;
196*04eeddc0SDimitry Andric 
197*04eeddc0SDimitry Andric     bool IsAdd = match(U, m_c_Add(m_Specific(InnerInductionPHI),
198*04eeddc0SDimitry Andric                                   m_Value(MatchedMul))) &&
199*04eeddc0SDimitry Andric                  match(MatchedMul, m_c_Mul(m_Specific(OuterInductionPHI),
200*04eeddc0SDimitry Andric                                            m_Value(MatchedItCount)));
201*04eeddc0SDimitry Andric 
202*04eeddc0SDimitry Andric     // Matches the same pattern as above, except it also looks for truncs
203*04eeddc0SDimitry Andric     // on the phi, which can be the result of widening the induction variables.
204*04eeddc0SDimitry Andric     bool IsAddTrunc =
205*04eeddc0SDimitry Andric         match(U, m_c_Add(m_Trunc(m_Specific(InnerInductionPHI)),
206*04eeddc0SDimitry Andric                          m_Value(MatchedMul))) &&
207*04eeddc0SDimitry Andric         match(MatchedMul, m_c_Mul(m_Trunc(m_Specific(OuterInductionPHI)),
208*04eeddc0SDimitry Andric                                   m_Value(MatchedItCount)));
209*04eeddc0SDimitry Andric 
210*04eeddc0SDimitry Andric     if (!MatchedItCount)
211*04eeddc0SDimitry Andric       return false;
212*04eeddc0SDimitry Andric 
213*04eeddc0SDimitry Andric     // Look through extends if the IV has been widened.
214*04eeddc0SDimitry Andric     if (Widened &&
215*04eeddc0SDimitry Andric         (isa<SExtInst>(MatchedItCount) || isa<ZExtInst>(MatchedItCount))) {
216*04eeddc0SDimitry Andric       assert(MatchedItCount->getType() == InnerInductionPHI->getType() &&
217*04eeddc0SDimitry Andric              "Unexpected type mismatch in types after widening");
218*04eeddc0SDimitry Andric       MatchedItCount = isa<SExtInst>(MatchedItCount)
219*04eeddc0SDimitry Andric                            ? dyn_cast<SExtInst>(MatchedItCount)->getOperand(0)
220*04eeddc0SDimitry Andric                            : dyn_cast<ZExtInst>(MatchedItCount)->getOperand(0);
221*04eeddc0SDimitry Andric     }
222*04eeddc0SDimitry Andric 
223*04eeddc0SDimitry Andric     if ((IsAdd || IsAddTrunc) && MatchedItCount == InnerTripCount) {
224*04eeddc0SDimitry Andric       LLVM_DEBUG(dbgs() << "Use is optimisable\n");
225*04eeddc0SDimitry Andric       ValidOuterPHIUses.insert(MatchedMul);
226*04eeddc0SDimitry Andric       LinearIVUses.insert(U);
227*04eeddc0SDimitry Andric       return true;
228*04eeddc0SDimitry Andric     }
229*04eeddc0SDimitry Andric 
230*04eeddc0SDimitry Andric     LLVM_DEBUG(dbgs() << "Did not match expected pattern, bailing\n");
231*04eeddc0SDimitry Andric     return false;
232*04eeddc0SDimitry Andric   }
233*04eeddc0SDimitry Andric 
234*04eeddc0SDimitry Andric   bool checkInnerInductionPhiUsers(SmallPtrSet<Value *, 4> &ValidOuterPHIUses) {
235*04eeddc0SDimitry Andric     Value *SExtInnerTripCount = InnerTripCount;
236*04eeddc0SDimitry Andric     if (Widened &&
237*04eeddc0SDimitry Andric         (isa<SExtInst>(InnerTripCount) || isa<ZExtInst>(InnerTripCount)))
238*04eeddc0SDimitry Andric       SExtInnerTripCount = cast<Instruction>(InnerTripCount)->getOperand(0);
239*04eeddc0SDimitry Andric 
240*04eeddc0SDimitry Andric     for (User *U : InnerInductionPHI->users()) {
241*04eeddc0SDimitry Andric       if (isInnerLoopIncrement(U))
242*04eeddc0SDimitry Andric         continue;
243*04eeddc0SDimitry Andric 
244*04eeddc0SDimitry Andric       // After widening the IVs, a trunc instruction might have been introduced,
245*04eeddc0SDimitry Andric       // so look through truncs.
246*04eeddc0SDimitry Andric       if (isa<TruncInst>(U)) {
247*04eeddc0SDimitry Andric         if (!U->hasOneUse())
248*04eeddc0SDimitry Andric           return false;
249*04eeddc0SDimitry Andric         U = *U->user_begin();
250*04eeddc0SDimitry Andric       }
251*04eeddc0SDimitry Andric 
252*04eeddc0SDimitry Andric       // If the use is in the compare (which is also the condition of the inner
253*04eeddc0SDimitry Andric       // branch) then the compare has been altered by another transformation e.g
254*04eeddc0SDimitry Andric       // icmp ult %inc, tripcount -> icmp ult %j, tripcount-1, where tripcount is
255*04eeddc0SDimitry Andric       // a constant. Ignore this use as the compare gets removed later anyway.
256*04eeddc0SDimitry Andric       if (isInnerLoopTest(U))
257*04eeddc0SDimitry Andric         continue;
258*04eeddc0SDimitry Andric 
259*04eeddc0SDimitry Andric       if (!matchLinearIVUser(U, SExtInnerTripCount, ValidOuterPHIUses))
260*04eeddc0SDimitry Andric         return false;
261*04eeddc0SDimitry Andric     }
262*04eeddc0SDimitry Andric     return true;
263*04eeddc0SDimitry Andric   }
264e8d8bef9SDimitry Andric };
265e8d8bef9SDimitry Andric 
266349cc55cSDimitry Andric static bool
267349cc55cSDimitry Andric setLoopComponents(Value *&TC, Value *&TripCount, BinaryOperator *&Increment,
268349cc55cSDimitry Andric                   SmallPtrSetImpl<Instruction *> &IterationInstructions) {
269349cc55cSDimitry Andric   TripCount = TC;
270349cc55cSDimitry Andric   IterationInstructions.insert(Increment);
271349cc55cSDimitry Andric   LLVM_DEBUG(dbgs() << "Found Increment: "; Increment->dump());
272349cc55cSDimitry Andric   LLVM_DEBUG(dbgs() << "Found trip count: "; TripCount->dump());
273349cc55cSDimitry Andric   LLVM_DEBUG(dbgs() << "Successfully found all loop components\n");
274349cc55cSDimitry Andric   return true;
275349cc55cSDimitry Andric }
276349cc55cSDimitry Andric 
277*04eeddc0SDimitry Andric // Given the RHS of the loop latch compare instruction, verify with SCEV
278*04eeddc0SDimitry Andric // that this is indeed the loop tripcount.
279*04eeddc0SDimitry Andric // TODO: This used to be a straightforward check but has grown to be quite
280*04eeddc0SDimitry Andric // complicated now. It is therefore worth revisiting what the additional
281*04eeddc0SDimitry Andric // benefits are of this (compared to relying on canonical loops and pattern
282*04eeddc0SDimitry Andric // matching).
283*04eeddc0SDimitry Andric static bool verifyTripCount(Value *RHS, Loop *L,
284*04eeddc0SDimitry Andric      SmallPtrSetImpl<Instruction *> &IterationInstructions,
285*04eeddc0SDimitry Andric     PHINode *&InductionPHI, Value *&TripCount, BinaryOperator *&Increment,
286*04eeddc0SDimitry Andric     BranchInst *&BackBranch, ScalarEvolution *SE, bool IsWidened) {
287*04eeddc0SDimitry Andric   const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
288*04eeddc0SDimitry Andric   if (isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
289*04eeddc0SDimitry Andric     LLVM_DEBUG(dbgs() << "Backedge-taken count is not predictable\n");
290*04eeddc0SDimitry Andric     return false;
291*04eeddc0SDimitry Andric   }
292*04eeddc0SDimitry Andric 
293*04eeddc0SDimitry Andric   // The Extend=false flag is used for getTripCountFromExitCount as we want
294*04eeddc0SDimitry Andric   // to verify and match it with the pattern matched tripcount. Please note
295*04eeddc0SDimitry Andric   // that overflow checks are performed in checkOverflow, but are first tried
296*04eeddc0SDimitry Andric   // to avoid by widening the IV.
297*04eeddc0SDimitry Andric   const SCEV *SCEVTripCount =
298*04eeddc0SDimitry Andric       SE->getTripCountFromExitCount(BackedgeTakenCount, /*Extend=*/false);
299*04eeddc0SDimitry Andric 
300*04eeddc0SDimitry Andric   const SCEV *SCEVRHS = SE->getSCEV(RHS);
301*04eeddc0SDimitry Andric   if (SCEVRHS == SCEVTripCount)
302*04eeddc0SDimitry Andric     return setLoopComponents(RHS, TripCount, Increment, IterationInstructions);
303*04eeddc0SDimitry Andric   ConstantInt *ConstantRHS = dyn_cast<ConstantInt>(RHS);
304*04eeddc0SDimitry Andric   if (ConstantRHS) {
305*04eeddc0SDimitry Andric     const SCEV *BackedgeTCExt = nullptr;
306*04eeddc0SDimitry Andric     if (IsWidened) {
307*04eeddc0SDimitry Andric       const SCEV *SCEVTripCountExt;
308*04eeddc0SDimitry Andric       // Find the extended backedge taken count and extended trip count using
309*04eeddc0SDimitry Andric       // SCEV. One of these should now match the RHS of the compare.
310*04eeddc0SDimitry Andric       BackedgeTCExt = SE->getZeroExtendExpr(BackedgeTakenCount, RHS->getType());
311*04eeddc0SDimitry Andric       SCEVTripCountExt = SE->getTripCountFromExitCount(BackedgeTCExt, false);
312*04eeddc0SDimitry Andric       if (SCEVRHS != BackedgeTCExt && SCEVRHS != SCEVTripCountExt) {
313*04eeddc0SDimitry Andric         LLVM_DEBUG(dbgs() << "Could not find valid trip count\n");
314*04eeddc0SDimitry Andric         return false;
315*04eeddc0SDimitry Andric       }
316*04eeddc0SDimitry Andric     }
317*04eeddc0SDimitry Andric     // If the RHS of the compare is equal to the backedge taken count we need
318*04eeddc0SDimitry Andric     // to add one to get the trip count.
319*04eeddc0SDimitry Andric     if (SCEVRHS == BackedgeTCExt || SCEVRHS == BackedgeTakenCount) {
320*04eeddc0SDimitry Andric       ConstantInt *One = ConstantInt::get(ConstantRHS->getType(), 1);
321*04eeddc0SDimitry Andric       Value *NewRHS = ConstantInt::get(
322*04eeddc0SDimitry Andric           ConstantRHS->getContext(), ConstantRHS->getValue() + One->getValue());
323*04eeddc0SDimitry Andric       return setLoopComponents(NewRHS, TripCount, Increment,
324*04eeddc0SDimitry Andric                                IterationInstructions);
325*04eeddc0SDimitry Andric     }
326*04eeddc0SDimitry Andric     return setLoopComponents(RHS, TripCount, Increment, IterationInstructions);
327*04eeddc0SDimitry Andric   }
328*04eeddc0SDimitry Andric   // If the RHS isn't a constant then check that the reason it doesn't match
329*04eeddc0SDimitry Andric   // the SCEV trip count is because the RHS is a ZExt or SExt instruction
330*04eeddc0SDimitry Andric   // (and take the trip count to be the RHS).
331*04eeddc0SDimitry Andric   if (!IsWidened) {
332*04eeddc0SDimitry Andric     LLVM_DEBUG(dbgs() << "Could not find valid trip count\n");
333*04eeddc0SDimitry Andric     return false;
334*04eeddc0SDimitry Andric   }
335*04eeddc0SDimitry Andric   auto *TripCountInst = dyn_cast<Instruction>(RHS);
336*04eeddc0SDimitry Andric   if (!TripCountInst) {
337*04eeddc0SDimitry Andric     LLVM_DEBUG(dbgs() << "Could not find valid trip count\n");
338*04eeddc0SDimitry Andric     return false;
339*04eeddc0SDimitry Andric   }
340*04eeddc0SDimitry Andric   if ((!isa<ZExtInst>(TripCountInst) && !isa<SExtInst>(TripCountInst)) ||
341*04eeddc0SDimitry Andric       SE->getSCEV(TripCountInst->getOperand(0)) != SCEVTripCount) {
342*04eeddc0SDimitry Andric     LLVM_DEBUG(dbgs() << "Could not find valid extended trip count\n");
343*04eeddc0SDimitry Andric     return false;
344*04eeddc0SDimitry Andric   }
345*04eeddc0SDimitry Andric   return setLoopComponents(RHS, TripCount, Increment, IterationInstructions);
346*04eeddc0SDimitry Andric }
347*04eeddc0SDimitry Andric 
348fe6060f1SDimitry Andric // Finds the induction variable, increment and trip count for a simple loop that
349fe6060f1SDimitry Andric // we can flatten.
350e8d8bef9SDimitry Andric static bool findLoopComponents(
351e8d8bef9SDimitry Andric     Loop *L, SmallPtrSetImpl<Instruction *> &IterationInstructions,
352fe6060f1SDimitry Andric     PHINode *&InductionPHI, Value *&TripCount, BinaryOperator *&Increment,
353fe6060f1SDimitry Andric     BranchInst *&BackBranch, ScalarEvolution *SE, bool IsWidened) {
354e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Finding components of loop: " << L->getName() << "\n");
355e8d8bef9SDimitry Andric 
356e8d8bef9SDimitry Andric   if (!L->isLoopSimplifyForm()) {
357e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Loop is not in normal form\n");
358e8d8bef9SDimitry Andric     return false;
359e8d8bef9SDimitry Andric   }
360e8d8bef9SDimitry Andric 
361fe6060f1SDimitry Andric   // Currently, to simplify the implementation, the Loop induction variable must
362fe6060f1SDimitry Andric   // start at zero and increment with a step size of one.
363fe6060f1SDimitry Andric   if (!L->isCanonical(*SE)) {
364fe6060f1SDimitry Andric     LLVM_DEBUG(dbgs() << "Loop is not canonical\n");
365fe6060f1SDimitry Andric     return false;
366fe6060f1SDimitry Andric   }
367fe6060f1SDimitry Andric 
368e8d8bef9SDimitry Andric   // There must be exactly one exiting block, and it must be the same at the
369e8d8bef9SDimitry Andric   // latch.
370e8d8bef9SDimitry Andric   BasicBlock *Latch = L->getLoopLatch();
371e8d8bef9SDimitry Andric   if (L->getExitingBlock() != Latch) {
372e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Exiting and latch block are different\n");
373e8d8bef9SDimitry Andric     return false;
374e8d8bef9SDimitry Andric   }
375e8d8bef9SDimitry Andric 
376e8d8bef9SDimitry Andric   // Find the induction PHI. If there is no induction PHI, we can't do the
377e8d8bef9SDimitry Andric   // transformation. TODO: could other variables trigger this? Do we have to
378e8d8bef9SDimitry Andric   // search for the best one?
379fe6060f1SDimitry Andric   InductionPHI = L->getInductionVariable(*SE);
380e8d8bef9SDimitry Andric   if (!InductionPHI) {
381e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Could not find induction PHI\n");
382e8d8bef9SDimitry Andric     return false;
383e8d8bef9SDimitry Andric   }
384fe6060f1SDimitry Andric   LLVM_DEBUG(dbgs() << "Found induction PHI: "; InductionPHI->dump());
385e8d8bef9SDimitry Andric 
386fe6060f1SDimitry Andric   bool ContinueOnTrue = L->contains(Latch->getTerminator()->getSuccessor(0));
387e8d8bef9SDimitry Andric   auto IsValidPredicate = [&](ICmpInst::Predicate Pred) {
388e8d8bef9SDimitry Andric     if (ContinueOnTrue)
389e8d8bef9SDimitry Andric       return Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_ULT;
390e8d8bef9SDimitry Andric     else
391e8d8bef9SDimitry Andric       return Pred == CmpInst::ICMP_EQ;
392e8d8bef9SDimitry Andric   };
393e8d8bef9SDimitry Andric 
394fe6060f1SDimitry Andric   // Find Compare and make sure it is valid. getLatchCmpInst checks that the
395fe6060f1SDimitry Andric   // back branch of the latch is conditional.
396fe6060f1SDimitry Andric   ICmpInst *Compare = L->getLatchCmpInst();
397e8d8bef9SDimitry Andric   if (!Compare || !IsValidPredicate(Compare->getUnsignedPredicate()) ||
398e8d8bef9SDimitry Andric       Compare->hasNUsesOrMore(2)) {
399e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Could not find valid comparison\n");
400e8d8bef9SDimitry Andric     return false;
401e8d8bef9SDimitry Andric   }
402fe6060f1SDimitry Andric   BackBranch = cast<BranchInst>(Latch->getTerminator());
403fe6060f1SDimitry Andric   IterationInstructions.insert(BackBranch);
404fe6060f1SDimitry Andric   LLVM_DEBUG(dbgs() << "Found back branch: "; BackBranch->dump());
405e8d8bef9SDimitry Andric   IterationInstructions.insert(Compare);
406e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Found comparison: "; Compare->dump());
407e8d8bef9SDimitry Andric 
408fe6060f1SDimitry Andric   // Find increment and trip count.
409fe6060f1SDimitry Andric   // There are exactly 2 incoming values to the induction phi; one from the
410fe6060f1SDimitry Andric   // pre-header and one from the latch. The incoming latch value is the
411fe6060f1SDimitry Andric   // increment variable.
412fe6060f1SDimitry Andric   Increment =
413fe6060f1SDimitry Andric       dyn_cast<BinaryOperator>(InductionPHI->getIncomingValueForBlock(Latch));
414fe6060f1SDimitry Andric   if (Increment->hasNUsesOrMore(3)) {
415fe6060f1SDimitry Andric     LLVM_DEBUG(dbgs() << "Could not find valid increment\n");
416e8d8bef9SDimitry Andric     return false;
417e8d8bef9SDimitry Andric   }
418fe6060f1SDimitry Andric   // The trip count is the RHS of the compare. If this doesn't match the trip
419349cc55cSDimitry Andric   // count computed by SCEV then this is because the trip count variable
420349cc55cSDimitry Andric   // has been widened so the types don't match, or because it is a constant and
421349cc55cSDimitry Andric   // another transformation has changed the compare (e.g. icmp ult %inc,
422349cc55cSDimitry Andric   // tripcount -> icmp ult %j, tripcount-1), or both.
423349cc55cSDimitry Andric   Value *RHS = Compare->getOperand(1);
424*04eeddc0SDimitry Andric 
425*04eeddc0SDimitry Andric   return verifyTripCount(RHS, L, IterationInstructions, InductionPHI, TripCount,
426*04eeddc0SDimitry Andric                          Increment, BackBranch, SE, IsWidened);
427e8d8bef9SDimitry Andric }
428e8d8bef9SDimitry Andric 
429fe6060f1SDimitry Andric static bool checkPHIs(FlattenInfo &FI, const TargetTransformInfo *TTI) {
430e8d8bef9SDimitry Andric   // All PHIs in the inner and outer headers must either be:
431e8d8bef9SDimitry Andric   // - The induction PHI, which we are going to rewrite as one induction in
432e8d8bef9SDimitry Andric   //   the new loop. This is already checked by findLoopComponents.
433e8d8bef9SDimitry Andric   // - An outer header PHI with all incoming values from outside the loop.
434e8d8bef9SDimitry Andric   //   LoopSimplify guarantees we have a pre-header, so we don't need to
435e8d8bef9SDimitry Andric   //   worry about that here.
436e8d8bef9SDimitry Andric   // - Pairs of PHIs in the inner and outer headers, which implement a
437e8d8bef9SDimitry Andric   //   loop-carried dependency that will still be valid in the new loop. To
438e8d8bef9SDimitry Andric   //   be valid, this variable must be modified only in the inner loop.
439e8d8bef9SDimitry Andric 
440e8d8bef9SDimitry Andric   // The set of PHI nodes in the outer loop header that we know will still be
441e8d8bef9SDimitry Andric   // valid after the transformation. These will not need to be modified (with
442e8d8bef9SDimitry Andric   // the exception of the induction variable), but we do need to check that
443e8d8bef9SDimitry Andric   // there are no unsafe PHI nodes.
444e8d8bef9SDimitry Andric   SmallPtrSet<PHINode *, 4> SafeOuterPHIs;
445e8d8bef9SDimitry Andric   SafeOuterPHIs.insert(FI.OuterInductionPHI);
446e8d8bef9SDimitry Andric 
447e8d8bef9SDimitry Andric   // Check that all PHI nodes in the inner loop header match one of the valid
448e8d8bef9SDimitry Andric   // patterns.
449e8d8bef9SDimitry Andric   for (PHINode &InnerPHI : FI.InnerLoop->getHeader()->phis()) {
450e8d8bef9SDimitry Andric     // The induction PHIs break these rules, and that's OK because we treat
451e8d8bef9SDimitry Andric     // them specially when doing the transformation.
452e8d8bef9SDimitry Andric     if (&InnerPHI == FI.InnerInductionPHI)
453e8d8bef9SDimitry Andric       continue;
454349cc55cSDimitry Andric     if (FI.isNarrowInductionPhi(&InnerPHI))
455349cc55cSDimitry Andric       continue;
456e8d8bef9SDimitry Andric 
457e8d8bef9SDimitry Andric     // Each inner loop PHI node must have two incoming values/blocks - one
458e8d8bef9SDimitry Andric     // from the pre-header, and one from the latch.
459e8d8bef9SDimitry Andric     assert(InnerPHI.getNumIncomingValues() == 2);
460e8d8bef9SDimitry Andric     Value *PreHeaderValue =
461e8d8bef9SDimitry Andric         InnerPHI.getIncomingValueForBlock(FI.InnerLoop->getLoopPreheader());
462e8d8bef9SDimitry Andric     Value *LatchValue =
463e8d8bef9SDimitry Andric         InnerPHI.getIncomingValueForBlock(FI.InnerLoop->getLoopLatch());
464e8d8bef9SDimitry Andric 
465e8d8bef9SDimitry Andric     // The incoming value from the outer loop must be the PHI node in the
466e8d8bef9SDimitry Andric     // outer loop header, with no modifications made in the top of the outer
467e8d8bef9SDimitry Andric     // loop.
468e8d8bef9SDimitry Andric     PHINode *OuterPHI = dyn_cast<PHINode>(PreHeaderValue);
469e8d8bef9SDimitry Andric     if (!OuterPHI || OuterPHI->getParent() != FI.OuterLoop->getHeader()) {
470e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "value modified in top of outer loop\n");
471e8d8bef9SDimitry Andric       return false;
472e8d8bef9SDimitry Andric     }
473e8d8bef9SDimitry Andric 
474e8d8bef9SDimitry Andric     // The other incoming value must come from the inner loop, without any
475e8d8bef9SDimitry Andric     // modifications in the tail end of the outer loop. We are in LCSSA form,
476e8d8bef9SDimitry Andric     // so this will actually be a PHI in the inner loop's exit block, which
477e8d8bef9SDimitry Andric     // only uses values from inside the inner loop.
478e8d8bef9SDimitry Andric     PHINode *LCSSAPHI = dyn_cast<PHINode>(
479e8d8bef9SDimitry Andric         OuterPHI->getIncomingValueForBlock(FI.OuterLoop->getLoopLatch()));
480e8d8bef9SDimitry Andric     if (!LCSSAPHI) {
481e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "could not find LCSSA PHI\n");
482e8d8bef9SDimitry Andric       return false;
483e8d8bef9SDimitry Andric     }
484e8d8bef9SDimitry Andric 
485e8d8bef9SDimitry Andric     // The value used by the LCSSA PHI must be the same one that the inner
486e8d8bef9SDimitry Andric     // loop's PHI uses.
487e8d8bef9SDimitry Andric     if (LCSSAPHI->hasConstantValue() != LatchValue) {
488e8d8bef9SDimitry Andric       LLVM_DEBUG(
489e8d8bef9SDimitry Andric           dbgs() << "LCSSA PHI incoming value does not match latch value\n");
490e8d8bef9SDimitry Andric       return false;
491e8d8bef9SDimitry Andric     }
492e8d8bef9SDimitry Andric 
493e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "PHI pair is safe:\n");
494e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "  Inner: "; InnerPHI.dump());
495e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "  Outer: "; OuterPHI->dump());
496e8d8bef9SDimitry Andric     SafeOuterPHIs.insert(OuterPHI);
497e8d8bef9SDimitry Andric     FI.InnerPHIsToTransform.insert(&InnerPHI);
498e8d8bef9SDimitry Andric   }
499e8d8bef9SDimitry Andric 
500e8d8bef9SDimitry Andric   for (PHINode &OuterPHI : FI.OuterLoop->getHeader()->phis()) {
501349cc55cSDimitry Andric     if (FI.isNarrowInductionPhi(&OuterPHI))
502349cc55cSDimitry Andric       continue;
503e8d8bef9SDimitry Andric     if (!SafeOuterPHIs.count(&OuterPHI)) {
504e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "found unsafe PHI in outer loop: "; OuterPHI.dump());
505e8d8bef9SDimitry Andric       return false;
506e8d8bef9SDimitry Andric     }
507e8d8bef9SDimitry Andric   }
508e8d8bef9SDimitry Andric 
509e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "checkPHIs: OK\n");
510e8d8bef9SDimitry Andric   return true;
511e8d8bef9SDimitry Andric }
512e8d8bef9SDimitry Andric 
513e8d8bef9SDimitry Andric static bool
514fe6060f1SDimitry Andric checkOuterLoopInsts(FlattenInfo &FI,
515e8d8bef9SDimitry Andric                     SmallPtrSetImpl<Instruction *> &IterationInstructions,
516e8d8bef9SDimitry Andric                     const TargetTransformInfo *TTI) {
517e8d8bef9SDimitry Andric   // Check for instructions in the outer but not inner loop. If any of these
518e8d8bef9SDimitry Andric   // have side-effects then this transformation is not legal, and if there is
519e8d8bef9SDimitry Andric   // a significant amount of code here which can't be optimised out that it's
520e8d8bef9SDimitry Andric   // not profitable (as these instructions would get executed for each
521e8d8bef9SDimitry Andric   // iteration of the inner loop).
522fe6060f1SDimitry Andric   InstructionCost RepeatedInstrCost = 0;
523e8d8bef9SDimitry Andric   for (auto *B : FI.OuterLoop->getBlocks()) {
524e8d8bef9SDimitry Andric     if (FI.InnerLoop->contains(B))
525e8d8bef9SDimitry Andric       continue;
526e8d8bef9SDimitry Andric 
527e8d8bef9SDimitry Andric     for (auto &I : *B) {
528e8d8bef9SDimitry Andric       if (!isa<PHINode>(&I) && !I.isTerminator() &&
529e8d8bef9SDimitry Andric           !isSafeToSpeculativelyExecute(&I)) {
530e8d8bef9SDimitry Andric         LLVM_DEBUG(dbgs() << "Cannot flatten because instruction may have "
531e8d8bef9SDimitry Andric                              "side effects: ";
532e8d8bef9SDimitry Andric                    I.dump());
533e8d8bef9SDimitry Andric         return false;
534e8d8bef9SDimitry Andric       }
535e8d8bef9SDimitry Andric       // The execution count of the outer loop's iteration instructions
536e8d8bef9SDimitry Andric       // (increment, compare and branch) will be increased, but the
537e8d8bef9SDimitry Andric       // equivalent instructions will be removed from the inner loop, so
538e8d8bef9SDimitry Andric       // they make a net difference of zero.
539e8d8bef9SDimitry Andric       if (IterationInstructions.count(&I))
540e8d8bef9SDimitry Andric         continue;
541e8d8bef9SDimitry Andric       // The uncoditional branch to the inner loop's header will turn into
542e8d8bef9SDimitry Andric       // a fall-through, so adds no cost.
543e8d8bef9SDimitry Andric       BranchInst *Br = dyn_cast<BranchInst>(&I);
544e8d8bef9SDimitry Andric       if (Br && Br->isUnconditional() &&
545e8d8bef9SDimitry Andric           Br->getSuccessor(0) == FI.InnerLoop->getHeader())
546e8d8bef9SDimitry Andric         continue;
547e8d8bef9SDimitry Andric       // Multiplies of the outer iteration variable and inner iteration
548e8d8bef9SDimitry Andric       // count will be optimised out.
549e8d8bef9SDimitry Andric       if (match(&I, m_c_Mul(m_Specific(FI.OuterInductionPHI),
550fe6060f1SDimitry Andric                             m_Specific(FI.InnerTripCount))))
551e8d8bef9SDimitry Andric         continue;
552fe6060f1SDimitry Andric       InstructionCost Cost =
553fe6060f1SDimitry Andric           TTI->getUserCost(&I, TargetTransformInfo::TCK_SizeAndLatency);
554e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "Cost " << Cost << ": "; I.dump());
555e8d8bef9SDimitry Andric       RepeatedInstrCost += Cost;
556e8d8bef9SDimitry Andric     }
557e8d8bef9SDimitry Andric   }
558e8d8bef9SDimitry Andric 
559e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Cost of instructions that will be repeated: "
560e8d8bef9SDimitry Andric                     << RepeatedInstrCost << "\n");
561e8d8bef9SDimitry Andric   // Bail out if flattening the loops would cause instructions in the outer
562e8d8bef9SDimitry Andric   // loop but not in the inner loop to be executed extra times.
563e8d8bef9SDimitry Andric   if (RepeatedInstrCost > RepeatedInstructionThreshold) {
564e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "checkOuterLoopInsts: not profitable, bailing.\n");
565e8d8bef9SDimitry Andric     return false;
566e8d8bef9SDimitry Andric   }
567e8d8bef9SDimitry Andric 
568e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "checkOuterLoopInsts: OK\n");
569e8d8bef9SDimitry Andric   return true;
570e8d8bef9SDimitry Andric }
571e8d8bef9SDimitry Andric 
572*04eeddc0SDimitry Andric 
573*04eeddc0SDimitry Andric 
574e8d8bef9SDimitry Andric // We require all uses of both induction variables to match this pattern:
575e8d8bef9SDimitry Andric //
576fe6060f1SDimitry Andric //   (OuterPHI * InnerTripCount) + InnerPHI
577e8d8bef9SDimitry Andric //
578e8d8bef9SDimitry Andric // Any uses of the induction variables not matching that pattern would
579e8d8bef9SDimitry Andric // require a div/mod to reconstruct in the flattened loop, so the
580e8d8bef9SDimitry Andric // transformation wouldn't be profitable.
581*04eeddc0SDimitry Andric static bool checkIVUsers(FlattenInfo &FI) {
582e8d8bef9SDimitry Andric   // Check that all uses of the inner loop's induction variable match the
583e8d8bef9SDimitry Andric   // expected pattern, recording the uses of the outer IV.
584e8d8bef9SDimitry Andric   SmallPtrSet<Value *, 4> ValidOuterPHIUses;
585*04eeddc0SDimitry Andric   if (!FI.checkInnerInductionPhiUsers(ValidOuterPHIUses))
586e8d8bef9SDimitry Andric     return false;
587e8d8bef9SDimitry Andric 
588e8d8bef9SDimitry Andric   // Check that there are no uses of the outer IV other than the ones found
589e8d8bef9SDimitry Andric   // as part of the pattern above.
590*04eeddc0SDimitry Andric   if (!FI.checkOuterInductionPhiUsers(ValidOuterPHIUses))
591e8d8bef9SDimitry Andric     return false;
592e8d8bef9SDimitry Andric 
593e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "checkIVUsers: OK\n";
594e8d8bef9SDimitry Andric              dbgs() << "Found " << FI.LinearIVUses.size()
595e8d8bef9SDimitry Andric                     << " value(s) that can be replaced:\n";
596e8d8bef9SDimitry Andric              for (Value *V : FI.LinearIVUses) {
597e8d8bef9SDimitry Andric                dbgs() << "  ";
598e8d8bef9SDimitry Andric                V->dump();
599e8d8bef9SDimitry Andric              });
600e8d8bef9SDimitry Andric   return true;
601e8d8bef9SDimitry Andric }
602e8d8bef9SDimitry Andric 
603e8d8bef9SDimitry Andric // Return an OverflowResult dependant on if overflow of the multiplication of
604fe6060f1SDimitry Andric // InnerTripCount and OuterTripCount can be assumed not to happen.
605fe6060f1SDimitry Andric static OverflowResult checkOverflow(FlattenInfo &FI, DominatorTree *DT,
606fe6060f1SDimitry Andric                                     AssumptionCache *AC) {
607e8d8bef9SDimitry Andric   Function *F = FI.OuterLoop->getHeader()->getParent();
608e8d8bef9SDimitry Andric   const DataLayout &DL = F->getParent()->getDataLayout();
609e8d8bef9SDimitry Andric 
610e8d8bef9SDimitry Andric   // For debugging/testing.
611e8d8bef9SDimitry Andric   if (AssumeNoOverflow)
612e8d8bef9SDimitry Andric     return OverflowResult::NeverOverflows;
613e8d8bef9SDimitry Andric 
614e8d8bef9SDimitry Andric   // Check if the multiply could not overflow due to known ranges of the
615e8d8bef9SDimitry Andric   // input values.
616e8d8bef9SDimitry Andric   OverflowResult OR = computeOverflowForUnsignedMul(
617fe6060f1SDimitry Andric       FI.InnerTripCount, FI.OuterTripCount, DL, AC,
618e8d8bef9SDimitry Andric       FI.OuterLoop->getLoopPreheader()->getTerminator(), DT);
619e8d8bef9SDimitry Andric   if (OR != OverflowResult::MayOverflow)
620e8d8bef9SDimitry Andric     return OR;
621e8d8bef9SDimitry Andric 
622e8d8bef9SDimitry Andric   for (Value *V : FI.LinearIVUses) {
623e8d8bef9SDimitry Andric     for (Value *U : V->users()) {
624e8d8bef9SDimitry Andric       if (auto *GEP = dyn_cast<GetElementPtrInst>(U)) {
625349cc55cSDimitry Andric         for (Value *GEPUser : U->users()) {
626*04eeddc0SDimitry Andric           auto *GEPUserInst = cast<Instruction>(GEPUser);
627349cc55cSDimitry Andric           if (!isa<LoadInst>(GEPUserInst) &&
628349cc55cSDimitry Andric               !(isa<StoreInst>(GEPUserInst) &&
629349cc55cSDimitry Andric                 GEP == GEPUserInst->getOperand(1)))
630349cc55cSDimitry Andric             continue;
631349cc55cSDimitry Andric           if (!isGuaranteedToExecuteForEveryIteration(GEPUserInst,
632349cc55cSDimitry Andric                                                       FI.InnerLoop))
633349cc55cSDimitry Andric             continue;
634349cc55cSDimitry Andric           // The IV is used as the operand of a GEP which dominates the loop
635349cc55cSDimitry Andric           // latch, and the IV is at least as wide as the address space of the
636349cc55cSDimitry Andric           // GEP. In this case, the GEP would wrap around the address space
637349cc55cSDimitry Andric           // before the IV increment wraps, which would be UB.
638e8d8bef9SDimitry Andric           if (GEP->isInBounds() &&
639e8d8bef9SDimitry Andric               V->getType()->getIntegerBitWidth() >=
640e8d8bef9SDimitry Andric                   DL.getPointerTypeSizeInBits(GEP->getType())) {
641e8d8bef9SDimitry Andric             LLVM_DEBUG(
642e8d8bef9SDimitry Andric                 dbgs() << "use of linear IV would be UB if overflow occurred: ";
643e8d8bef9SDimitry Andric                 GEP->dump());
644e8d8bef9SDimitry Andric             return OverflowResult::NeverOverflows;
645e8d8bef9SDimitry Andric           }
646e8d8bef9SDimitry Andric         }
647e8d8bef9SDimitry Andric       }
648e8d8bef9SDimitry Andric     }
649349cc55cSDimitry Andric   }
650e8d8bef9SDimitry Andric 
651e8d8bef9SDimitry Andric   return OverflowResult::MayOverflow;
652e8d8bef9SDimitry Andric }
653e8d8bef9SDimitry Andric 
654fe6060f1SDimitry Andric static bool CanFlattenLoopPair(FlattenInfo &FI, DominatorTree *DT, LoopInfo *LI,
655fe6060f1SDimitry Andric                                ScalarEvolution *SE, AssumptionCache *AC,
656fe6060f1SDimitry Andric                                const TargetTransformInfo *TTI) {
657e8d8bef9SDimitry Andric   SmallPtrSet<Instruction *, 8> IterationInstructions;
658fe6060f1SDimitry Andric   if (!findLoopComponents(FI.InnerLoop, IterationInstructions,
659fe6060f1SDimitry Andric                           FI.InnerInductionPHI, FI.InnerTripCount,
660fe6060f1SDimitry Andric                           FI.InnerIncrement, FI.InnerBranch, SE, FI.Widened))
661e8d8bef9SDimitry Andric     return false;
662fe6060f1SDimitry Andric   if (!findLoopComponents(FI.OuterLoop, IterationInstructions,
663fe6060f1SDimitry Andric                           FI.OuterInductionPHI, FI.OuterTripCount,
664fe6060f1SDimitry Andric                           FI.OuterIncrement, FI.OuterBranch, SE, FI.Widened))
665e8d8bef9SDimitry Andric     return false;
666e8d8bef9SDimitry Andric 
667fe6060f1SDimitry Andric   // Both of the loop trip count values must be invariant in the outer loop
668e8d8bef9SDimitry Andric   // (non-instructions are all inherently invariant).
669fe6060f1SDimitry Andric   if (!FI.OuterLoop->isLoopInvariant(FI.InnerTripCount)) {
670fe6060f1SDimitry Andric     LLVM_DEBUG(dbgs() << "inner loop trip count not invariant\n");
671e8d8bef9SDimitry Andric     return false;
672e8d8bef9SDimitry Andric   }
673fe6060f1SDimitry Andric   if (!FI.OuterLoop->isLoopInvariant(FI.OuterTripCount)) {
674fe6060f1SDimitry Andric     LLVM_DEBUG(dbgs() << "outer loop trip count not invariant\n");
675e8d8bef9SDimitry Andric     return false;
676e8d8bef9SDimitry Andric   }
677e8d8bef9SDimitry Andric 
678e8d8bef9SDimitry Andric   if (!checkPHIs(FI, TTI))
679e8d8bef9SDimitry Andric     return false;
680e8d8bef9SDimitry Andric 
681e8d8bef9SDimitry Andric   // FIXME: it should be possible to handle different types correctly.
682e8d8bef9SDimitry Andric   if (FI.InnerInductionPHI->getType() != FI.OuterInductionPHI->getType())
683e8d8bef9SDimitry Andric     return false;
684e8d8bef9SDimitry Andric 
685e8d8bef9SDimitry Andric   if (!checkOuterLoopInsts(FI, IterationInstructions, TTI))
686e8d8bef9SDimitry Andric     return false;
687e8d8bef9SDimitry Andric 
688e8d8bef9SDimitry Andric   // Find the values in the loop that can be replaced with the linearized
689e8d8bef9SDimitry Andric   // induction variable, and check that there are no other uses of the inner
690e8d8bef9SDimitry Andric   // or outer induction variable. If there were, we could still do this
691e8d8bef9SDimitry Andric   // transformation, but we'd have to insert a div/mod to calculate the
692e8d8bef9SDimitry Andric   // original IVs, so it wouldn't be profitable.
693e8d8bef9SDimitry Andric   if (!checkIVUsers(FI))
694e8d8bef9SDimitry Andric     return false;
695e8d8bef9SDimitry Andric 
696e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "CanFlattenLoopPair: OK\n");
697e8d8bef9SDimitry Andric   return true;
698e8d8bef9SDimitry Andric }
699e8d8bef9SDimitry Andric 
700fe6060f1SDimitry Andric static bool DoFlattenLoopPair(FlattenInfo &FI, DominatorTree *DT, LoopInfo *LI,
701fe6060f1SDimitry Andric                               ScalarEvolution *SE, AssumptionCache *AC,
702*04eeddc0SDimitry Andric                               const TargetTransformInfo *TTI, LPMUpdater *U,
703*04eeddc0SDimitry Andric                               MemorySSAUpdater *MSSAU) {
704e8d8bef9SDimitry Andric   Function *F = FI.OuterLoop->getHeader()->getParent();
705e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Checks all passed, doing the transformation\n");
706e8d8bef9SDimitry Andric   {
707e8d8bef9SDimitry Andric     using namespace ore;
708e8d8bef9SDimitry Andric     OptimizationRemark Remark(DEBUG_TYPE, "Flattened", FI.InnerLoop->getStartLoc(),
709e8d8bef9SDimitry Andric                               FI.InnerLoop->getHeader());
710e8d8bef9SDimitry Andric     OptimizationRemarkEmitter ORE(F);
711e8d8bef9SDimitry Andric     Remark << "Flattened into outer loop";
712e8d8bef9SDimitry Andric     ORE.emit(Remark);
713e8d8bef9SDimitry Andric   }
714e8d8bef9SDimitry Andric 
715fe6060f1SDimitry Andric   Value *NewTripCount = BinaryOperator::CreateMul(
716fe6060f1SDimitry Andric       FI.InnerTripCount, FI.OuterTripCount, "flatten.tripcount",
717e8d8bef9SDimitry Andric       FI.OuterLoop->getLoopPreheader()->getTerminator());
718e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Created new trip count in preheader: ";
719e8d8bef9SDimitry Andric              NewTripCount->dump());
720e8d8bef9SDimitry Andric 
721e8d8bef9SDimitry Andric   // Fix up PHI nodes that take values from the inner loop back-edge, which
722e8d8bef9SDimitry Andric   // we are about to remove.
723e8d8bef9SDimitry Andric   FI.InnerInductionPHI->removeIncomingValue(FI.InnerLoop->getLoopLatch());
724e8d8bef9SDimitry Andric 
725e8d8bef9SDimitry Andric   // The old Phi will be optimised away later, but for now we can't leave
726e8d8bef9SDimitry Andric   // leave it in an invalid state, so are updating them too.
727e8d8bef9SDimitry Andric   for (PHINode *PHI : FI.InnerPHIsToTransform)
728e8d8bef9SDimitry Andric     PHI->removeIncomingValue(FI.InnerLoop->getLoopLatch());
729e8d8bef9SDimitry Andric 
730e8d8bef9SDimitry Andric   // Modify the trip count of the outer loop to be the product of the two
731e8d8bef9SDimitry Andric   // trip counts.
732e8d8bef9SDimitry Andric   cast<User>(FI.OuterBranch->getCondition())->setOperand(1, NewTripCount);
733e8d8bef9SDimitry Andric 
734e8d8bef9SDimitry Andric   // Replace the inner loop backedge with an unconditional branch to the exit.
735e8d8bef9SDimitry Andric   BasicBlock *InnerExitBlock = FI.InnerLoop->getExitBlock();
736e8d8bef9SDimitry Andric   BasicBlock *InnerExitingBlock = FI.InnerLoop->getExitingBlock();
737e8d8bef9SDimitry Andric   InnerExitingBlock->getTerminator()->eraseFromParent();
738e8d8bef9SDimitry Andric   BranchInst::Create(InnerExitBlock, InnerExitingBlock);
739*04eeddc0SDimitry Andric 
740*04eeddc0SDimitry Andric   // Update the DomTree and MemorySSA.
741e8d8bef9SDimitry Andric   DT->deleteEdge(InnerExitingBlock, FI.InnerLoop->getHeader());
742*04eeddc0SDimitry Andric   if (MSSAU)
743*04eeddc0SDimitry Andric     MSSAU->removeEdge(InnerExitingBlock, FI.InnerLoop->getHeader());
744e8d8bef9SDimitry Andric 
745e8d8bef9SDimitry Andric   // Replace all uses of the polynomial calculated from the two induction
746e8d8bef9SDimitry Andric   // variables with the one new one.
747e8d8bef9SDimitry Andric   IRBuilder<> Builder(FI.OuterInductionPHI->getParent()->getTerminator());
748e8d8bef9SDimitry Andric   for (Value *V : FI.LinearIVUses) {
749e8d8bef9SDimitry Andric     Value *OuterValue = FI.OuterInductionPHI;
750e8d8bef9SDimitry Andric     if (FI.Widened)
751e8d8bef9SDimitry Andric       OuterValue = Builder.CreateTrunc(FI.OuterInductionPHI, V->getType(),
752e8d8bef9SDimitry Andric                                        "flatten.trunciv");
753e8d8bef9SDimitry Andric 
754*04eeddc0SDimitry Andric     LLVM_DEBUG(dbgs() << "Replacing: "; V->dump(); dbgs() << "with:      ";
755*04eeddc0SDimitry Andric                OuterValue->dump());
756e8d8bef9SDimitry Andric     V->replaceAllUsesWith(OuterValue);
757e8d8bef9SDimitry Andric   }
758e8d8bef9SDimitry Andric 
759e8d8bef9SDimitry Andric   // Tell LoopInfo, SCEV and the pass manager that the inner loop has been
760e8d8bef9SDimitry Andric   // deleted, and any information that have about the outer loop invalidated.
761e8d8bef9SDimitry Andric   SE->forgetLoop(FI.OuterLoop);
762e8d8bef9SDimitry Andric   SE->forgetLoop(FI.InnerLoop);
763349cc55cSDimitry Andric   if (U)
764349cc55cSDimitry Andric     U->markLoopAsDeleted(*FI.InnerLoop, FI.InnerLoop->getName());
765e8d8bef9SDimitry Andric   LI->erase(FI.InnerLoop);
766349cc55cSDimitry Andric 
767349cc55cSDimitry Andric   // Increment statistic value.
768349cc55cSDimitry Andric   NumFlattened++;
769349cc55cSDimitry Andric 
770e8d8bef9SDimitry Andric   return true;
771e8d8bef9SDimitry Andric }
772e8d8bef9SDimitry Andric 
773fe6060f1SDimitry Andric static bool CanWidenIV(FlattenInfo &FI, DominatorTree *DT, LoopInfo *LI,
774fe6060f1SDimitry Andric                        ScalarEvolution *SE, AssumptionCache *AC,
775fe6060f1SDimitry Andric                        const TargetTransformInfo *TTI) {
776e8d8bef9SDimitry Andric   if (!WidenIV) {
777e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Widening the IVs is disabled\n");
778e8d8bef9SDimitry Andric     return false;
779e8d8bef9SDimitry Andric   }
780e8d8bef9SDimitry Andric 
781e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Try widening the IVs\n");
782e8d8bef9SDimitry Andric   Module *M = FI.InnerLoop->getHeader()->getParent()->getParent();
783e8d8bef9SDimitry Andric   auto &DL = M->getDataLayout();
784e8d8bef9SDimitry Andric   auto *InnerType = FI.InnerInductionPHI->getType();
785e8d8bef9SDimitry Andric   auto *OuterType = FI.OuterInductionPHI->getType();
786e8d8bef9SDimitry Andric   unsigned MaxLegalSize = DL.getLargestLegalIntTypeSizeInBits();
787e8d8bef9SDimitry Andric   auto *MaxLegalType = DL.getLargestLegalIntType(M->getContext());
788e8d8bef9SDimitry Andric 
789e8d8bef9SDimitry Andric   // If both induction types are less than the maximum legal integer width,
790e8d8bef9SDimitry Andric   // promote both to the widest type available so we know calculating
791fe6060f1SDimitry Andric   // (OuterTripCount * InnerTripCount) as the new trip count is safe.
792e8d8bef9SDimitry Andric   if (InnerType != OuterType ||
793e8d8bef9SDimitry Andric       InnerType->getScalarSizeInBits() >= MaxLegalSize ||
794*04eeddc0SDimitry Andric       MaxLegalType->getScalarSizeInBits() <
795*04eeddc0SDimitry Andric           InnerType->getScalarSizeInBits() * 2) {
796e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Can't widen the IV\n");
797e8d8bef9SDimitry Andric     return false;
798e8d8bef9SDimitry Andric   }
799e8d8bef9SDimitry Andric 
800e8d8bef9SDimitry Andric   SCEVExpander Rewriter(*SE, DL, "loopflatten");
801e8d8bef9SDimitry Andric   SmallVector<WeakTrackingVH, 4> DeadInsts;
802fe6060f1SDimitry Andric   unsigned ElimExt = 0;
803fe6060f1SDimitry Andric   unsigned Widened = 0;
804e8d8bef9SDimitry Andric 
805349cc55cSDimitry Andric   auto CreateWideIV = [&](WideIVInfo WideIV, bool &Deleted) -> bool {
806*04eeddc0SDimitry Andric     PHINode *WidePhi =
807*04eeddc0SDimitry Andric         createWideIV(WideIV, LI, SE, Rewriter, DT, DeadInsts, ElimExt, Widened,
808*04eeddc0SDimitry Andric                      true /* HasGuards */, true /* UsePostIncrementRanges */);
809e8d8bef9SDimitry Andric     if (!WidePhi)
810e8d8bef9SDimitry Andric       return false;
811e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Created wide phi: "; WidePhi->dump());
812fe6060f1SDimitry Andric     LLVM_DEBUG(dbgs() << "Deleting old phi: "; WideIV.NarrowIV->dump());
813349cc55cSDimitry Andric     Deleted = RecursivelyDeleteDeadPHINode(WideIV.NarrowIV);
814349cc55cSDimitry Andric     return true;
815349cc55cSDimitry Andric   };
816349cc55cSDimitry Andric 
817349cc55cSDimitry Andric   bool Deleted;
818349cc55cSDimitry Andric   if (!CreateWideIV({FI.InnerInductionPHI, MaxLegalType, false}, Deleted))
819349cc55cSDimitry Andric     return false;
820349cc55cSDimitry Andric   // Add the narrow phi to list, so that it will be adjusted later when the
821349cc55cSDimitry Andric   // the transformation is performed.
822349cc55cSDimitry Andric   if (!Deleted)
823349cc55cSDimitry Andric     FI.InnerPHIsToTransform.insert(FI.InnerInductionPHI);
824349cc55cSDimitry Andric 
825349cc55cSDimitry Andric   if (!CreateWideIV({FI.OuterInductionPHI, MaxLegalType, false}, Deleted))
826349cc55cSDimitry Andric     return false;
827349cc55cSDimitry Andric 
828fe6060f1SDimitry Andric   assert(Widened && "Widened IV expected");
829e8d8bef9SDimitry Andric   FI.Widened = true;
830349cc55cSDimitry Andric 
831349cc55cSDimitry Andric   // Save the old/narrow induction phis, which we need to ignore in CheckPHIs.
832349cc55cSDimitry Andric   FI.NarrowInnerInductionPHI = FI.InnerInductionPHI;
833349cc55cSDimitry Andric   FI.NarrowOuterInductionPHI = FI.OuterInductionPHI;
834349cc55cSDimitry Andric 
835349cc55cSDimitry Andric   // After widening, rediscover all the loop components.
836e8d8bef9SDimitry Andric   return CanFlattenLoopPair(FI, DT, LI, SE, AC, TTI);
837e8d8bef9SDimitry Andric }
838e8d8bef9SDimitry Andric 
839fe6060f1SDimitry Andric static bool FlattenLoopPair(FlattenInfo &FI, DominatorTree *DT, LoopInfo *LI,
840fe6060f1SDimitry Andric                             ScalarEvolution *SE, AssumptionCache *AC,
841*04eeddc0SDimitry Andric                             const TargetTransformInfo *TTI, LPMUpdater *U,
842*04eeddc0SDimitry Andric                             MemorySSAUpdater *MSSAU) {
843e8d8bef9SDimitry Andric   LLVM_DEBUG(
844e8d8bef9SDimitry Andric       dbgs() << "Loop flattening running on outer loop "
845e8d8bef9SDimitry Andric              << FI.OuterLoop->getHeader()->getName() << " and inner loop "
846e8d8bef9SDimitry Andric              << FI.InnerLoop->getHeader()->getName() << " in "
847e8d8bef9SDimitry Andric              << FI.OuterLoop->getHeader()->getParent()->getName() << "\n");
848e8d8bef9SDimitry Andric 
849e8d8bef9SDimitry Andric   if (!CanFlattenLoopPair(FI, DT, LI, SE, AC, TTI))
850e8d8bef9SDimitry Andric     return false;
851e8d8bef9SDimitry Andric 
852e8d8bef9SDimitry Andric   // Check if we can widen the induction variables to avoid overflow checks.
853349cc55cSDimitry Andric   bool CanFlatten = CanWidenIV(FI, DT, LI, SE, AC, TTI);
854e8d8bef9SDimitry Andric 
855349cc55cSDimitry Andric   // It can happen that after widening of the IV, flattening may not be
856349cc55cSDimitry Andric   // possible/happening, e.g. when it is deemed unprofitable. So bail here if
857349cc55cSDimitry Andric   // that is the case.
858349cc55cSDimitry Andric   // TODO: IV widening without performing the actual flattening transformation
859349cc55cSDimitry Andric   // is not ideal. While this codegen change should not matter much, it is an
860349cc55cSDimitry Andric   // unnecessary change which is better to avoid. It's unlikely this happens
861349cc55cSDimitry Andric   // often, because if it's unprofitibale after widening, it should be
862349cc55cSDimitry Andric   // unprofitabe before widening as checked in the first round of checks. But
863349cc55cSDimitry Andric   // 'RepeatedInstructionThreshold' is set to only 2, which can probably be
864349cc55cSDimitry Andric   // relaxed. Because this is making a code change (the IV widening, but not
865349cc55cSDimitry Andric   // the flattening), we return true here.
866349cc55cSDimitry Andric   if (FI.Widened && !CanFlatten)
867349cc55cSDimitry Andric     return true;
868349cc55cSDimitry Andric 
869349cc55cSDimitry Andric   // If we have widened and can perform the transformation, do that here.
870349cc55cSDimitry Andric   if (CanFlatten)
871*04eeddc0SDimitry Andric     return DoFlattenLoopPair(FI, DT, LI, SE, AC, TTI, U, MSSAU);
872349cc55cSDimitry Andric 
873349cc55cSDimitry Andric   // Otherwise, if we haven't widened the IV, check if the new iteration
874349cc55cSDimitry Andric   // variable might overflow. In this case, we need to version the loop, and
875349cc55cSDimitry Andric   // select the original version at runtime if the iteration space is too
876349cc55cSDimitry Andric   // large.
877e8d8bef9SDimitry Andric   // TODO: We currently don't version the loop.
878e8d8bef9SDimitry Andric   OverflowResult OR = checkOverflow(FI, DT, AC);
879e8d8bef9SDimitry Andric   if (OR == OverflowResult::AlwaysOverflowsHigh ||
880e8d8bef9SDimitry Andric       OR == OverflowResult::AlwaysOverflowsLow) {
881e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Multiply would always overflow, so not profitable\n");
882e8d8bef9SDimitry Andric     return false;
883e8d8bef9SDimitry Andric   } else if (OR == OverflowResult::MayOverflow) {
884e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Multiply might overflow, not flattening\n");
885e8d8bef9SDimitry Andric     return false;
886e8d8bef9SDimitry Andric   }
887e8d8bef9SDimitry Andric 
888e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Multiply cannot overflow, modifying loop in-place\n");
889*04eeddc0SDimitry Andric   return DoFlattenLoopPair(FI, DT, LI, SE, AC, TTI, U, MSSAU);
890e8d8bef9SDimitry Andric }
891e8d8bef9SDimitry Andric 
892fe6060f1SDimitry Andric bool Flatten(LoopNest &LN, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE,
893*04eeddc0SDimitry Andric              AssumptionCache *AC, TargetTransformInfo *TTI, LPMUpdater *U,
894*04eeddc0SDimitry Andric              MemorySSAUpdater *MSSAU) {
895e8d8bef9SDimitry Andric   bool Changed = false;
896fe6060f1SDimitry Andric   for (Loop *InnerLoop : LN.getLoops()) {
897e8d8bef9SDimitry Andric     auto *OuterLoop = InnerLoop->getParentLoop();
898e8d8bef9SDimitry Andric     if (!OuterLoop)
899e8d8bef9SDimitry Andric       continue;
900fe6060f1SDimitry Andric     FlattenInfo FI(OuterLoop, InnerLoop);
901*04eeddc0SDimitry Andric     Changed |= FlattenLoopPair(FI, DT, LI, SE, AC, TTI, U, MSSAU);
902e8d8bef9SDimitry Andric   }
903e8d8bef9SDimitry Andric   return Changed;
904e8d8bef9SDimitry Andric }
905e8d8bef9SDimitry Andric 
906fe6060f1SDimitry Andric PreservedAnalyses LoopFlattenPass::run(LoopNest &LN, LoopAnalysisManager &LAM,
907fe6060f1SDimitry Andric                                        LoopStandardAnalysisResults &AR,
908fe6060f1SDimitry Andric                                        LPMUpdater &U) {
909e8d8bef9SDimitry Andric 
910fe6060f1SDimitry Andric   bool Changed = false;
911fe6060f1SDimitry Andric 
912*04eeddc0SDimitry Andric   Optional<MemorySSAUpdater> MSSAU;
913*04eeddc0SDimitry Andric   if (AR.MSSA) {
914*04eeddc0SDimitry Andric     MSSAU = MemorySSAUpdater(AR.MSSA);
915*04eeddc0SDimitry Andric     if (VerifyMemorySSA)
916*04eeddc0SDimitry Andric       AR.MSSA->verifyMemorySSA();
917*04eeddc0SDimitry Andric   }
918*04eeddc0SDimitry Andric 
919fe6060f1SDimitry Andric   // The loop flattening pass requires loops to be
920fe6060f1SDimitry Andric   // in simplified form, and also needs LCSSA. Running
921fe6060f1SDimitry Andric   // this pass will simplify all loops that contain inner loops,
922fe6060f1SDimitry Andric   // regardless of whether anything ends up being flattened.
923*04eeddc0SDimitry Andric   Changed |= Flatten(LN, &AR.DT, &AR.LI, &AR.SE, &AR.AC, &AR.TTI, &U,
924*04eeddc0SDimitry Andric                      MSSAU.hasValue() ? MSSAU.getPointer() : nullptr);
925fe6060f1SDimitry Andric 
926fe6060f1SDimitry Andric   if (!Changed)
927e8d8bef9SDimitry Andric     return PreservedAnalyses::all();
928e8d8bef9SDimitry Andric 
929*04eeddc0SDimitry Andric   if (AR.MSSA && VerifyMemorySSA)
930*04eeddc0SDimitry Andric     AR.MSSA->verifyMemorySSA();
931*04eeddc0SDimitry Andric 
932*04eeddc0SDimitry Andric   auto PA = getLoopPassPreservedAnalyses();
933*04eeddc0SDimitry Andric   if (AR.MSSA)
934*04eeddc0SDimitry Andric     PA.preserve<MemorySSAAnalysis>();
935*04eeddc0SDimitry Andric   return PA;
936e8d8bef9SDimitry Andric }
937e8d8bef9SDimitry Andric 
938e8d8bef9SDimitry Andric namespace {
939e8d8bef9SDimitry Andric class LoopFlattenLegacyPass : public FunctionPass {
940e8d8bef9SDimitry Andric public:
941e8d8bef9SDimitry Andric   static char ID; // Pass ID, replacement for typeid
942e8d8bef9SDimitry Andric   LoopFlattenLegacyPass() : FunctionPass(ID) {
943e8d8bef9SDimitry Andric     initializeLoopFlattenLegacyPassPass(*PassRegistry::getPassRegistry());
944e8d8bef9SDimitry Andric   }
945e8d8bef9SDimitry Andric 
946e8d8bef9SDimitry Andric   // Possibly flatten loop L into its child.
947e8d8bef9SDimitry Andric   bool runOnFunction(Function &F) override;
948e8d8bef9SDimitry Andric 
949e8d8bef9SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
950e8d8bef9SDimitry Andric     getLoopAnalysisUsage(AU);
951e8d8bef9SDimitry Andric     AU.addRequired<TargetTransformInfoWrapperPass>();
952e8d8bef9SDimitry Andric     AU.addPreserved<TargetTransformInfoWrapperPass>();
953e8d8bef9SDimitry Andric     AU.addRequired<AssumptionCacheTracker>();
954e8d8bef9SDimitry Andric     AU.addPreserved<AssumptionCacheTracker>();
955*04eeddc0SDimitry Andric     AU.addPreserved<MemorySSAWrapperPass>();
956e8d8bef9SDimitry Andric   }
957e8d8bef9SDimitry Andric };
958e8d8bef9SDimitry Andric } // namespace
959e8d8bef9SDimitry Andric 
960e8d8bef9SDimitry Andric char LoopFlattenLegacyPass::ID = 0;
961e8d8bef9SDimitry Andric INITIALIZE_PASS_BEGIN(LoopFlattenLegacyPass, "loop-flatten", "Flattens loops",
962e8d8bef9SDimitry Andric                       false, false)
963e8d8bef9SDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
964e8d8bef9SDimitry Andric INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
965e8d8bef9SDimitry Andric INITIALIZE_PASS_END(LoopFlattenLegacyPass, "loop-flatten", "Flattens loops",
966e8d8bef9SDimitry Andric                     false, false)
967e8d8bef9SDimitry Andric 
968*04eeddc0SDimitry Andric FunctionPass *llvm::createLoopFlattenPass() {
969*04eeddc0SDimitry Andric   return new LoopFlattenLegacyPass();
970*04eeddc0SDimitry Andric }
971e8d8bef9SDimitry Andric 
972e8d8bef9SDimitry Andric bool LoopFlattenLegacyPass::runOnFunction(Function &F) {
973e8d8bef9SDimitry Andric   ScalarEvolution *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
974e8d8bef9SDimitry Andric   LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
975e8d8bef9SDimitry Andric   auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
976e8d8bef9SDimitry Andric   DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
977e8d8bef9SDimitry Andric   auto &TTIP = getAnalysis<TargetTransformInfoWrapperPass>();
978e8d8bef9SDimitry Andric   auto *TTI = &TTIP.getTTI(F);
979e8d8bef9SDimitry Andric   auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
980*04eeddc0SDimitry Andric   auto *MSSA = getAnalysisIfAvailable<MemorySSAWrapperPass>();
981*04eeddc0SDimitry Andric 
982*04eeddc0SDimitry Andric   Optional<MemorySSAUpdater> MSSAU;
983*04eeddc0SDimitry Andric   if (MSSA)
984*04eeddc0SDimitry Andric     MSSAU = MemorySSAUpdater(&MSSA->getMSSA());
985*04eeddc0SDimitry Andric 
986fe6060f1SDimitry Andric   bool Changed = false;
987fe6060f1SDimitry Andric   for (Loop *L : *LI) {
988fe6060f1SDimitry Andric     auto LN = LoopNest::getLoopNest(*L, *SE);
989*04eeddc0SDimitry Andric     Changed |= Flatten(*LN, DT, LI, SE, AC, TTI, nullptr,
990*04eeddc0SDimitry Andric                        MSSAU.hasValue() ? MSSAU.getPointer() : nullptr);
991fe6060f1SDimitry Andric   }
992fe6060f1SDimitry Andric   return Changed;
993e8d8bef9SDimitry Andric }
994