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