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 isComputableLoopNest(LoopVector LoopList) {
453     for (Loop *L : LoopList) {
454       const SCEV *ExitCountOuter = SE->getBackedgeTakenCount(L);
455       if (isa<SCEVCouldNotCompute>(ExitCountOuter)) {
456         LLVM_DEBUG(dbgs() << "Couldn't compute backedge count\n");
457         return false;
458       }
459       if (L->getNumBackEdges() != 1) {
460         LLVM_DEBUG(dbgs() << "NumBackEdges is not equal to 1\n");
461         return false;
462       }
463       if (!L->getExitingBlock()) {
464         LLVM_DEBUG(dbgs() << "Loop doesn't have unique exit block\n");
465         return false;
466       }
467     }
468     return true;
469   }
470 
471   unsigned selectLoopForInterchange(const LoopVector &LoopList) {
472     // TODO: Add a better heuristic to select the loop to be interchanged based
473     // on the dependence matrix. Currently we select the innermost loop.
474     return LoopList.size() - 1;
475   }
476 
477   bool processLoopList(LoopVector LoopList) {
478     bool Changed = false;
479     unsigned LoopNestDepth = LoopList.size();
480     if (LoopNestDepth < 2) {
481       LLVM_DEBUG(dbgs() << "Loop doesn't contain minimum nesting level.\n");
482       return false;
483     }
484     if (LoopNestDepth > MaxLoopNestDepth) {
485       LLVM_DEBUG(dbgs() << "Cannot handle loops of depth greater than "
486                         << MaxLoopNestDepth << "\n");
487       return false;
488     }
489     if (!isComputableLoopNest(LoopList)) {
490       LLVM_DEBUG(dbgs() << "Not valid loop candidate for interchange\n");
491       return false;
492     }
493 
494     LLVM_DEBUG(dbgs() << "Processing LoopList of size = " << LoopNestDepth
495                       << "\n");
496 
497     CharMatrix DependencyMatrix;
498     Loop *OuterMostLoop = *(LoopList.begin());
499     if (!populateDependencyMatrix(DependencyMatrix, LoopNestDepth,
500                                   OuterMostLoop, DI)) {
501       LLVM_DEBUG(dbgs() << "Populating dependency matrix failed\n");
502       return false;
503     }
504 #ifdef DUMP_DEP_MATRICIES
505     LLVM_DEBUG(dbgs() << "Dependence before interchange\n");
506     printDepMatrix(DependencyMatrix);
507 #endif
508 
509     // Get the Outermost loop exit.
510     BasicBlock *LoopNestExit = OuterMostLoop->getExitBlock();
511     if (!LoopNestExit) {
512       LLVM_DEBUG(dbgs() << "OuterMostLoop needs an unique exit block");
513       return false;
514     }
515 
516     unsigned SelecLoopId = selectLoopForInterchange(LoopList);
517     // Move the selected loop outwards to the best possible position.
518     for (unsigned i = SelecLoopId; i > 0; i--) {
519       bool Interchanged = processLoop(LoopList[i], LoopList[i - 1], i, i - 1,
520                                       LoopNestExit, DependencyMatrix);
521       if (!Interchanged)
522         return Changed;
523       // Loops interchanged reflect the same in LoopList
524       std::swap(LoopList[i - 1], LoopList[i]);
525 
526       // Update the DependencyMatrix
527       interChangeDependencies(DependencyMatrix, i, i - 1);
528 #ifdef DUMP_DEP_MATRICIES
529       LLVM_DEBUG(dbgs() << "Dependence after interchange\n");
530       printDepMatrix(DependencyMatrix);
531 #endif
532       Changed |= Interchanged;
533     }
534     return Changed;
535   }
536 
537   bool processLoop(Loop *InnerLoop, Loop *OuterLoop, unsigned InnerLoopId,
538                    unsigned OuterLoopId, BasicBlock *LoopNestExit,
539                    std::vector<std::vector<char>> &DependencyMatrix) {
540     LLVM_DEBUG(dbgs() << "Processing InnerLoopId = " << InnerLoopId
541                       << " and OuterLoopId = " << OuterLoopId << "\n");
542 
543     LoopInterchangeLegality LIL(OuterLoop, InnerLoop, SE, ORE);
544     if (!LIL.canInterchangeLoops(InnerLoopId, OuterLoopId, DependencyMatrix)) {
545       LLVM_DEBUG(dbgs() << "Not interchanging loops. Cannot prove legality.\n");
546       return false;
547     }
548     LLVM_DEBUG(dbgs() << "Loops are legal to interchange\n");
549     LoopInterchangeProfitability LIP(OuterLoop, InnerLoop, SE, ORE);
550     if (!LIP.isProfitable(InnerLoopId, OuterLoopId, DependencyMatrix)) {
551       LLVM_DEBUG(dbgs() << "Interchanging loops not profitable.\n");
552       return false;
553     }
554 
555     ORE->emit([&]() {
556       return OptimizationRemark(DEBUG_TYPE, "Interchanged",
557                                 InnerLoop->getStartLoc(),
558                                 InnerLoop->getHeader())
559              << "Loop interchanged with enclosing loop.";
560     });
561 
562     LoopInterchangeTransform LIT(OuterLoop, InnerLoop, SE, LI, DT, LoopNestExit,
563                                  LIL);
564     LIT.transform();
565     LLVM_DEBUG(dbgs() << "Loops interchanged.\n");
566     LoopsInterchanged++;
567 
568     assert(InnerLoop->isLCSSAForm(*DT) &&
569            "Inner loop not left in LCSSA form after loop interchange!");
570     assert(OuterLoop->isLCSSAForm(*DT) &&
571            "Outer loop not left in LCSSA form after loop interchange!");
572 
573     return true;
574   }
575 };
576 
577 } // end anonymous namespace
578 
579 bool LoopInterchangeLegality::containsUnsafeInstructions(BasicBlock *BB) {
580   return any_of(*BB, [](const Instruction &I) {
581     return I.mayHaveSideEffects() || I.mayReadFromMemory();
582   });
583 }
584 
585 bool LoopInterchangeLegality::tightlyNested(Loop *OuterLoop, Loop *InnerLoop) {
586   BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
587   BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
588   BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch();
589 
590   LLVM_DEBUG(dbgs() << "Checking if loops are tightly nested\n");
591 
592   // A perfectly nested loop will not have any branch in between the outer and
593   // inner block i.e. outer header will branch to either inner preheader and
594   // outerloop latch.
595   BranchInst *OuterLoopHeaderBI =
596       dyn_cast<BranchInst>(OuterLoopHeader->getTerminator());
597   if (!OuterLoopHeaderBI)
598     return false;
599 
600   for (BasicBlock *Succ : successors(OuterLoopHeaderBI))
601     if (Succ != InnerLoopPreHeader && Succ != InnerLoop->getHeader() &&
602         Succ != OuterLoopLatch)
603       return false;
604 
605   LLVM_DEBUG(dbgs() << "Checking instructions in Loop header and Loop latch\n");
606   // We do not have any basic block in between now make sure the outer header
607   // and outer loop latch doesn't contain any unsafe instructions.
608   if (containsUnsafeInstructions(OuterLoopHeader) ||
609       containsUnsafeInstructions(OuterLoopLatch))
610     return false;
611 
612   // Also make sure the inner loop preheader does not contain any unsafe
613   // instructions. Note that all instructions in the preheader will be moved to
614   // the outer loop header when interchanging.
615   if (InnerLoopPreHeader != OuterLoopHeader &&
616       containsUnsafeInstructions(InnerLoopPreHeader))
617     return false;
618 
619   LLVM_DEBUG(dbgs() << "Loops are perfectly nested\n");
620   // We have a perfect loop nest.
621   return true;
622 }
623 
624 bool LoopInterchangeLegality::isLoopStructureUnderstood(
625     PHINode *InnerInduction) {
626   unsigned Num = InnerInduction->getNumOperands();
627   BasicBlock *InnerLoopPreheader = InnerLoop->getLoopPreheader();
628   for (unsigned i = 0; i < Num; ++i) {
629     Value *Val = InnerInduction->getOperand(i);
630     if (isa<Constant>(Val))
631       continue;
632     Instruction *I = dyn_cast<Instruction>(Val);
633     if (!I)
634       return false;
635     // TODO: Handle triangular loops.
636     // e.g. for(int i=0;i<N;i++)
637     //        for(int j=i;j<N;j++)
638     unsigned IncomBlockIndx = PHINode::getIncomingValueNumForOperand(i);
639     if (InnerInduction->getIncomingBlock(IncomBlockIndx) ==
640             InnerLoopPreheader &&
641         !OuterLoop->isLoopInvariant(I)) {
642       return false;
643     }
644   }
645   return true;
646 }
647 
648 // If SV is a LCSSA PHI node with a single incoming value, return the incoming
649 // value.
650 static Value *followLCSSA(Value *SV) {
651   PHINode *PHI = dyn_cast<PHINode>(SV);
652   if (!PHI)
653     return SV;
654 
655   if (PHI->getNumIncomingValues() != 1)
656     return SV;
657   return followLCSSA(PHI->getIncomingValue(0));
658 }
659 
660 // Check V's users to see if it is involved in a reduction in L.
661 static PHINode *findInnerReductionPhi(Loop *L, Value *V) {
662   // Reduction variables cannot be constants.
663   if (isa<Constant>(V))
664     return nullptr;
665 
666   for (Value *User : V->users()) {
667     if (PHINode *PHI = dyn_cast<PHINode>(User)) {
668       if (PHI->getNumIncomingValues() == 1)
669         continue;
670       RecurrenceDescriptor RD;
671       if (RecurrenceDescriptor::isReductionPHI(PHI, L, RD))
672         return PHI;
673       return nullptr;
674     }
675   }
676 
677   return nullptr;
678 }
679 
680 bool LoopInterchangeLegality::findInductionAndReductions(
681     Loop *L, SmallVector<PHINode *, 8> &Inductions, Loop *InnerLoop) {
682   if (!L->getLoopLatch() || !L->getLoopPredecessor())
683     return false;
684   for (PHINode &PHI : L->getHeader()->phis()) {
685     RecurrenceDescriptor RD;
686     InductionDescriptor ID;
687     if (InductionDescriptor::isInductionPHI(&PHI, L, SE, ID))
688       Inductions.push_back(&PHI);
689     else {
690       // PHIs in inner loops need to be part of a reduction in the outer loop,
691       // discovered when checking the PHIs of the outer loop earlier.
692       if (!InnerLoop) {
693         if (!OuterInnerReductions.count(&PHI)) {
694           LLVM_DEBUG(dbgs() << "Inner loop PHI is not part of reductions "
695                                "across the outer loop.\n");
696           return false;
697         }
698       } else {
699         assert(PHI.getNumIncomingValues() == 2 &&
700                "Phis in loop header should have exactly 2 incoming values");
701         // Check if we have a PHI node in the outer loop that has a reduction
702         // result from the inner loop as an incoming value.
703         Value *V = followLCSSA(PHI.getIncomingValueForBlock(L->getLoopLatch()));
704         PHINode *InnerRedPhi = findInnerReductionPhi(InnerLoop, V);
705         if (!InnerRedPhi ||
706             !llvm::is_contained(InnerRedPhi->incoming_values(), &PHI)) {
707           LLVM_DEBUG(
708               dbgs()
709               << "Failed to recognize PHI as an induction or reduction.\n");
710           return false;
711         }
712         OuterInnerReductions.insert(&PHI);
713         OuterInnerReductions.insert(InnerRedPhi);
714       }
715     }
716   }
717   return true;
718 }
719 
720 // This function indicates the current limitations in the transform as a result
721 // of which we do not proceed.
722 bool LoopInterchangeLegality::currentLimitations() {
723   BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
724   BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
725 
726   // transform currently expects the loop latches to also be the exiting
727   // blocks.
728   if (InnerLoop->getExitingBlock() != InnerLoopLatch ||
729       OuterLoop->getExitingBlock() != OuterLoop->getLoopLatch() ||
730       !isa<BranchInst>(InnerLoopLatch->getTerminator()) ||
731       !isa<BranchInst>(OuterLoop->getLoopLatch()->getTerminator())) {
732     LLVM_DEBUG(
733         dbgs() << "Loops where the latch is not the exiting block are not"
734                << " supported currently.\n");
735     ORE->emit([&]() {
736       return OptimizationRemarkMissed(DEBUG_TYPE, "ExitingNotLatch",
737                                       OuterLoop->getStartLoc(),
738                                       OuterLoop->getHeader())
739              << "Loops where the latch is not the exiting block cannot be"
740                 " interchange currently.";
741     });
742     return true;
743   }
744 
745   PHINode *InnerInductionVar;
746   SmallVector<PHINode *, 8> Inductions;
747   if (!findInductionAndReductions(OuterLoop, Inductions, InnerLoop)) {
748     LLVM_DEBUG(
749         dbgs() << "Only outer loops with induction or reduction PHI nodes "
750                << "are supported currently.\n");
751     ORE->emit([&]() {
752       return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedPHIOuter",
753                                       OuterLoop->getStartLoc(),
754                                       OuterLoop->getHeader())
755              << "Only outer loops with induction or reduction PHI nodes can be"
756                 " interchanged currently.";
757     });
758     return true;
759   }
760 
761   // TODO: Currently we handle only loops with 1 induction variable.
762   if (Inductions.size() != 1) {
763     LLVM_DEBUG(dbgs() << "Loops with more than 1 induction variables are not "
764                       << "supported currently.\n");
765     ORE->emit([&]() {
766       return OptimizationRemarkMissed(DEBUG_TYPE, "MultiIndutionOuter",
767                                       OuterLoop->getStartLoc(),
768                                       OuterLoop->getHeader())
769              << "Only outer loops with 1 induction variable can be "
770                 "interchanged currently.";
771     });
772     return true;
773   }
774 
775   Inductions.clear();
776   if (!findInductionAndReductions(InnerLoop, Inductions, nullptr)) {
777     LLVM_DEBUG(
778         dbgs() << "Only inner loops with induction or reduction PHI nodes "
779                << "are supported currently.\n");
780     ORE->emit([&]() {
781       return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedPHIInner",
782                                       InnerLoop->getStartLoc(),
783                                       InnerLoop->getHeader())
784              << "Only inner loops with induction or reduction PHI nodes can be"
785                 " interchange currently.";
786     });
787     return true;
788   }
789 
790   // TODO: Currently we handle only loops with 1 induction variable.
791   if (Inductions.size() != 1) {
792     LLVM_DEBUG(
793         dbgs() << "We currently only support loops with 1 induction variable."
794                << "Failed to interchange due to current limitation\n");
795     ORE->emit([&]() {
796       return OptimizationRemarkMissed(DEBUG_TYPE, "MultiInductionInner",
797                                       InnerLoop->getStartLoc(),
798                                       InnerLoop->getHeader())
799              << "Only inner loops with 1 induction variable can be "
800                 "interchanged currently.";
801     });
802     return true;
803   }
804   InnerInductionVar = Inductions.pop_back_val();
805 
806   // TODO: Triangular loops are not handled for now.
807   if (!isLoopStructureUnderstood(InnerInductionVar)) {
808     LLVM_DEBUG(dbgs() << "Loop structure not understood by pass\n");
809     ORE->emit([&]() {
810       return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedStructureInner",
811                                       InnerLoop->getStartLoc(),
812                                       InnerLoop->getHeader())
813              << "Inner loop structure not understood currently.";
814     });
815     return true;
816   }
817 
818   // TODO: Current limitation: Since we split the inner loop latch at the point
819   // were induction variable is incremented (induction.next); We cannot have
820   // more than 1 user of induction.next since it would result in broken code
821   // after split.
822   // e.g.
823   // for(i=0;i<N;i++) {
824   //    for(j = 0;j<M;j++) {
825   //      A[j+1][i+2] = A[j][i]+k;
826   //  }
827   // }
828   Instruction *InnerIndexVarInc = nullptr;
829   if (InnerInductionVar->getIncomingBlock(0) == InnerLoopPreHeader)
830     InnerIndexVarInc =
831         dyn_cast<Instruction>(InnerInductionVar->getIncomingValue(1));
832   else
833     InnerIndexVarInc =
834         dyn_cast<Instruction>(InnerInductionVar->getIncomingValue(0));
835 
836   if (!InnerIndexVarInc) {
837     LLVM_DEBUG(
838         dbgs() << "Did not find an instruction to increment the induction "
839                << "variable.\n");
840     ORE->emit([&]() {
841       return OptimizationRemarkMissed(DEBUG_TYPE, "NoIncrementInInner",
842                                       InnerLoop->getStartLoc(),
843                                       InnerLoop->getHeader())
844              << "The inner loop does not increment the induction variable.";
845     });
846     return true;
847   }
848 
849   // Since we split the inner loop latch on this induction variable. Make sure
850   // we do not have any instruction between the induction variable and branch
851   // instruction.
852 
853   bool FoundInduction = false;
854   for (const Instruction &I :
855        llvm::reverse(InnerLoopLatch->instructionsWithoutDebug())) {
856     if (isa<BranchInst>(I) || isa<CmpInst>(I) || isa<TruncInst>(I) ||
857         isa<ZExtInst>(I))
858       continue;
859 
860     // We found an instruction. If this is not induction variable then it is not
861     // safe to split this loop latch.
862     if (!I.isIdenticalTo(InnerIndexVarInc)) {
863       LLVM_DEBUG(dbgs() << "Found unsupported instructions between induction "
864                         << "variable increment and branch.\n");
865       ORE->emit([&]() {
866         return OptimizationRemarkMissed(
867                    DEBUG_TYPE, "UnsupportedInsBetweenInduction",
868                    InnerLoop->getStartLoc(), InnerLoop->getHeader())
869                << "Found unsupported instruction between induction variable "
870                   "increment and branch.";
871       });
872       return true;
873     }
874 
875     FoundInduction = true;
876     break;
877   }
878   // The loop latch ended and we didn't find the induction variable return as
879   // current limitation.
880   if (!FoundInduction) {
881     LLVM_DEBUG(dbgs() << "Did not find the induction variable.\n");
882     ORE->emit([&]() {
883       return OptimizationRemarkMissed(DEBUG_TYPE, "NoIndutionVariable",
884                                       InnerLoop->getStartLoc(),
885                                       InnerLoop->getHeader())
886              << "Did not find the induction variable.";
887     });
888     return true;
889   }
890   return false;
891 }
892 
893 // We currently only support LCSSA PHI nodes in the inner loop exit, if their
894 // users are either reduction PHIs or PHIs outside the outer loop (which means
895 // the we are only interested in the final value after the loop).
896 static bool
897 areInnerLoopExitPHIsSupported(Loop *InnerL, Loop *OuterL,
898                               SmallPtrSetImpl<PHINode *> &Reductions) {
899   BasicBlock *InnerExit = OuterL->getUniqueExitBlock();
900   for (PHINode &PHI : InnerExit->phis()) {
901     // Reduction lcssa phi will have only 1 incoming block that from loop latch.
902     if (PHI.getNumIncomingValues() > 1)
903       return false;
904     if (any_of(PHI.users(), [&Reductions, OuterL](User *U) {
905           PHINode *PN = dyn_cast<PHINode>(U);
906           return !PN ||
907                  (!Reductions.count(PN) && OuterL->contains(PN->getParent()));
908         })) {
909       return false;
910     }
911   }
912   return true;
913 }
914 
915 // We currently support LCSSA PHI nodes in the outer loop exit, if their
916 // incoming values do not come from the outer loop latch or if the
917 // outer loop latch has a single predecessor. In that case, the value will
918 // be available if both the inner and outer loop conditions are true, which
919 // will still be true after interchanging. If we have multiple predecessor,
920 // that may not be the case, e.g. because the outer loop latch may be executed
921 // if the inner loop is not executed.
922 static bool areOuterLoopExitPHIsSupported(Loop *OuterLoop, Loop *InnerLoop) {
923   BasicBlock *LoopNestExit = OuterLoop->getUniqueExitBlock();
924   for (PHINode &PHI : LoopNestExit->phis()) {
925     //  FIXME: We currently are not able to detect floating point reductions
926     //         and have to use floating point PHIs as a proxy to prevent
927     //         interchanging in the presence of floating point reductions.
928     if (PHI.getType()->isFloatingPointTy())
929       return false;
930     for (unsigned i = 0; i < PHI.getNumIncomingValues(); i++) {
931      Instruction *IncomingI = dyn_cast<Instruction>(PHI.getIncomingValue(i));
932      if (!IncomingI || IncomingI->getParent() != OuterLoop->getLoopLatch())
933        continue;
934 
935      // The incoming value is defined in the outer loop latch. Currently we
936      // only support that in case the outer loop latch has a single predecessor.
937      // This guarantees that the outer loop latch is executed if and only if
938      // the inner loop is executed (because tightlyNested() guarantees that the
939      // outer loop header only branches to the inner loop or the outer loop
940      // latch).
941      // FIXME: We could weaken this logic and allow multiple predecessors,
942      //        if the values are produced outside the loop latch. We would need
943      //        additional logic to update the PHI nodes in the exit block as
944      //        well.
945      if (OuterLoop->getLoopLatch()->getUniquePredecessor() == nullptr)
946        return false;
947     }
948   }
949   return true;
950 }
951 
952 bool LoopInterchangeLegality::canInterchangeLoops(unsigned InnerLoopId,
953                                                   unsigned OuterLoopId,
954                                                   CharMatrix &DepMatrix) {
955   if (!isLegalToInterChangeLoops(DepMatrix, InnerLoopId, OuterLoopId)) {
956     LLVM_DEBUG(dbgs() << "Failed interchange InnerLoopId = " << InnerLoopId
957                       << " and OuterLoopId = " << OuterLoopId
958                       << " due to dependence\n");
959     ORE->emit([&]() {
960       return OptimizationRemarkMissed(DEBUG_TYPE, "Dependence",
961                                       InnerLoop->getStartLoc(),
962                                       InnerLoop->getHeader())
963              << "Cannot interchange loops due to dependences.";
964     });
965     return false;
966   }
967   // Check if outer and inner loop contain legal instructions only.
968   for (auto *BB : OuterLoop->blocks())
969     for (Instruction &I : BB->instructionsWithoutDebug())
970       if (CallInst *CI = dyn_cast<CallInst>(&I)) {
971         // readnone functions do not prevent interchanging.
972         if (CI->doesNotReadMemory())
973           continue;
974         LLVM_DEBUG(
975             dbgs() << "Loops with call instructions cannot be interchanged "
976                    << "safely.");
977         ORE->emit([&]() {
978           return OptimizationRemarkMissed(DEBUG_TYPE, "CallInst",
979                                           CI->getDebugLoc(),
980                                           CI->getParent())
981                  << "Cannot interchange loops due to call instruction.";
982         });
983 
984         return false;
985       }
986 
987   // TODO: The loops could not be interchanged due to current limitations in the
988   // transform module.
989   if (currentLimitations()) {
990     LLVM_DEBUG(dbgs() << "Not legal because of current transform limitation\n");
991     return false;
992   }
993 
994   // Check if the loops are tightly nested.
995   if (!tightlyNested(OuterLoop, InnerLoop)) {
996     LLVM_DEBUG(dbgs() << "Loops not tightly nested\n");
997     ORE->emit([&]() {
998       return OptimizationRemarkMissed(DEBUG_TYPE, "NotTightlyNested",
999                                       InnerLoop->getStartLoc(),
1000                                       InnerLoop->getHeader())
1001              << "Cannot interchange loops because they are not tightly "
1002                 "nested.";
1003     });
1004     return false;
1005   }
1006 
1007   if (!areInnerLoopExitPHIsSupported(OuterLoop, InnerLoop,
1008                                      OuterInnerReductions)) {
1009     LLVM_DEBUG(dbgs() << "Found unsupported PHI nodes in inner loop exit.\n");
1010     ORE->emit([&]() {
1011       return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedExitPHI",
1012                                       InnerLoop->getStartLoc(),
1013                                       InnerLoop->getHeader())
1014              << "Found unsupported PHI node in loop exit.";
1015     });
1016     return false;
1017   }
1018 
1019   if (!areOuterLoopExitPHIsSupported(OuterLoop, InnerLoop)) {
1020     LLVM_DEBUG(dbgs() << "Found unsupported PHI nodes in outer loop exit.\n");
1021     ORE->emit([&]() {
1022       return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedExitPHI",
1023                                       OuterLoop->getStartLoc(),
1024                                       OuterLoop->getHeader())
1025              << "Found unsupported PHI node in loop exit.";
1026     });
1027     return false;
1028   }
1029 
1030   return true;
1031 }
1032 
1033 int LoopInterchangeProfitability::getInstrOrderCost() {
1034   unsigned GoodOrder, BadOrder;
1035   BadOrder = GoodOrder = 0;
1036   for (BasicBlock *BB : InnerLoop->blocks()) {
1037     for (Instruction &Ins : *BB) {
1038       if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Ins)) {
1039         unsigned NumOp = GEP->getNumOperands();
1040         bool FoundInnerInduction = false;
1041         bool FoundOuterInduction = false;
1042         for (unsigned i = 0; i < NumOp; ++i) {
1043           // Skip operands that are not SCEV-able.
1044           if (!SE->isSCEVable(GEP->getOperand(i)->getType()))
1045             continue;
1046 
1047           const SCEV *OperandVal = SE->getSCEV(GEP->getOperand(i));
1048           const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(OperandVal);
1049           if (!AR)
1050             continue;
1051 
1052           // If we find the inner induction after an outer induction e.g.
1053           // for(int i=0;i<N;i++)
1054           //   for(int j=0;j<N;j++)
1055           //     A[i][j] = A[i-1][j-1]+k;
1056           // then it is a good order.
1057           if (AR->getLoop() == InnerLoop) {
1058             // We found an InnerLoop induction after OuterLoop induction. It is
1059             // a good order.
1060             FoundInnerInduction = true;
1061             if (FoundOuterInduction) {
1062               GoodOrder++;
1063               break;
1064             }
1065           }
1066           // If we find the outer induction after an inner induction e.g.
1067           // for(int i=0;i<N;i++)
1068           //   for(int j=0;j<N;j++)
1069           //     A[j][i] = A[j-1][i-1]+k;
1070           // then it is a bad order.
1071           if (AR->getLoop() == OuterLoop) {
1072             // We found an OuterLoop induction after InnerLoop induction. It is
1073             // a bad order.
1074             FoundOuterInduction = true;
1075             if (FoundInnerInduction) {
1076               BadOrder++;
1077               break;
1078             }
1079           }
1080         }
1081       }
1082     }
1083   }
1084   return GoodOrder - BadOrder;
1085 }
1086 
1087 static bool isProfitableForVectorization(unsigned InnerLoopId,
1088                                          unsigned OuterLoopId,
1089                                          CharMatrix &DepMatrix) {
1090   // TODO: Improve this heuristic to catch more cases.
1091   // If the inner loop is loop independent or doesn't carry any dependency it is
1092   // profitable to move this to outer position.
1093   for (auto &Row : DepMatrix) {
1094     if (Row[InnerLoopId] != 'S' && Row[InnerLoopId] != 'I')
1095       return false;
1096     // TODO: We need to improve this heuristic.
1097     if (Row[OuterLoopId] != '=')
1098       return false;
1099   }
1100   // If outer loop has dependence and inner loop is loop independent then it is
1101   // profitable to interchange to enable parallelism.
1102   // If there are no dependences, interchanging will not improve anything.
1103   return !DepMatrix.empty();
1104 }
1105 
1106 bool LoopInterchangeProfitability::isProfitable(unsigned InnerLoopId,
1107                                                 unsigned OuterLoopId,
1108                                                 CharMatrix &DepMatrix) {
1109   // TODO: Add better profitability checks.
1110   // e.g
1111   // 1) Construct dependency matrix and move the one with no loop carried dep
1112   //    inside to enable vectorization.
1113 
1114   // This is rough cost estimation algorithm. It counts the good and bad order
1115   // of induction variables in the instruction and allows reordering if number
1116   // of bad orders is more than good.
1117   int Cost = getInstrOrderCost();
1118   LLVM_DEBUG(dbgs() << "Cost = " << Cost << "\n");
1119   if (Cost < -LoopInterchangeCostThreshold)
1120     return true;
1121 
1122   // It is not profitable as per current cache profitability model. But check if
1123   // we can move this loop outside to improve parallelism.
1124   if (isProfitableForVectorization(InnerLoopId, OuterLoopId, DepMatrix))
1125     return true;
1126 
1127   ORE->emit([&]() {
1128     return OptimizationRemarkMissed(DEBUG_TYPE, "InterchangeNotProfitable",
1129                                     InnerLoop->getStartLoc(),
1130                                     InnerLoop->getHeader())
1131            << "Interchanging loops is too costly (cost="
1132            << ore::NV("Cost", Cost) << ", threshold="
1133            << ore::NV("Threshold", LoopInterchangeCostThreshold)
1134            << ") and it does not improve parallelism.";
1135   });
1136   return false;
1137 }
1138 
1139 void LoopInterchangeTransform::removeChildLoop(Loop *OuterLoop,
1140                                                Loop *InnerLoop) {
1141   for (Loop *L : *OuterLoop)
1142     if (L == InnerLoop) {
1143       OuterLoop->removeChildLoop(L);
1144       return;
1145     }
1146   llvm_unreachable("Couldn't find loop");
1147 }
1148 
1149 /// Update LoopInfo, after interchanging. NewInner and NewOuter refer to the
1150 /// new inner and outer loop after interchanging: NewInner is the original
1151 /// outer loop and NewOuter is the original inner loop.
1152 ///
1153 /// Before interchanging, we have the following structure
1154 /// Outer preheader
1155 //  Outer header
1156 //    Inner preheader
1157 //    Inner header
1158 //      Inner body
1159 //      Inner latch
1160 //   outer bbs
1161 //   Outer latch
1162 //
1163 // After interchanging:
1164 // Inner preheader
1165 // Inner header
1166 //   Outer preheader
1167 //   Outer header
1168 //     Inner body
1169 //     outer bbs
1170 //     Outer latch
1171 //   Inner latch
1172 void LoopInterchangeTransform::restructureLoops(
1173     Loop *NewInner, Loop *NewOuter, BasicBlock *OrigInnerPreHeader,
1174     BasicBlock *OrigOuterPreHeader) {
1175   Loop *OuterLoopParent = OuterLoop->getParentLoop();
1176   // The original inner loop preheader moves from the new inner loop to
1177   // the parent loop, if there is one.
1178   NewInner->removeBlockFromLoop(OrigInnerPreHeader);
1179   LI->changeLoopFor(OrigInnerPreHeader, OuterLoopParent);
1180 
1181   // Switch the loop levels.
1182   if (OuterLoopParent) {
1183     // Remove the loop from its parent loop.
1184     removeChildLoop(OuterLoopParent, NewInner);
1185     removeChildLoop(NewInner, NewOuter);
1186     OuterLoopParent->addChildLoop(NewOuter);
1187   } else {
1188     removeChildLoop(NewInner, NewOuter);
1189     LI->changeTopLevelLoop(NewInner, NewOuter);
1190   }
1191   while (!NewOuter->isInnermost())
1192     NewInner->addChildLoop(NewOuter->removeChildLoop(NewOuter->begin()));
1193   NewOuter->addChildLoop(NewInner);
1194 
1195   // BBs from the original inner loop.
1196   SmallVector<BasicBlock *, 8> OrigInnerBBs(NewOuter->blocks());
1197 
1198   // Add BBs from the original outer loop to the original inner loop (excluding
1199   // BBs already in inner loop)
1200   for (BasicBlock *BB : NewInner->blocks())
1201     if (LI->getLoopFor(BB) == NewInner)
1202       NewOuter->addBlockEntry(BB);
1203 
1204   // Now remove inner loop header and latch from the new inner loop and move
1205   // other BBs (the loop body) to the new inner loop.
1206   BasicBlock *OuterHeader = NewOuter->getHeader();
1207   BasicBlock *OuterLatch = NewOuter->getLoopLatch();
1208   for (BasicBlock *BB : OrigInnerBBs) {
1209     // Nothing will change for BBs in child loops.
1210     if (LI->getLoopFor(BB) != NewOuter)
1211       continue;
1212     // Remove the new outer loop header and latch from the new inner loop.
1213     if (BB == OuterHeader || BB == OuterLatch)
1214       NewInner->removeBlockFromLoop(BB);
1215     else
1216       LI->changeLoopFor(BB, NewInner);
1217   }
1218 
1219   // The preheader of the original outer loop becomes part of the new
1220   // outer loop.
1221   NewOuter->addBlockEntry(OrigOuterPreHeader);
1222   LI->changeLoopFor(OrigOuterPreHeader, NewOuter);
1223 
1224   // Tell SE that we move the loops around.
1225   SE->forgetLoop(NewOuter);
1226   SE->forgetLoop(NewInner);
1227 }
1228 
1229 bool LoopInterchangeTransform::transform() {
1230   bool Transformed = false;
1231   Instruction *InnerIndexVar;
1232 
1233   if (InnerLoop->getSubLoops().empty()) {
1234     BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
1235     LLVM_DEBUG(dbgs() << "Splitting the inner loop latch\n");
1236     PHINode *InductionPHI = getInductionVariable(InnerLoop, SE);
1237     if (!InductionPHI) {
1238       LLVM_DEBUG(dbgs() << "Failed to find the point to split loop latch \n");
1239       return false;
1240     }
1241 
1242     if (InductionPHI->getIncomingBlock(0) == InnerLoopPreHeader)
1243       InnerIndexVar = dyn_cast<Instruction>(InductionPHI->getIncomingValue(1));
1244     else
1245       InnerIndexVar = dyn_cast<Instruction>(InductionPHI->getIncomingValue(0));
1246 
1247     // Ensure that InductionPHI is the first Phi node.
1248     if (&InductionPHI->getParent()->front() != InductionPHI)
1249       InductionPHI->moveBefore(&InductionPHI->getParent()->front());
1250 
1251     // Create a new latch block for the inner loop. We split at the
1252     // current latch's terminator and then move the condition and all
1253     // operands that are not either loop-invariant or the induction PHI into the
1254     // new latch block.
1255     BasicBlock *NewLatch =
1256         SplitBlock(InnerLoop->getLoopLatch(),
1257                    InnerLoop->getLoopLatch()->getTerminator(), DT, LI);
1258 
1259     SmallSetVector<Instruction *, 4> WorkList;
1260     unsigned i = 0;
1261     auto MoveInstructions = [&i, &WorkList, this, InductionPHI, NewLatch]() {
1262       for (; i < WorkList.size(); i++) {
1263         // Duplicate instruction and move it the new latch. Update uses that
1264         // have been moved.
1265         Instruction *NewI = WorkList[i]->clone();
1266         NewI->insertBefore(NewLatch->getFirstNonPHI());
1267         assert(!NewI->mayHaveSideEffects() &&
1268                "Moving instructions with side-effects may change behavior of "
1269                "the loop nest!");
1270         for (auto UI = WorkList[i]->use_begin(), UE = WorkList[i]->use_end();
1271              UI != UE;) {
1272           Use &U = *UI++;
1273           Instruction *UserI = cast<Instruction>(U.getUser());
1274           if (!InnerLoop->contains(UserI->getParent()) ||
1275               UserI->getParent() == NewLatch || UserI == InductionPHI)
1276             U.set(NewI);
1277         }
1278         // Add operands of moved instruction to the worklist, except if they are
1279         // outside the inner loop or are the induction PHI.
1280         for (Value *Op : WorkList[i]->operands()) {
1281           Instruction *OpI = dyn_cast<Instruction>(Op);
1282           if (!OpI ||
1283               this->LI->getLoopFor(OpI->getParent()) != this->InnerLoop ||
1284               OpI == InductionPHI)
1285             continue;
1286           WorkList.insert(OpI);
1287         }
1288       }
1289     };
1290 
1291     // FIXME: Should we interchange when we have a constant condition?
1292     Instruction *CondI = dyn_cast<Instruction>(
1293         cast<BranchInst>(InnerLoop->getLoopLatch()->getTerminator())
1294             ->getCondition());
1295     if (CondI)
1296       WorkList.insert(CondI);
1297     MoveInstructions();
1298     WorkList.insert(cast<Instruction>(InnerIndexVar));
1299     MoveInstructions();
1300 
1301     // Splits the inner loops phi nodes out into a separate basic block.
1302     BasicBlock *InnerLoopHeader = InnerLoop->getHeader();
1303     SplitBlock(InnerLoopHeader, InnerLoopHeader->getFirstNonPHI(), DT, LI);
1304     LLVM_DEBUG(dbgs() << "splitting InnerLoopHeader done\n");
1305   }
1306 
1307   // Instructions in the original inner loop preheader may depend on values
1308   // defined in the outer loop header. Move them there, because the original
1309   // inner loop preheader will become the entry into the interchanged loop nest.
1310   // Currently we move all instructions and rely on LICM to move invariant
1311   // instructions outside the loop nest.
1312   BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
1313   BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
1314   if (InnerLoopPreHeader != OuterLoopHeader) {
1315     SmallPtrSet<Instruction *, 4> NeedsMoving;
1316     for (Instruction &I :
1317          make_early_inc_range(make_range(InnerLoopPreHeader->begin(),
1318                                          std::prev(InnerLoopPreHeader->end()))))
1319       I.moveBefore(OuterLoopHeader->getTerminator());
1320   }
1321 
1322   Transformed |= adjustLoopLinks();
1323   if (!Transformed) {
1324     LLVM_DEBUG(dbgs() << "adjustLoopLinks failed\n");
1325     return false;
1326   }
1327 
1328   return true;
1329 }
1330 
1331 /// \brief Move all instructions except the terminator from FromBB right before
1332 /// InsertBefore
1333 static void moveBBContents(BasicBlock *FromBB, Instruction *InsertBefore) {
1334   auto &ToList = InsertBefore->getParent()->getInstList();
1335   auto &FromList = FromBB->getInstList();
1336 
1337   ToList.splice(InsertBefore->getIterator(), FromList, FromList.begin(),
1338                 FromBB->getTerminator()->getIterator());
1339 }
1340 
1341 /// Swap instructions between \p BB1 and \p BB2 but keep terminators intact.
1342 static void swapBBContents(BasicBlock *BB1, BasicBlock *BB2) {
1343   // Save all non-terminator instructions of BB1 into TempInstrs and unlink them
1344   // from BB1 afterwards.
1345   auto Iter = map_range(*BB1, [](Instruction &I) { return &I; });
1346   SmallVector<Instruction *, 4> TempInstrs(Iter.begin(), std::prev(Iter.end()));
1347   for (Instruction *I : TempInstrs)
1348     I->removeFromParent();
1349 
1350   // Move instructions from BB2 to BB1.
1351   moveBBContents(BB2, BB1->getTerminator());
1352 
1353   // Move instructions from TempInstrs to BB2.
1354   for (Instruction *I : TempInstrs)
1355     I->insertBefore(BB2->getTerminator());
1356 }
1357 
1358 // Update BI to jump to NewBB instead of OldBB. Records updates to the
1359 // dominator tree in DTUpdates. If \p MustUpdateOnce is true, assert that
1360 // \p OldBB  is exactly once in BI's successor list.
1361 static void updateSuccessor(BranchInst *BI, BasicBlock *OldBB,
1362                             BasicBlock *NewBB,
1363                             std::vector<DominatorTree::UpdateType> &DTUpdates,
1364                             bool MustUpdateOnce = true) {
1365   assert((!MustUpdateOnce ||
1366           llvm::count_if(successors(BI),
1367                          [OldBB](BasicBlock *BB) {
1368                            return BB == OldBB;
1369                          }) == 1) && "BI must jump to OldBB exactly once.");
1370   bool Changed = false;
1371   for (Use &Op : BI->operands())
1372     if (Op == OldBB) {
1373       Op.set(NewBB);
1374       Changed = true;
1375     }
1376 
1377   if (Changed) {
1378     DTUpdates.push_back(
1379         {DominatorTree::UpdateKind::Insert, BI->getParent(), NewBB});
1380     DTUpdates.push_back(
1381         {DominatorTree::UpdateKind::Delete, BI->getParent(), OldBB});
1382   }
1383   assert(Changed && "Expected a successor to be updated");
1384 }
1385 
1386 // Move Lcssa PHIs to the right place.
1387 static void moveLCSSAPhis(BasicBlock *InnerExit, BasicBlock *InnerHeader,
1388                           BasicBlock *InnerLatch, BasicBlock *OuterHeader,
1389                           BasicBlock *OuterLatch, BasicBlock *OuterExit,
1390                           Loop *InnerLoop, LoopInfo *LI) {
1391 
1392   // Deal with LCSSA PHI nodes in the exit block of the inner loop, that are
1393   // defined either in the header or latch. Those blocks will become header and
1394   // latch of the new outer loop, and the only possible users can PHI nodes
1395   // in the exit block of the loop nest or the outer loop header (reduction
1396   // PHIs, in that case, the incoming value must be defined in the inner loop
1397   // header). We can just substitute the user with the incoming value and remove
1398   // the PHI.
1399   for (PHINode &P : make_early_inc_range(InnerExit->phis())) {
1400     assert(P.getNumIncomingValues() == 1 &&
1401            "Only loops with a single exit are supported!");
1402 
1403     // Incoming values are guaranteed be instructions currently.
1404     auto IncI = cast<Instruction>(P.getIncomingValueForBlock(InnerLatch));
1405     // Skip phis with incoming values from the inner loop body, excluding the
1406     // header and latch.
1407     if (IncI->getParent() != InnerLatch && IncI->getParent() != InnerHeader)
1408       continue;
1409 
1410     assert(all_of(P.users(),
1411                   [OuterHeader, OuterExit, IncI, InnerHeader](User *U) {
1412                     return (cast<PHINode>(U)->getParent() == OuterHeader &&
1413                             IncI->getParent() == InnerHeader) ||
1414                            cast<PHINode>(U)->getParent() == OuterExit;
1415                   }) &&
1416            "Can only replace phis iff the uses are in the loop nest exit or "
1417            "the incoming value is defined in the inner header (it will "
1418            "dominate all loop blocks after interchanging)");
1419     P.replaceAllUsesWith(IncI);
1420     P.eraseFromParent();
1421   }
1422 
1423   SmallVector<PHINode *, 8> LcssaInnerExit;
1424   for (PHINode &P : InnerExit->phis())
1425     LcssaInnerExit.push_back(&P);
1426 
1427   SmallVector<PHINode *, 8> LcssaInnerLatch;
1428   for (PHINode &P : InnerLatch->phis())
1429     LcssaInnerLatch.push_back(&P);
1430 
1431   // Lcssa PHIs for values used outside the inner loop are in InnerExit.
1432   // If a PHI node has users outside of InnerExit, it has a use outside the
1433   // interchanged loop and we have to preserve it. We move these to
1434   // InnerLatch, which will become the new exit block for the innermost
1435   // loop after interchanging.
1436   for (PHINode *P : LcssaInnerExit)
1437     P->moveBefore(InnerLatch->getFirstNonPHI());
1438 
1439   // If the inner loop latch contains LCSSA PHIs, those come from a child loop
1440   // and we have to move them to the new inner latch.
1441   for (PHINode *P : LcssaInnerLatch)
1442     P->moveBefore(InnerExit->getFirstNonPHI());
1443 
1444   // Deal with LCSSA PHI nodes in the loop nest exit block. For PHIs that have
1445   // incoming values defined in the outer loop, we have to add a new PHI
1446   // in the inner loop latch, which became the exit block of the outer loop,
1447   // after interchanging.
1448   if (OuterExit) {
1449     for (PHINode &P : OuterExit->phis()) {
1450       if (P.getNumIncomingValues() != 1)
1451         continue;
1452       // Skip Phis with incoming values defined in the inner loop. Those should
1453       // already have been updated.
1454       auto I = dyn_cast<Instruction>(P.getIncomingValue(0));
1455       if (!I || LI->getLoopFor(I->getParent()) == InnerLoop)
1456         continue;
1457 
1458       PHINode *NewPhi = dyn_cast<PHINode>(P.clone());
1459       NewPhi->setIncomingValue(0, P.getIncomingValue(0));
1460       NewPhi->setIncomingBlock(0, OuterLatch);
1461       NewPhi->insertBefore(InnerLatch->getFirstNonPHI());
1462       P.setIncomingValue(0, NewPhi);
1463     }
1464   }
1465 
1466   // Now adjust the incoming blocks for the LCSSA PHIs.
1467   // For PHIs moved from Inner's exit block, we need to replace Inner's latch
1468   // with the new latch.
1469   InnerLatch->replacePhiUsesWith(InnerLatch, OuterLatch);
1470 }
1471 
1472 bool LoopInterchangeTransform::adjustLoopBranches() {
1473   LLVM_DEBUG(dbgs() << "adjustLoopBranches called\n");
1474   std::vector<DominatorTree::UpdateType> DTUpdates;
1475 
1476   BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader();
1477   BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
1478 
1479   assert(OuterLoopPreHeader != OuterLoop->getHeader() &&
1480          InnerLoopPreHeader != InnerLoop->getHeader() && OuterLoopPreHeader &&
1481          InnerLoopPreHeader && "Guaranteed by loop-simplify form");
1482   // Ensure that both preheaders do not contain PHI nodes and have single
1483   // predecessors. This allows us to move them easily. We use
1484   // InsertPreHeaderForLoop to create an 'extra' preheader, if the existing
1485   // preheaders do not satisfy those conditions.
1486   if (isa<PHINode>(OuterLoopPreHeader->begin()) ||
1487       !OuterLoopPreHeader->getUniquePredecessor())
1488     OuterLoopPreHeader =
1489         InsertPreheaderForLoop(OuterLoop, DT, LI, nullptr, true);
1490   if (InnerLoopPreHeader == OuterLoop->getHeader())
1491     InnerLoopPreHeader =
1492         InsertPreheaderForLoop(InnerLoop, DT, LI, nullptr, true);
1493 
1494   // Adjust the loop preheader
1495   BasicBlock *InnerLoopHeader = InnerLoop->getHeader();
1496   BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
1497   BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
1498   BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch();
1499   BasicBlock *OuterLoopPredecessor = OuterLoopPreHeader->getUniquePredecessor();
1500   BasicBlock *InnerLoopLatchPredecessor =
1501       InnerLoopLatch->getUniquePredecessor();
1502   BasicBlock *InnerLoopLatchSuccessor;
1503   BasicBlock *OuterLoopLatchSuccessor;
1504 
1505   BranchInst *OuterLoopLatchBI =
1506       dyn_cast<BranchInst>(OuterLoopLatch->getTerminator());
1507   BranchInst *InnerLoopLatchBI =
1508       dyn_cast<BranchInst>(InnerLoopLatch->getTerminator());
1509   BranchInst *OuterLoopHeaderBI =
1510       dyn_cast<BranchInst>(OuterLoopHeader->getTerminator());
1511   BranchInst *InnerLoopHeaderBI =
1512       dyn_cast<BranchInst>(InnerLoopHeader->getTerminator());
1513 
1514   if (!OuterLoopPredecessor || !InnerLoopLatchPredecessor ||
1515       !OuterLoopLatchBI || !InnerLoopLatchBI || !OuterLoopHeaderBI ||
1516       !InnerLoopHeaderBI)
1517     return false;
1518 
1519   BranchInst *InnerLoopLatchPredecessorBI =
1520       dyn_cast<BranchInst>(InnerLoopLatchPredecessor->getTerminator());
1521   BranchInst *OuterLoopPredecessorBI =
1522       dyn_cast<BranchInst>(OuterLoopPredecessor->getTerminator());
1523 
1524   if (!OuterLoopPredecessorBI || !InnerLoopLatchPredecessorBI)
1525     return false;
1526   BasicBlock *InnerLoopHeaderSuccessor = InnerLoopHeader->getUniqueSuccessor();
1527   if (!InnerLoopHeaderSuccessor)
1528     return false;
1529 
1530   // Adjust Loop Preheader and headers.
1531   // The branches in the outer loop predecessor and the outer loop header can
1532   // be unconditional branches or conditional branches with duplicates. Consider
1533   // this when updating the successors.
1534   updateSuccessor(OuterLoopPredecessorBI, OuterLoopPreHeader,
1535                   InnerLoopPreHeader, DTUpdates, /*MustUpdateOnce=*/false);
1536   // The outer loop header might or might not branch to the outer latch.
1537   // We are guaranteed to branch to the inner loop preheader.
1538   if (llvm::is_contained(OuterLoopHeaderBI->successors(), OuterLoopLatch))
1539     updateSuccessor(OuterLoopHeaderBI, OuterLoopLatch, LoopExit, DTUpdates,
1540                     /*MustUpdateOnce=*/false);
1541   updateSuccessor(OuterLoopHeaderBI, InnerLoopPreHeader,
1542                   InnerLoopHeaderSuccessor, DTUpdates,
1543                   /*MustUpdateOnce=*/false);
1544 
1545   // Adjust reduction PHI's now that the incoming block has changed.
1546   InnerLoopHeaderSuccessor->replacePhiUsesWith(InnerLoopHeader,
1547                                                OuterLoopHeader);
1548 
1549   updateSuccessor(InnerLoopHeaderBI, InnerLoopHeaderSuccessor,
1550                   OuterLoopPreHeader, DTUpdates);
1551 
1552   // -------------Adjust loop latches-----------
1553   if (InnerLoopLatchBI->getSuccessor(0) == InnerLoopHeader)
1554     InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(1);
1555   else
1556     InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(0);
1557 
1558   updateSuccessor(InnerLoopLatchPredecessorBI, InnerLoopLatch,
1559                   InnerLoopLatchSuccessor, DTUpdates);
1560 
1561 
1562   if (OuterLoopLatchBI->getSuccessor(0) == OuterLoopHeader)
1563     OuterLoopLatchSuccessor = OuterLoopLatchBI->getSuccessor(1);
1564   else
1565     OuterLoopLatchSuccessor = OuterLoopLatchBI->getSuccessor(0);
1566 
1567   updateSuccessor(InnerLoopLatchBI, InnerLoopLatchSuccessor,
1568                   OuterLoopLatchSuccessor, DTUpdates);
1569   updateSuccessor(OuterLoopLatchBI, OuterLoopLatchSuccessor, InnerLoopLatch,
1570                   DTUpdates);
1571 
1572   DT->applyUpdates(DTUpdates);
1573   restructureLoops(OuterLoop, InnerLoop, InnerLoopPreHeader,
1574                    OuterLoopPreHeader);
1575 
1576   moveLCSSAPhis(InnerLoopLatchSuccessor, InnerLoopHeader, InnerLoopLatch,
1577                 OuterLoopHeader, OuterLoopLatch, InnerLoop->getExitBlock(),
1578                 InnerLoop, LI);
1579   // For PHIs in the exit block of the outer loop, outer's latch has been
1580   // replaced by Inners'.
1581   OuterLoopLatchSuccessor->replacePhiUsesWith(OuterLoopLatch, InnerLoopLatch);
1582 
1583   // Now update the reduction PHIs in the inner and outer loop headers.
1584   SmallVector<PHINode *, 4> InnerLoopPHIs, OuterLoopPHIs;
1585   for (PHINode &PHI : drop_begin(InnerLoopHeader->phis()))
1586     InnerLoopPHIs.push_back(cast<PHINode>(&PHI));
1587   for (PHINode &PHI : drop_begin(OuterLoopHeader->phis()))
1588     OuterLoopPHIs.push_back(cast<PHINode>(&PHI));
1589 
1590   auto &OuterInnerReductions = LIL.getOuterInnerReductions();
1591   (void)OuterInnerReductions;
1592 
1593   // Now move the remaining reduction PHIs from outer to inner loop header and
1594   // vice versa. The PHI nodes must be part of a reduction across the inner and
1595   // outer loop and all the remains to do is and updating the incoming blocks.
1596   for (PHINode *PHI : OuterLoopPHIs) {
1597     PHI->moveBefore(InnerLoopHeader->getFirstNonPHI());
1598     assert(OuterInnerReductions.count(PHI) && "Expected a reduction PHI node");
1599   }
1600   for (PHINode *PHI : InnerLoopPHIs) {
1601     PHI->moveBefore(OuterLoopHeader->getFirstNonPHI());
1602     assert(OuterInnerReductions.count(PHI) && "Expected a reduction PHI node");
1603   }
1604 
1605   // Update the incoming blocks for moved PHI nodes.
1606   OuterLoopHeader->replacePhiUsesWith(InnerLoopPreHeader, OuterLoopPreHeader);
1607   OuterLoopHeader->replacePhiUsesWith(InnerLoopLatch, OuterLoopLatch);
1608   InnerLoopHeader->replacePhiUsesWith(OuterLoopPreHeader, InnerLoopPreHeader);
1609   InnerLoopHeader->replacePhiUsesWith(OuterLoopLatch, InnerLoopLatch);
1610 
1611   // Values defined in the outer loop header could be used in the inner loop
1612   // latch. In that case, we need to create LCSSA phis for them, because after
1613   // interchanging they will be defined in the new inner loop and used in the
1614   // new outer loop.
1615   IRBuilder<> Builder(OuterLoopHeader->getContext());
1616   SmallVector<Instruction *, 4> MayNeedLCSSAPhis;
1617   for (Instruction &I :
1618        make_range(OuterLoopHeader->begin(), std::prev(OuterLoopHeader->end())))
1619     MayNeedLCSSAPhis.push_back(&I);
1620   formLCSSAForInstructions(MayNeedLCSSAPhis, *DT, *LI, SE, Builder);
1621 
1622   return true;
1623 }
1624 
1625 bool LoopInterchangeTransform::adjustLoopLinks() {
1626   // Adjust all branches in the inner and outer loop.
1627   bool Changed = adjustLoopBranches();
1628   if (Changed) {
1629     // We have interchanged the preheaders so we need to interchange the data in
1630     // the preheaders as well. This is because the content of the inner
1631     // preheader was previously executed inside the outer loop.
1632     BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader();
1633     BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
1634     swapBBContents(OuterLoopPreHeader, InnerLoopPreHeader);
1635   }
1636   return Changed;
1637 }
1638 
1639 /// Main LoopInterchange Pass.
1640 struct LoopInterchangeLegacyPass : public LoopPass {
1641   static char ID;
1642 
1643   LoopInterchangeLegacyPass() : LoopPass(ID) {
1644     initializeLoopInterchangeLegacyPassPass(*PassRegistry::getPassRegistry());
1645   }
1646 
1647   void getAnalysisUsage(AnalysisUsage &AU) const override {
1648     AU.addRequired<DependenceAnalysisWrapperPass>();
1649     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
1650 
1651     getLoopAnalysisUsage(AU);
1652   }
1653 
1654   bool runOnLoop(Loop *L, LPPassManager &LPM) override {
1655     if (skipLoop(L))
1656       return false;
1657 
1658     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1659     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1660     auto *DI = &getAnalysis<DependenceAnalysisWrapperPass>().getDI();
1661     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1662     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
1663 
1664     return LoopInterchange(SE, LI, DI, DT, ORE).run(L);
1665   }
1666 };
1667 
1668 char LoopInterchangeLegacyPass::ID = 0;
1669 
1670 INITIALIZE_PASS_BEGIN(LoopInterchangeLegacyPass, "loop-interchange",
1671                       "Interchanges loops for cache reuse", false, false)
1672 INITIALIZE_PASS_DEPENDENCY(LoopPass)
1673 INITIALIZE_PASS_DEPENDENCY(DependenceAnalysisWrapperPass)
1674 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
1675 
1676 INITIALIZE_PASS_END(LoopInterchangeLegacyPass, "loop-interchange",
1677                     "Interchanges loops for cache reuse", false, false)
1678 
1679 Pass *llvm::createLoopInterchangePass() {
1680   return new LoopInterchangeLegacyPass();
1681 }
1682 
1683 PreservedAnalyses LoopInterchangePass::run(Loop &L, LoopAnalysisManager &AM,
1684                                            LoopStandardAnalysisResults &AR,
1685                                            LPMUpdater &U) {
1686   Function &F = *L.getHeader()->getParent();
1687 
1688   DependenceInfo DI(&F, &AR.AA, &AR.SE, &AR.LI);
1689   OptimizationRemarkEmitter ORE(&F);
1690   if (!LoopInterchange(&AR.SE, &AR.LI, &DI, &AR.DT, &ORE).run(&L))
1691     return PreservedAnalyses::all();
1692   return getLoopPassPreservedAnalyses();
1693 }
1694