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