1 //===- LoopInterchange.cpp - Loop interchange 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 handles loop interchange transform.
10 // This pass interchanges loops to provide a more cache-friendly memory access
11 // patterns.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/Transforms/Scalar/LoopInterchange.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/Analysis/DependenceAnalysis.h"
21 #include "llvm/Analysis/LoopInfo.h"
22 #include "llvm/Analysis/LoopPass.h"
23 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
24 #include "llvm/Analysis/ScalarEvolution.h"
25 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
26 #include "llvm/IR/BasicBlock.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DiagnosticInfo.h"
29 #include "llvm/IR/Dominators.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/IRBuilder.h"
32 #include "llvm/IR/InstrTypes.h"
33 #include "llvm/IR/Instruction.h"
34 #include "llvm/IR/Instructions.h"
35 #include "llvm/IR/Type.h"
36 #include "llvm/IR/User.h"
37 #include "llvm/IR/Value.h"
38 #include "llvm/InitializePasses.h"
39 #include "llvm/Pass.h"
40 #include "llvm/Support/Casting.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/Support/ErrorHandling.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include "llvm/Transforms/Scalar.h"
46 #include "llvm/Transforms/Utils.h"
47 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
48 #include "llvm/Transforms/Utils/LoopUtils.h"
49 #include <cassert>
50 #include <utility>
51 #include <vector>
52 
53 using namespace llvm;
54 
55 #define DEBUG_TYPE "loop-interchange"
56 
57 STATISTIC(LoopsInterchanged, "Number of loops interchanged");
58 
59 static cl::opt<int> LoopInterchangeCostThreshold(
60     "loop-interchange-threshold", cl::init(0), cl::Hidden,
61     cl::desc("Interchange if you gain more than this number"));
62 
63 namespace {
64 
65 using LoopVector = SmallVector<Loop *, 8>;
66 
67 // TODO: Check if we can use a sparse matrix here.
68 using CharMatrix = std::vector<std::vector<char>>;
69 
70 } // end anonymous namespace
71 
72 // Maximum number of dependencies that can be handled in the dependency matrix.
73 static const unsigned MaxMemInstrCount = 100;
74 
75 // Maximum loop depth supported.
76 static const unsigned MaxLoopNestDepth = 10;
77 
78 #ifdef DUMP_DEP_MATRICIES
79 static void printDepMatrix(CharMatrix &DepMatrix) {
80   for (auto &Row : DepMatrix) {
81     for (auto D : Row)
82       LLVM_DEBUG(dbgs() << D << " ");
83     LLVM_DEBUG(dbgs() << "\n");
84   }
85 }
86 #endif
87 
88 static bool populateDependencyMatrix(CharMatrix &DepMatrix, unsigned Level,
89                                      Loop *L, DependenceInfo *DI) {
90   using ValueVector = SmallVector<Value *, 16>;
91 
92   ValueVector MemInstr;
93 
94   // For each block.
95   for (BasicBlock *BB : L->blocks()) {
96     // Scan the BB and collect legal loads and stores.
97     for (Instruction &I : *BB) {
98       if (!isa<Instruction>(I))
99         return false;
100       if (auto *Ld = dyn_cast<LoadInst>(&I)) {
101         if (!Ld->isSimple())
102           return false;
103         MemInstr.push_back(&I);
104       } else if (auto *St = dyn_cast<StoreInst>(&I)) {
105         if (!St->isSimple())
106           return false;
107         MemInstr.push_back(&I);
108       }
109     }
110   }
111 
112   LLVM_DEBUG(dbgs() << "Found " << MemInstr.size()
113                     << " Loads and Stores to analyze\n");
114 
115   ValueVector::iterator I, IE, J, JE;
116 
117   for (I = MemInstr.begin(), IE = MemInstr.end(); I != IE; ++I) {
118     for (J = I, JE = MemInstr.end(); J != JE; ++J) {
119       std::vector<char> Dep;
120       Instruction *Src = cast<Instruction>(*I);
121       Instruction *Dst = cast<Instruction>(*J);
122       if (Src == Dst)
123         continue;
124       // Ignore Input dependencies.
125       if (isa<LoadInst>(Src) && isa<LoadInst>(Dst))
126         continue;
127       // Track Output, Flow, and Anti dependencies.
128       if (auto D = DI->depends(Src, Dst, true)) {
129         assert(D->isOrdered() && "Expected an output, flow or anti dep.");
130         LLVM_DEBUG(StringRef DepType =
131                        D->isFlow() ? "flow" : D->isAnti() ? "anti" : "output";
132                    dbgs() << "Found " << DepType
133                           << " dependency between Src and Dst\n"
134                           << " Src:" << *Src << "\n Dst:" << *Dst << '\n');
135         unsigned Levels = D->getLevels();
136         char Direction;
137         for (unsigned II = 1; II <= Levels; ++II) {
138           const SCEV *Distance = D->getDistance(II);
139           const SCEVConstant *SCEVConst =
140               dyn_cast_or_null<SCEVConstant>(Distance);
141           if (SCEVConst) {
142             const ConstantInt *CI = SCEVConst->getValue();
143             if (CI->isNegative())
144               Direction = '<';
145             else if (CI->isZero())
146               Direction = '=';
147             else
148               Direction = '>';
149             Dep.push_back(Direction);
150           } else if (D->isScalar(II)) {
151             Direction = 'S';
152             Dep.push_back(Direction);
153           } else {
154             unsigned Dir = D->getDirection(II);
155             if (Dir == Dependence::DVEntry::LT ||
156                 Dir == Dependence::DVEntry::LE)
157               Direction = '<';
158             else if (Dir == Dependence::DVEntry::GT ||
159                      Dir == Dependence::DVEntry::GE)
160               Direction = '>';
161             else if (Dir == Dependence::DVEntry::EQ)
162               Direction = '=';
163             else
164               Direction = '*';
165             Dep.push_back(Direction);
166           }
167         }
168         while (Dep.size() != Level) {
169           Dep.push_back('I');
170         }
171 
172         DepMatrix.push_back(Dep);
173         if (DepMatrix.size() > MaxMemInstrCount) {
174           LLVM_DEBUG(dbgs() << "Cannot handle more than " << MaxMemInstrCount
175                             << " dependencies inside loop\n");
176           return false;
177         }
178       }
179     }
180   }
181 
182   return true;
183 }
184 
185 // A loop is moved from index 'from' to an index 'to'. Update the Dependence
186 // matrix by exchanging the two columns.
187 static void interChangeDependencies(CharMatrix &DepMatrix, unsigned FromIndx,
188                                     unsigned ToIndx) {
189   unsigned numRows = DepMatrix.size();
190   for (unsigned i = 0; i < numRows; ++i) {
191     char TmpVal = DepMatrix[i][ToIndx];
192     DepMatrix[i][ToIndx] = DepMatrix[i][FromIndx];
193     DepMatrix[i][FromIndx] = TmpVal;
194   }
195 }
196 
197 // Checks if outermost non '=','S'or'I' dependence in the dependence matrix is
198 // '>'
199 static bool isOuterMostDepPositive(CharMatrix &DepMatrix, unsigned Row,
200                                    unsigned Column) {
201   for (unsigned i = 0; i <= Column; ++i) {
202     if (DepMatrix[Row][i] == '<')
203       return false;
204     if (DepMatrix[Row][i] == '>')
205       return true;
206   }
207   // All dependencies were '=','S' or 'I'
208   return false;
209 }
210 
211 // Checks if no dependence exist in the dependency matrix in Row before Column.
212 static bool containsNoDependence(CharMatrix &DepMatrix, unsigned Row,
213                                  unsigned Column) {
214   for (unsigned i = 0; i < Column; ++i) {
215     if (DepMatrix[Row][i] != '=' && DepMatrix[Row][i] != 'S' &&
216         DepMatrix[Row][i] != 'I')
217       return false;
218   }
219   return true;
220 }
221 
222 static bool validDepInterchange(CharMatrix &DepMatrix, unsigned Row,
223                                 unsigned OuterLoopId, char InnerDep,
224                                 char OuterDep) {
225   if (isOuterMostDepPositive(DepMatrix, Row, OuterLoopId))
226     return false;
227 
228   if (InnerDep == OuterDep)
229     return true;
230 
231   // It is legal to interchange if and only if after interchange no row has a
232   // '>' direction as the leftmost non-'='.
233 
234   if (InnerDep == '=' || InnerDep == 'S' || InnerDep == 'I')
235     return true;
236 
237   if (InnerDep == '<')
238     return true;
239 
240   if (InnerDep == '>') {
241     // If OuterLoopId represents outermost loop then interchanging will make the
242     // 1st dependency as '>'
243     if (OuterLoopId == 0)
244       return false;
245 
246     // If all dependencies before OuterloopId are '=','S'or 'I'. Then
247     // interchanging will result in this row having an outermost non '='
248     // dependency of '>'
249     if (!containsNoDependence(DepMatrix, Row, OuterLoopId))
250       return true;
251   }
252 
253   return false;
254 }
255 
256 // Checks if it is legal to interchange 2 loops.
257 // [Theorem] A permutation of the loops in a perfect nest is legal if and only
258 // if the direction matrix, after the same permutation is applied to its
259 // columns, has no ">" direction as the leftmost non-"=" direction in any row.
260 static bool isLegalToInterChangeLoops(CharMatrix &DepMatrix,
261                                       unsigned InnerLoopId,
262                                       unsigned OuterLoopId) {
263   unsigned NumRows = DepMatrix.size();
264   // For each row check if it is valid to interchange.
265   for (unsigned Row = 0; Row < NumRows; ++Row) {
266     char InnerDep = DepMatrix[Row][InnerLoopId];
267     char OuterDep = DepMatrix[Row][OuterLoopId];
268     if (InnerDep == '*' || OuterDep == '*')
269       return false;
270     if (!validDepInterchange(DepMatrix, Row, OuterLoopId, InnerDep, OuterDep))
271       return false;
272   }
273   return true;
274 }
275 
276 static LoopVector populateWorklist(Loop &L) {
277   LLVM_DEBUG(dbgs() << "Calling populateWorklist on Func: "
278                     << L.getHeader()->getParent()->getName() << " Loop: %"
279                     << L.getHeader()->getName() << '\n');
280   LoopVector LoopList;
281   Loop *CurrentLoop = &L;
282   const std::vector<Loop *> *Vec = &CurrentLoop->getSubLoops();
283   while (!Vec->empty()) {
284     // The current loop has multiple subloops in it hence it is not tightly
285     // nested.
286     // Discard all loops above it added into Worklist.
287     if (Vec->size() != 1)
288       return {};
289 
290     LoopList.push_back(CurrentLoop);
291     CurrentLoop = Vec->front();
292     Vec = &CurrentLoop->getSubLoops();
293   }
294   LoopList.push_back(CurrentLoop);
295   return LoopList;
296 }
297 
298 static PHINode *getInductionVariable(Loop *L, ScalarEvolution *SE) {
299   PHINode *InnerIndexVar = L->getCanonicalInductionVariable();
300   if (InnerIndexVar)
301     return InnerIndexVar;
302   if (L->getLoopLatch() == nullptr || L->getLoopPredecessor() == nullptr)
303     return nullptr;
304   for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
305     PHINode *PhiVar = cast<PHINode>(I);
306     Type *PhiTy = PhiVar->getType();
307     if (!PhiTy->isIntegerTy() && !PhiTy->isFloatingPointTy() &&
308         !PhiTy->isPointerTy())
309       return nullptr;
310     const SCEVAddRecExpr *AddRec =
311         dyn_cast<SCEVAddRecExpr>(SE->getSCEV(PhiVar));
312     if (!AddRec || !AddRec->isAffine())
313       continue;
314     const SCEV *Step = AddRec->getStepRecurrence(*SE);
315     if (!isa<SCEVConstant>(Step))
316       continue;
317     // Found the induction variable.
318     // FIXME: Handle loops with more than one induction variable. Note that,
319     // currently, legality makes sure we have only one induction variable.
320     return PhiVar;
321   }
322   return nullptr;
323 }
324 
325 namespace {
326 
327 /// LoopInterchangeLegality checks if it is legal to interchange the loop.
328 class LoopInterchangeLegality {
329 public:
330   LoopInterchangeLegality(Loop *Outer, Loop *Inner, ScalarEvolution *SE,
331                           OptimizationRemarkEmitter *ORE)
332       : OuterLoop(Outer), InnerLoop(Inner), SE(SE), ORE(ORE) {}
333 
334   /// Check if the loops can be interchanged.
335   bool canInterchangeLoops(unsigned InnerLoopId, unsigned OuterLoopId,
336                            CharMatrix &DepMatrix);
337 
338   /// Check if the loop structure is understood. We do not handle triangular
339   /// loops for now.
340   bool isLoopStructureUnderstood(PHINode *InnerInductionVar);
341 
342   bool currentLimitations();
343 
344   const SmallPtrSetImpl<PHINode *> &getOuterInnerReductions() const {
345     return OuterInnerReductions;
346   }
347 
348 private:
349   bool tightlyNested(Loop *Outer, Loop *Inner);
350   bool containsUnsafeInstructions(BasicBlock *BB);
351 
352   /// Discover induction and reduction PHIs in the header of \p L. Induction
353   /// PHIs are added to \p Inductions, reductions are added to
354   /// OuterInnerReductions. When the outer loop is passed, the inner loop needs
355   /// to be passed as \p InnerLoop.
356   bool findInductionAndReductions(Loop *L,
357                                   SmallVector<PHINode *, 8> &Inductions,
358                                   Loop *InnerLoop);
359 
360   Loop *OuterLoop;
361   Loop *InnerLoop;
362 
363   ScalarEvolution *SE;
364 
365   /// Interface to emit optimization remarks.
366   OptimizationRemarkEmitter *ORE;
367 
368   /// Set of reduction PHIs taking part of a reduction across the inner and
369   /// outer loop.
370   SmallPtrSet<PHINode *, 4> OuterInnerReductions;
371 };
372 
373 /// LoopInterchangeProfitability checks if it is profitable to interchange the
374 /// loop.
375 class LoopInterchangeProfitability {
376 public:
377   LoopInterchangeProfitability(Loop *Outer, Loop *Inner, ScalarEvolution *SE,
378                                OptimizationRemarkEmitter *ORE)
379       : OuterLoop(Outer), InnerLoop(Inner), SE(SE), ORE(ORE) {}
380 
381   /// Check if the loop interchange is profitable.
382   bool isProfitable(unsigned InnerLoopId, unsigned OuterLoopId,
383                     CharMatrix &DepMatrix);
384 
385 private:
386   int getInstrOrderCost();
387 
388   Loop *OuterLoop;
389   Loop *InnerLoop;
390 
391   /// Scev analysis.
392   ScalarEvolution *SE;
393 
394   /// Interface to emit optimization remarks.
395   OptimizationRemarkEmitter *ORE;
396 };
397 
398 /// LoopInterchangeTransform interchanges the loop.
399 class LoopInterchangeTransform {
400 public:
401   LoopInterchangeTransform(Loop *Outer, Loop *Inner, ScalarEvolution *SE,
402                            LoopInfo *LI, DominatorTree *DT,
403                            BasicBlock *LoopNestExit,
404                            const LoopInterchangeLegality &LIL)
405       : OuterLoop(Outer), InnerLoop(Inner), SE(SE), LI(LI), DT(DT),
406         LoopExit(LoopNestExit), LIL(LIL) {}
407 
408   /// Interchange OuterLoop and InnerLoop.
409   bool transform();
410   void restructureLoops(Loop *NewInner, Loop *NewOuter,
411                         BasicBlock *OrigInnerPreHeader,
412                         BasicBlock *OrigOuterPreHeader);
413   void removeChildLoop(Loop *OuterLoop, Loop *InnerLoop);
414 
415 private:
416   bool adjustLoopLinks();
417   bool adjustLoopBranches();
418 
419   Loop *OuterLoop;
420   Loop *InnerLoop;
421 
422   /// Scev analysis.
423   ScalarEvolution *SE;
424 
425   LoopInfo *LI;
426   DominatorTree *DT;
427   BasicBlock *LoopExit;
428 
429   const LoopInterchangeLegality &LIL;
430 };
431 
432 struct LoopInterchange {
433   ScalarEvolution *SE = nullptr;
434   LoopInfo *LI = nullptr;
435   DependenceInfo *DI = nullptr;
436   DominatorTree *DT = nullptr;
437 
438   /// Interface to emit optimization remarks.
439   OptimizationRemarkEmitter *ORE;
440 
441   LoopInterchange(ScalarEvolution *SE, LoopInfo *LI, DependenceInfo *DI,
442                   DominatorTree *DT, OptimizationRemarkEmitter *ORE)
443       : SE(SE), LI(LI), DI(DI), DT(DT), ORE(ORE) {}
444 
445   bool run(Loop *L) {
446     if (L->getParentLoop())
447       return false;
448 
449     return processLoopList(populateWorklist(*L));
450   }
451 
452   bool run(LoopNest &LN) {
453     const auto &LoopList = LN.getLoops();
454     for (unsigned I = 1; I < LoopList.size(); ++I)
455       if (LoopList[I]->getParentLoop() != LoopList[I - 1])
456         return false;
457     return processLoopList(LoopList);
458   }
459 
460   bool isComputableLoopNest(ArrayRef<Loop *> LoopList) {
461     for (Loop *L : LoopList) {
462       const SCEV *ExitCountOuter = SE->getBackedgeTakenCount(L);
463       if (isa<SCEVCouldNotCompute>(ExitCountOuter)) {
464         LLVM_DEBUG(dbgs() << "Couldn't compute backedge count\n");
465         return false;
466       }
467       if (L->getNumBackEdges() != 1) {
468         LLVM_DEBUG(dbgs() << "NumBackEdges is not equal to 1\n");
469         return false;
470       }
471       if (!L->getExitingBlock()) {
472         LLVM_DEBUG(dbgs() << "Loop doesn't have unique exit block\n");
473         return false;
474       }
475     }
476     return true;
477   }
478 
479   unsigned selectLoopForInterchange(ArrayRef<Loop *> LoopList) {
480     // TODO: Add a better heuristic to select the loop to be interchanged based
481     // on the dependence matrix. Currently we select the innermost loop.
482     return LoopList.size() - 1;
483   }
484 
485   bool processLoopList(ArrayRef<Loop *> LoopList) {
486     bool Changed = false;
487     unsigned LoopNestDepth = LoopList.size();
488     if (LoopNestDepth < 2) {
489       LLVM_DEBUG(dbgs() << "Loop doesn't contain minimum nesting level.\n");
490       return false;
491     }
492     if (LoopNestDepth > MaxLoopNestDepth) {
493       LLVM_DEBUG(dbgs() << "Cannot handle loops of depth greater than "
494                         << MaxLoopNestDepth << "\n");
495       return false;
496     }
497     if (!isComputableLoopNest(LoopList)) {
498       LLVM_DEBUG(dbgs() << "Not valid loop candidate for interchange\n");
499       return false;
500     }
501 
502     LLVM_DEBUG(dbgs() << "Processing LoopList of size = " << LoopNestDepth
503                       << "\n");
504 
505     CharMatrix DependencyMatrix;
506     Loop *OuterMostLoop = *(LoopList.begin());
507     if (!populateDependencyMatrix(DependencyMatrix, LoopNestDepth,
508                                   OuterMostLoop, DI)) {
509       LLVM_DEBUG(dbgs() << "Populating dependency matrix failed\n");
510       return false;
511     }
512 #ifdef DUMP_DEP_MATRICIES
513     LLVM_DEBUG(dbgs() << "Dependence before interchange\n");
514     printDepMatrix(DependencyMatrix);
515 #endif
516 
517     // Get the Outermost loop exit.
518     BasicBlock *LoopNestExit = OuterMostLoop->getExitBlock();
519     if (!LoopNestExit) {
520       LLVM_DEBUG(dbgs() << "OuterMostLoop needs an unique exit block");
521       return false;
522     }
523 
524     unsigned SelecLoopId = selectLoopForInterchange(LoopList);
525     // Move the selected loop outwards to the best possible position.
526     Loop *LoopToBeInterchanged = LoopList[SelecLoopId];
527     for (unsigned i = SelecLoopId; i > 0; i--) {
528       bool Interchanged = processLoop(LoopToBeInterchanged, LoopList[i - 1], i,
529                                       i - 1, LoopNestExit, DependencyMatrix);
530       if (!Interchanged)
531         return Changed;
532       // Update the DependencyMatrix
533       interChangeDependencies(DependencyMatrix, i, i - 1);
534 #ifdef DUMP_DEP_MATRICIES
535       LLVM_DEBUG(dbgs() << "Dependence after interchange\n");
536       printDepMatrix(DependencyMatrix);
537 #endif
538       Changed |= Interchanged;
539     }
540     return Changed;
541   }
542 
543   bool processLoop(Loop *InnerLoop, Loop *OuterLoop, unsigned InnerLoopId,
544                    unsigned OuterLoopId, BasicBlock *LoopNestExit,
545                    std::vector<std::vector<char>> &DependencyMatrix) {
546     LLVM_DEBUG(dbgs() << "Processing InnerLoopId = " << InnerLoopId
547                       << " and OuterLoopId = " << OuterLoopId << "\n");
548     LoopInterchangeLegality LIL(OuterLoop, InnerLoop, SE, ORE);
549     if (!LIL.canInterchangeLoops(InnerLoopId, OuterLoopId, DependencyMatrix)) {
550       LLVM_DEBUG(dbgs() << "Not interchanging loops. Cannot prove legality.\n");
551       return false;
552     }
553     LLVM_DEBUG(dbgs() << "Loops are legal to interchange\n");
554     LoopInterchangeProfitability LIP(OuterLoop, InnerLoop, SE, ORE);
555     if (!LIP.isProfitable(InnerLoopId, OuterLoopId, DependencyMatrix)) {
556       LLVM_DEBUG(dbgs() << "Interchanging loops not profitable.\n");
557       return false;
558     }
559 
560     ORE->emit([&]() {
561       return OptimizationRemark(DEBUG_TYPE, "Interchanged",
562                                 InnerLoop->getStartLoc(),
563                                 InnerLoop->getHeader())
564              << "Loop interchanged with enclosing loop.";
565     });
566 
567     LoopInterchangeTransform LIT(OuterLoop, InnerLoop, SE, LI, DT, LoopNestExit,
568                                  LIL);
569     LIT.transform();
570     LLVM_DEBUG(dbgs() << "Loops interchanged.\n");
571     LoopsInterchanged++;
572 
573     assert(InnerLoop->isLCSSAForm(*DT) &&
574            "Inner loop not left in LCSSA form after loop interchange!");
575     assert(OuterLoop->isLCSSAForm(*DT) &&
576            "Outer loop not left in LCSSA form after loop interchange!");
577 
578     return true;
579   }
580 };
581 
582 } // end anonymous namespace
583 
584 bool LoopInterchangeLegality::containsUnsafeInstructions(BasicBlock *BB) {
585   return any_of(*BB, [](const Instruction &I) {
586     return I.mayHaveSideEffects() || I.mayReadFromMemory();
587   });
588 }
589 
590 bool LoopInterchangeLegality::tightlyNested(Loop *OuterLoop, Loop *InnerLoop) {
591   BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
592   BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
593   BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch();
594 
595   LLVM_DEBUG(dbgs() << "Checking if loops are tightly nested\n");
596 
597   // A perfectly nested loop will not have any branch in between the outer and
598   // inner block i.e. outer header will branch to either inner preheader and
599   // outerloop latch.
600   BranchInst *OuterLoopHeaderBI =
601       dyn_cast<BranchInst>(OuterLoopHeader->getTerminator());
602   if (!OuterLoopHeaderBI)
603     return false;
604 
605   for (BasicBlock *Succ : successors(OuterLoopHeaderBI))
606     if (Succ != InnerLoopPreHeader && Succ != InnerLoop->getHeader() &&
607         Succ != OuterLoopLatch)
608       return false;
609 
610   LLVM_DEBUG(dbgs() << "Checking instructions in Loop header and Loop latch\n");
611   // We do not have any basic block in between now make sure the outer header
612   // and outer loop latch doesn't contain any unsafe instructions.
613   if (containsUnsafeInstructions(OuterLoopHeader) ||
614       containsUnsafeInstructions(OuterLoopLatch))
615     return false;
616 
617   // Also make sure the inner loop preheader does not contain any unsafe
618   // instructions. Note that all instructions in the preheader will be moved to
619   // the outer loop header when interchanging.
620   if (InnerLoopPreHeader != OuterLoopHeader &&
621       containsUnsafeInstructions(InnerLoopPreHeader))
622     return false;
623 
624   LLVM_DEBUG(dbgs() << "Loops are perfectly nested\n");
625   // We have a perfect loop nest.
626   return true;
627 }
628 
629 bool LoopInterchangeLegality::isLoopStructureUnderstood(
630     PHINode *InnerInduction) {
631   unsigned Num = InnerInduction->getNumOperands();
632   BasicBlock *InnerLoopPreheader = InnerLoop->getLoopPreheader();
633   for (unsigned i = 0; i < Num; ++i) {
634     Value *Val = InnerInduction->getOperand(i);
635     if (isa<Constant>(Val))
636       continue;
637     Instruction *I = dyn_cast<Instruction>(Val);
638     if (!I)
639       return false;
640     // TODO: Handle triangular loops.
641     // e.g. for(int i=0;i<N;i++)
642     //        for(int j=i;j<N;j++)
643     unsigned IncomBlockIndx = PHINode::getIncomingValueNumForOperand(i);
644     if (InnerInduction->getIncomingBlock(IncomBlockIndx) ==
645             InnerLoopPreheader &&
646         !OuterLoop->isLoopInvariant(I)) {
647       return false;
648     }
649   }
650   return true;
651 }
652 
653 // If SV is a LCSSA PHI node with a single incoming value, return the incoming
654 // value.
655 static Value *followLCSSA(Value *SV) {
656   PHINode *PHI = dyn_cast<PHINode>(SV);
657   if (!PHI)
658     return SV;
659 
660   if (PHI->getNumIncomingValues() != 1)
661     return SV;
662   return followLCSSA(PHI->getIncomingValue(0));
663 }
664 
665 // Check V's users to see if it is involved in a reduction in L.
666 static PHINode *findInnerReductionPhi(Loop *L, Value *V) {
667   // Reduction variables cannot be constants.
668   if (isa<Constant>(V))
669     return nullptr;
670 
671   for (Value *User : V->users()) {
672     if (PHINode *PHI = dyn_cast<PHINode>(User)) {
673       if (PHI->getNumIncomingValues() == 1)
674         continue;
675       RecurrenceDescriptor RD;
676       if (RecurrenceDescriptor::isReductionPHI(PHI, L, RD))
677         return PHI;
678       return nullptr;
679     }
680   }
681 
682   return nullptr;
683 }
684 
685 bool LoopInterchangeLegality::findInductionAndReductions(
686     Loop *L, SmallVector<PHINode *, 8> &Inductions, Loop *InnerLoop) {
687   if (!L->getLoopLatch() || !L->getLoopPredecessor())
688     return false;
689   for (PHINode &PHI : L->getHeader()->phis()) {
690     RecurrenceDescriptor RD;
691     InductionDescriptor ID;
692     if (InductionDescriptor::isInductionPHI(&PHI, L, SE, ID))
693       Inductions.push_back(&PHI);
694     else {
695       // PHIs in inner loops need to be part of a reduction in the outer loop,
696       // discovered when checking the PHIs of the outer loop earlier.
697       if (!InnerLoop) {
698         if (!OuterInnerReductions.count(&PHI)) {
699           LLVM_DEBUG(dbgs() << "Inner loop PHI is not part of reductions "
700                                "across the outer loop.\n");
701           return false;
702         }
703       } else {
704         assert(PHI.getNumIncomingValues() == 2 &&
705                "Phis in loop header should have exactly 2 incoming values");
706         // Check if we have a PHI node in the outer loop that has a reduction
707         // result from the inner loop as an incoming value.
708         Value *V = followLCSSA(PHI.getIncomingValueForBlock(L->getLoopLatch()));
709         PHINode *InnerRedPhi = findInnerReductionPhi(InnerLoop, V);
710         if (!InnerRedPhi ||
711             !llvm::is_contained(InnerRedPhi->incoming_values(), &PHI)) {
712           LLVM_DEBUG(
713               dbgs()
714               << "Failed to recognize PHI as an induction or reduction.\n");
715           return false;
716         }
717         OuterInnerReductions.insert(&PHI);
718         OuterInnerReductions.insert(InnerRedPhi);
719       }
720     }
721   }
722   return true;
723 }
724 
725 // This function indicates the current limitations in the transform as a result
726 // of which we do not proceed.
727 bool LoopInterchangeLegality::currentLimitations() {
728   BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
729   BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
730 
731   // transform currently expects the loop latches to also be the exiting
732   // blocks.
733   if (InnerLoop->getExitingBlock() != InnerLoopLatch ||
734       OuterLoop->getExitingBlock() != OuterLoop->getLoopLatch() ||
735       !isa<BranchInst>(InnerLoopLatch->getTerminator()) ||
736       !isa<BranchInst>(OuterLoop->getLoopLatch()->getTerminator())) {
737     LLVM_DEBUG(
738         dbgs() << "Loops where the latch is not the exiting block are not"
739                << " supported currently.\n");
740     ORE->emit([&]() {
741       return OptimizationRemarkMissed(DEBUG_TYPE, "ExitingNotLatch",
742                                       OuterLoop->getStartLoc(),
743                                       OuterLoop->getHeader())
744              << "Loops where the latch is not the exiting block cannot be"
745                 " interchange currently.";
746     });
747     return true;
748   }
749 
750   PHINode *InnerInductionVar;
751   SmallVector<PHINode *, 8> Inductions;
752   if (!findInductionAndReductions(OuterLoop, Inductions, InnerLoop)) {
753     LLVM_DEBUG(
754         dbgs() << "Only outer loops with induction or reduction PHI nodes "
755                << "are supported currently.\n");
756     ORE->emit([&]() {
757       return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedPHIOuter",
758                                       OuterLoop->getStartLoc(),
759                                       OuterLoop->getHeader())
760              << "Only outer loops with induction or reduction PHI nodes can be"
761                 " interchanged currently.";
762     });
763     return true;
764   }
765 
766   // TODO: Currently we handle only loops with 1 induction variable.
767   if (Inductions.size() != 1) {
768     LLVM_DEBUG(dbgs() << "Loops with more than 1 induction variables are not "
769                       << "supported currently.\n");
770     ORE->emit([&]() {
771       return OptimizationRemarkMissed(DEBUG_TYPE, "MultiIndutionOuter",
772                                       OuterLoop->getStartLoc(),
773                                       OuterLoop->getHeader())
774              << "Only outer loops with 1 induction variable can be "
775                 "interchanged currently.";
776     });
777     return true;
778   }
779 
780   Inductions.clear();
781   if (!findInductionAndReductions(InnerLoop, Inductions, nullptr)) {
782     LLVM_DEBUG(
783         dbgs() << "Only inner loops with induction or reduction PHI nodes "
784                << "are supported currently.\n");
785     ORE->emit([&]() {
786       return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedPHIInner",
787                                       InnerLoop->getStartLoc(),
788                                       InnerLoop->getHeader())
789              << "Only inner loops with induction or reduction PHI nodes can be"
790                 " interchange currently.";
791     });
792     return true;
793   }
794 
795   // TODO: Currently we handle only loops with 1 induction variable.
796   if (Inductions.size() != 1) {
797     LLVM_DEBUG(
798         dbgs() << "We currently only support loops with 1 induction variable."
799                << "Failed to interchange due to current limitation\n");
800     ORE->emit([&]() {
801       return OptimizationRemarkMissed(DEBUG_TYPE, "MultiInductionInner",
802                                       InnerLoop->getStartLoc(),
803                                       InnerLoop->getHeader())
804              << "Only inner loops with 1 induction variable can be "
805                 "interchanged currently.";
806     });
807     return true;
808   }
809   InnerInductionVar = Inductions.pop_back_val();
810 
811   // TODO: Triangular loops are not handled for now.
812   if (!isLoopStructureUnderstood(InnerInductionVar)) {
813     LLVM_DEBUG(dbgs() << "Loop structure not understood by pass\n");
814     ORE->emit([&]() {
815       return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedStructureInner",
816                                       InnerLoop->getStartLoc(),
817                                       InnerLoop->getHeader())
818              << "Inner loop structure not understood currently.";
819     });
820     return true;
821   }
822 
823   // TODO: Current limitation: Since we split the inner loop latch at the point
824   // were induction variable is incremented (induction.next); We cannot have
825   // more than 1 user of induction.next since it would result in broken code
826   // after split.
827   // e.g.
828   // for(i=0;i<N;i++) {
829   //    for(j = 0;j<M;j++) {
830   //      A[j+1][i+2] = A[j][i]+k;
831   //  }
832   // }
833   Instruction *InnerIndexVarInc = nullptr;
834   if (InnerInductionVar->getIncomingBlock(0) == InnerLoopPreHeader)
835     InnerIndexVarInc =
836         dyn_cast<Instruction>(InnerInductionVar->getIncomingValue(1));
837   else
838     InnerIndexVarInc =
839         dyn_cast<Instruction>(InnerInductionVar->getIncomingValue(0));
840 
841   if (!InnerIndexVarInc) {
842     LLVM_DEBUG(
843         dbgs() << "Did not find an instruction to increment the induction "
844                << "variable.\n");
845     ORE->emit([&]() {
846       return OptimizationRemarkMissed(DEBUG_TYPE, "NoIncrementInInner",
847                                       InnerLoop->getStartLoc(),
848                                       InnerLoop->getHeader())
849              << "The inner loop does not increment the induction variable.";
850     });
851     return true;
852   }
853 
854   // Since we split the inner loop latch on this induction variable. Make sure
855   // we do not have any instruction between the induction variable and branch
856   // instruction.
857 
858   bool FoundInduction = false;
859   for (const Instruction &I :
860        llvm::reverse(InnerLoopLatch->instructionsWithoutDebug())) {
861     if (isa<BranchInst>(I) || isa<CmpInst>(I) || isa<TruncInst>(I) ||
862         isa<ZExtInst>(I))
863       continue;
864 
865     // We found an instruction. If this is not induction variable then it is not
866     // safe to split this loop latch.
867     if (!I.isIdenticalTo(InnerIndexVarInc)) {
868       LLVM_DEBUG(dbgs() << "Found unsupported instructions between induction "
869                         << "variable increment and branch.\n");
870       ORE->emit([&]() {
871         return OptimizationRemarkMissed(
872                    DEBUG_TYPE, "UnsupportedInsBetweenInduction",
873                    InnerLoop->getStartLoc(), InnerLoop->getHeader())
874                << "Found unsupported instruction between induction variable "
875                   "increment and branch.";
876       });
877       return true;
878     }
879 
880     FoundInduction = true;
881     break;
882   }
883   // The loop latch ended and we didn't find the induction variable return as
884   // current limitation.
885   if (!FoundInduction) {
886     LLVM_DEBUG(dbgs() << "Did not find the induction variable.\n");
887     ORE->emit([&]() {
888       return OptimizationRemarkMissed(DEBUG_TYPE, "NoIndutionVariable",
889                                       InnerLoop->getStartLoc(),
890                                       InnerLoop->getHeader())
891              << "Did not find the induction variable.";
892     });
893     return true;
894   }
895   return false;
896 }
897 
898 // We currently only support LCSSA PHI nodes in the inner loop exit, if their
899 // users are either reduction PHIs or PHIs outside the outer loop (which means
900 // the we are only interested in the final value after the loop).
901 static bool
902 areInnerLoopExitPHIsSupported(Loop *InnerL, Loop *OuterL,
903                               SmallPtrSetImpl<PHINode *> &Reductions) {
904   BasicBlock *InnerExit = OuterL->getUniqueExitBlock();
905   for (PHINode &PHI : InnerExit->phis()) {
906     // Reduction lcssa phi will have only 1 incoming block that from loop latch.
907     if (PHI.getNumIncomingValues() > 1)
908       return false;
909     if (any_of(PHI.users(), [&Reductions, OuterL](User *U) {
910           PHINode *PN = dyn_cast<PHINode>(U);
911           return !PN ||
912                  (!Reductions.count(PN) && OuterL->contains(PN->getParent()));
913         })) {
914       return false;
915     }
916   }
917   return true;
918 }
919 
920 // We currently support LCSSA PHI nodes in the outer loop exit, if their
921 // incoming values do not come from the outer loop latch or if the
922 // outer loop latch has a single predecessor. In that case, the value will
923 // be available if both the inner and outer loop conditions are true, which
924 // will still be true after interchanging. If we have multiple predecessor,
925 // that may not be the case, e.g. because the outer loop latch may be executed
926 // if the inner loop is not executed.
927 static bool areOuterLoopExitPHIsSupported(Loop *OuterLoop, Loop *InnerLoop) {
928   BasicBlock *LoopNestExit = OuterLoop->getUniqueExitBlock();
929   for (PHINode &PHI : LoopNestExit->phis()) {
930     //  FIXME: We currently are not able to detect floating point reductions
931     //         and have to use floating point PHIs as a proxy to prevent
932     //         interchanging in the presence of floating point reductions.
933     if (PHI.getType()->isFloatingPointTy())
934       return false;
935     for (unsigned i = 0; i < PHI.getNumIncomingValues(); i++) {
936      Instruction *IncomingI = dyn_cast<Instruction>(PHI.getIncomingValue(i));
937      if (!IncomingI || IncomingI->getParent() != OuterLoop->getLoopLatch())
938        continue;
939 
940      // The incoming value is defined in the outer loop latch. Currently we
941      // only support that in case the outer loop latch has a single predecessor.
942      // This guarantees that the outer loop latch is executed if and only if
943      // the inner loop is executed (because tightlyNested() guarantees that the
944      // outer loop header only branches to the inner loop or the outer loop
945      // latch).
946      // FIXME: We could weaken this logic and allow multiple predecessors,
947      //        if the values are produced outside the loop latch. We would need
948      //        additional logic to update the PHI nodes in the exit block as
949      //        well.
950      if (OuterLoop->getLoopLatch()->getUniquePredecessor() == nullptr)
951        return false;
952     }
953   }
954   return true;
955 }
956 
957 bool LoopInterchangeLegality::canInterchangeLoops(unsigned InnerLoopId,
958                                                   unsigned OuterLoopId,
959                                                   CharMatrix &DepMatrix) {
960   if (!isLegalToInterChangeLoops(DepMatrix, InnerLoopId, OuterLoopId)) {
961     LLVM_DEBUG(dbgs() << "Failed interchange InnerLoopId = " << InnerLoopId
962                       << " and OuterLoopId = " << OuterLoopId
963                       << " due to dependence\n");
964     ORE->emit([&]() {
965       return OptimizationRemarkMissed(DEBUG_TYPE, "Dependence",
966                                       InnerLoop->getStartLoc(),
967                                       InnerLoop->getHeader())
968              << "Cannot interchange loops due to dependences.";
969     });
970     return false;
971   }
972   // Check if outer and inner loop contain legal instructions only.
973   for (auto *BB : OuterLoop->blocks())
974     for (Instruction &I : BB->instructionsWithoutDebug())
975       if (CallInst *CI = dyn_cast<CallInst>(&I)) {
976         // readnone functions do not prevent interchanging.
977         if (CI->doesNotReadMemory())
978           continue;
979         LLVM_DEBUG(
980             dbgs() << "Loops with call instructions cannot be interchanged "
981                    << "safely.");
982         ORE->emit([&]() {
983           return OptimizationRemarkMissed(DEBUG_TYPE, "CallInst",
984                                           CI->getDebugLoc(),
985                                           CI->getParent())
986                  << "Cannot interchange loops due to call instruction.";
987         });
988 
989         return false;
990       }
991 
992   // TODO: The loops could not be interchanged due to current limitations in the
993   // transform module.
994   if (currentLimitations()) {
995     LLVM_DEBUG(dbgs() << "Not legal because of current transform limitation\n");
996     return false;
997   }
998 
999   // Check if the loops are tightly nested.
1000   if (!tightlyNested(OuterLoop, InnerLoop)) {
1001     LLVM_DEBUG(dbgs() << "Loops not tightly nested\n");
1002     ORE->emit([&]() {
1003       return OptimizationRemarkMissed(DEBUG_TYPE, "NotTightlyNested",
1004                                       InnerLoop->getStartLoc(),
1005                                       InnerLoop->getHeader())
1006              << "Cannot interchange loops because they are not tightly "
1007                 "nested.";
1008     });
1009     return false;
1010   }
1011 
1012   if (!areInnerLoopExitPHIsSupported(OuterLoop, InnerLoop,
1013                                      OuterInnerReductions)) {
1014     LLVM_DEBUG(dbgs() << "Found unsupported PHI nodes in inner loop exit.\n");
1015     ORE->emit([&]() {
1016       return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedExitPHI",
1017                                       InnerLoop->getStartLoc(),
1018                                       InnerLoop->getHeader())
1019              << "Found unsupported PHI node in loop exit.";
1020     });
1021     return false;
1022   }
1023 
1024   if (!areOuterLoopExitPHIsSupported(OuterLoop, InnerLoop)) {
1025     LLVM_DEBUG(dbgs() << "Found unsupported PHI nodes in outer loop exit.\n");
1026     ORE->emit([&]() {
1027       return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedExitPHI",
1028                                       OuterLoop->getStartLoc(),
1029                                       OuterLoop->getHeader())
1030              << "Found unsupported PHI node in loop exit.";
1031     });
1032     return false;
1033   }
1034 
1035   return true;
1036 }
1037 
1038 int LoopInterchangeProfitability::getInstrOrderCost() {
1039   unsigned GoodOrder, BadOrder;
1040   BadOrder = GoodOrder = 0;
1041   for (BasicBlock *BB : InnerLoop->blocks()) {
1042     for (Instruction &Ins : *BB) {
1043       if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Ins)) {
1044         unsigned NumOp = GEP->getNumOperands();
1045         bool FoundInnerInduction = false;
1046         bool FoundOuterInduction = false;
1047         for (unsigned i = 0; i < NumOp; ++i) {
1048           // Skip operands that are not SCEV-able.
1049           if (!SE->isSCEVable(GEP->getOperand(i)->getType()))
1050             continue;
1051 
1052           const SCEV *OperandVal = SE->getSCEV(GEP->getOperand(i));
1053           const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(OperandVal);
1054           if (!AR)
1055             continue;
1056 
1057           // If we find the inner induction after an outer induction e.g.
1058           // for(int i=0;i<N;i++)
1059           //   for(int j=0;j<N;j++)
1060           //     A[i][j] = A[i-1][j-1]+k;
1061           // then it is a good order.
1062           if (AR->getLoop() == InnerLoop) {
1063             // We found an InnerLoop induction after OuterLoop induction. It is
1064             // a good order.
1065             FoundInnerInduction = true;
1066             if (FoundOuterInduction) {
1067               GoodOrder++;
1068               break;
1069             }
1070           }
1071           // If we find the outer induction after an inner induction e.g.
1072           // for(int i=0;i<N;i++)
1073           //   for(int j=0;j<N;j++)
1074           //     A[j][i] = A[j-1][i-1]+k;
1075           // then it is a bad order.
1076           if (AR->getLoop() == OuterLoop) {
1077             // We found an OuterLoop induction after InnerLoop induction. It is
1078             // a bad order.
1079             FoundOuterInduction = true;
1080             if (FoundInnerInduction) {
1081               BadOrder++;
1082               break;
1083             }
1084           }
1085         }
1086       }
1087     }
1088   }
1089   return GoodOrder - BadOrder;
1090 }
1091 
1092 static bool isProfitableForVectorization(unsigned InnerLoopId,
1093                                          unsigned OuterLoopId,
1094                                          CharMatrix &DepMatrix) {
1095   // TODO: Improve this heuristic to catch more cases.
1096   // If the inner loop is loop independent or doesn't carry any dependency it is
1097   // profitable to move this to outer position.
1098   for (auto &Row : DepMatrix) {
1099     if (Row[InnerLoopId] != 'S' && Row[InnerLoopId] != 'I')
1100       return false;
1101     // TODO: We need to improve this heuristic.
1102     if (Row[OuterLoopId] != '=')
1103       return false;
1104   }
1105   // If outer loop has dependence and inner loop is loop independent then it is
1106   // profitable to interchange to enable parallelism.
1107   // If there are no dependences, interchanging will not improve anything.
1108   return !DepMatrix.empty();
1109 }
1110 
1111 bool LoopInterchangeProfitability::isProfitable(unsigned InnerLoopId,
1112                                                 unsigned OuterLoopId,
1113                                                 CharMatrix &DepMatrix) {
1114   // TODO: Add better profitability checks.
1115   // e.g
1116   // 1) Construct dependency matrix and move the one with no loop carried dep
1117   //    inside to enable vectorization.
1118 
1119   // This is rough cost estimation algorithm. It counts the good and bad order
1120   // of induction variables in the instruction and allows reordering if number
1121   // of bad orders is more than good.
1122   int Cost = getInstrOrderCost();
1123   LLVM_DEBUG(dbgs() << "Cost = " << Cost << "\n");
1124   if (Cost < -LoopInterchangeCostThreshold)
1125     return true;
1126 
1127   // It is not profitable as per current cache profitability model. But check if
1128   // we can move this loop outside to improve parallelism.
1129   if (isProfitableForVectorization(InnerLoopId, OuterLoopId, DepMatrix))
1130     return true;
1131 
1132   ORE->emit([&]() {
1133     return OptimizationRemarkMissed(DEBUG_TYPE, "InterchangeNotProfitable",
1134                                     InnerLoop->getStartLoc(),
1135                                     InnerLoop->getHeader())
1136            << "Interchanging loops is too costly (cost="
1137            << ore::NV("Cost", Cost) << ", threshold="
1138            << ore::NV("Threshold", LoopInterchangeCostThreshold)
1139            << ") and it does not improve parallelism.";
1140   });
1141   return false;
1142 }
1143 
1144 void LoopInterchangeTransform::removeChildLoop(Loop *OuterLoop,
1145                                                Loop *InnerLoop) {
1146   for (Loop *L : *OuterLoop)
1147     if (L == InnerLoop) {
1148       OuterLoop->removeChildLoop(L);
1149       return;
1150     }
1151   llvm_unreachable("Couldn't find loop");
1152 }
1153 
1154 /// Update LoopInfo, after interchanging. NewInner and NewOuter refer to the
1155 /// new inner and outer loop after interchanging: NewInner is the original
1156 /// outer loop and NewOuter is the original inner loop.
1157 ///
1158 /// Before interchanging, we have the following structure
1159 /// Outer preheader
1160 //  Outer header
1161 //    Inner preheader
1162 //    Inner header
1163 //      Inner body
1164 //      Inner latch
1165 //   outer bbs
1166 //   Outer latch
1167 //
1168 // After interchanging:
1169 // Inner preheader
1170 // Inner header
1171 //   Outer preheader
1172 //   Outer header
1173 //     Inner body
1174 //     outer bbs
1175 //     Outer latch
1176 //   Inner latch
1177 void LoopInterchangeTransform::restructureLoops(
1178     Loop *NewInner, Loop *NewOuter, BasicBlock *OrigInnerPreHeader,
1179     BasicBlock *OrigOuterPreHeader) {
1180   Loop *OuterLoopParent = OuterLoop->getParentLoop();
1181   // The original inner loop preheader moves from the new inner loop to
1182   // the parent loop, if there is one.
1183   NewInner->removeBlockFromLoop(OrigInnerPreHeader);
1184   LI->changeLoopFor(OrigInnerPreHeader, OuterLoopParent);
1185 
1186   // Switch the loop levels.
1187   if (OuterLoopParent) {
1188     // Remove the loop from its parent loop.
1189     removeChildLoop(OuterLoopParent, NewInner);
1190     removeChildLoop(NewInner, NewOuter);
1191     OuterLoopParent->addChildLoop(NewOuter);
1192   } else {
1193     removeChildLoop(NewInner, NewOuter);
1194     LI->changeTopLevelLoop(NewInner, NewOuter);
1195   }
1196   while (!NewOuter->isInnermost())
1197     NewInner->addChildLoop(NewOuter->removeChildLoop(NewOuter->begin()));
1198   NewOuter->addChildLoop(NewInner);
1199 
1200   // BBs from the original inner loop.
1201   SmallVector<BasicBlock *, 8> OrigInnerBBs(NewOuter->blocks());
1202 
1203   // Add BBs from the original outer loop to the original inner loop (excluding
1204   // BBs already in inner loop)
1205   for (BasicBlock *BB : NewInner->blocks())
1206     if (LI->getLoopFor(BB) == NewInner)
1207       NewOuter->addBlockEntry(BB);
1208 
1209   // Now remove inner loop header and latch from the new inner loop and move
1210   // other BBs (the loop body) to the new inner loop.
1211   BasicBlock *OuterHeader = NewOuter->getHeader();
1212   BasicBlock *OuterLatch = NewOuter->getLoopLatch();
1213   for (BasicBlock *BB : OrigInnerBBs) {
1214     // Nothing will change for BBs in child loops.
1215     if (LI->getLoopFor(BB) != NewOuter)
1216       continue;
1217     // Remove the new outer loop header and latch from the new inner loop.
1218     if (BB == OuterHeader || BB == OuterLatch)
1219       NewInner->removeBlockFromLoop(BB);
1220     else
1221       LI->changeLoopFor(BB, NewInner);
1222   }
1223 
1224   // The preheader of the original outer loop becomes part of the new
1225   // outer loop.
1226   NewOuter->addBlockEntry(OrigOuterPreHeader);
1227   LI->changeLoopFor(OrigOuterPreHeader, NewOuter);
1228 
1229   // Tell SE that we move the loops around.
1230   SE->forgetLoop(NewOuter);
1231   SE->forgetLoop(NewInner);
1232 }
1233 
1234 bool LoopInterchangeTransform::transform() {
1235   bool Transformed = false;
1236   Instruction *InnerIndexVar;
1237 
1238   if (InnerLoop->getSubLoops().empty()) {
1239     BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
1240     LLVM_DEBUG(dbgs() << "Splitting the inner loop latch\n");
1241     PHINode *InductionPHI = getInductionVariable(InnerLoop, SE);
1242     if (!InductionPHI) {
1243       LLVM_DEBUG(dbgs() << "Failed to find the point to split loop latch \n");
1244       return false;
1245     }
1246 
1247     if (InductionPHI->getIncomingBlock(0) == InnerLoopPreHeader)
1248       InnerIndexVar = dyn_cast<Instruction>(InductionPHI->getIncomingValue(1));
1249     else
1250       InnerIndexVar = dyn_cast<Instruction>(InductionPHI->getIncomingValue(0));
1251 
1252     // Ensure that InductionPHI is the first Phi node.
1253     if (&InductionPHI->getParent()->front() != InductionPHI)
1254       InductionPHI->moveBefore(&InductionPHI->getParent()->front());
1255 
1256     // Create a new latch block for the inner loop. We split at the
1257     // current latch's terminator and then move the condition and all
1258     // operands that are not either loop-invariant or the induction PHI into the
1259     // new latch block.
1260     BasicBlock *NewLatch =
1261         SplitBlock(InnerLoop->getLoopLatch(),
1262                    InnerLoop->getLoopLatch()->getTerminator(), DT, LI);
1263 
1264     SmallSetVector<Instruction *, 4> WorkList;
1265     unsigned i = 0;
1266     auto MoveInstructions = [&i, &WorkList, this, InductionPHI, NewLatch]() {
1267       for (; i < WorkList.size(); i++) {
1268         // Duplicate instruction and move it the new latch. Update uses that
1269         // have been moved.
1270         Instruction *NewI = WorkList[i]->clone();
1271         NewI->insertBefore(NewLatch->getFirstNonPHI());
1272         assert(!NewI->mayHaveSideEffects() &&
1273                "Moving instructions with side-effects may change behavior of "
1274                "the loop nest!");
1275         for (auto UI = WorkList[i]->use_begin(), UE = WorkList[i]->use_end();
1276              UI != UE;) {
1277           Use &U = *UI++;
1278           Instruction *UserI = cast<Instruction>(U.getUser());
1279           if (!InnerLoop->contains(UserI->getParent()) ||
1280               UserI->getParent() == NewLatch || UserI == InductionPHI)
1281             U.set(NewI);
1282         }
1283         // Add operands of moved instruction to the worklist, except if they are
1284         // outside the inner loop or are the induction PHI.
1285         for (Value *Op : WorkList[i]->operands()) {
1286           Instruction *OpI = dyn_cast<Instruction>(Op);
1287           if (!OpI ||
1288               this->LI->getLoopFor(OpI->getParent()) != this->InnerLoop ||
1289               OpI == InductionPHI)
1290             continue;
1291           WorkList.insert(OpI);
1292         }
1293       }
1294     };
1295 
1296     // FIXME: Should we interchange when we have a constant condition?
1297     Instruction *CondI = dyn_cast<Instruction>(
1298         cast<BranchInst>(InnerLoop->getLoopLatch()->getTerminator())
1299             ->getCondition());
1300     if (CondI)
1301       WorkList.insert(CondI);
1302     MoveInstructions();
1303     WorkList.insert(cast<Instruction>(InnerIndexVar));
1304     MoveInstructions();
1305 
1306     // Splits the inner loops phi nodes out into a separate basic block.
1307     BasicBlock *InnerLoopHeader = InnerLoop->getHeader();
1308     SplitBlock(InnerLoopHeader, InnerLoopHeader->getFirstNonPHI(), DT, LI);
1309     LLVM_DEBUG(dbgs() << "splitting InnerLoopHeader done\n");
1310   }
1311 
1312   // Instructions in the original inner loop preheader may depend on values
1313   // defined in the outer loop header. Move them there, because the original
1314   // inner loop preheader will become the entry into the interchanged loop nest.
1315   // Currently we move all instructions and rely on LICM to move invariant
1316   // instructions outside the loop nest.
1317   BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
1318   BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
1319   if (InnerLoopPreHeader != OuterLoopHeader) {
1320     SmallPtrSet<Instruction *, 4> NeedsMoving;
1321     for (Instruction &I :
1322          make_early_inc_range(make_range(InnerLoopPreHeader->begin(),
1323                                          std::prev(InnerLoopPreHeader->end()))))
1324       I.moveBefore(OuterLoopHeader->getTerminator());
1325   }
1326 
1327   Transformed |= adjustLoopLinks();
1328   if (!Transformed) {
1329     LLVM_DEBUG(dbgs() << "adjustLoopLinks failed\n");
1330     return false;
1331   }
1332 
1333   return true;
1334 }
1335 
1336 /// \brief Move all instructions except the terminator from FromBB right before
1337 /// InsertBefore
1338 static void moveBBContents(BasicBlock *FromBB, Instruction *InsertBefore) {
1339   auto &ToList = InsertBefore->getParent()->getInstList();
1340   auto &FromList = FromBB->getInstList();
1341 
1342   ToList.splice(InsertBefore->getIterator(), FromList, FromList.begin(),
1343                 FromBB->getTerminator()->getIterator());
1344 }
1345 
1346 /// Swap instructions between \p BB1 and \p BB2 but keep terminators intact.
1347 static void swapBBContents(BasicBlock *BB1, BasicBlock *BB2) {
1348   // Save all non-terminator instructions of BB1 into TempInstrs and unlink them
1349   // from BB1 afterwards.
1350   auto Iter = map_range(*BB1, [](Instruction &I) { return &I; });
1351   SmallVector<Instruction *, 4> TempInstrs(Iter.begin(), std::prev(Iter.end()));
1352   for (Instruction *I : TempInstrs)
1353     I->removeFromParent();
1354 
1355   // Move instructions from BB2 to BB1.
1356   moveBBContents(BB2, BB1->getTerminator());
1357 
1358   // Move instructions from TempInstrs to BB2.
1359   for (Instruction *I : TempInstrs)
1360     I->insertBefore(BB2->getTerminator());
1361 }
1362 
1363 // Update BI to jump to NewBB instead of OldBB. Records updates to the
1364 // dominator tree in DTUpdates. If \p MustUpdateOnce is true, assert that
1365 // \p OldBB  is exactly once in BI's successor list.
1366 static void updateSuccessor(BranchInst *BI, BasicBlock *OldBB,
1367                             BasicBlock *NewBB,
1368                             std::vector<DominatorTree::UpdateType> &DTUpdates,
1369                             bool MustUpdateOnce = true) {
1370   assert((!MustUpdateOnce ||
1371           llvm::count_if(successors(BI),
1372                          [OldBB](BasicBlock *BB) {
1373                            return BB == OldBB;
1374                          }) == 1) && "BI must jump to OldBB exactly once.");
1375   bool Changed = false;
1376   for (Use &Op : BI->operands())
1377     if (Op == OldBB) {
1378       Op.set(NewBB);
1379       Changed = true;
1380     }
1381 
1382   if (Changed) {
1383     DTUpdates.push_back(
1384         {DominatorTree::UpdateKind::Insert, BI->getParent(), NewBB});
1385     DTUpdates.push_back(
1386         {DominatorTree::UpdateKind::Delete, BI->getParent(), OldBB});
1387   }
1388   assert(Changed && "Expected a successor to be updated");
1389 }
1390 
1391 // Move Lcssa PHIs to the right place.
1392 static void moveLCSSAPhis(BasicBlock *InnerExit, BasicBlock *InnerHeader,
1393                           BasicBlock *InnerLatch, BasicBlock *OuterHeader,
1394                           BasicBlock *OuterLatch, BasicBlock *OuterExit,
1395                           Loop *InnerLoop, LoopInfo *LI) {
1396 
1397   // Deal with LCSSA PHI nodes in the exit block of the inner loop, that are
1398   // defined either in the header or latch. Those blocks will become header and
1399   // latch of the new outer loop, and the only possible users can PHI nodes
1400   // in the exit block of the loop nest or the outer loop header (reduction
1401   // PHIs, in that case, the incoming value must be defined in the inner loop
1402   // header). We can just substitute the user with the incoming value and remove
1403   // the PHI.
1404   for (PHINode &P : make_early_inc_range(InnerExit->phis())) {
1405     assert(P.getNumIncomingValues() == 1 &&
1406            "Only loops with a single exit are supported!");
1407 
1408     // Incoming values are guaranteed be instructions currently.
1409     auto IncI = cast<Instruction>(P.getIncomingValueForBlock(InnerLatch));
1410     // Skip phis with incoming values from the inner loop body, excluding the
1411     // header and latch.
1412     if (IncI->getParent() != InnerLatch && IncI->getParent() != InnerHeader)
1413       continue;
1414 
1415     assert(all_of(P.users(),
1416                   [OuterHeader, OuterExit, IncI, InnerHeader](User *U) {
1417                     return (cast<PHINode>(U)->getParent() == OuterHeader &&
1418                             IncI->getParent() == InnerHeader) ||
1419                            cast<PHINode>(U)->getParent() == OuterExit;
1420                   }) &&
1421            "Can only replace phis iff the uses are in the loop nest exit or "
1422            "the incoming value is defined in the inner header (it will "
1423            "dominate all loop blocks after interchanging)");
1424     P.replaceAllUsesWith(IncI);
1425     P.eraseFromParent();
1426   }
1427 
1428   SmallVector<PHINode *, 8> LcssaInnerExit;
1429   for (PHINode &P : InnerExit->phis())
1430     LcssaInnerExit.push_back(&P);
1431 
1432   SmallVector<PHINode *, 8> LcssaInnerLatch;
1433   for (PHINode &P : InnerLatch->phis())
1434     LcssaInnerLatch.push_back(&P);
1435 
1436   // Lcssa PHIs for values used outside the inner loop are in InnerExit.
1437   // If a PHI node has users outside of InnerExit, it has a use outside the
1438   // interchanged loop and we have to preserve it. We move these to
1439   // InnerLatch, which will become the new exit block for the innermost
1440   // loop after interchanging.
1441   for (PHINode *P : LcssaInnerExit)
1442     P->moveBefore(InnerLatch->getFirstNonPHI());
1443 
1444   // If the inner loop latch contains LCSSA PHIs, those come from a child loop
1445   // and we have to move them to the new inner latch.
1446   for (PHINode *P : LcssaInnerLatch)
1447     P->moveBefore(InnerExit->getFirstNonPHI());
1448 
1449   // Deal with LCSSA PHI nodes in the loop nest exit block. For PHIs that have
1450   // incoming values defined in the outer loop, we have to add a new PHI
1451   // in the inner loop latch, which became the exit block of the outer loop,
1452   // after interchanging.
1453   if (OuterExit) {
1454     for (PHINode &P : OuterExit->phis()) {
1455       if (P.getNumIncomingValues() != 1)
1456         continue;
1457       // Skip Phis with incoming values defined in the inner loop. Those should
1458       // already have been updated.
1459       auto I = dyn_cast<Instruction>(P.getIncomingValue(0));
1460       if (!I || LI->getLoopFor(I->getParent()) == InnerLoop)
1461         continue;
1462 
1463       PHINode *NewPhi = dyn_cast<PHINode>(P.clone());
1464       NewPhi->setIncomingValue(0, P.getIncomingValue(0));
1465       NewPhi->setIncomingBlock(0, OuterLatch);
1466       NewPhi->insertBefore(InnerLatch->getFirstNonPHI());
1467       P.setIncomingValue(0, NewPhi);
1468     }
1469   }
1470 
1471   // Now adjust the incoming blocks for the LCSSA PHIs.
1472   // For PHIs moved from Inner's exit block, we need to replace Inner's latch
1473   // with the new latch.
1474   InnerLatch->replacePhiUsesWith(InnerLatch, OuterLatch);
1475 }
1476 
1477 bool LoopInterchangeTransform::adjustLoopBranches() {
1478   LLVM_DEBUG(dbgs() << "adjustLoopBranches called\n");
1479   std::vector<DominatorTree::UpdateType> DTUpdates;
1480 
1481   BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader();
1482   BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
1483 
1484   assert(OuterLoopPreHeader != OuterLoop->getHeader() &&
1485          InnerLoopPreHeader != InnerLoop->getHeader() && OuterLoopPreHeader &&
1486          InnerLoopPreHeader && "Guaranteed by loop-simplify form");
1487   // Ensure that both preheaders do not contain PHI nodes and have single
1488   // predecessors. This allows us to move them easily. We use
1489   // InsertPreHeaderForLoop to create an 'extra' preheader, if the existing
1490   // preheaders do not satisfy those conditions.
1491   if (isa<PHINode>(OuterLoopPreHeader->begin()) ||
1492       !OuterLoopPreHeader->getUniquePredecessor())
1493     OuterLoopPreHeader =
1494         InsertPreheaderForLoop(OuterLoop, DT, LI, nullptr, true);
1495   if (InnerLoopPreHeader == OuterLoop->getHeader())
1496     InnerLoopPreHeader =
1497         InsertPreheaderForLoop(InnerLoop, DT, LI, nullptr, true);
1498 
1499   // Adjust the loop preheader
1500   BasicBlock *InnerLoopHeader = InnerLoop->getHeader();
1501   BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
1502   BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
1503   BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch();
1504   BasicBlock *OuterLoopPredecessor = OuterLoopPreHeader->getUniquePredecessor();
1505   BasicBlock *InnerLoopLatchPredecessor =
1506       InnerLoopLatch->getUniquePredecessor();
1507   BasicBlock *InnerLoopLatchSuccessor;
1508   BasicBlock *OuterLoopLatchSuccessor;
1509 
1510   BranchInst *OuterLoopLatchBI =
1511       dyn_cast<BranchInst>(OuterLoopLatch->getTerminator());
1512   BranchInst *InnerLoopLatchBI =
1513       dyn_cast<BranchInst>(InnerLoopLatch->getTerminator());
1514   BranchInst *OuterLoopHeaderBI =
1515       dyn_cast<BranchInst>(OuterLoopHeader->getTerminator());
1516   BranchInst *InnerLoopHeaderBI =
1517       dyn_cast<BranchInst>(InnerLoopHeader->getTerminator());
1518 
1519   if (!OuterLoopPredecessor || !InnerLoopLatchPredecessor ||
1520       !OuterLoopLatchBI || !InnerLoopLatchBI || !OuterLoopHeaderBI ||
1521       !InnerLoopHeaderBI)
1522     return false;
1523 
1524   BranchInst *InnerLoopLatchPredecessorBI =
1525       dyn_cast<BranchInst>(InnerLoopLatchPredecessor->getTerminator());
1526   BranchInst *OuterLoopPredecessorBI =
1527       dyn_cast<BranchInst>(OuterLoopPredecessor->getTerminator());
1528 
1529   if (!OuterLoopPredecessorBI || !InnerLoopLatchPredecessorBI)
1530     return false;
1531   BasicBlock *InnerLoopHeaderSuccessor = InnerLoopHeader->getUniqueSuccessor();
1532   if (!InnerLoopHeaderSuccessor)
1533     return false;
1534 
1535   // Adjust Loop Preheader and headers.
1536   // The branches in the outer loop predecessor and the outer loop header can
1537   // be unconditional branches or conditional branches with duplicates. Consider
1538   // this when updating the successors.
1539   updateSuccessor(OuterLoopPredecessorBI, OuterLoopPreHeader,
1540                   InnerLoopPreHeader, DTUpdates, /*MustUpdateOnce=*/false);
1541   // The outer loop header might or might not branch to the outer latch.
1542   // We are guaranteed to branch to the inner loop preheader.
1543   if (llvm::is_contained(OuterLoopHeaderBI->successors(), OuterLoopLatch))
1544     updateSuccessor(OuterLoopHeaderBI, OuterLoopLatch, LoopExit, DTUpdates,
1545                     /*MustUpdateOnce=*/false);
1546   updateSuccessor(OuterLoopHeaderBI, InnerLoopPreHeader,
1547                   InnerLoopHeaderSuccessor, DTUpdates,
1548                   /*MustUpdateOnce=*/false);
1549 
1550   // Adjust reduction PHI's now that the incoming block has changed.
1551   InnerLoopHeaderSuccessor->replacePhiUsesWith(InnerLoopHeader,
1552                                                OuterLoopHeader);
1553 
1554   updateSuccessor(InnerLoopHeaderBI, InnerLoopHeaderSuccessor,
1555                   OuterLoopPreHeader, DTUpdates);
1556 
1557   // -------------Adjust loop latches-----------
1558   if (InnerLoopLatchBI->getSuccessor(0) == InnerLoopHeader)
1559     InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(1);
1560   else
1561     InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(0);
1562 
1563   updateSuccessor(InnerLoopLatchPredecessorBI, InnerLoopLatch,
1564                   InnerLoopLatchSuccessor, DTUpdates);
1565 
1566 
1567   if (OuterLoopLatchBI->getSuccessor(0) == OuterLoopHeader)
1568     OuterLoopLatchSuccessor = OuterLoopLatchBI->getSuccessor(1);
1569   else
1570     OuterLoopLatchSuccessor = OuterLoopLatchBI->getSuccessor(0);
1571 
1572   updateSuccessor(InnerLoopLatchBI, InnerLoopLatchSuccessor,
1573                   OuterLoopLatchSuccessor, DTUpdates);
1574   updateSuccessor(OuterLoopLatchBI, OuterLoopLatchSuccessor, InnerLoopLatch,
1575                   DTUpdates);
1576 
1577   DT->applyUpdates(DTUpdates);
1578   restructureLoops(OuterLoop, InnerLoop, InnerLoopPreHeader,
1579                    OuterLoopPreHeader);
1580 
1581   moveLCSSAPhis(InnerLoopLatchSuccessor, InnerLoopHeader, InnerLoopLatch,
1582                 OuterLoopHeader, OuterLoopLatch, InnerLoop->getExitBlock(),
1583                 InnerLoop, LI);
1584   // For PHIs in the exit block of the outer loop, outer's latch has been
1585   // replaced by Inners'.
1586   OuterLoopLatchSuccessor->replacePhiUsesWith(OuterLoopLatch, InnerLoopLatch);
1587 
1588   // Now update the reduction PHIs in the inner and outer loop headers.
1589   SmallVector<PHINode *, 4> InnerLoopPHIs, OuterLoopPHIs;
1590   for (PHINode &PHI : drop_begin(InnerLoopHeader->phis()))
1591     InnerLoopPHIs.push_back(cast<PHINode>(&PHI));
1592   for (PHINode &PHI : drop_begin(OuterLoopHeader->phis()))
1593     OuterLoopPHIs.push_back(cast<PHINode>(&PHI));
1594 
1595   auto &OuterInnerReductions = LIL.getOuterInnerReductions();
1596   (void)OuterInnerReductions;
1597 
1598   // Now move the remaining reduction PHIs from outer to inner loop header and
1599   // vice versa. The PHI nodes must be part of a reduction across the inner and
1600   // outer loop and all the remains to do is and updating the incoming blocks.
1601   for (PHINode *PHI : OuterLoopPHIs) {
1602     PHI->moveBefore(InnerLoopHeader->getFirstNonPHI());
1603     assert(OuterInnerReductions.count(PHI) && "Expected a reduction PHI node");
1604   }
1605   for (PHINode *PHI : InnerLoopPHIs) {
1606     PHI->moveBefore(OuterLoopHeader->getFirstNonPHI());
1607     assert(OuterInnerReductions.count(PHI) && "Expected a reduction PHI node");
1608   }
1609 
1610   // Update the incoming blocks for moved PHI nodes.
1611   OuterLoopHeader->replacePhiUsesWith(InnerLoopPreHeader, OuterLoopPreHeader);
1612   OuterLoopHeader->replacePhiUsesWith(InnerLoopLatch, OuterLoopLatch);
1613   InnerLoopHeader->replacePhiUsesWith(OuterLoopPreHeader, InnerLoopPreHeader);
1614   InnerLoopHeader->replacePhiUsesWith(OuterLoopLatch, InnerLoopLatch);
1615 
1616   // Values defined in the outer loop header could be used in the inner loop
1617   // latch. In that case, we need to create LCSSA phis for them, because after
1618   // interchanging they will be defined in the new inner loop and used in the
1619   // new outer loop.
1620   IRBuilder<> Builder(OuterLoopHeader->getContext());
1621   SmallVector<Instruction *, 4> MayNeedLCSSAPhis;
1622   for (Instruction &I :
1623        make_range(OuterLoopHeader->begin(), std::prev(OuterLoopHeader->end())))
1624     MayNeedLCSSAPhis.push_back(&I);
1625   formLCSSAForInstructions(MayNeedLCSSAPhis, *DT, *LI, SE, Builder);
1626 
1627   return true;
1628 }
1629 
1630 bool LoopInterchangeTransform::adjustLoopLinks() {
1631   // Adjust all branches in the inner and outer loop.
1632   bool Changed = adjustLoopBranches();
1633   if (Changed) {
1634     // We have interchanged the preheaders so we need to interchange the data in
1635     // the preheaders as well. This is because the content of the inner
1636     // preheader was previously executed inside the outer loop.
1637     BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader();
1638     BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
1639     swapBBContents(OuterLoopPreHeader, InnerLoopPreHeader);
1640   }
1641   return Changed;
1642 }
1643 
1644 /// Main LoopInterchange Pass.
1645 struct LoopInterchangeLegacyPass : public LoopPass {
1646   static char ID;
1647 
1648   LoopInterchangeLegacyPass() : LoopPass(ID) {
1649     initializeLoopInterchangeLegacyPassPass(*PassRegistry::getPassRegistry());
1650   }
1651 
1652   void getAnalysisUsage(AnalysisUsage &AU) const override {
1653     AU.addRequired<DependenceAnalysisWrapperPass>();
1654     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
1655 
1656     getLoopAnalysisUsage(AU);
1657   }
1658 
1659   bool runOnLoop(Loop *L, LPPassManager &LPM) override {
1660     if (skipLoop(L))
1661       return false;
1662 
1663     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1664     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1665     auto *DI = &getAnalysis<DependenceAnalysisWrapperPass>().getDI();
1666     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1667     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
1668 
1669     return LoopInterchange(SE, LI, DI, DT, ORE).run(L);
1670   }
1671 };
1672 
1673 char LoopInterchangeLegacyPass::ID = 0;
1674 
1675 INITIALIZE_PASS_BEGIN(LoopInterchangeLegacyPass, "loop-interchange",
1676                       "Interchanges loops for cache reuse", false, false)
1677 INITIALIZE_PASS_DEPENDENCY(LoopPass)
1678 INITIALIZE_PASS_DEPENDENCY(DependenceAnalysisWrapperPass)
1679 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
1680 
1681 INITIALIZE_PASS_END(LoopInterchangeLegacyPass, "loop-interchange",
1682                     "Interchanges loops for cache reuse", false, false)
1683 
1684 Pass *llvm::createLoopInterchangePass() {
1685   return new LoopInterchangeLegacyPass();
1686 }
1687 
1688 PreservedAnalyses LoopInterchangePass::run(LoopNest &LN,
1689                                            LoopAnalysisManager &AM,
1690                                            LoopStandardAnalysisResults &AR,
1691                                            LPMUpdater &U) {
1692   Function &F = *LN.getParent();
1693 
1694   DependenceInfo DI(&F, &AR.AA, &AR.SE, &AR.LI);
1695   OptimizationRemarkEmitter ORE(&F);
1696   if (!LoopInterchange(&AR.SE, &AR.LI, &DI, &AR.DT, &ORE).run(LN))
1697     return PreservedAnalyses::all();
1698   return getLoopPassPreservedAnalyses();
1699 }
1700