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