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