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