xref: /freebsd-src/contrib/llvm-project/llvm/lib/Transforms/Scalar/LoopFlatten.cpp (revision 81ad626541db97eb356e2c1d4a20eb2a26a766ab)
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:
1304eeddc0SDimitry 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]);
1704eeddc0SDimitry Andric //
18e8d8bef9SDimitry Andric // into one loop:
1904eeddc0SDimitry 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 //
2804eeddc0SDimitry Andric // We also need to prove that N*M will not overflow. The preferred solution is
2904eeddc0SDimitry Andric // to widen the IV, which avoids overflow checks, so that is tried first. If
3004eeddc0SDimitry Andric // the IV cannot be widened, then we try to determine that this new tripcount
3104eeddc0SDimitry Andric // expression won't overflow.
3204eeddc0SDimitry Andric //
3304eeddc0SDimitry Andric // Q: Does LoopFlatten use SCEV?
3404eeddc0SDimitry Andric // Short answer: Yes and no.
3504eeddc0SDimitry Andric //
3604eeddc0SDimitry Andric // Long answer:
3704eeddc0SDimitry Andric // For this transformation to be valid, we require all uses of the induction
3804eeddc0SDimitry Andric // variables to be linear expressions of the form i*M+j. The different Loop
3904eeddc0SDimitry Andric // APIs are used to get some loop components like the induction variable,
4004eeddc0SDimitry Andric // compare statement, etc. In addition, we do some pattern matching to find the
4104eeddc0SDimitry Andric // linear expressions and other loop components like the loop increment. The
4204eeddc0SDimitry Andric // latter are examples of expressions that do use the induction variable, but
4304eeddc0SDimitry Andric // are safe to ignore when we check all uses to be of the form i*M+j. We keep
4404eeddc0SDimitry Andric // track of all of this in bookkeeping struct FlattenInfo.
4504eeddc0SDimitry Andric // We assume the loops to be canonical, i.e. starting at 0 and increment with
4604eeddc0SDimitry Andric // 1. This makes RHS of the compare the loop tripcount (with the right
4704eeddc0SDimitry Andric // predicate). We use SCEV to then sanity check that this tripcount matches
4804eeddc0SDimitry 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*81ad6265SDimitry Andric #include "llvm/Analysis/LoopNestAnalysis.h"
5804eeddc0SDimitry Andric #include "llvm/Analysis/MemorySSAUpdater.h"
59e8d8bef9SDimitry Andric #include "llvm/Analysis/OptimizationRemarkEmitter.h"
60e8d8bef9SDimitry Andric #include "llvm/Analysis/ScalarEvolution.h"
61e8d8bef9SDimitry Andric #include "llvm/Analysis/TargetTransformInfo.h"
62e8d8bef9SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
63e8d8bef9SDimitry Andric #include "llvm/IR/Dominators.h"
64e8d8bef9SDimitry Andric #include "llvm/IR/Function.h"
65e8d8bef9SDimitry Andric #include "llvm/IR/IRBuilder.h"
66e8d8bef9SDimitry Andric #include "llvm/IR/Module.h"
67e8d8bef9SDimitry Andric #include "llvm/IR/PatternMatch.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"
73*81ad6265SDimitry Andric #include "llvm/Transforms/Scalar/LoopPassManager.h"
74e8d8bef9SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
75e8d8bef9SDimitry Andric #include "llvm/Transforms/Utils/LoopUtils.h"
76e8d8bef9SDimitry Andric #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
77e8d8bef9SDimitry Andric #include "llvm/Transforms/Utils/SimplifyIndVar.h"
78e8d8bef9SDimitry Andric 
79e8d8bef9SDimitry Andric using namespace llvm;
80e8d8bef9SDimitry Andric using namespace llvm::PatternMatch;
81e8d8bef9SDimitry Andric 
82349cc55cSDimitry Andric #define DEBUG_TYPE "loop-flatten"
83349cc55cSDimitry Andric 
84349cc55cSDimitry Andric STATISTIC(NumFlattened, "Number of loops flattened");
85349cc55cSDimitry Andric 
86e8d8bef9SDimitry Andric static cl::opt<unsigned> RepeatedInstructionThreshold(
87e8d8bef9SDimitry Andric     "loop-flatten-cost-threshold", cl::Hidden, cl::init(2),
88e8d8bef9SDimitry Andric     cl::desc("Limit on the cost of instructions that can be repeated due to "
89e8d8bef9SDimitry Andric              "loop flattening"));
90e8d8bef9SDimitry Andric 
91e8d8bef9SDimitry Andric static cl::opt<bool>
92e8d8bef9SDimitry Andric     AssumeNoOverflow("loop-flatten-assume-no-overflow", cl::Hidden,
93e8d8bef9SDimitry Andric                      cl::init(false),
94e8d8bef9SDimitry Andric                      cl::desc("Assume that the product of the two iteration "
95fe6060f1SDimitry Andric                               "trip counts will never overflow"));
96e8d8bef9SDimitry Andric 
97e8d8bef9SDimitry Andric static cl::opt<bool>
9804eeddc0SDimitry Andric     WidenIV("loop-flatten-widen-iv", cl::Hidden, cl::init(true),
99e8d8bef9SDimitry Andric             cl::desc("Widen the loop induction variables, if possible, so "
100e8d8bef9SDimitry Andric                      "overflow checks won't reject flattening"));
101e8d8bef9SDimitry Andric 
10204eeddc0SDimitry Andric // We require all uses of both induction variables to match this pattern:
10304eeddc0SDimitry Andric //
10404eeddc0SDimitry Andric //   (OuterPHI * InnerTripCount) + InnerPHI
10504eeddc0SDimitry Andric //
10604eeddc0SDimitry Andric // I.e., it needs to be a linear expression of the induction variables and the
10704eeddc0SDimitry Andric // inner loop trip count. We keep track of all different expressions on which
10804eeddc0SDimitry Andric // checks will be performed in this bookkeeping struct.
10904eeddc0SDimitry Andric //
110e8d8bef9SDimitry Andric struct FlattenInfo {
11104eeddc0SDimitry Andric   Loop *OuterLoop = nullptr;  // The loop pair to be flattened.
112e8d8bef9SDimitry Andric   Loop *InnerLoop = nullptr;
11304eeddc0SDimitry Andric 
11404eeddc0SDimitry Andric   PHINode *InnerInductionPHI = nullptr; // These PHINodes correspond to loop
11504eeddc0SDimitry Andric   PHINode *OuterInductionPHI = nullptr; // induction variables, which are
11604eeddc0SDimitry Andric                                         // expected to start at zero and
11704eeddc0SDimitry Andric                                         // increment by one on each loop.
11804eeddc0SDimitry Andric 
11904eeddc0SDimitry Andric   Value *InnerTripCount = nullptr; // The product of these two tripcounts
12004eeddc0SDimitry Andric   Value *OuterTripCount = nullptr; // will be the new flattened loop
12104eeddc0SDimitry Andric                                    // tripcount. Also used to recognise a
12204eeddc0SDimitry Andric                                    // linear expression that will be replaced.
12304eeddc0SDimitry Andric 
12404eeddc0SDimitry Andric   SmallPtrSet<Value *, 4> LinearIVUses;  // Contains the linear expressions
12504eeddc0SDimitry Andric                                          // of the form i*M+j that will be
12604eeddc0SDimitry Andric                                          // replaced.
12704eeddc0SDimitry Andric 
12804eeddc0SDimitry Andric   BinaryOperator *InnerIncrement = nullptr;  // Uses of induction variables in
12904eeddc0SDimitry Andric   BinaryOperator *OuterIncrement = nullptr;  // loop control statements that
13004eeddc0SDimitry Andric   BranchInst *InnerBranch = nullptr;         // are safe to ignore.
13104eeddc0SDimitry Andric 
13204eeddc0SDimitry Andric   BranchInst *OuterBranch = nullptr; // The instruction that needs to be
13304eeddc0SDimitry Andric                                      // updated with new tripcount.
13404eeddc0SDimitry Andric 
135e8d8bef9SDimitry Andric   SmallPtrSet<PHINode *, 4> InnerPHIsToTransform;
136e8d8bef9SDimitry Andric 
13704eeddc0SDimitry Andric   bool Widened = false; // Whether this holds the flatten info before or after
13804eeddc0SDimitry Andric                         // widening.
139e8d8bef9SDimitry Andric 
14004eeddc0SDimitry Andric   PHINode *NarrowInnerInductionPHI = nullptr; // Holds the old/narrow induction
14104eeddc0SDimitry Andric   PHINode *NarrowOuterInductionPHI = nullptr; // phis, i.e. the Phis before IV
14204eeddc0SDimitry Andric                                               // has been apllied. Used to skip
14304eeddc0SDimitry Andric                                               // checks on phi nodes.
144349cc55cSDimitry Andric 
145e8d8bef9SDimitry Andric   FlattenInfo(Loop *OL, Loop *IL) : OuterLoop(OL), InnerLoop(IL){};
146349cc55cSDimitry Andric 
147349cc55cSDimitry Andric   bool isNarrowInductionPhi(PHINode *Phi) {
148349cc55cSDimitry Andric     // This can't be the narrow phi if we haven't widened the IV first.
149349cc55cSDimitry Andric     if (!Widened)
150349cc55cSDimitry Andric       return false;
151349cc55cSDimitry Andric     return NarrowInnerInductionPHI == Phi || NarrowOuterInductionPHI == Phi;
152349cc55cSDimitry Andric   }
15304eeddc0SDimitry Andric   bool isInnerLoopIncrement(User *U) {
15404eeddc0SDimitry Andric     return InnerIncrement == U;
15504eeddc0SDimitry Andric   }
15604eeddc0SDimitry Andric   bool isOuterLoopIncrement(User *U) {
15704eeddc0SDimitry Andric     return OuterIncrement == U;
15804eeddc0SDimitry Andric   }
15904eeddc0SDimitry Andric   bool isInnerLoopTest(User *U) {
16004eeddc0SDimitry Andric     return InnerBranch->getCondition() == U;
16104eeddc0SDimitry Andric   }
16204eeddc0SDimitry Andric 
16304eeddc0SDimitry Andric   bool checkOuterInductionPhiUsers(SmallPtrSet<Value *, 4> &ValidOuterPHIUses) {
16404eeddc0SDimitry Andric     for (User *U : OuterInductionPHI->users()) {
16504eeddc0SDimitry Andric       if (isOuterLoopIncrement(U))
16604eeddc0SDimitry Andric         continue;
16704eeddc0SDimitry Andric 
16804eeddc0SDimitry Andric       auto IsValidOuterPHIUses = [&] (User *U) -> bool {
16904eeddc0SDimitry Andric         LLVM_DEBUG(dbgs() << "Found use of outer induction variable: "; U->dump());
17004eeddc0SDimitry Andric         if (!ValidOuterPHIUses.count(U)) {
17104eeddc0SDimitry Andric           LLVM_DEBUG(dbgs() << "Did not match expected pattern, bailing\n");
17204eeddc0SDimitry Andric           return false;
17304eeddc0SDimitry Andric         }
17404eeddc0SDimitry Andric         LLVM_DEBUG(dbgs() << "Use is optimisable\n");
17504eeddc0SDimitry Andric         return true;
17604eeddc0SDimitry Andric       };
17704eeddc0SDimitry Andric 
17804eeddc0SDimitry Andric       if (auto *V = dyn_cast<TruncInst>(U)) {
17904eeddc0SDimitry Andric         for (auto *K : V->users()) {
18004eeddc0SDimitry Andric           if (!IsValidOuterPHIUses(K))
18104eeddc0SDimitry Andric             return false;
18204eeddc0SDimitry Andric         }
18304eeddc0SDimitry Andric         continue;
18404eeddc0SDimitry Andric       }
18504eeddc0SDimitry Andric 
18604eeddc0SDimitry Andric       if (!IsValidOuterPHIUses(U))
18704eeddc0SDimitry Andric         return false;
18804eeddc0SDimitry Andric     }
18904eeddc0SDimitry Andric     return true;
19004eeddc0SDimitry Andric   }
19104eeddc0SDimitry Andric 
19204eeddc0SDimitry Andric   bool matchLinearIVUser(User *U, Value *InnerTripCount,
19304eeddc0SDimitry Andric                          SmallPtrSet<Value *, 4> &ValidOuterPHIUses) {
19404eeddc0SDimitry Andric     LLVM_DEBUG(dbgs() << "Found use of inner induction variable: "; U->dump());
19504eeddc0SDimitry Andric     Value *MatchedMul = nullptr;
19604eeddc0SDimitry Andric     Value *MatchedItCount = nullptr;
19704eeddc0SDimitry Andric 
19804eeddc0SDimitry Andric     bool IsAdd = match(U, m_c_Add(m_Specific(InnerInductionPHI),
19904eeddc0SDimitry Andric                                   m_Value(MatchedMul))) &&
20004eeddc0SDimitry Andric                  match(MatchedMul, m_c_Mul(m_Specific(OuterInductionPHI),
20104eeddc0SDimitry Andric                                            m_Value(MatchedItCount)));
20204eeddc0SDimitry Andric 
20304eeddc0SDimitry Andric     // Matches the same pattern as above, except it also looks for truncs
20404eeddc0SDimitry Andric     // on the phi, which can be the result of widening the induction variables.
20504eeddc0SDimitry Andric     bool IsAddTrunc =
20604eeddc0SDimitry Andric         match(U, m_c_Add(m_Trunc(m_Specific(InnerInductionPHI)),
20704eeddc0SDimitry Andric                          m_Value(MatchedMul))) &&
20804eeddc0SDimitry Andric         match(MatchedMul, m_c_Mul(m_Trunc(m_Specific(OuterInductionPHI)),
20904eeddc0SDimitry Andric                                   m_Value(MatchedItCount)));
21004eeddc0SDimitry Andric 
21104eeddc0SDimitry Andric     if (!MatchedItCount)
21204eeddc0SDimitry Andric       return false;
21304eeddc0SDimitry Andric 
214*81ad6265SDimitry Andric     // Look through extends if the IV has been widened. Don't look through
215*81ad6265SDimitry Andric     // extends if we already looked through a trunc.
216*81ad6265SDimitry Andric     if (Widened && IsAdd &&
21704eeddc0SDimitry Andric         (isa<SExtInst>(MatchedItCount) || isa<ZExtInst>(MatchedItCount))) {
21804eeddc0SDimitry Andric       assert(MatchedItCount->getType() == InnerInductionPHI->getType() &&
21904eeddc0SDimitry Andric              "Unexpected type mismatch in types after widening");
22004eeddc0SDimitry Andric       MatchedItCount = isa<SExtInst>(MatchedItCount)
22104eeddc0SDimitry Andric                            ? dyn_cast<SExtInst>(MatchedItCount)->getOperand(0)
22204eeddc0SDimitry Andric                            : dyn_cast<ZExtInst>(MatchedItCount)->getOperand(0);
22304eeddc0SDimitry Andric     }
22404eeddc0SDimitry Andric 
22504eeddc0SDimitry Andric     if ((IsAdd || IsAddTrunc) && MatchedItCount == InnerTripCount) {
22604eeddc0SDimitry Andric       LLVM_DEBUG(dbgs() << "Use is optimisable\n");
22704eeddc0SDimitry Andric       ValidOuterPHIUses.insert(MatchedMul);
22804eeddc0SDimitry Andric       LinearIVUses.insert(U);
22904eeddc0SDimitry Andric       return true;
23004eeddc0SDimitry Andric     }
23104eeddc0SDimitry Andric 
23204eeddc0SDimitry Andric     LLVM_DEBUG(dbgs() << "Did not match expected pattern, bailing\n");
23304eeddc0SDimitry Andric     return false;
23404eeddc0SDimitry Andric   }
23504eeddc0SDimitry Andric 
23604eeddc0SDimitry Andric   bool checkInnerInductionPhiUsers(SmallPtrSet<Value *, 4> &ValidOuterPHIUses) {
23704eeddc0SDimitry Andric     Value *SExtInnerTripCount = InnerTripCount;
23804eeddc0SDimitry Andric     if (Widened &&
23904eeddc0SDimitry Andric         (isa<SExtInst>(InnerTripCount) || isa<ZExtInst>(InnerTripCount)))
24004eeddc0SDimitry Andric       SExtInnerTripCount = cast<Instruction>(InnerTripCount)->getOperand(0);
24104eeddc0SDimitry Andric 
24204eeddc0SDimitry Andric     for (User *U : InnerInductionPHI->users()) {
24304eeddc0SDimitry Andric       if (isInnerLoopIncrement(U))
24404eeddc0SDimitry Andric         continue;
24504eeddc0SDimitry Andric 
24604eeddc0SDimitry Andric       // After widening the IVs, a trunc instruction might have been introduced,
24704eeddc0SDimitry Andric       // so look through truncs.
24804eeddc0SDimitry Andric       if (isa<TruncInst>(U)) {
24904eeddc0SDimitry Andric         if (!U->hasOneUse())
25004eeddc0SDimitry Andric           return false;
25104eeddc0SDimitry Andric         U = *U->user_begin();
25204eeddc0SDimitry Andric       }
25304eeddc0SDimitry Andric 
25404eeddc0SDimitry Andric       // If the use is in the compare (which is also the condition of the inner
25504eeddc0SDimitry Andric       // branch) then the compare has been altered by another transformation e.g
25604eeddc0SDimitry Andric       // icmp ult %inc, tripcount -> icmp ult %j, tripcount-1, where tripcount is
25704eeddc0SDimitry Andric       // a constant. Ignore this use as the compare gets removed later anyway.
25804eeddc0SDimitry Andric       if (isInnerLoopTest(U))
25904eeddc0SDimitry Andric         continue;
26004eeddc0SDimitry Andric 
26104eeddc0SDimitry Andric       if (!matchLinearIVUser(U, SExtInnerTripCount, ValidOuterPHIUses))
26204eeddc0SDimitry Andric         return false;
26304eeddc0SDimitry Andric     }
26404eeddc0SDimitry Andric     return true;
26504eeddc0SDimitry Andric   }
266e8d8bef9SDimitry Andric };
267e8d8bef9SDimitry Andric 
268349cc55cSDimitry Andric static bool
269349cc55cSDimitry Andric setLoopComponents(Value *&TC, Value *&TripCount, BinaryOperator *&Increment,
270349cc55cSDimitry Andric                   SmallPtrSetImpl<Instruction *> &IterationInstructions) {
271349cc55cSDimitry Andric   TripCount = TC;
272349cc55cSDimitry Andric   IterationInstructions.insert(Increment);
273349cc55cSDimitry Andric   LLVM_DEBUG(dbgs() << "Found Increment: "; Increment->dump());
274349cc55cSDimitry Andric   LLVM_DEBUG(dbgs() << "Found trip count: "; TripCount->dump());
275349cc55cSDimitry Andric   LLVM_DEBUG(dbgs() << "Successfully found all loop components\n");
276349cc55cSDimitry Andric   return true;
277349cc55cSDimitry Andric }
278349cc55cSDimitry Andric 
27904eeddc0SDimitry Andric // Given the RHS of the loop latch compare instruction, verify with SCEV
28004eeddc0SDimitry Andric // that this is indeed the loop tripcount.
28104eeddc0SDimitry Andric // TODO: This used to be a straightforward check but has grown to be quite
28204eeddc0SDimitry Andric // complicated now. It is therefore worth revisiting what the additional
28304eeddc0SDimitry Andric // benefits are of this (compared to relying on canonical loops and pattern
28404eeddc0SDimitry Andric // matching).
28504eeddc0SDimitry Andric static bool verifyTripCount(Value *RHS, Loop *L,
28604eeddc0SDimitry Andric      SmallPtrSetImpl<Instruction *> &IterationInstructions,
28704eeddc0SDimitry Andric     PHINode *&InductionPHI, Value *&TripCount, BinaryOperator *&Increment,
28804eeddc0SDimitry Andric     BranchInst *&BackBranch, ScalarEvolution *SE, bool IsWidened) {
28904eeddc0SDimitry Andric   const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
29004eeddc0SDimitry Andric   if (isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
29104eeddc0SDimitry Andric     LLVM_DEBUG(dbgs() << "Backedge-taken count is not predictable\n");
29204eeddc0SDimitry Andric     return false;
29304eeddc0SDimitry Andric   }
29404eeddc0SDimitry Andric 
29504eeddc0SDimitry Andric   // The Extend=false flag is used for getTripCountFromExitCount as we want
29604eeddc0SDimitry Andric   // to verify and match it with the pattern matched tripcount. Please note
29704eeddc0SDimitry Andric   // that overflow checks are performed in checkOverflow, but are first tried
29804eeddc0SDimitry Andric   // to avoid by widening the IV.
29904eeddc0SDimitry Andric   const SCEV *SCEVTripCount =
30004eeddc0SDimitry Andric       SE->getTripCountFromExitCount(BackedgeTakenCount, /*Extend=*/false);
30104eeddc0SDimitry Andric 
30204eeddc0SDimitry Andric   const SCEV *SCEVRHS = SE->getSCEV(RHS);
30304eeddc0SDimitry Andric   if (SCEVRHS == SCEVTripCount)
30404eeddc0SDimitry Andric     return setLoopComponents(RHS, TripCount, Increment, IterationInstructions);
30504eeddc0SDimitry Andric   ConstantInt *ConstantRHS = dyn_cast<ConstantInt>(RHS);
30604eeddc0SDimitry Andric   if (ConstantRHS) {
30704eeddc0SDimitry Andric     const SCEV *BackedgeTCExt = nullptr;
30804eeddc0SDimitry Andric     if (IsWidened) {
30904eeddc0SDimitry Andric       const SCEV *SCEVTripCountExt;
31004eeddc0SDimitry Andric       // Find the extended backedge taken count and extended trip count using
31104eeddc0SDimitry Andric       // SCEV. One of these should now match the RHS of the compare.
31204eeddc0SDimitry Andric       BackedgeTCExt = SE->getZeroExtendExpr(BackedgeTakenCount, RHS->getType());
31304eeddc0SDimitry Andric       SCEVTripCountExt = SE->getTripCountFromExitCount(BackedgeTCExt, false);
31404eeddc0SDimitry Andric       if (SCEVRHS != BackedgeTCExt && SCEVRHS != SCEVTripCountExt) {
31504eeddc0SDimitry Andric         LLVM_DEBUG(dbgs() << "Could not find valid trip count\n");
31604eeddc0SDimitry Andric         return false;
31704eeddc0SDimitry Andric       }
31804eeddc0SDimitry Andric     }
31904eeddc0SDimitry Andric     // If the RHS of the compare is equal to the backedge taken count we need
32004eeddc0SDimitry Andric     // to add one to get the trip count.
32104eeddc0SDimitry Andric     if (SCEVRHS == BackedgeTCExt || SCEVRHS == BackedgeTakenCount) {
32204eeddc0SDimitry Andric       ConstantInt *One = ConstantInt::get(ConstantRHS->getType(), 1);
32304eeddc0SDimitry Andric       Value *NewRHS = ConstantInt::get(
32404eeddc0SDimitry Andric           ConstantRHS->getContext(), ConstantRHS->getValue() + One->getValue());
32504eeddc0SDimitry Andric       return setLoopComponents(NewRHS, TripCount, Increment,
32604eeddc0SDimitry Andric                                IterationInstructions);
32704eeddc0SDimitry Andric     }
32804eeddc0SDimitry Andric     return setLoopComponents(RHS, TripCount, Increment, IterationInstructions);
32904eeddc0SDimitry Andric   }
33004eeddc0SDimitry Andric   // If the RHS isn't a constant then check that the reason it doesn't match
33104eeddc0SDimitry Andric   // the SCEV trip count is because the RHS is a ZExt or SExt instruction
33204eeddc0SDimitry Andric   // (and take the trip count to be the RHS).
33304eeddc0SDimitry Andric   if (!IsWidened) {
33404eeddc0SDimitry Andric     LLVM_DEBUG(dbgs() << "Could not find valid trip count\n");
33504eeddc0SDimitry Andric     return false;
33604eeddc0SDimitry Andric   }
33704eeddc0SDimitry Andric   auto *TripCountInst = dyn_cast<Instruction>(RHS);
33804eeddc0SDimitry Andric   if (!TripCountInst) {
33904eeddc0SDimitry Andric     LLVM_DEBUG(dbgs() << "Could not find valid trip count\n");
34004eeddc0SDimitry Andric     return false;
34104eeddc0SDimitry Andric   }
34204eeddc0SDimitry Andric   if ((!isa<ZExtInst>(TripCountInst) && !isa<SExtInst>(TripCountInst)) ||
34304eeddc0SDimitry Andric       SE->getSCEV(TripCountInst->getOperand(0)) != SCEVTripCount) {
34404eeddc0SDimitry Andric     LLVM_DEBUG(dbgs() << "Could not find valid extended trip count\n");
34504eeddc0SDimitry Andric     return false;
34604eeddc0SDimitry Andric   }
34704eeddc0SDimitry Andric   return setLoopComponents(RHS, TripCount, Increment, IterationInstructions);
34804eeddc0SDimitry Andric }
34904eeddc0SDimitry Andric 
350fe6060f1SDimitry Andric // Finds the induction variable, increment and trip count for a simple loop that
351fe6060f1SDimitry Andric // we can flatten.
352e8d8bef9SDimitry Andric static bool findLoopComponents(
353e8d8bef9SDimitry Andric     Loop *L, SmallPtrSetImpl<Instruction *> &IterationInstructions,
354fe6060f1SDimitry Andric     PHINode *&InductionPHI, Value *&TripCount, BinaryOperator *&Increment,
355fe6060f1SDimitry Andric     BranchInst *&BackBranch, ScalarEvolution *SE, bool IsWidened) {
356e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Finding components of loop: " << L->getName() << "\n");
357e8d8bef9SDimitry Andric 
358e8d8bef9SDimitry Andric   if (!L->isLoopSimplifyForm()) {
359e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Loop is not in normal form\n");
360e8d8bef9SDimitry Andric     return false;
361e8d8bef9SDimitry Andric   }
362e8d8bef9SDimitry Andric 
363fe6060f1SDimitry Andric   // Currently, to simplify the implementation, the Loop induction variable must
364fe6060f1SDimitry Andric   // start at zero and increment with a step size of one.
365fe6060f1SDimitry Andric   if (!L->isCanonical(*SE)) {
366fe6060f1SDimitry Andric     LLVM_DEBUG(dbgs() << "Loop is not canonical\n");
367fe6060f1SDimitry Andric     return false;
368fe6060f1SDimitry Andric   }
369fe6060f1SDimitry Andric 
370e8d8bef9SDimitry Andric   // There must be exactly one exiting block, and it must be the same at the
371e8d8bef9SDimitry Andric   // latch.
372e8d8bef9SDimitry Andric   BasicBlock *Latch = L->getLoopLatch();
373e8d8bef9SDimitry Andric   if (L->getExitingBlock() != Latch) {
374e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Exiting and latch block are different\n");
375e8d8bef9SDimitry Andric     return false;
376e8d8bef9SDimitry Andric   }
377e8d8bef9SDimitry Andric 
378e8d8bef9SDimitry Andric   // Find the induction PHI. If there is no induction PHI, we can't do the
379e8d8bef9SDimitry Andric   // transformation. TODO: could other variables trigger this? Do we have to
380e8d8bef9SDimitry Andric   // search for the best one?
381fe6060f1SDimitry Andric   InductionPHI = L->getInductionVariable(*SE);
382e8d8bef9SDimitry Andric   if (!InductionPHI) {
383e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Could not find induction PHI\n");
384e8d8bef9SDimitry Andric     return false;
385e8d8bef9SDimitry Andric   }
386fe6060f1SDimitry Andric   LLVM_DEBUG(dbgs() << "Found induction PHI: "; InductionPHI->dump());
387e8d8bef9SDimitry Andric 
388fe6060f1SDimitry Andric   bool ContinueOnTrue = L->contains(Latch->getTerminator()->getSuccessor(0));
389e8d8bef9SDimitry Andric   auto IsValidPredicate = [&](ICmpInst::Predicate Pred) {
390e8d8bef9SDimitry Andric     if (ContinueOnTrue)
391e8d8bef9SDimitry Andric       return Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_ULT;
392e8d8bef9SDimitry Andric     else
393e8d8bef9SDimitry Andric       return Pred == CmpInst::ICMP_EQ;
394e8d8bef9SDimitry Andric   };
395e8d8bef9SDimitry Andric 
396fe6060f1SDimitry Andric   // Find Compare and make sure it is valid. getLatchCmpInst checks that the
397fe6060f1SDimitry Andric   // back branch of the latch is conditional.
398fe6060f1SDimitry Andric   ICmpInst *Compare = L->getLatchCmpInst();
399e8d8bef9SDimitry Andric   if (!Compare || !IsValidPredicate(Compare->getUnsignedPredicate()) ||
400e8d8bef9SDimitry Andric       Compare->hasNUsesOrMore(2)) {
401e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Could not find valid comparison\n");
402e8d8bef9SDimitry Andric     return false;
403e8d8bef9SDimitry Andric   }
404fe6060f1SDimitry Andric   BackBranch = cast<BranchInst>(Latch->getTerminator());
405fe6060f1SDimitry Andric   IterationInstructions.insert(BackBranch);
406fe6060f1SDimitry Andric   LLVM_DEBUG(dbgs() << "Found back branch: "; BackBranch->dump());
407e8d8bef9SDimitry Andric   IterationInstructions.insert(Compare);
408e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Found comparison: "; Compare->dump());
409e8d8bef9SDimitry Andric 
410fe6060f1SDimitry Andric   // Find increment and trip count.
411fe6060f1SDimitry Andric   // There are exactly 2 incoming values to the induction phi; one from the
412fe6060f1SDimitry Andric   // pre-header and one from the latch. The incoming latch value is the
413fe6060f1SDimitry Andric   // increment variable.
414fe6060f1SDimitry Andric   Increment =
415*81ad6265SDimitry Andric       cast<BinaryOperator>(InductionPHI->getIncomingValueForBlock(Latch));
416fe6060f1SDimitry Andric   if (Increment->hasNUsesOrMore(3)) {
417fe6060f1SDimitry Andric     LLVM_DEBUG(dbgs() << "Could not find valid increment\n");
418e8d8bef9SDimitry Andric     return false;
419e8d8bef9SDimitry Andric   }
420fe6060f1SDimitry Andric   // The trip count is the RHS of the compare. If this doesn't match the trip
421349cc55cSDimitry Andric   // count computed by SCEV then this is because the trip count variable
422349cc55cSDimitry Andric   // has been widened so the types don't match, or because it is a constant and
423349cc55cSDimitry Andric   // another transformation has changed the compare (e.g. icmp ult %inc,
424349cc55cSDimitry Andric   // tripcount -> icmp ult %j, tripcount-1), or both.
425349cc55cSDimitry Andric   Value *RHS = Compare->getOperand(1);
42604eeddc0SDimitry Andric 
42704eeddc0SDimitry Andric   return verifyTripCount(RHS, L, IterationInstructions, InductionPHI, TripCount,
42804eeddc0SDimitry Andric                          Increment, BackBranch, SE, IsWidened);
429e8d8bef9SDimitry Andric }
430e8d8bef9SDimitry Andric 
431fe6060f1SDimitry Andric static bool checkPHIs(FlattenInfo &FI, const TargetTransformInfo *TTI) {
432e8d8bef9SDimitry Andric   // All PHIs in the inner and outer headers must either be:
433e8d8bef9SDimitry Andric   // - The induction PHI, which we are going to rewrite as one induction in
434e8d8bef9SDimitry Andric   //   the new loop. This is already checked by findLoopComponents.
435e8d8bef9SDimitry Andric   // - An outer header PHI with all incoming values from outside the loop.
436e8d8bef9SDimitry Andric   //   LoopSimplify guarantees we have a pre-header, so we don't need to
437e8d8bef9SDimitry Andric   //   worry about that here.
438e8d8bef9SDimitry Andric   // - Pairs of PHIs in the inner and outer headers, which implement a
439e8d8bef9SDimitry Andric   //   loop-carried dependency that will still be valid in the new loop. To
440e8d8bef9SDimitry Andric   //   be valid, this variable must be modified only in the inner loop.
441e8d8bef9SDimitry Andric 
442e8d8bef9SDimitry Andric   // The set of PHI nodes in the outer loop header that we know will still be
443e8d8bef9SDimitry Andric   // valid after the transformation. These will not need to be modified (with
444e8d8bef9SDimitry Andric   // the exception of the induction variable), but we do need to check that
445e8d8bef9SDimitry Andric   // there are no unsafe PHI nodes.
446e8d8bef9SDimitry Andric   SmallPtrSet<PHINode *, 4> SafeOuterPHIs;
447e8d8bef9SDimitry Andric   SafeOuterPHIs.insert(FI.OuterInductionPHI);
448e8d8bef9SDimitry Andric 
449e8d8bef9SDimitry Andric   // Check that all PHI nodes in the inner loop header match one of the valid
450e8d8bef9SDimitry Andric   // patterns.
451e8d8bef9SDimitry Andric   for (PHINode &InnerPHI : FI.InnerLoop->getHeader()->phis()) {
452e8d8bef9SDimitry Andric     // The induction PHIs break these rules, and that's OK because we treat
453e8d8bef9SDimitry Andric     // them specially when doing the transformation.
454e8d8bef9SDimitry Andric     if (&InnerPHI == FI.InnerInductionPHI)
455e8d8bef9SDimitry Andric       continue;
456349cc55cSDimitry Andric     if (FI.isNarrowInductionPhi(&InnerPHI))
457349cc55cSDimitry Andric       continue;
458e8d8bef9SDimitry Andric 
459e8d8bef9SDimitry Andric     // Each inner loop PHI node must have two incoming values/blocks - one
460e8d8bef9SDimitry Andric     // from the pre-header, and one from the latch.
461e8d8bef9SDimitry Andric     assert(InnerPHI.getNumIncomingValues() == 2);
462e8d8bef9SDimitry Andric     Value *PreHeaderValue =
463e8d8bef9SDimitry Andric         InnerPHI.getIncomingValueForBlock(FI.InnerLoop->getLoopPreheader());
464e8d8bef9SDimitry Andric     Value *LatchValue =
465e8d8bef9SDimitry Andric         InnerPHI.getIncomingValueForBlock(FI.InnerLoop->getLoopLatch());
466e8d8bef9SDimitry Andric 
467e8d8bef9SDimitry Andric     // The incoming value from the outer loop must be the PHI node in the
468e8d8bef9SDimitry Andric     // outer loop header, with no modifications made in the top of the outer
469e8d8bef9SDimitry Andric     // loop.
470e8d8bef9SDimitry Andric     PHINode *OuterPHI = dyn_cast<PHINode>(PreHeaderValue);
471e8d8bef9SDimitry Andric     if (!OuterPHI || OuterPHI->getParent() != FI.OuterLoop->getHeader()) {
472e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "value modified in top of outer loop\n");
473e8d8bef9SDimitry Andric       return false;
474e8d8bef9SDimitry Andric     }
475e8d8bef9SDimitry Andric 
476e8d8bef9SDimitry Andric     // The other incoming value must come from the inner loop, without any
477e8d8bef9SDimitry Andric     // modifications in the tail end of the outer loop. We are in LCSSA form,
478e8d8bef9SDimitry Andric     // so this will actually be a PHI in the inner loop's exit block, which
479e8d8bef9SDimitry Andric     // only uses values from inside the inner loop.
480e8d8bef9SDimitry Andric     PHINode *LCSSAPHI = dyn_cast<PHINode>(
481e8d8bef9SDimitry Andric         OuterPHI->getIncomingValueForBlock(FI.OuterLoop->getLoopLatch()));
482e8d8bef9SDimitry Andric     if (!LCSSAPHI) {
483e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "could not find LCSSA PHI\n");
484e8d8bef9SDimitry Andric       return false;
485e8d8bef9SDimitry Andric     }
486e8d8bef9SDimitry Andric 
487e8d8bef9SDimitry Andric     // The value used by the LCSSA PHI must be the same one that the inner
488e8d8bef9SDimitry Andric     // loop's PHI uses.
489e8d8bef9SDimitry Andric     if (LCSSAPHI->hasConstantValue() != LatchValue) {
490e8d8bef9SDimitry Andric       LLVM_DEBUG(
491e8d8bef9SDimitry Andric           dbgs() << "LCSSA PHI incoming value does not match latch value\n");
492e8d8bef9SDimitry Andric       return false;
493e8d8bef9SDimitry Andric     }
494e8d8bef9SDimitry Andric 
495e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "PHI pair is safe:\n");
496e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "  Inner: "; InnerPHI.dump());
497e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "  Outer: "; OuterPHI->dump());
498e8d8bef9SDimitry Andric     SafeOuterPHIs.insert(OuterPHI);
499e8d8bef9SDimitry Andric     FI.InnerPHIsToTransform.insert(&InnerPHI);
500e8d8bef9SDimitry Andric   }
501e8d8bef9SDimitry Andric 
502e8d8bef9SDimitry Andric   for (PHINode &OuterPHI : FI.OuterLoop->getHeader()->phis()) {
503349cc55cSDimitry Andric     if (FI.isNarrowInductionPhi(&OuterPHI))
504349cc55cSDimitry Andric       continue;
505e8d8bef9SDimitry Andric     if (!SafeOuterPHIs.count(&OuterPHI)) {
506e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "found unsafe PHI in outer loop: "; OuterPHI.dump());
507e8d8bef9SDimitry Andric       return false;
508e8d8bef9SDimitry Andric     }
509e8d8bef9SDimitry Andric   }
510e8d8bef9SDimitry Andric 
511e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "checkPHIs: OK\n");
512e8d8bef9SDimitry Andric   return true;
513e8d8bef9SDimitry Andric }
514e8d8bef9SDimitry Andric 
515e8d8bef9SDimitry Andric static bool
516fe6060f1SDimitry Andric checkOuterLoopInsts(FlattenInfo &FI,
517e8d8bef9SDimitry Andric                     SmallPtrSetImpl<Instruction *> &IterationInstructions,
518e8d8bef9SDimitry Andric                     const TargetTransformInfo *TTI) {
519e8d8bef9SDimitry Andric   // Check for instructions in the outer but not inner loop. If any of these
520e8d8bef9SDimitry Andric   // have side-effects then this transformation is not legal, and if there is
521e8d8bef9SDimitry Andric   // a significant amount of code here which can't be optimised out that it's
522e8d8bef9SDimitry Andric   // not profitable (as these instructions would get executed for each
523e8d8bef9SDimitry Andric   // iteration of the inner loop).
524fe6060f1SDimitry Andric   InstructionCost RepeatedInstrCost = 0;
525e8d8bef9SDimitry Andric   for (auto *B : FI.OuterLoop->getBlocks()) {
526e8d8bef9SDimitry Andric     if (FI.InnerLoop->contains(B))
527e8d8bef9SDimitry Andric       continue;
528e8d8bef9SDimitry Andric 
529e8d8bef9SDimitry Andric     for (auto &I : *B) {
530e8d8bef9SDimitry Andric       if (!isa<PHINode>(&I) && !I.isTerminator() &&
531e8d8bef9SDimitry Andric           !isSafeToSpeculativelyExecute(&I)) {
532e8d8bef9SDimitry Andric         LLVM_DEBUG(dbgs() << "Cannot flatten because instruction may have "
533e8d8bef9SDimitry Andric                              "side effects: ";
534e8d8bef9SDimitry Andric                    I.dump());
535e8d8bef9SDimitry Andric         return false;
536e8d8bef9SDimitry Andric       }
537e8d8bef9SDimitry Andric       // The execution count of the outer loop's iteration instructions
538e8d8bef9SDimitry Andric       // (increment, compare and branch) will be increased, but the
539e8d8bef9SDimitry Andric       // equivalent instructions will be removed from the inner loop, so
540e8d8bef9SDimitry Andric       // they make a net difference of zero.
541e8d8bef9SDimitry Andric       if (IterationInstructions.count(&I))
542e8d8bef9SDimitry Andric         continue;
543e8d8bef9SDimitry Andric       // The uncoditional branch to the inner loop's header will turn into
544e8d8bef9SDimitry Andric       // a fall-through, so adds no cost.
545e8d8bef9SDimitry Andric       BranchInst *Br = dyn_cast<BranchInst>(&I);
546e8d8bef9SDimitry Andric       if (Br && Br->isUnconditional() &&
547e8d8bef9SDimitry Andric           Br->getSuccessor(0) == FI.InnerLoop->getHeader())
548e8d8bef9SDimitry Andric         continue;
549e8d8bef9SDimitry Andric       // Multiplies of the outer iteration variable and inner iteration
550e8d8bef9SDimitry Andric       // count will be optimised out.
551e8d8bef9SDimitry Andric       if (match(&I, m_c_Mul(m_Specific(FI.OuterInductionPHI),
552fe6060f1SDimitry Andric                             m_Specific(FI.InnerTripCount))))
553e8d8bef9SDimitry Andric         continue;
554fe6060f1SDimitry Andric       InstructionCost Cost =
555fe6060f1SDimitry Andric           TTI->getUserCost(&I, TargetTransformInfo::TCK_SizeAndLatency);
556e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "Cost " << Cost << ": "; I.dump());
557e8d8bef9SDimitry Andric       RepeatedInstrCost += Cost;
558e8d8bef9SDimitry Andric     }
559e8d8bef9SDimitry Andric   }
560e8d8bef9SDimitry Andric 
561e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Cost of instructions that will be repeated: "
562e8d8bef9SDimitry Andric                     << RepeatedInstrCost << "\n");
563e8d8bef9SDimitry Andric   // Bail out if flattening the loops would cause instructions in the outer
564e8d8bef9SDimitry Andric   // loop but not in the inner loop to be executed extra times.
565e8d8bef9SDimitry Andric   if (RepeatedInstrCost > RepeatedInstructionThreshold) {
566e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "checkOuterLoopInsts: not profitable, bailing.\n");
567e8d8bef9SDimitry Andric     return false;
568e8d8bef9SDimitry Andric   }
569e8d8bef9SDimitry Andric 
570e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "checkOuterLoopInsts: OK\n");
571e8d8bef9SDimitry Andric   return true;
572e8d8bef9SDimitry Andric }
573e8d8bef9SDimitry Andric 
57404eeddc0SDimitry Andric 
57504eeddc0SDimitry Andric 
576e8d8bef9SDimitry Andric // We require all uses of both induction variables to match this pattern:
577e8d8bef9SDimitry Andric //
578fe6060f1SDimitry Andric //   (OuterPHI * InnerTripCount) + InnerPHI
579e8d8bef9SDimitry Andric //
580e8d8bef9SDimitry Andric // Any uses of the induction variables not matching that pattern would
581e8d8bef9SDimitry Andric // require a div/mod to reconstruct in the flattened loop, so the
582e8d8bef9SDimitry Andric // transformation wouldn't be profitable.
58304eeddc0SDimitry Andric static bool checkIVUsers(FlattenInfo &FI) {
584e8d8bef9SDimitry Andric   // Check that all uses of the inner loop's induction variable match the
585e8d8bef9SDimitry Andric   // expected pattern, recording the uses of the outer IV.
586e8d8bef9SDimitry Andric   SmallPtrSet<Value *, 4> ValidOuterPHIUses;
58704eeddc0SDimitry Andric   if (!FI.checkInnerInductionPhiUsers(ValidOuterPHIUses))
588e8d8bef9SDimitry Andric     return false;
589e8d8bef9SDimitry Andric 
590e8d8bef9SDimitry Andric   // Check that there are no uses of the outer IV other than the ones found
591e8d8bef9SDimitry Andric   // as part of the pattern above.
59204eeddc0SDimitry Andric   if (!FI.checkOuterInductionPhiUsers(ValidOuterPHIUses))
593e8d8bef9SDimitry Andric     return false;
594e8d8bef9SDimitry Andric 
595e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "checkIVUsers: OK\n";
596e8d8bef9SDimitry Andric              dbgs() << "Found " << FI.LinearIVUses.size()
597e8d8bef9SDimitry Andric                     << " value(s) that can be replaced:\n";
598e8d8bef9SDimitry Andric              for (Value *V : FI.LinearIVUses) {
599e8d8bef9SDimitry Andric                dbgs() << "  ";
600e8d8bef9SDimitry Andric                V->dump();
601e8d8bef9SDimitry Andric              });
602e8d8bef9SDimitry Andric   return true;
603e8d8bef9SDimitry Andric }
604e8d8bef9SDimitry Andric 
605e8d8bef9SDimitry Andric // Return an OverflowResult dependant on if overflow of the multiplication of
606fe6060f1SDimitry Andric // InnerTripCount and OuterTripCount can be assumed not to happen.
607fe6060f1SDimitry Andric static OverflowResult checkOverflow(FlattenInfo &FI, DominatorTree *DT,
608fe6060f1SDimitry Andric                                     AssumptionCache *AC) {
609e8d8bef9SDimitry Andric   Function *F = FI.OuterLoop->getHeader()->getParent();
610e8d8bef9SDimitry Andric   const DataLayout &DL = F->getParent()->getDataLayout();
611e8d8bef9SDimitry Andric 
612e8d8bef9SDimitry Andric   // For debugging/testing.
613e8d8bef9SDimitry Andric   if (AssumeNoOverflow)
614e8d8bef9SDimitry Andric     return OverflowResult::NeverOverflows;
615e8d8bef9SDimitry Andric 
616e8d8bef9SDimitry Andric   // Check if the multiply could not overflow due to known ranges of the
617e8d8bef9SDimitry Andric   // input values.
618e8d8bef9SDimitry Andric   OverflowResult OR = computeOverflowForUnsignedMul(
619fe6060f1SDimitry Andric       FI.InnerTripCount, FI.OuterTripCount, DL, AC,
620e8d8bef9SDimitry Andric       FI.OuterLoop->getLoopPreheader()->getTerminator(), DT);
621e8d8bef9SDimitry Andric   if (OR != OverflowResult::MayOverflow)
622e8d8bef9SDimitry Andric     return OR;
623e8d8bef9SDimitry Andric 
624e8d8bef9SDimitry Andric   for (Value *V : FI.LinearIVUses) {
625e8d8bef9SDimitry Andric     for (Value *U : V->users()) {
626e8d8bef9SDimitry Andric       if (auto *GEP = dyn_cast<GetElementPtrInst>(U)) {
627349cc55cSDimitry Andric         for (Value *GEPUser : U->users()) {
62804eeddc0SDimitry Andric           auto *GEPUserInst = cast<Instruction>(GEPUser);
629349cc55cSDimitry Andric           if (!isa<LoadInst>(GEPUserInst) &&
630349cc55cSDimitry Andric               !(isa<StoreInst>(GEPUserInst) &&
631349cc55cSDimitry Andric                 GEP == GEPUserInst->getOperand(1)))
632349cc55cSDimitry Andric             continue;
633349cc55cSDimitry Andric           if (!isGuaranteedToExecuteForEveryIteration(GEPUserInst,
634349cc55cSDimitry Andric                                                       FI.InnerLoop))
635349cc55cSDimitry Andric             continue;
636349cc55cSDimitry Andric           // The IV is used as the operand of a GEP which dominates the loop
637349cc55cSDimitry Andric           // latch, and the IV is at least as wide as the address space of the
638349cc55cSDimitry Andric           // GEP. In this case, the GEP would wrap around the address space
639349cc55cSDimitry Andric           // before the IV increment wraps, which would be UB.
640e8d8bef9SDimitry Andric           if (GEP->isInBounds() &&
641e8d8bef9SDimitry Andric               V->getType()->getIntegerBitWidth() >=
642e8d8bef9SDimitry Andric                   DL.getPointerTypeSizeInBits(GEP->getType())) {
643e8d8bef9SDimitry Andric             LLVM_DEBUG(
644e8d8bef9SDimitry Andric                 dbgs() << "use of linear IV would be UB if overflow occurred: ";
645e8d8bef9SDimitry Andric                 GEP->dump());
646e8d8bef9SDimitry Andric             return OverflowResult::NeverOverflows;
647e8d8bef9SDimitry Andric           }
648e8d8bef9SDimitry Andric         }
649e8d8bef9SDimitry Andric       }
650e8d8bef9SDimitry Andric     }
651349cc55cSDimitry Andric   }
652e8d8bef9SDimitry Andric 
653e8d8bef9SDimitry Andric   return OverflowResult::MayOverflow;
654e8d8bef9SDimitry Andric }
655e8d8bef9SDimitry Andric 
656fe6060f1SDimitry Andric static bool CanFlattenLoopPair(FlattenInfo &FI, DominatorTree *DT, LoopInfo *LI,
657fe6060f1SDimitry Andric                                ScalarEvolution *SE, AssumptionCache *AC,
658fe6060f1SDimitry Andric                                const TargetTransformInfo *TTI) {
659e8d8bef9SDimitry Andric   SmallPtrSet<Instruction *, 8> IterationInstructions;
660fe6060f1SDimitry Andric   if (!findLoopComponents(FI.InnerLoop, IterationInstructions,
661fe6060f1SDimitry Andric                           FI.InnerInductionPHI, FI.InnerTripCount,
662fe6060f1SDimitry Andric                           FI.InnerIncrement, FI.InnerBranch, SE, FI.Widened))
663e8d8bef9SDimitry Andric     return false;
664fe6060f1SDimitry Andric   if (!findLoopComponents(FI.OuterLoop, IterationInstructions,
665fe6060f1SDimitry Andric                           FI.OuterInductionPHI, FI.OuterTripCount,
666fe6060f1SDimitry Andric                           FI.OuterIncrement, FI.OuterBranch, SE, FI.Widened))
667e8d8bef9SDimitry Andric     return false;
668e8d8bef9SDimitry Andric 
669fe6060f1SDimitry Andric   // Both of the loop trip count values must be invariant in the outer loop
670e8d8bef9SDimitry Andric   // (non-instructions are all inherently invariant).
671fe6060f1SDimitry Andric   if (!FI.OuterLoop->isLoopInvariant(FI.InnerTripCount)) {
672fe6060f1SDimitry Andric     LLVM_DEBUG(dbgs() << "inner loop trip count not invariant\n");
673e8d8bef9SDimitry Andric     return false;
674e8d8bef9SDimitry Andric   }
675fe6060f1SDimitry Andric   if (!FI.OuterLoop->isLoopInvariant(FI.OuterTripCount)) {
676fe6060f1SDimitry Andric     LLVM_DEBUG(dbgs() << "outer loop trip count not invariant\n");
677e8d8bef9SDimitry Andric     return false;
678e8d8bef9SDimitry Andric   }
679e8d8bef9SDimitry Andric 
680e8d8bef9SDimitry Andric   if (!checkPHIs(FI, TTI))
681e8d8bef9SDimitry Andric     return false;
682e8d8bef9SDimitry Andric 
683e8d8bef9SDimitry Andric   // FIXME: it should be possible to handle different types correctly.
684e8d8bef9SDimitry Andric   if (FI.InnerInductionPHI->getType() != FI.OuterInductionPHI->getType())
685e8d8bef9SDimitry Andric     return false;
686e8d8bef9SDimitry Andric 
687e8d8bef9SDimitry Andric   if (!checkOuterLoopInsts(FI, IterationInstructions, TTI))
688e8d8bef9SDimitry Andric     return false;
689e8d8bef9SDimitry Andric 
690e8d8bef9SDimitry Andric   // Find the values in the loop that can be replaced with the linearized
691e8d8bef9SDimitry Andric   // induction variable, and check that there are no other uses of the inner
692e8d8bef9SDimitry Andric   // or outer induction variable. If there were, we could still do this
693e8d8bef9SDimitry Andric   // transformation, but we'd have to insert a div/mod to calculate the
694e8d8bef9SDimitry Andric   // original IVs, so it wouldn't be profitable.
695e8d8bef9SDimitry Andric   if (!checkIVUsers(FI))
696e8d8bef9SDimitry Andric     return false;
697e8d8bef9SDimitry Andric 
698e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "CanFlattenLoopPair: OK\n");
699e8d8bef9SDimitry Andric   return true;
700e8d8bef9SDimitry Andric }
701e8d8bef9SDimitry Andric 
702fe6060f1SDimitry Andric static bool DoFlattenLoopPair(FlattenInfo &FI, DominatorTree *DT, LoopInfo *LI,
703fe6060f1SDimitry Andric                               ScalarEvolution *SE, AssumptionCache *AC,
70404eeddc0SDimitry Andric                               const TargetTransformInfo *TTI, LPMUpdater *U,
70504eeddc0SDimitry Andric                               MemorySSAUpdater *MSSAU) {
706e8d8bef9SDimitry Andric   Function *F = FI.OuterLoop->getHeader()->getParent();
707e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Checks all passed, doing the transformation\n");
708e8d8bef9SDimitry Andric   {
709e8d8bef9SDimitry Andric     using namespace ore;
710e8d8bef9SDimitry Andric     OptimizationRemark Remark(DEBUG_TYPE, "Flattened", FI.InnerLoop->getStartLoc(),
711e8d8bef9SDimitry Andric                               FI.InnerLoop->getHeader());
712e8d8bef9SDimitry Andric     OptimizationRemarkEmitter ORE(F);
713e8d8bef9SDimitry Andric     Remark << "Flattened into outer loop";
714e8d8bef9SDimitry Andric     ORE.emit(Remark);
715e8d8bef9SDimitry Andric   }
716e8d8bef9SDimitry Andric 
717fe6060f1SDimitry Andric   Value *NewTripCount = BinaryOperator::CreateMul(
718fe6060f1SDimitry Andric       FI.InnerTripCount, FI.OuterTripCount, "flatten.tripcount",
719e8d8bef9SDimitry Andric       FI.OuterLoop->getLoopPreheader()->getTerminator());
720e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Created new trip count in preheader: ";
721e8d8bef9SDimitry Andric              NewTripCount->dump());
722e8d8bef9SDimitry Andric 
723e8d8bef9SDimitry Andric   // Fix up PHI nodes that take values from the inner loop back-edge, which
724e8d8bef9SDimitry Andric   // we are about to remove.
725e8d8bef9SDimitry Andric   FI.InnerInductionPHI->removeIncomingValue(FI.InnerLoop->getLoopLatch());
726e8d8bef9SDimitry Andric 
727e8d8bef9SDimitry Andric   // The old Phi will be optimised away later, but for now we can't leave
728e8d8bef9SDimitry Andric   // leave it in an invalid state, so are updating them too.
729e8d8bef9SDimitry Andric   for (PHINode *PHI : FI.InnerPHIsToTransform)
730e8d8bef9SDimitry Andric     PHI->removeIncomingValue(FI.InnerLoop->getLoopLatch());
731e8d8bef9SDimitry Andric 
732e8d8bef9SDimitry Andric   // Modify the trip count of the outer loop to be the product of the two
733e8d8bef9SDimitry Andric   // trip counts.
734e8d8bef9SDimitry Andric   cast<User>(FI.OuterBranch->getCondition())->setOperand(1, NewTripCount);
735e8d8bef9SDimitry Andric 
736e8d8bef9SDimitry Andric   // Replace the inner loop backedge with an unconditional branch to the exit.
737e8d8bef9SDimitry Andric   BasicBlock *InnerExitBlock = FI.InnerLoop->getExitBlock();
738e8d8bef9SDimitry Andric   BasicBlock *InnerExitingBlock = FI.InnerLoop->getExitingBlock();
739e8d8bef9SDimitry Andric   InnerExitingBlock->getTerminator()->eraseFromParent();
740e8d8bef9SDimitry Andric   BranchInst::Create(InnerExitBlock, InnerExitingBlock);
74104eeddc0SDimitry Andric 
74204eeddc0SDimitry Andric   // Update the DomTree and MemorySSA.
743e8d8bef9SDimitry Andric   DT->deleteEdge(InnerExitingBlock, FI.InnerLoop->getHeader());
74404eeddc0SDimitry Andric   if (MSSAU)
74504eeddc0SDimitry Andric     MSSAU->removeEdge(InnerExitingBlock, FI.InnerLoop->getHeader());
746e8d8bef9SDimitry Andric 
747e8d8bef9SDimitry Andric   // Replace all uses of the polynomial calculated from the two induction
748e8d8bef9SDimitry Andric   // variables with the one new one.
749e8d8bef9SDimitry Andric   IRBuilder<> Builder(FI.OuterInductionPHI->getParent()->getTerminator());
750e8d8bef9SDimitry Andric   for (Value *V : FI.LinearIVUses) {
751e8d8bef9SDimitry Andric     Value *OuterValue = FI.OuterInductionPHI;
752e8d8bef9SDimitry Andric     if (FI.Widened)
753e8d8bef9SDimitry Andric       OuterValue = Builder.CreateTrunc(FI.OuterInductionPHI, V->getType(),
754e8d8bef9SDimitry Andric                                        "flatten.trunciv");
755e8d8bef9SDimitry Andric 
75604eeddc0SDimitry Andric     LLVM_DEBUG(dbgs() << "Replacing: "; V->dump(); dbgs() << "with:      ";
75704eeddc0SDimitry Andric                OuterValue->dump());
758e8d8bef9SDimitry Andric     V->replaceAllUsesWith(OuterValue);
759e8d8bef9SDimitry Andric   }
760e8d8bef9SDimitry Andric 
761e8d8bef9SDimitry Andric   // Tell LoopInfo, SCEV and the pass manager that the inner loop has been
762e8d8bef9SDimitry Andric   // deleted, and any information that have about the outer loop invalidated.
763e8d8bef9SDimitry Andric   SE->forgetLoop(FI.OuterLoop);
764e8d8bef9SDimitry Andric   SE->forgetLoop(FI.InnerLoop);
765349cc55cSDimitry Andric   if (U)
766349cc55cSDimitry Andric     U->markLoopAsDeleted(*FI.InnerLoop, FI.InnerLoop->getName());
767e8d8bef9SDimitry Andric   LI->erase(FI.InnerLoop);
768349cc55cSDimitry Andric 
769349cc55cSDimitry Andric   // Increment statistic value.
770349cc55cSDimitry Andric   NumFlattened++;
771349cc55cSDimitry Andric 
772e8d8bef9SDimitry Andric   return true;
773e8d8bef9SDimitry Andric }
774e8d8bef9SDimitry Andric 
775fe6060f1SDimitry Andric static bool CanWidenIV(FlattenInfo &FI, DominatorTree *DT, LoopInfo *LI,
776fe6060f1SDimitry Andric                        ScalarEvolution *SE, AssumptionCache *AC,
777fe6060f1SDimitry Andric                        const TargetTransformInfo *TTI) {
778e8d8bef9SDimitry Andric   if (!WidenIV) {
779e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Widening the IVs is disabled\n");
780e8d8bef9SDimitry Andric     return false;
781e8d8bef9SDimitry Andric   }
782e8d8bef9SDimitry Andric 
783e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Try widening the IVs\n");
784e8d8bef9SDimitry Andric   Module *M = FI.InnerLoop->getHeader()->getParent()->getParent();
785e8d8bef9SDimitry Andric   auto &DL = M->getDataLayout();
786e8d8bef9SDimitry Andric   auto *InnerType = FI.InnerInductionPHI->getType();
787e8d8bef9SDimitry Andric   auto *OuterType = FI.OuterInductionPHI->getType();
788e8d8bef9SDimitry Andric   unsigned MaxLegalSize = DL.getLargestLegalIntTypeSizeInBits();
789e8d8bef9SDimitry Andric   auto *MaxLegalType = DL.getLargestLegalIntType(M->getContext());
790e8d8bef9SDimitry Andric 
791e8d8bef9SDimitry Andric   // If both induction types are less than the maximum legal integer width,
792e8d8bef9SDimitry Andric   // promote both to the widest type available so we know calculating
793fe6060f1SDimitry Andric   // (OuterTripCount * InnerTripCount) as the new trip count is safe.
794e8d8bef9SDimitry Andric   if (InnerType != OuterType ||
795e8d8bef9SDimitry Andric       InnerType->getScalarSizeInBits() >= MaxLegalSize ||
79604eeddc0SDimitry Andric       MaxLegalType->getScalarSizeInBits() <
79704eeddc0SDimitry Andric           InnerType->getScalarSizeInBits() * 2) {
798e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Can't widen the IV\n");
799e8d8bef9SDimitry Andric     return false;
800e8d8bef9SDimitry Andric   }
801e8d8bef9SDimitry Andric 
802e8d8bef9SDimitry Andric   SCEVExpander Rewriter(*SE, DL, "loopflatten");
803e8d8bef9SDimitry Andric   SmallVector<WeakTrackingVH, 4> DeadInsts;
804fe6060f1SDimitry Andric   unsigned ElimExt = 0;
805fe6060f1SDimitry Andric   unsigned Widened = 0;
806e8d8bef9SDimitry Andric 
807349cc55cSDimitry Andric   auto CreateWideIV = [&](WideIVInfo WideIV, bool &Deleted) -> bool {
80804eeddc0SDimitry Andric     PHINode *WidePhi =
80904eeddc0SDimitry Andric         createWideIV(WideIV, LI, SE, Rewriter, DT, DeadInsts, ElimExt, Widened,
81004eeddc0SDimitry Andric                      true /* HasGuards */, true /* UsePostIncrementRanges */);
811e8d8bef9SDimitry Andric     if (!WidePhi)
812e8d8bef9SDimitry Andric       return false;
813e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Created wide phi: "; WidePhi->dump());
814fe6060f1SDimitry Andric     LLVM_DEBUG(dbgs() << "Deleting old phi: "; WideIV.NarrowIV->dump());
815349cc55cSDimitry Andric     Deleted = RecursivelyDeleteDeadPHINode(WideIV.NarrowIV);
816349cc55cSDimitry Andric     return true;
817349cc55cSDimitry Andric   };
818349cc55cSDimitry Andric 
819349cc55cSDimitry Andric   bool Deleted;
820349cc55cSDimitry Andric   if (!CreateWideIV({FI.InnerInductionPHI, MaxLegalType, false}, Deleted))
821349cc55cSDimitry Andric     return false;
822349cc55cSDimitry Andric   // Add the narrow phi to list, so that it will be adjusted later when the
823349cc55cSDimitry Andric   // the transformation is performed.
824349cc55cSDimitry Andric   if (!Deleted)
825349cc55cSDimitry Andric     FI.InnerPHIsToTransform.insert(FI.InnerInductionPHI);
826349cc55cSDimitry Andric 
827349cc55cSDimitry Andric   if (!CreateWideIV({FI.OuterInductionPHI, MaxLegalType, false}, Deleted))
828349cc55cSDimitry Andric     return false;
829349cc55cSDimitry Andric 
830fe6060f1SDimitry Andric   assert(Widened && "Widened IV expected");
831e8d8bef9SDimitry Andric   FI.Widened = true;
832349cc55cSDimitry Andric 
833349cc55cSDimitry Andric   // Save the old/narrow induction phis, which we need to ignore in CheckPHIs.
834349cc55cSDimitry Andric   FI.NarrowInnerInductionPHI = FI.InnerInductionPHI;
835349cc55cSDimitry Andric   FI.NarrowOuterInductionPHI = FI.OuterInductionPHI;
836349cc55cSDimitry Andric 
837349cc55cSDimitry Andric   // After widening, rediscover all the loop components.
838e8d8bef9SDimitry Andric   return CanFlattenLoopPair(FI, DT, LI, SE, AC, TTI);
839e8d8bef9SDimitry Andric }
840e8d8bef9SDimitry Andric 
841fe6060f1SDimitry Andric static bool FlattenLoopPair(FlattenInfo &FI, DominatorTree *DT, LoopInfo *LI,
842fe6060f1SDimitry Andric                             ScalarEvolution *SE, AssumptionCache *AC,
84304eeddc0SDimitry Andric                             const TargetTransformInfo *TTI, LPMUpdater *U,
84404eeddc0SDimitry Andric                             MemorySSAUpdater *MSSAU) {
845e8d8bef9SDimitry Andric   LLVM_DEBUG(
846e8d8bef9SDimitry Andric       dbgs() << "Loop flattening running on outer loop "
847e8d8bef9SDimitry Andric              << FI.OuterLoop->getHeader()->getName() << " and inner loop "
848e8d8bef9SDimitry Andric              << FI.InnerLoop->getHeader()->getName() << " in "
849e8d8bef9SDimitry Andric              << FI.OuterLoop->getHeader()->getParent()->getName() << "\n");
850e8d8bef9SDimitry Andric 
851e8d8bef9SDimitry Andric   if (!CanFlattenLoopPair(FI, DT, LI, SE, AC, TTI))
852e8d8bef9SDimitry Andric     return false;
853e8d8bef9SDimitry Andric 
854e8d8bef9SDimitry Andric   // Check if we can widen the induction variables to avoid overflow checks.
855349cc55cSDimitry Andric   bool CanFlatten = CanWidenIV(FI, DT, LI, SE, AC, TTI);
856e8d8bef9SDimitry Andric 
857349cc55cSDimitry Andric   // It can happen that after widening of the IV, flattening may not be
858349cc55cSDimitry Andric   // possible/happening, e.g. when it is deemed unprofitable. So bail here if
859349cc55cSDimitry Andric   // that is the case.
860349cc55cSDimitry Andric   // TODO: IV widening without performing the actual flattening transformation
861349cc55cSDimitry Andric   // is not ideal. While this codegen change should not matter much, it is an
862349cc55cSDimitry Andric   // unnecessary change which is better to avoid. It's unlikely this happens
863349cc55cSDimitry Andric   // often, because if it's unprofitibale after widening, it should be
864349cc55cSDimitry Andric   // unprofitabe before widening as checked in the first round of checks. But
865349cc55cSDimitry Andric   // 'RepeatedInstructionThreshold' is set to only 2, which can probably be
866349cc55cSDimitry Andric   // relaxed. Because this is making a code change (the IV widening, but not
867349cc55cSDimitry Andric   // the flattening), we return true here.
868349cc55cSDimitry Andric   if (FI.Widened && !CanFlatten)
869349cc55cSDimitry Andric     return true;
870349cc55cSDimitry Andric 
871349cc55cSDimitry Andric   // If we have widened and can perform the transformation, do that here.
872349cc55cSDimitry Andric   if (CanFlatten)
87304eeddc0SDimitry Andric     return DoFlattenLoopPair(FI, DT, LI, SE, AC, TTI, U, MSSAU);
874349cc55cSDimitry Andric 
875349cc55cSDimitry Andric   // Otherwise, if we haven't widened the IV, check if the new iteration
876349cc55cSDimitry Andric   // variable might overflow. In this case, we need to version the loop, and
877349cc55cSDimitry Andric   // select the original version at runtime if the iteration space is too
878349cc55cSDimitry Andric   // large.
879e8d8bef9SDimitry Andric   // TODO: We currently don't version the loop.
880e8d8bef9SDimitry Andric   OverflowResult OR = checkOverflow(FI, DT, AC);
881e8d8bef9SDimitry Andric   if (OR == OverflowResult::AlwaysOverflowsHigh ||
882e8d8bef9SDimitry Andric       OR == OverflowResult::AlwaysOverflowsLow) {
883e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Multiply would always overflow, so not profitable\n");
884e8d8bef9SDimitry Andric     return false;
885e8d8bef9SDimitry Andric   } else if (OR == OverflowResult::MayOverflow) {
886e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Multiply might overflow, not flattening\n");
887e8d8bef9SDimitry Andric     return false;
888e8d8bef9SDimitry Andric   }
889e8d8bef9SDimitry Andric 
890e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Multiply cannot overflow, modifying loop in-place\n");
89104eeddc0SDimitry Andric   return DoFlattenLoopPair(FI, DT, LI, SE, AC, TTI, U, MSSAU);
892e8d8bef9SDimitry Andric }
893e8d8bef9SDimitry Andric 
894fe6060f1SDimitry Andric bool Flatten(LoopNest &LN, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE,
89504eeddc0SDimitry Andric              AssumptionCache *AC, TargetTransformInfo *TTI, LPMUpdater *U,
89604eeddc0SDimitry Andric              MemorySSAUpdater *MSSAU) {
897e8d8bef9SDimitry Andric   bool Changed = false;
898fe6060f1SDimitry Andric   for (Loop *InnerLoop : LN.getLoops()) {
899e8d8bef9SDimitry Andric     auto *OuterLoop = InnerLoop->getParentLoop();
900e8d8bef9SDimitry Andric     if (!OuterLoop)
901e8d8bef9SDimitry Andric       continue;
902fe6060f1SDimitry Andric     FlattenInfo FI(OuterLoop, InnerLoop);
90304eeddc0SDimitry Andric     Changed |= FlattenLoopPair(FI, DT, LI, SE, AC, TTI, U, MSSAU);
904e8d8bef9SDimitry Andric   }
905e8d8bef9SDimitry Andric   return Changed;
906e8d8bef9SDimitry Andric }
907e8d8bef9SDimitry Andric 
908fe6060f1SDimitry Andric PreservedAnalyses LoopFlattenPass::run(LoopNest &LN, LoopAnalysisManager &LAM,
909fe6060f1SDimitry Andric                                        LoopStandardAnalysisResults &AR,
910fe6060f1SDimitry Andric                                        LPMUpdater &U) {
911e8d8bef9SDimitry Andric 
912fe6060f1SDimitry Andric   bool Changed = false;
913fe6060f1SDimitry Andric 
91404eeddc0SDimitry Andric   Optional<MemorySSAUpdater> MSSAU;
91504eeddc0SDimitry Andric   if (AR.MSSA) {
91604eeddc0SDimitry Andric     MSSAU = MemorySSAUpdater(AR.MSSA);
91704eeddc0SDimitry Andric     if (VerifyMemorySSA)
91804eeddc0SDimitry Andric       AR.MSSA->verifyMemorySSA();
91904eeddc0SDimitry Andric   }
92004eeddc0SDimitry Andric 
921fe6060f1SDimitry Andric   // The loop flattening pass requires loops to be
922fe6060f1SDimitry Andric   // in simplified form, and also needs LCSSA. Running
923fe6060f1SDimitry Andric   // this pass will simplify all loops that contain inner loops,
924fe6060f1SDimitry Andric   // regardless of whether anything ends up being flattened.
92504eeddc0SDimitry Andric   Changed |= Flatten(LN, &AR.DT, &AR.LI, &AR.SE, &AR.AC, &AR.TTI, &U,
926*81ad6265SDimitry Andric                      MSSAU ? MSSAU.getPointer() : nullptr);
927fe6060f1SDimitry Andric 
928fe6060f1SDimitry Andric   if (!Changed)
929e8d8bef9SDimitry Andric     return PreservedAnalyses::all();
930e8d8bef9SDimitry Andric 
93104eeddc0SDimitry Andric   if (AR.MSSA && VerifyMemorySSA)
93204eeddc0SDimitry Andric     AR.MSSA->verifyMemorySSA();
93304eeddc0SDimitry Andric 
93404eeddc0SDimitry Andric   auto PA = getLoopPassPreservedAnalyses();
93504eeddc0SDimitry Andric   if (AR.MSSA)
93604eeddc0SDimitry Andric     PA.preserve<MemorySSAAnalysis>();
93704eeddc0SDimitry Andric   return PA;
938e8d8bef9SDimitry Andric }
939e8d8bef9SDimitry Andric 
940e8d8bef9SDimitry Andric namespace {
941e8d8bef9SDimitry Andric class LoopFlattenLegacyPass : public FunctionPass {
942e8d8bef9SDimitry Andric public:
943e8d8bef9SDimitry Andric   static char ID; // Pass ID, replacement for typeid
944e8d8bef9SDimitry Andric   LoopFlattenLegacyPass() : FunctionPass(ID) {
945e8d8bef9SDimitry Andric     initializeLoopFlattenLegacyPassPass(*PassRegistry::getPassRegistry());
946e8d8bef9SDimitry Andric   }
947e8d8bef9SDimitry Andric 
948e8d8bef9SDimitry Andric   // Possibly flatten loop L into its child.
949e8d8bef9SDimitry Andric   bool runOnFunction(Function &F) override;
950e8d8bef9SDimitry Andric 
951e8d8bef9SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
952e8d8bef9SDimitry Andric     getLoopAnalysisUsage(AU);
953e8d8bef9SDimitry Andric     AU.addRequired<TargetTransformInfoWrapperPass>();
954e8d8bef9SDimitry Andric     AU.addPreserved<TargetTransformInfoWrapperPass>();
955e8d8bef9SDimitry Andric     AU.addRequired<AssumptionCacheTracker>();
956e8d8bef9SDimitry Andric     AU.addPreserved<AssumptionCacheTracker>();
95704eeddc0SDimitry Andric     AU.addPreserved<MemorySSAWrapperPass>();
958e8d8bef9SDimitry Andric   }
959e8d8bef9SDimitry Andric };
960e8d8bef9SDimitry Andric } // namespace
961e8d8bef9SDimitry Andric 
962e8d8bef9SDimitry Andric char LoopFlattenLegacyPass::ID = 0;
963e8d8bef9SDimitry Andric INITIALIZE_PASS_BEGIN(LoopFlattenLegacyPass, "loop-flatten", "Flattens loops",
964e8d8bef9SDimitry Andric                       false, false)
965e8d8bef9SDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
966e8d8bef9SDimitry Andric INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
967e8d8bef9SDimitry Andric INITIALIZE_PASS_END(LoopFlattenLegacyPass, "loop-flatten", "Flattens loops",
968e8d8bef9SDimitry Andric                     false, false)
969e8d8bef9SDimitry Andric 
97004eeddc0SDimitry Andric FunctionPass *llvm::createLoopFlattenPass() {
97104eeddc0SDimitry Andric   return new LoopFlattenLegacyPass();
97204eeddc0SDimitry Andric }
973e8d8bef9SDimitry Andric 
974e8d8bef9SDimitry Andric bool LoopFlattenLegacyPass::runOnFunction(Function &F) {
975e8d8bef9SDimitry Andric   ScalarEvolution *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
976e8d8bef9SDimitry Andric   LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
977e8d8bef9SDimitry Andric   auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
978e8d8bef9SDimitry Andric   DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
979e8d8bef9SDimitry Andric   auto &TTIP = getAnalysis<TargetTransformInfoWrapperPass>();
980e8d8bef9SDimitry Andric   auto *TTI = &TTIP.getTTI(F);
981e8d8bef9SDimitry Andric   auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
98204eeddc0SDimitry Andric   auto *MSSA = getAnalysisIfAvailable<MemorySSAWrapperPass>();
98304eeddc0SDimitry Andric 
98404eeddc0SDimitry Andric   Optional<MemorySSAUpdater> MSSAU;
98504eeddc0SDimitry Andric   if (MSSA)
98604eeddc0SDimitry Andric     MSSAU = MemorySSAUpdater(&MSSA->getMSSA());
98704eeddc0SDimitry Andric 
988fe6060f1SDimitry Andric   bool Changed = false;
989fe6060f1SDimitry Andric   for (Loop *L : *LI) {
990fe6060f1SDimitry Andric     auto LN = LoopNest::getLoopNest(*L, *SE);
99104eeddc0SDimitry Andric     Changed |= Flatten(*LN, DT, LI, SE, AC, TTI, nullptr,
992*81ad6265SDimitry Andric                        MSSAU ? MSSAU.getPointer() : nullptr);
993fe6060f1SDimitry Andric   }
994fe6060f1SDimitry Andric   return Changed;
995e8d8bef9SDimitry Andric }
996