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