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