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