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