blob: b4a1dddca61effda748036be426885555646e84b [file] [log] [blame]
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +00001//===- LoopInterchange.cpp - Loop interchange pass-------------------------===//
Karthik Bhat88db86d2015-03-06 10:11:25 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Karthik Bhat88db86d2015-03-06 10:11:25 +00006//
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
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000015#include "llvm/ADT/STLExtras.h"
Karthik Bhat88db86d2015-03-06 10:11:25 +000016#include "llvm/ADT/SmallVector.h"
Florian Hahn6e004332018-04-05 10:39:23 +000017#include "llvm/ADT/Statistic.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000018#include "llvm/ADT/StringRef.h"
Karthik Bhat88db86d2015-03-06 10:11:25 +000019#include "llvm/Analysis/DependenceAnalysis.h"
20#include "llvm/Analysis/LoopInfo.h"
Florian Hahn8600fee2018-10-01 09:59:48 +000021#include "llvm/Analysis/LoopPass.h"
Adam Nemet0965da22017-10-09 23:19:02 +000022#include "llvm/Analysis/OptimizationRemarkEmitter.h"
Karthik Bhat88db86d2015-03-06 10:11:25 +000023#include "llvm/Analysis/ScalarEvolution.h"
Karthik Bhat88db86d2015-03-06 10:11:25 +000024#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000025#include "llvm/IR/BasicBlock.h"
26#include "llvm/IR/Constants.h"
27#include "llvm/IR/DiagnosticInfo.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000028#include "llvm/IR/Dominators.h"
Karthik Bhat88db86d2015-03-06 10:11:25 +000029#include "llvm/IR/Function.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000030#include "llvm/IR/InstrTypes.h"
31#include "llvm/IR/Instruction.h"
32#include "llvm/IR/Instructions.h"
33#include "llvm/IR/Type.h"
34#include "llvm/IR/User.h"
35#include "llvm/IR/Value.h"
Karthik Bhat88db86d2015-03-06 10:11:25 +000036#include "llvm/Pass.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000037#include "llvm/Support/Casting.h"
38#include "llvm/Support/CommandLine.h"
Karthik Bhat88db86d2015-03-06 10:11:25 +000039#include "llvm/Support/Debug.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000040#include "llvm/Support/ErrorHandling.h"
Karthik Bhat88db86d2015-03-06 10:11:25 +000041#include "llvm/Support/raw_ostream.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000042#include "llvm/Transforms/Scalar.h"
David Blaikiea373d182018-03-28 17:44:36 +000043#include "llvm/Transforms/Utils.h"
Karthik Bhat88db86d2015-03-06 10:11:25 +000044#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000045#include "llvm/Transforms/Utils/LoopUtils.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000046#include <cassert>
47#include <utility>
48#include <vector>
Davide Italiano9d8f6f82017-01-29 01:55:24 +000049
Karthik Bhat88db86d2015-03-06 10:11:25 +000050using namespace llvm;
51
52#define DEBUG_TYPE "loop-interchange"
53
Florian Hahn6e004332018-04-05 10:39:23 +000054STATISTIC(LoopsInterchanged, "Number of loops interchanged");
55
Chad Rosier72431892016-09-14 17:07:13 +000056static 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
Karthik Bhat88db86d2015-03-06 10:11:25 +000060namespace {
61
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000062using LoopVector = SmallVector<Loop *, 8>;
Karthik Bhat88db86d2015-03-06 10:11:25 +000063
64// TODO: Check if we can use a sparse matrix here.
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000065using CharMatrix = std::vector<std::vector<char>>;
66
67} // end anonymous namespace
Karthik Bhat88db86d2015-03-06 10:11:25 +000068
69// Maximum number of dependencies that can be handled in the dependency matrix.
70static const unsigned MaxMemInstrCount = 100;
71
72// Maximum loop depth supported.
73static const unsigned MaxLoopNestDepth = 10;
74
Karthik Bhat88db86d2015-03-06 10:11:25 +000075#ifdef DUMP_DEP_MATRICIES
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000076static void printDepMatrix(CharMatrix &DepMatrix) {
Florian Hahnf66efd62017-07-24 11:41:30 +000077 for (auto &Row : DepMatrix) {
78 for (auto D : Row)
Nicola Zaghend34e60c2018-05-14 12:53:11 +000079 LLVM_DEBUG(dbgs() << D << " ");
80 LLVM_DEBUG(dbgs() << "\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +000081 }
82}
83#endif
84
Karthik Bhat8210fdf2015-04-23 04:51:44 +000085static bool populateDependencyMatrix(CharMatrix &DepMatrix, unsigned Level,
Chandler Carruth49c22192016-05-12 22:19:39 +000086 Loop *L, DependenceInfo *DI) {
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000087 using ValueVector = SmallVector<Value *, 16>;
88
Karthik Bhat88db86d2015-03-06 10:11:25 +000089 ValueVector MemInstr;
90
Karthik Bhat88db86d2015-03-06 10:11:25 +000091 // For each block.
Florian Hahnf66efd62017-07-24 11:41:30 +000092 for (BasicBlock *BB : L->blocks()) {
Karthik Bhat88db86d2015-03-06 10:11:25 +000093 // Scan the BB and collect legal loads and stores.
Florian Hahnf66efd62017-07-24 11:41:30 +000094 for (Instruction &I : *BB) {
Chad Rosier09c11092016-09-13 12:56:04 +000095 if (!isa<Instruction>(I))
Karthik Bhat88db86d2015-03-06 10:11:25 +000096 return false;
Florian Hahnf66efd62017-07-24 11:41:30 +000097 if (auto *Ld = dyn_cast<LoadInst>(&I)) {
Chad Rosier09c11092016-09-13 12:56:04 +000098 if (!Ld->isSimple())
99 return false;
Florian Hahnf66efd62017-07-24 11:41:30 +0000100 MemInstr.push_back(&I);
101 } else if (auto *St = dyn_cast<StoreInst>(&I)) {
Chad Rosier09c11092016-09-13 12:56:04 +0000102 if (!St->isSimple())
103 return false;
Florian Hahnf66efd62017-07-24 11:41:30 +0000104 MemInstr.push_back(&I);
Chad Rosier09c11092016-09-13 12:56:04 +0000105 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000106 }
107 }
108
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000109 LLVM_DEBUG(dbgs() << "Found " << MemInstr.size()
110 << " Loads and Stores to analyze\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000111
112 ValueVector::iterator I, IE, J, JE;
113
114 for (I = MemInstr.begin(), IE = MemInstr.end(); I != IE; ++I) {
115 for (J = I, JE = MemInstr.end(); J != JE; ++J) {
116 std::vector<char> Dep;
Chad Rosier09c11092016-09-13 12:56:04 +0000117 Instruction *Src = cast<Instruction>(*I);
118 Instruction *Dst = cast<Instruction>(*J);
Chad Rosier90bcb912016-09-07 16:07:17 +0000119 if (Src == Dst)
Karthik Bhat88db86d2015-03-06 10:11:25 +0000120 continue;
Chad Rosier00eb8db2016-09-21 19:16:47 +0000121 // Ignore Input dependencies.
Chad Rosier90bcb912016-09-07 16:07:17 +0000122 if (isa<LoadInst>(Src) && isa<LoadInst>(Dst))
Karthik Bhat88db86d2015-03-06 10:11:25 +0000123 continue;
Chad Rosier00eb8db2016-09-21 19:16:47 +0000124 // Track Output, Flow, and Anti dependencies.
Chad Rosier90bcb912016-09-07 16:07:17 +0000125 if (auto D = DI->depends(Src, Dst, true)) {
Chad Rosier00eb8db2016-09-21 19:16:47 +0000126 assert(D->isOrdered() && "Expected an output, flow or anti dep.");
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000127 LLVM_DEBUG(StringRef DepType =
128 D->isFlow() ? "flow" : D->isAnti() ? "anti" : "output";
129 dbgs() << "Found " << DepType
130 << " dependency between Src and Dst\n"
131 << " Src:" << *Src << "\n Dst:" << *Dst << '\n');
Chad Rosier00eb8db2016-09-21 19:16:47 +0000132 unsigned Levels = D->getLevels();
133 char Direction;
134 for (unsigned II = 1; II <= Levels; ++II) {
135 const SCEV *Distance = D->getDistance(II);
136 const SCEVConstant *SCEVConst =
137 dyn_cast_or_null<SCEVConstant>(Distance);
138 if (SCEVConst) {
139 const ConstantInt *CI = SCEVConst->getValue();
140 if (CI->isNegative())
141 Direction = '<';
142 else if (CI->isZero())
143 Direction = '=';
144 else
145 Direction = '>';
146 Dep.push_back(Direction);
147 } else if (D->isScalar(II)) {
148 Direction = 'S';
149 Dep.push_back(Direction);
150 } else {
151 unsigned Dir = D->getDirection(II);
152 if (Dir == Dependence::DVEntry::LT ||
153 Dir == Dependence::DVEntry::LE)
154 Direction = '<';
155 else if (Dir == Dependence::DVEntry::GT ||
156 Dir == Dependence::DVEntry::GE)
157 Direction = '>';
158 else if (Dir == Dependence::DVEntry::EQ)
159 Direction = '=';
160 else
161 Direction = '*';
162 Dep.push_back(Direction);
163 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000164 }
Chad Rosier00eb8db2016-09-21 19:16:47 +0000165 while (Dep.size() != Level) {
166 Dep.push_back('I');
167 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000168
Chad Rosier00eb8db2016-09-21 19:16:47 +0000169 DepMatrix.push_back(Dep);
170 if (DepMatrix.size() > MaxMemInstrCount) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000171 LLVM_DEBUG(dbgs() << "Cannot handle more than " << MaxMemInstrCount
172 << " dependencies inside loop\n");
Chad Rosier00eb8db2016-09-21 19:16:47 +0000173 return false;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000174 }
175 }
176 }
177 }
178
Karthik Bhat88db86d2015-03-06 10:11:25 +0000179 return true;
180}
181
182// A loop is moved from index 'from' to an index 'to'. Update the Dependence
183// matrix by exchanging the two columns.
Chad Rosierd18ea062016-09-13 13:00:29 +0000184static void interChangeDependencies(CharMatrix &DepMatrix, unsigned FromIndx,
185 unsigned ToIndx) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000186 unsigned numRows = DepMatrix.size();
187 for (unsigned i = 0; i < numRows; ++i) {
188 char TmpVal = DepMatrix[i][ToIndx];
189 DepMatrix[i][ToIndx] = DepMatrix[i][FromIndx];
190 DepMatrix[i][FromIndx] = TmpVal;
191 }
192}
193
194// Checks if outermost non '=','S'or'I' dependence in the dependence matrix is
195// '>'
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000196static bool isOuterMostDepPositive(CharMatrix &DepMatrix, unsigned Row,
197 unsigned Column) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000198 for (unsigned i = 0; i <= Column; ++i) {
199 if (DepMatrix[Row][i] == '<')
200 return false;
201 if (DepMatrix[Row][i] == '>')
202 return true;
203 }
204 // All dependencies were '=','S' or 'I'
205 return false;
206}
207
208// Checks if no dependence exist in the dependency matrix in Row before Column.
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000209static bool containsNoDependence(CharMatrix &DepMatrix, unsigned Row,
210 unsigned Column) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000211 for (unsigned i = 0; i < Column; ++i) {
Chandler Carruthfca1ff02016-11-03 16:39:25 +0000212 if (DepMatrix[Row][i] != '=' && DepMatrix[Row][i] != 'S' &&
Karthik Bhat88db86d2015-03-06 10:11:25 +0000213 DepMatrix[Row][i] != 'I')
214 return false;
215 }
216 return true;
217}
218
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000219static bool validDepInterchange(CharMatrix &DepMatrix, unsigned Row,
220 unsigned OuterLoopId, char InnerDep,
221 char OuterDep) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000222 if (isOuterMostDepPositive(DepMatrix, Row, OuterLoopId))
223 return false;
224
225 if (InnerDep == OuterDep)
226 return true;
227
228 // It is legal to interchange if and only if after interchange no row has a
229 // '>' direction as the leftmost non-'='.
230
231 if (InnerDep == '=' || InnerDep == 'S' || InnerDep == 'I')
232 return true;
233
234 if (InnerDep == '<')
235 return true;
236
237 if (InnerDep == '>') {
238 // If OuterLoopId represents outermost loop then interchanging will make the
239 // 1st dependency as '>'
240 if (OuterLoopId == 0)
241 return false;
242
243 // If all dependencies before OuterloopId are '=','S'or 'I'. Then
244 // interchanging will result in this row having an outermost non '='
245 // dependency of '>'
246 if (!containsNoDependence(DepMatrix, Row, OuterLoopId))
247 return true;
248 }
249
250 return false;
251}
252
253// Checks if it is legal to interchange 2 loops.
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000254// [Theorem] A permutation of the loops in a perfect nest is legal if and only
Chad Rosier61683a22016-09-13 13:08:53 +0000255// if the direction matrix, after the same permutation is applied to its
256// columns, has no ">" direction as the leftmost non-"=" direction in any row.
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000257static bool isLegalToInterChangeLoops(CharMatrix &DepMatrix,
258 unsigned InnerLoopId,
259 unsigned OuterLoopId) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000260 unsigned NumRows = DepMatrix.size();
261 // For each row check if it is valid to interchange.
262 for (unsigned Row = 0; Row < NumRows; ++Row) {
263 char InnerDep = DepMatrix[Row][InnerLoopId];
264 char OuterDep = DepMatrix[Row][OuterLoopId];
265 if (InnerDep == '*' || OuterDep == '*')
266 return false;
Chad Rosier61683a22016-09-13 13:08:53 +0000267 if (!validDepInterchange(DepMatrix, Row, OuterLoopId, InnerDep, OuterDep))
Karthik Bhat88db86d2015-03-06 10:11:25 +0000268 return false;
269 }
270 return true;
271}
272
Florian Hahn8600fee2018-10-01 09:59:48 +0000273static LoopVector populateWorklist(Loop &L) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000274 LLVM_DEBUG(dbgs() << "Calling populateWorklist on Func: "
275 << L.getHeader()->getParent()->getName() << " Loop: %"
276 << L.getHeader()->getName() << '\n');
Karthik Bhat88db86d2015-03-06 10:11:25 +0000277 LoopVector LoopList;
278 Loop *CurrentLoop = &L;
Benjamin Kramere448b5b2015-07-13 17:21:14 +0000279 const std::vector<Loop *> *Vec = &CurrentLoop->getSubLoops();
280 while (!Vec->empty()) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000281 // The current loop has multiple subloops in it hence it is not tightly
282 // nested.
283 // Discard all loops above it added into Worklist.
Florian Hahn8600fee2018-10-01 09:59:48 +0000284 if (Vec->size() != 1)
285 return {};
286
Karthik Bhat88db86d2015-03-06 10:11:25 +0000287 LoopList.push_back(CurrentLoop);
Benjamin Kramere448b5b2015-07-13 17:21:14 +0000288 CurrentLoop = Vec->front();
289 Vec = &CurrentLoop->getSubLoops();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000290 }
291 LoopList.push_back(CurrentLoop);
Florian Hahn8600fee2018-10-01 09:59:48 +0000292 return LoopList;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000293}
294
Kit Barton987fdfd2019-05-23 20:53:05 +0000295static PHINode *getInductionVariable(Loop *L, ScalarEvolution *SE) {
296 PHINode *InnerIndexVar = L->getCanonicalInductionVariable();
297 if (InnerIndexVar)
298 return InnerIndexVar;
299 if (L->getLoopLatch() == nullptr || L->getLoopPredecessor() == nullptr)
300 return nullptr;
301 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
302 PHINode *PhiVar = cast<PHINode>(I);
303 Type *PhiTy = PhiVar->getType();
304 if (!PhiTy->isIntegerTy() && !PhiTy->isFloatingPointTy() &&
305 !PhiTy->isPointerTy())
306 return nullptr;
307 const SCEVAddRecExpr *AddRec =
308 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(PhiVar));
309 if (!AddRec || !AddRec->isAffine())
310 continue;
311 const SCEV *Step = AddRec->getStepRecurrence(*SE);
312 if (!isa<SCEVConstant>(Step))
313 continue;
314 // Found the induction variable.
315 // FIXME: Handle loops with more than one induction variable. Note that,
316 // currently, legality makes sure we have only one induction variable.
317 return PhiVar;
318 }
319 return nullptr;
320}
321
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000322namespace {
323
Karthik Bhat88db86d2015-03-06 10:11:25 +0000324/// LoopInterchangeLegality checks if it is legal to interchange the loop.
325class LoopInterchangeLegality {
326public:
327 LoopInterchangeLegality(Loop *Outer, Loop *Inner, ScalarEvolution *SE,
Florian Hahnad993522017-07-15 13:13:19 +0000328 OptimizationRemarkEmitter *ORE)
Florian Hahnc51d0882018-09-06 10:41:01 +0000329 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), ORE(ORE) {}
Karthik Bhat88db86d2015-03-06 10:11:25 +0000330
331 /// Check if the loops can be interchanged.
332 bool canInterchangeLoops(unsigned InnerLoopId, unsigned OuterLoopId,
333 CharMatrix &DepMatrix);
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000334
Karthik Bhat88db86d2015-03-06 10:11:25 +0000335 /// Check if the loop structure is understood. We do not handle triangular
336 /// loops for now.
337 bool isLoopStructureUnderstood(PHINode *InnerInductionVar);
338
339 bool currentLimitations();
340
Florian Hahna684a992018-11-08 20:44:19 +0000341 const SmallPtrSetImpl<PHINode *> &getOuterInnerReductions() const {
342 return OuterInnerReductions;
343 }
344
Karthik Bhat88db86d2015-03-06 10:11:25 +0000345private:
346 bool tightlyNested(Loop *Outer, Loop *Inner);
Florian Hahnc8bd6ea2018-11-01 19:25:00 +0000347 bool containsUnsafeInstructions(BasicBlock *BB);
Florian Hahna684a992018-11-08 20:44:19 +0000348
349 /// Discover induction and reduction PHIs in the header of \p L. Induction
350 /// PHIs are added to \p Inductions, reductions are added to
351 /// OuterInnerReductions. When the outer loop is passed, the inner loop needs
352 /// to be passed as \p InnerLoop.
353 bool findInductionAndReductions(Loop *L,
354 SmallVector<PHINode *, 8> &Inductions,
355 Loop *InnerLoop);
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000356
Karthik Bhat88db86d2015-03-06 10:11:25 +0000357 Loop *OuterLoop;
358 Loop *InnerLoop;
359
Karthik Bhat88db86d2015-03-06 10:11:25 +0000360 ScalarEvolution *SE;
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000361
Florian Hahnad993522017-07-15 13:13:19 +0000362 /// Interface to emit optimization remarks.
363 OptimizationRemarkEmitter *ORE;
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000364
Florian Hahna684a992018-11-08 20:44:19 +0000365 /// Set of reduction PHIs taking part of a reduction across the inner and
366 /// outer loop.
367 SmallPtrSet<PHINode *, 4> OuterInnerReductions;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000368};
369
370/// LoopInterchangeProfitability checks if it is profitable to interchange the
371/// loop.
372class LoopInterchangeProfitability {
373public:
Florian Hahnad993522017-07-15 13:13:19 +0000374 LoopInterchangeProfitability(Loop *Outer, Loop *Inner, ScalarEvolution *SE,
375 OptimizationRemarkEmitter *ORE)
376 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), ORE(ORE) {}
Karthik Bhat88db86d2015-03-06 10:11:25 +0000377
Vikram TV74b41112015-12-09 05:16:24 +0000378 /// Check if the loop interchange is profitable.
Karthik Bhat88db86d2015-03-06 10:11:25 +0000379 bool isProfitable(unsigned InnerLoopId, unsigned OuterLoopId,
380 CharMatrix &DepMatrix);
381
382private:
383 int getInstrOrderCost();
384
385 Loop *OuterLoop;
386 Loop *InnerLoop;
387
388 /// Scev analysis.
389 ScalarEvolution *SE;
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000390
Florian Hahnad993522017-07-15 13:13:19 +0000391 /// Interface to emit optimization remarks.
392 OptimizationRemarkEmitter *ORE;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000393};
394
Vikram TV74b41112015-12-09 05:16:24 +0000395/// LoopInterchangeTransform interchanges the loop.
Karthik Bhat88db86d2015-03-06 10:11:25 +0000396class LoopInterchangeTransform {
397public:
398 LoopInterchangeTransform(Loop *Outer, Loop *Inner, ScalarEvolution *SE,
399 LoopInfo *LI, DominatorTree *DT,
Florian Hahna684a992018-11-08 20:44:19 +0000400 BasicBlock *LoopNestExit,
401 const LoopInterchangeLegality &LIL)
Karthik Bhat88db86d2015-03-06 10:11:25 +0000402 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), LI(LI), DT(DT),
Florian Hahna684a992018-11-08 20:44:19 +0000403 LoopExit(LoopNestExit), LIL(LIL) {}
Karthik Bhat88db86d2015-03-06 10:11:25 +0000404
405 /// Interchange OuterLoop and InnerLoop.
406 bool transform();
Florian Hahn831a7572018-04-05 09:48:45 +0000407 void restructureLoops(Loop *NewInner, Loop *NewOuter,
408 BasicBlock *OrigInnerPreHeader,
409 BasicBlock *OrigOuterPreHeader);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000410 void removeChildLoop(Loop *OuterLoop, Loop *InnerLoop);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000411
412private:
Karthik Bhat88db86d2015-03-06 10:11:25 +0000413 void splitInnerLoopHeader();
414 bool adjustLoopLinks();
415 void adjustLoopPreheaders();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000416 bool adjustLoopBranches();
417
418 Loop *OuterLoop;
419 Loop *InnerLoop;
420
421 /// Scev analysis.
422 ScalarEvolution *SE;
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000423
Karthik Bhat88db86d2015-03-06 10:11:25 +0000424 LoopInfo *LI;
425 DominatorTree *DT;
426 BasicBlock *LoopExit;
Florian Hahna684a992018-11-08 20:44:19 +0000427
428 const LoopInterchangeLegality &LIL;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000429};
430
Vikram TV74b41112015-12-09 05:16:24 +0000431// Main LoopInterchange Pass.
Florian Hahn8600fee2018-10-01 09:59:48 +0000432struct LoopInterchange : public LoopPass {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000433 static char ID;
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000434 ScalarEvolution *SE = nullptr;
435 LoopInfo *LI = nullptr;
436 DependenceInfo *DI = nullptr;
437 DominatorTree *DT = nullptr;
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000438
Florian Hahnad993522017-07-15 13:13:19 +0000439 /// Interface to emit optimization remarks.
440 OptimizationRemarkEmitter *ORE;
441
Florian Hahn8600fee2018-10-01 09:59:48 +0000442 LoopInterchange() : LoopPass(ID) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000443 initializeLoopInterchangePass(*PassRegistry::getPassRegistry());
444 }
445
446 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth49c22192016-05-12 22:19:39 +0000447 AU.addRequired<DependenceAnalysisWrapperPass>();
Florian Hahnad993522017-07-15 13:13:19 +0000448 AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
Florian Hahnc6296fe2018-02-14 13:13:15 +0000449
Florian Hahn8600fee2018-10-01 09:59:48 +0000450 getLoopAnalysisUsage(AU);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000451 }
452
Florian Hahn8600fee2018-10-01 09:59:48 +0000453 bool runOnLoop(Loop *L, LPPassManager &LPM) override {
454 if (skipLoop(L) || L->getParentLoop())
Florian Hahn8d72ecc2018-09-28 10:20:07 +0000455 return false;
Andrew Kaylor50271f72016-05-03 22:32:30 +0000456
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000457 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000458 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Chandler Carruth49c22192016-05-12 22:19:39 +0000459 DI = &getAnalysis<DependenceAnalysisWrapperPass>().getDI();
Florian Hahnc6296fe2018-02-14 13:13:15 +0000460 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Florian Hahnad993522017-07-15 13:13:19 +0000461 ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
Justin Bogner843fb202015-12-15 19:40:57 +0000462
Florian Hahn8600fee2018-10-01 09:59:48 +0000463 return processLoopList(populateWorklist(*L));
Karthik Bhat88db86d2015-03-06 10:11:25 +0000464 }
465
466 bool isComputableLoopNest(LoopVector LoopList) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000467 for (Loop *L : LoopList) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000468 const SCEV *ExitCountOuter = SE->getBackedgeTakenCount(L);
469 if (ExitCountOuter == SE->getCouldNotCompute()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000470 LLVM_DEBUG(dbgs() << "Couldn't compute backedge count\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000471 return false;
472 }
473 if (L->getNumBackEdges() != 1) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000474 LLVM_DEBUG(dbgs() << "NumBackEdges is not equal to 1\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000475 return false;
476 }
477 if (!L->getExitingBlock()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000478 LLVM_DEBUG(dbgs() << "Loop doesn't have unique exit block\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000479 return false;
480 }
481 }
482 return true;
483 }
484
Benjamin Kramerc321e532016-06-08 19:09:22 +0000485 unsigned selectLoopForInterchange(const LoopVector &LoopList) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000486 // TODO: Add a better heuristic to select the loop to be interchanged based
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000487 // on the dependence matrix. Currently we select the innermost loop.
Karthik Bhat88db86d2015-03-06 10:11:25 +0000488 return LoopList.size() - 1;
489 }
490
Florian Hahn8600fee2018-10-01 09:59:48 +0000491 bool processLoopList(LoopVector LoopList) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000492 bool Changed = false;
Chad Rosier7ea0d392016-09-13 13:30:30 +0000493 unsigned LoopNestDepth = LoopList.size();
494 if (LoopNestDepth < 2) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000495 LLVM_DEBUG(dbgs() << "Loop doesn't contain minimum nesting level.\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000496 return false;
497 }
Chad Rosier7ea0d392016-09-13 13:30:30 +0000498 if (LoopNestDepth > MaxLoopNestDepth) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000499 LLVM_DEBUG(dbgs() << "Cannot handle loops of depth greater than "
500 << MaxLoopNestDepth << "\n");
Chad Rosier7ea0d392016-09-13 13:30:30 +0000501 return false;
502 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000503 if (!isComputableLoopNest(LoopList)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000504 LLVM_DEBUG(dbgs() << "Not valid loop candidate for interchange\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000505 return false;
506 }
Chad Rosier7ea0d392016-09-13 13:30:30 +0000507
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000508 LLVM_DEBUG(dbgs() << "Processing LoopList of size = " << LoopNestDepth
509 << "\n");
Chad Rosier7ea0d392016-09-13 13:30:30 +0000510
511 CharMatrix DependencyMatrix;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000512 Loop *OuterMostLoop = *(LoopList.begin());
Chad Rosier7ea0d392016-09-13 13:30:30 +0000513 if (!populateDependencyMatrix(DependencyMatrix, LoopNestDepth,
Chandler Carruth49c22192016-05-12 22:19:39 +0000514 OuterMostLoop, DI)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000515 LLVM_DEBUG(dbgs() << "Populating dependency matrix failed\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000516 return false;
517 }
518#ifdef DUMP_DEP_MATRICIES
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000519 LLVM_DEBUG(dbgs() << "Dependence before interchange\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000520 printDepMatrix(DependencyMatrix);
521#endif
522
Karthik Bhat88db86d2015-03-06 10:11:25 +0000523 // Get the Outermost loop exit.
Florian Hahn1da30c62018-04-25 09:35:54 +0000524 BasicBlock *LoopNestExit = OuterMostLoop->getExitBlock();
525 if (!LoopNestExit) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000526 LLVM_DEBUG(dbgs() << "OuterMostLoop needs an unique exit block");
Florian Hahn1da30c62018-04-25 09:35:54 +0000527 return false;
528 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000529
Karthik Bhat88db86d2015-03-06 10:11:25 +0000530 unsigned SelecLoopId = selectLoopForInterchange(LoopList);
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000531 // Move the selected loop outwards to the best possible position.
Karthik Bhat88db86d2015-03-06 10:11:25 +0000532 for (unsigned i = SelecLoopId; i > 0; i--) {
533 bool Interchanged =
534 processLoop(LoopList, i, i - 1, LoopNestExit, DependencyMatrix);
535 if (!Interchanged)
536 return Changed;
537 // Loops interchanged reflect the same in LoopList
Benjamin Kramer79442922015-03-06 18:59:14 +0000538 std::swap(LoopList[i - 1], LoopList[i]);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000539
540 // Update the DependencyMatrix
Chad Rosierd18ea062016-09-13 13:00:29 +0000541 interChangeDependencies(DependencyMatrix, i, i - 1);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000542#ifdef DUMP_DEP_MATRICIES
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000543 LLVM_DEBUG(dbgs() << "Dependence after interchange\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000544 printDepMatrix(DependencyMatrix);
545#endif
546 Changed |= Interchanged;
547 }
548 return Changed;
549 }
550
551 bool processLoop(LoopVector LoopList, unsigned InnerLoopId,
552 unsigned OuterLoopId, BasicBlock *LoopNestExit,
553 std::vector<std::vector<char>> &DependencyMatrix) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000554 LLVM_DEBUG(dbgs() << "Processing Inner Loop Id = " << InnerLoopId
555 << " and OuterLoopId = " << OuterLoopId << "\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000556 Loop *InnerLoop = LoopList[InnerLoopId];
557 Loop *OuterLoop = LoopList[OuterLoopId];
558
Florian Hahnc51d0882018-09-06 10:41:01 +0000559 LoopInterchangeLegality LIL(OuterLoop, InnerLoop, SE, ORE);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000560 if (!LIL.canInterchangeLoops(InnerLoopId, OuterLoopId, DependencyMatrix)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000561 LLVM_DEBUG(dbgs() << "Not interchanging loops. Cannot prove legality.\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000562 return false;
563 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000564 LLVM_DEBUG(dbgs() << "Loops are legal to interchange\n");
Florian Hahnad993522017-07-15 13:13:19 +0000565 LoopInterchangeProfitability LIP(OuterLoop, InnerLoop, SE, ORE);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000566 if (!LIP.isProfitable(InnerLoopId, OuterLoopId, DependencyMatrix)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000567 LLVM_DEBUG(dbgs() << "Interchanging loops not profitable.\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000568 return false;
569 }
570
Vivek Pandya95906582017-10-11 17:12:59 +0000571 ORE->emit([&]() {
572 return OptimizationRemark(DEBUG_TYPE, "Interchanged",
573 InnerLoop->getStartLoc(),
574 InnerLoop->getHeader())
575 << "Loop interchanged with enclosing loop.";
576 });
Florian Hahnad993522017-07-15 13:13:19 +0000577
Florian Hahna684a992018-11-08 20:44:19 +0000578 LoopInterchangeTransform LIT(OuterLoop, InnerLoop, SE, LI, DT, LoopNestExit,
579 LIL);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000580 LIT.transform();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000581 LLVM_DEBUG(dbgs() << "Loops interchanged.\n");
Florian Hahn6e004332018-04-05 10:39:23 +0000582 LoopsInterchanged++;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000583 return true;
584 }
585};
586
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000587} // end anonymous namespace
588
Florian Hahnc8bd6ea2018-11-01 19:25:00 +0000589bool LoopInterchangeLegality::containsUnsafeInstructions(BasicBlock *BB) {
590 return any_of(*BB, [](const Instruction &I) {
591 return I.mayHaveSideEffects() || I.mayReadFromMemory();
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000592 });
593}
Karthik Bhat88db86d2015-03-06 10:11:25 +0000594
Karthik Bhat88db86d2015-03-06 10:11:25 +0000595bool LoopInterchangeLegality::tightlyNested(Loop *OuterLoop, Loop *InnerLoop) {
596 BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
597 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
598 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch();
599
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000600 LLVM_DEBUG(dbgs() << "Checking if loops are tightly nested\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000601
602 // A perfectly nested loop will not have any branch in between the outer and
603 // inner block i.e. outer header will branch to either inner preheader and
604 // outerloop latch.
Chad Rosierf7c76f92016-09-21 13:28:41 +0000605 BranchInst *OuterLoopHeaderBI =
Karthik Bhat88db86d2015-03-06 10:11:25 +0000606 dyn_cast<BranchInst>(OuterLoopHeader->getTerminator());
Chad Rosierf7c76f92016-09-21 13:28:41 +0000607 if (!OuterLoopHeaderBI)
Karthik Bhat88db86d2015-03-06 10:11:25 +0000608 return false;
Chad Rosierf7c76f92016-09-21 13:28:41 +0000609
Chandler Carruth96fc1de2018-08-26 08:41:15 +0000610 for (BasicBlock *Succ : successors(OuterLoopHeaderBI))
Florian Hahn236f6fe2018-09-06 09:57:27 +0000611 if (Succ != InnerLoopPreHeader && Succ != InnerLoop->getHeader() &&
612 Succ != OuterLoopLatch)
Karthik Bhat88db86d2015-03-06 10:11:25 +0000613 return false;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000614
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000615 LLVM_DEBUG(dbgs() << "Checking instructions in Loop header and Loop latch\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000616 // We do not have any basic block in between now make sure the outer header
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000617 // and outer loop latch doesn't contain any unsafe instructions.
Florian Hahnc8bd6ea2018-11-01 19:25:00 +0000618 if (containsUnsafeInstructions(OuterLoopHeader) ||
619 containsUnsafeInstructions(OuterLoopLatch))
Karthik Bhat88db86d2015-03-06 10:11:25 +0000620 return false;
621
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000622 LLVM_DEBUG(dbgs() << "Loops are perfectly nested\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000623 // We have a perfect loop nest.
624 return true;
625}
626
Karthik Bhat88db86d2015-03-06 10:11:25 +0000627bool LoopInterchangeLegality::isLoopStructureUnderstood(
628 PHINode *InnerInduction) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000629 unsigned Num = InnerInduction->getNumOperands();
630 BasicBlock *InnerLoopPreheader = InnerLoop->getLoopPreheader();
631 for (unsigned i = 0; i < Num; ++i) {
632 Value *Val = InnerInduction->getOperand(i);
633 if (isa<Constant>(Val))
634 continue;
635 Instruction *I = dyn_cast<Instruction>(Val);
636 if (!I)
637 return false;
638 // TODO: Handle triangular loops.
639 // e.g. for(int i=0;i<N;i++)
640 // for(int j=i;j<N;j++)
641 unsigned IncomBlockIndx = PHINode::getIncomingValueNumForOperand(i);
642 if (InnerInduction->getIncomingBlock(IncomBlockIndx) ==
643 InnerLoopPreheader &&
644 !OuterLoop->isLoopInvariant(I)) {
645 return false;
646 }
647 }
648 return true;
649}
650
Florian Hahna684a992018-11-08 20:44:19 +0000651// If SV is a LCSSA PHI node with a single incoming value, return the incoming
652// value.
653static Value *followLCSSA(Value *SV) {
654 PHINode *PHI = dyn_cast<PHINode>(SV);
655 if (!PHI)
656 return SV;
657
658 if (PHI->getNumIncomingValues() != 1)
659 return SV;
660 return followLCSSA(PHI->getIncomingValue(0));
661}
662
663// Check V's users to see if it is involved in a reduction in L.
664static PHINode *findInnerReductionPhi(Loop *L, Value *V) {
665 for (Value *User : V->users()) {
666 if (PHINode *PHI = dyn_cast<PHINode>(User)) {
667 if (PHI->getNumIncomingValues() == 1)
668 continue;
669 RecurrenceDescriptor RD;
670 if (RecurrenceDescriptor::isReductionPHI(PHI, L, RD))
671 return PHI;
672 return nullptr;
673 }
674 }
675
676 return nullptr;
677}
678
679bool LoopInterchangeLegality::findInductionAndReductions(
680 Loop *L, SmallVector<PHINode *, 8> &Inductions, Loop *InnerLoop) {
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000681 if (!L->getLoopLatch() || !L->getLoopPredecessor())
682 return false;
Florian Hahn5912c662018-05-02 10:53:04 +0000683 for (PHINode &PHI : L->getHeader()->phis()) {
Tyler Nowicki0a913102015-06-16 18:07:34 +0000684 RecurrenceDescriptor RD;
James Molloy1bbf15c2015-08-27 09:53:00 +0000685 InductionDescriptor ID;
Florian Hahn5912c662018-05-02 10:53:04 +0000686 if (InductionDescriptor::isInductionPHI(&PHI, L, SE, ID))
687 Inductions.push_back(&PHI);
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000688 else {
Florian Hahna684a992018-11-08 20:44:19 +0000689 // PHIs in inner loops need to be part of a reduction in the outer loop,
690 // discovered when checking the PHIs of the outer loop earlier.
691 if (!InnerLoop) {
692 if (OuterInnerReductions.find(&PHI) == OuterInnerReductions.end()) {
693 LLVM_DEBUG(dbgs() << "Inner loop PHI is not part of reductions "
694 "across the outer loop.\n");
695 return false;
696 }
697 } else {
698 assert(PHI.getNumIncomingValues() == 2 &&
699 "Phis in loop header should have exactly 2 incoming values");
700 // Check if we have a PHI node in the outer loop that has a reduction
701 // result from the inner loop as an incoming value.
702 Value *V = followLCSSA(PHI.getIncomingValueForBlock(L->getLoopLatch()));
703 PHINode *InnerRedPhi = findInnerReductionPhi(InnerLoop, V);
704 if (!InnerRedPhi ||
705 !llvm::any_of(InnerRedPhi->incoming_values(),
706 [&PHI](Value *V) { return V == &PHI; })) {
707 LLVM_DEBUG(
708 dbgs()
709 << "Failed to recognize PHI as an induction or reduction.\n");
710 return false;
711 }
712 OuterInnerReductions.insert(&PHI);
713 OuterInnerReductions.insert(InnerRedPhi);
714 }
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000715 }
716 }
717 return true;
718}
719
720static bool containsSafePHI(BasicBlock *Block, bool isOuterLoopExitBlock) {
Florian Hahn5912c662018-05-02 10:53:04 +0000721 for (PHINode &PHI : Block->phis()) {
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000722 // Reduction lcssa phi will have only 1 incoming block that from loop latch.
Florian Hahn5912c662018-05-02 10:53:04 +0000723 if (PHI.getNumIncomingValues() > 1)
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000724 return false;
Florian Hahn5912c662018-05-02 10:53:04 +0000725 Instruction *Ins = dyn_cast<Instruction>(PHI.getIncomingValue(0));
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000726 if (!Ins)
727 return false;
728 // Incoming value for lcssa phi's in outer loop exit can only be inner loop
729 // exits lcssa phi else it would not be tightly nested.
730 if (!isa<PHINode>(Ins) && isOuterLoopExitBlock)
731 return false;
732 }
733 return true;
734}
735
Karthik Bhat88db86d2015-03-06 10:11:25 +0000736// This function indicates the current limitations in the transform as a result
737// of which we do not proceed.
738bool LoopInterchangeLegality::currentLimitations() {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000739 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000740 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
Florian Hahn1da30c62018-04-25 09:35:54 +0000741
742 // transform currently expects the loop latches to also be the exiting
743 // blocks.
744 if (InnerLoop->getExitingBlock() != InnerLoopLatch ||
745 OuterLoop->getExitingBlock() != OuterLoop->getLoopLatch() ||
746 !isa<BranchInst>(InnerLoopLatch->getTerminator()) ||
747 !isa<BranchInst>(OuterLoop->getLoopLatch()->getTerminator())) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000748 LLVM_DEBUG(
749 dbgs() << "Loops where the latch is not the exiting block are not"
750 << " supported currently.\n");
Florian Hahn1da30c62018-04-25 09:35:54 +0000751 ORE->emit([&]() {
752 return OptimizationRemarkMissed(DEBUG_TYPE, "ExitingNotLatch",
753 OuterLoop->getStartLoc(),
754 OuterLoop->getHeader())
755 << "Loops where the latch is not the exiting block cannot be"
756 " interchange currently.";
757 });
758 return true;
759 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000760
761 PHINode *InnerInductionVar;
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000762 SmallVector<PHINode *, 8> Inductions;
Florian Hahna684a992018-11-08 20:44:19 +0000763 if (!findInductionAndReductions(OuterLoop, Inductions, InnerLoop)) {
764 LLVM_DEBUG(
765 dbgs() << "Only outer loops with induction or reduction PHI nodes "
766 << "are supported currently.\n");
767 ORE->emit([&]() {
768 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedPHIOuter",
769 OuterLoop->getStartLoc(),
770 OuterLoop->getHeader())
771 << "Only outer loops with induction or reduction PHI nodes can be"
772 " interchanged currently.";
773 });
774 return true;
775 }
776
777 // TODO: Currently we handle only loops with 1 induction variable.
778 if (Inductions.size() != 1) {
779 LLVM_DEBUG(dbgs() << "Loops with more than 1 induction variables are not "
780 << "supported currently.\n");
781 ORE->emit([&]() {
782 return OptimizationRemarkMissed(DEBUG_TYPE, "MultiIndutionOuter",
783 OuterLoop->getStartLoc(),
784 OuterLoop->getHeader())
785 << "Only outer loops with 1 induction variable can be "
786 "interchanged currently.";
787 });
788 return true;
789 }
790
791 Inductions.clear();
792 if (!findInductionAndReductions(InnerLoop, Inductions, nullptr)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000793 LLVM_DEBUG(
794 dbgs() << "Only inner loops with induction or reduction PHI nodes "
795 << "are supported currently.\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000796 ORE->emit([&]() {
797 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedPHIInner",
798 InnerLoop->getStartLoc(),
799 InnerLoop->getHeader())
800 << "Only inner loops with induction or reduction PHI nodes can be"
801 " interchange currently.";
802 });
Karthik Bhat88db86d2015-03-06 10:11:25 +0000803 return true;
Florian Hahn4eeff392017-07-03 15:32:00 +0000804 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000805
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000806 // TODO: Currently we handle only loops with 1 induction variable.
807 if (Inductions.size() != 1) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000808 LLVM_DEBUG(
809 dbgs() << "We currently only support loops with 1 induction variable."
810 << "Failed to interchange due to current limitation\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000811 ORE->emit([&]() {
812 return OptimizationRemarkMissed(DEBUG_TYPE, "MultiInductionInner",
813 InnerLoop->getStartLoc(),
814 InnerLoop->getHeader())
815 << "Only inner loops with 1 induction variable can be "
816 "interchanged currently.";
817 });
Karthik Bhat88db86d2015-03-06 10:11:25 +0000818 return true;
819 }
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000820 InnerInductionVar = Inductions.pop_back_val();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000821
822 // TODO: Triangular loops are not handled for now.
823 if (!isLoopStructureUnderstood(InnerInductionVar)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000824 LLVM_DEBUG(dbgs() << "Loop structure not understood by pass\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000825 ORE->emit([&]() {
826 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedStructureInner",
827 InnerLoop->getStartLoc(),
828 InnerLoop->getHeader())
829 << "Inner loop structure not understood currently.";
830 });
Karthik Bhat88db86d2015-03-06 10:11:25 +0000831 return true;
832 }
833
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000834 // TODO: We only handle LCSSA PHI's corresponding to reduction for now.
Florian Hahn1da30c62018-04-25 09:35:54 +0000835 BasicBlock *InnerExit = InnerLoop->getExitBlock();
836 if (!containsSafePHI(InnerExit, false)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000837 LLVM_DEBUG(
838 dbgs() << "Can only handle LCSSA PHIs in inner loops currently.\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000839 ORE->emit([&]() {
840 return OptimizationRemarkMissed(DEBUG_TYPE, "NoLCSSAPHIOuterInner",
841 InnerLoop->getStartLoc(),
842 InnerLoop->getHeader())
843 << "Only inner loops with LCSSA PHIs can be interchange "
844 "currently.";
845 });
Karthik Bhat88db86d2015-03-06 10:11:25 +0000846 return true;
Florian Hahn4eeff392017-07-03 15:32:00 +0000847 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000848
849 // TODO: Current limitation: Since we split the inner loop latch at the point
850 // were induction variable is incremented (induction.next); We cannot have
851 // more than 1 user of induction.next since it would result in broken code
852 // after split.
853 // e.g.
854 // for(i=0;i<N;i++) {
855 // for(j = 0;j<M;j++) {
856 // A[j+1][i+2] = A[j][i]+k;
857 // }
858 // }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000859 Instruction *InnerIndexVarInc = nullptr;
860 if (InnerInductionVar->getIncomingBlock(0) == InnerLoopPreHeader)
861 InnerIndexVarInc =
862 dyn_cast<Instruction>(InnerInductionVar->getIncomingValue(1));
863 else
864 InnerIndexVarInc =
865 dyn_cast<Instruction>(InnerInductionVar->getIncomingValue(0));
866
Florian Hahn4eeff392017-07-03 15:32:00 +0000867 if (!InnerIndexVarInc) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000868 LLVM_DEBUG(
869 dbgs() << "Did not find an instruction to increment the induction "
870 << "variable.\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000871 ORE->emit([&]() {
872 return OptimizationRemarkMissed(DEBUG_TYPE, "NoIncrementInInner",
873 InnerLoop->getStartLoc(),
874 InnerLoop->getHeader())
875 << "The inner loop does not increment the induction variable.";
876 });
Pete Cooper11bd9582015-07-27 18:37:58 +0000877 return true;
Florian Hahn4eeff392017-07-03 15:32:00 +0000878 }
Pete Cooper11bd9582015-07-27 18:37:58 +0000879
Karthik Bhat88db86d2015-03-06 10:11:25 +0000880 // Since we split the inner loop latch on this induction variable. Make sure
881 // we do not have any instruction between the induction variable and branch
882 // instruction.
883
David Majnemerd7708772016-06-24 04:05:21 +0000884 bool FoundInduction = false;
Florian Hahnfd2bc112018-04-26 10:26:17 +0000885 for (const Instruction &I :
886 llvm::reverse(InnerLoopLatch->instructionsWithoutDebug())) {
Florian Hahncd783452017-08-25 16:52:29 +0000887 if (isa<BranchInst>(I) || isa<CmpInst>(I) || isa<TruncInst>(I) ||
888 isa<ZExtInst>(I))
Karthik Bhat88db86d2015-03-06 10:11:25 +0000889 continue;
Florian Hahn4eeff392017-07-03 15:32:00 +0000890
Karthik Bhat88db86d2015-03-06 10:11:25 +0000891 // We found an instruction. If this is not induction variable then it is not
892 // safe to split this loop latch.
Florian Hahn4eeff392017-07-03 15:32:00 +0000893 if (!I.isIdenticalTo(InnerIndexVarInc)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000894 LLVM_DEBUG(dbgs() << "Found unsupported instructions between induction "
895 << "variable increment and branch.\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000896 ORE->emit([&]() {
897 return OptimizationRemarkMissed(
898 DEBUG_TYPE, "UnsupportedInsBetweenInduction",
899 InnerLoop->getStartLoc(), InnerLoop->getHeader())
900 << "Found unsupported instruction between induction variable "
901 "increment and branch.";
902 });
Karthik Bhat88db86d2015-03-06 10:11:25 +0000903 return true;
Florian Hahn4eeff392017-07-03 15:32:00 +0000904 }
David Majnemerd7708772016-06-24 04:05:21 +0000905
906 FoundInduction = true;
907 break;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000908 }
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000909 // The loop latch ended and we didn't find the induction variable return as
Karthik Bhat88db86d2015-03-06 10:11:25 +0000910 // current limitation.
Florian Hahn4eeff392017-07-03 15:32:00 +0000911 if (!FoundInduction) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000912 LLVM_DEBUG(dbgs() << "Did not find the induction variable.\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000913 ORE->emit([&]() {
914 return OptimizationRemarkMissed(DEBUG_TYPE, "NoIndutionVariable",
915 InnerLoop->getStartLoc(),
916 InnerLoop->getHeader())
917 << "Did not find the induction variable.";
918 });
Karthik Bhat88db86d2015-03-06 10:11:25 +0000919 return true;
Florian Hahn4eeff392017-07-03 15:32:00 +0000920 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000921 return false;
922}
923
Florian Hahnf3fea0f2018-04-27 13:52:51 +0000924// We currently support LCSSA PHI nodes in the outer loop exit, if their
925// incoming values do not come from the outer loop latch or if the
926// outer loop latch has a single predecessor. In that case, the value will
927// be available if both the inner and outer loop conditions are true, which
928// will still be true after interchanging. If we have multiple predecessor,
929// that may not be the case, e.g. because the outer loop latch may be executed
930// if the inner loop is not executed.
931static bool areLoopExitPHIsSupported(Loop *OuterLoop, Loop *InnerLoop) {
932 BasicBlock *LoopNestExit = OuterLoop->getUniqueExitBlock();
933 for (PHINode &PHI : LoopNestExit->phis()) {
934 // FIXME: We currently are not able to detect floating point reductions
935 // and have to use floating point PHIs as a proxy to prevent
936 // interchanging in the presence of floating point reductions.
937 if (PHI.getType()->isFloatingPointTy())
938 return false;
939 for (unsigned i = 0; i < PHI.getNumIncomingValues(); i++) {
940 Instruction *IncomingI = dyn_cast<Instruction>(PHI.getIncomingValue(i));
941 if (!IncomingI || IncomingI->getParent() != OuterLoop->getLoopLatch())
942 continue;
943
944 // The incoming value is defined in the outer loop latch. Currently we
945 // only support that in case the outer loop latch has a single predecessor.
946 // This guarantees that the outer loop latch is executed if and only if
947 // the inner loop is executed (because tightlyNested() guarantees that the
948 // outer loop header only branches to the inner loop or the outer loop
949 // latch).
950 // FIXME: We could weaken this logic and allow multiple predecessors,
951 // if the values are produced outside the loop latch. We would need
952 // additional logic to update the PHI nodes in the exit block as
953 // well.
954 if (OuterLoop->getLoopLatch()->getUniquePredecessor() == nullptr)
955 return false;
956 }
957 }
958 return true;
959}
960
Karthik Bhat88db86d2015-03-06 10:11:25 +0000961bool LoopInterchangeLegality::canInterchangeLoops(unsigned InnerLoopId,
962 unsigned OuterLoopId,
963 CharMatrix &DepMatrix) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000964 if (!isLegalToInterChangeLoops(DepMatrix, InnerLoopId, OuterLoopId)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000965 LLVM_DEBUG(dbgs() << "Failed interchange InnerLoopId = " << InnerLoopId
966 << " and OuterLoopId = " << OuterLoopId
967 << " due to dependence\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000968 ORE->emit([&]() {
969 return OptimizationRemarkMissed(DEBUG_TYPE, "Dependence",
970 InnerLoop->getStartLoc(),
971 InnerLoop->getHeader())
972 << "Cannot interchange loops due to dependences.";
973 });
Karthik Bhat88db86d2015-03-06 10:11:25 +0000974 return false;
975 }
Florian Hahn42840492017-07-31 09:00:52 +0000976 // Check if outer and inner loop contain legal instructions only.
977 for (auto *BB : OuterLoop->blocks())
Florian Hahnfd2bc112018-04-26 10:26:17 +0000978 for (Instruction &I : BB->instructionsWithoutDebug())
Florian Hahn42840492017-07-31 09:00:52 +0000979 if (CallInst *CI = dyn_cast<CallInst>(&I)) {
980 // readnone functions do not prevent interchanging.
981 if (CI->doesNotReadMemory())
982 continue;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000983 LLVM_DEBUG(
984 dbgs() << "Loops with call instructions cannot be interchanged "
985 << "safely.");
Florian Hahn9467ccf2018-04-03 20:54:04 +0000986 ORE->emit([&]() {
987 return OptimizationRemarkMissed(DEBUG_TYPE, "CallInst",
988 CI->getDebugLoc(),
989 CI->getParent())
990 << "Cannot interchange loops due to call instruction.";
991 });
992
Florian Hahn42840492017-07-31 09:00:52 +0000993 return false;
994 }
995
Karthik Bhat88db86d2015-03-06 10:11:25 +0000996 // TODO: The loops could not be interchanged due to current limitations in the
997 // transform module.
998 if (currentLimitations()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000999 LLVM_DEBUG(dbgs() << "Not legal because of current transform limitation\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +00001000 return false;
1001 }
1002
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001003 // Check if the loops are tightly nested.
1004 if (!tightlyNested(OuterLoop, InnerLoop)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001005 LLVM_DEBUG(dbgs() << "Loops not tightly nested\n");
Vivek Pandya95906582017-10-11 17:12:59 +00001006 ORE->emit([&]() {
1007 return OptimizationRemarkMissed(DEBUG_TYPE, "NotTightlyNested",
1008 InnerLoop->getStartLoc(),
1009 InnerLoop->getHeader())
1010 << "Cannot interchange loops because they are not tightly "
1011 "nested.";
1012 });
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001013 return false;
1014 }
1015
Florian Hahnf3fea0f2018-04-27 13:52:51 +00001016 if (!areLoopExitPHIsSupported(OuterLoop, InnerLoop)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001017 LLVM_DEBUG(dbgs() << "Found unsupported PHI nodes in outer loop exit.\n");
Florian Hahnf3fea0f2018-04-27 13:52:51 +00001018 ORE->emit([&]() {
1019 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedExitPHI",
1020 OuterLoop->getStartLoc(),
1021 OuterLoop->getHeader())
1022 << "Found unsupported PHI node in loop exit.";
1023 });
1024 return false;
1025 }
1026
Karthik Bhat88db86d2015-03-06 10:11:25 +00001027 return true;
1028}
1029
1030int LoopInterchangeProfitability::getInstrOrderCost() {
1031 unsigned GoodOrder, BadOrder;
1032 BadOrder = GoodOrder = 0;
Florian Hahnf66efd62017-07-24 11:41:30 +00001033 for (BasicBlock *BB : InnerLoop->blocks()) {
1034 for (Instruction &Ins : *BB) {
Karthik Bhat88db86d2015-03-06 10:11:25 +00001035 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Ins)) {
1036 unsigned NumOp = GEP->getNumOperands();
1037 bool FoundInnerInduction = false;
1038 bool FoundOuterInduction = false;
1039 for (unsigned i = 0; i < NumOp; ++i) {
1040 const SCEV *OperandVal = SE->getSCEV(GEP->getOperand(i));
1041 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(OperandVal);
1042 if (!AR)
1043 continue;
1044
1045 // If we find the inner induction after an outer induction e.g.
1046 // for(int i=0;i<N;i++)
1047 // for(int j=0;j<N;j++)
1048 // A[i][j] = A[i-1][j-1]+k;
1049 // then it is a good order.
1050 if (AR->getLoop() == InnerLoop) {
1051 // We found an InnerLoop induction after OuterLoop induction. It is
1052 // a good order.
1053 FoundInnerInduction = true;
1054 if (FoundOuterInduction) {
1055 GoodOrder++;
1056 break;
1057 }
1058 }
1059 // If we find the outer induction after an inner induction e.g.
1060 // for(int i=0;i<N;i++)
1061 // for(int j=0;j<N;j++)
1062 // A[j][i] = A[j-1][i-1]+k;
1063 // then it is a bad order.
1064 if (AR->getLoop() == OuterLoop) {
1065 // We found an OuterLoop induction after InnerLoop induction. It is
1066 // a bad order.
1067 FoundOuterInduction = true;
1068 if (FoundInnerInduction) {
1069 BadOrder++;
1070 break;
1071 }
1072 }
1073 }
1074 }
1075 }
1076 }
1077 return GoodOrder - BadOrder;
1078}
1079
Chad Rosiere6b3a632016-09-14 17:12:30 +00001080static bool isProfitableForVectorization(unsigned InnerLoopId,
1081 unsigned OuterLoopId,
1082 CharMatrix &DepMatrix) {
Karthik Bhat88db86d2015-03-06 10:11:25 +00001083 // TODO: Improve this heuristic to catch more cases.
1084 // If the inner loop is loop independent or doesn't carry any dependency it is
1085 // profitable to move this to outer position.
Florian Hahnf66efd62017-07-24 11:41:30 +00001086 for (auto &Row : DepMatrix) {
1087 if (Row[InnerLoopId] != 'S' && Row[InnerLoopId] != 'I')
Karthik Bhat88db86d2015-03-06 10:11:25 +00001088 return false;
1089 // TODO: We need to improve this heuristic.
Florian Hahnf66efd62017-07-24 11:41:30 +00001090 if (Row[OuterLoopId] != '=')
Karthik Bhat88db86d2015-03-06 10:11:25 +00001091 return false;
1092 }
1093 // If outer loop has dependence and inner loop is loop independent then it is
1094 // profitable to interchange to enable parallelism.
Florian Hahnceee7882018-04-24 16:55:32 +00001095 // If there are no dependences, interchanging will not improve anything.
1096 return !DepMatrix.empty();
Karthik Bhat88db86d2015-03-06 10:11:25 +00001097}
1098
1099bool LoopInterchangeProfitability::isProfitable(unsigned InnerLoopId,
1100 unsigned OuterLoopId,
1101 CharMatrix &DepMatrix) {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001102 // TODO: Add better profitability checks.
Karthik Bhat88db86d2015-03-06 10:11:25 +00001103 // e.g
1104 // 1) Construct dependency matrix and move the one with no loop carried dep
1105 // inside to enable vectorization.
1106
1107 // This is rough cost estimation algorithm. It counts the good and bad order
1108 // of induction variables in the instruction and allows reordering if number
1109 // of bad orders is more than good.
Chad Rosier72431892016-09-14 17:07:13 +00001110 int Cost = getInstrOrderCost();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001111 LLVM_DEBUG(dbgs() << "Cost = " << Cost << "\n");
Chad Rosier72431892016-09-14 17:07:13 +00001112 if (Cost < -LoopInterchangeCostThreshold)
Karthik Bhat88db86d2015-03-06 10:11:25 +00001113 return true;
1114
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001115 // It is not profitable as per current cache profitability model. But check if
Karthik Bhat88db86d2015-03-06 10:11:25 +00001116 // we can move this loop outside to improve parallelism.
Florian Hahnad993522017-07-15 13:13:19 +00001117 if (isProfitableForVectorization(InnerLoopId, OuterLoopId, DepMatrix))
1118 return true;
1119
Vivek Pandya95906582017-10-11 17:12:59 +00001120 ORE->emit([&]() {
1121 return OptimizationRemarkMissed(DEBUG_TYPE, "InterchangeNotProfitable",
1122 InnerLoop->getStartLoc(),
1123 InnerLoop->getHeader())
1124 << "Interchanging loops is too costly (cost="
1125 << ore::NV("Cost", Cost) << ", threshold="
1126 << ore::NV("Threshold", LoopInterchangeCostThreshold)
1127 << ") and it does not improve parallelism.";
1128 });
Florian Hahnad993522017-07-15 13:13:19 +00001129 return false;
Karthik Bhat88db86d2015-03-06 10:11:25 +00001130}
1131
1132void LoopInterchangeTransform::removeChildLoop(Loop *OuterLoop,
1133 Loop *InnerLoop) {
Florian Hahn5912c662018-05-02 10:53:04 +00001134 for (Loop *L : *OuterLoop)
1135 if (L == InnerLoop) {
1136 OuterLoop->removeChildLoop(L);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001137 return;
1138 }
Benjamin Kramer8ceb3232015-10-25 22:28:27 +00001139 llvm_unreachable("Couldn't find loop");
Karthik Bhat88db86d2015-03-06 10:11:25 +00001140}
Daniel Jasper6adbd7a2015-03-06 10:39:14 +00001141
Florian Hahn831a7572018-04-05 09:48:45 +00001142/// Update LoopInfo, after interchanging. NewInner and NewOuter refer to the
1143/// new inner and outer loop after interchanging: NewInner is the original
1144/// outer loop and NewOuter is the original inner loop.
1145///
1146/// Before interchanging, we have the following structure
1147/// Outer preheader
1148// Outer header
1149// Inner preheader
1150// Inner header
1151// Inner body
1152// Inner latch
1153// outer bbs
1154// Outer latch
1155//
1156// After interchanging:
1157// Inner preheader
1158// Inner header
1159// Outer preheader
1160// Outer header
1161// Inner body
1162// outer bbs
1163// Outer latch
1164// Inner latch
1165void LoopInterchangeTransform::restructureLoops(
1166 Loop *NewInner, Loop *NewOuter, BasicBlock *OrigInnerPreHeader,
1167 BasicBlock *OrigOuterPreHeader) {
Karthik Bhat88db86d2015-03-06 10:11:25 +00001168 Loop *OuterLoopParent = OuterLoop->getParentLoop();
Florian Hahn831a7572018-04-05 09:48:45 +00001169 // The original inner loop preheader moves from the new inner loop to
1170 // the parent loop, if there is one.
1171 NewInner->removeBlockFromLoop(OrigInnerPreHeader);
1172 LI->changeLoopFor(OrigInnerPreHeader, OuterLoopParent);
1173
1174 // Switch the loop levels.
Karthik Bhat88db86d2015-03-06 10:11:25 +00001175 if (OuterLoopParent) {
1176 // Remove the loop from its parent loop.
Florian Hahn831a7572018-04-05 09:48:45 +00001177 removeChildLoop(OuterLoopParent, NewInner);
1178 removeChildLoop(NewInner, NewOuter);
1179 OuterLoopParent->addChildLoop(NewOuter);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001180 } else {
Florian Hahn831a7572018-04-05 09:48:45 +00001181 removeChildLoop(NewInner, NewOuter);
1182 LI->changeTopLevelLoop(NewInner, NewOuter);
1183 }
1184 while (!NewOuter->empty())
1185 NewInner->addChildLoop(NewOuter->removeChildLoop(NewOuter->begin()));
1186 NewOuter->addChildLoop(NewInner);
1187
1188 // BBs from the original inner loop.
1189 SmallVector<BasicBlock *, 8> OrigInnerBBs(NewOuter->blocks());
1190
1191 // Add BBs from the original outer loop to the original inner loop (excluding
1192 // BBs already in inner loop)
1193 for (BasicBlock *BB : NewInner->blocks())
1194 if (LI->getLoopFor(BB) == NewInner)
1195 NewOuter->addBlockEntry(BB);
1196
1197 // Now remove inner loop header and latch from the new inner loop and move
1198 // other BBs (the loop body) to the new inner loop.
1199 BasicBlock *OuterHeader = NewOuter->getHeader();
1200 BasicBlock *OuterLatch = NewOuter->getLoopLatch();
1201 for (BasicBlock *BB : OrigInnerBBs) {
Florian Hahn744181852018-04-23 21:38:19 +00001202 // Nothing will change for BBs in child loops.
1203 if (LI->getLoopFor(BB) != NewOuter)
1204 continue;
Florian Hahn831a7572018-04-05 09:48:45 +00001205 // Remove the new outer loop header and latch from the new inner loop.
1206 if (BB == OuterHeader || BB == OuterLatch)
1207 NewInner->removeBlockFromLoop(BB);
1208 else
1209 LI->changeLoopFor(BB, NewInner);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001210 }
1211
Florian Hahn831a7572018-04-05 09:48:45 +00001212 // The preheader of the original outer loop becomes part of the new
1213 // outer loop.
1214 NewOuter->addBlockEntry(OrigOuterPreHeader);
1215 LI->changeLoopFor(OrigOuterPreHeader, NewOuter);
Florian Hahn3afb9742018-09-14 07:50:20 +00001216
1217 // Tell SE that we move the loops around.
1218 SE->forgetLoop(NewOuter);
1219 SE->forgetLoop(NewInner);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001220}
1221
1222bool LoopInterchangeTransform::transform() {
Karthik Bhat88db86d2015-03-06 10:11:25 +00001223 bool Transformed = false;
1224 Instruction *InnerIndexVar;
1225
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +00001226 if (InnerLoop->getSubLoops().empty()) {
Karthik Bhat88db86d2015-03-06 10:11:25 +00001227 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
Florian Hahne4961212019-09-11 08:23:23 +00001228 LLVM_DEBUG(dbgs() << "Splitting the inner loop latch\n");
Kit Barton987fdfd2019-05-23 20:53:05 +00001229 PHINode *InductionPHI = getInductionVariable(InnerLoop, SE);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001230 if (!InductionPHI) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001231 LLVM_DEBUG(dbgs() << "Failed to find the point to split loop latch \n");
Karthik Bhat88db86d2015-03-06 10:11:25 +00001232 return false;
1233 }
1234
1235 if (InductionPHI->getIncomingBlock(0) == InnerLoopPreHeader)
1236 InnerIndexVar = dyn_cast<Instruction>(InductionPHI->getIncomingValue(1));
1237 else
1238 InnerIndexVar = dyn_cast<Instruction>(InductionPHI->getIncomingValue(0));
1239
Florian Hahnd8fcf0d2018-06-19 08:03:24 +00001240 // Ensure that InductionPHI is the first Phi node.
David Green907b60f2017-10-21 13:58:37 +00001241 if (&InductionPHI->getParent()->front() != InductionPHI)
1242 InductionPHI->moveBefore(&InductionPHI->getParent()->front());
1243
Florian Hahne4961212019-09-11 08:23:23 +00001244 // Create a new latch block for the inner loop. We split at the
1245 // current latch's terminator and then move the condition and all
1246 // operands that are not either loop-invariant or the induction PHI into the
1247 // new latch block.
1248 BasicBlock *NewLatch =
1249 SplitBlock(InnerLoop->getLoopLatch(),
1250 InnerLoop->getLoopLatch()->getTerminator(), DT, LI);
1251
1252 SmallSetVector<Instruction *, 4> WorkList;
1253 unsigned i = 0;
1254 auto MoveInstructions = [&i, &WorkList, this, InductionPHI, NewLatch]() {
1255 for (; i < WorkList.size(); i++) {
1256 // Duplicate instruction and move it the new latch. Update uses that
1257 // have been moved.
1258 Instruction *NewI = WorkList[i]->clone();
1259 NewI->insertBefore(NewLatch->getFirstNonPHI());
1260 assert(!NewI->mayHaveSideEffects() &&
1261 "Moving instructions with side-effects may change behavior of "
1262 "the loop nest!");
1263 for (auto UI = WorkList[i]->use_begin(), UE = WorkList[i]->use_end();
1264 UI != UE;) {
1265 Use &U = *UI++;
1266 Instruction *UserI = cast<Instruction>(U.getUser());
1267 if (!InnerLoop->contains(UserI->getParent()) ||
1268 UserI->getParent() == NewLatch || UserI == InductionPHI)
1269 U.set(NewI);
1270 }
1271 // Add operands of moved instruction to the worklist, except if they are
1272 // outside the inner loop or are the induction PHI.
1273 for (Value *Op : WorkList[i]->operands()) {
1274 Instruction *OpI = dyn_cast<Instruction>(Op);
1275 if (!OpI ||
1276 this->LI->getLoopFor(OpI->getParent()) != this->InnerLoop ||
1277 OpI == InductionPHI)
1278 continue;
1279 WorkList.insert(OpI);
1280 }
1281 }
1282 };
1283
1284 // FIXME: Should we interchange when we have a constant condition?
1285 Instruction *CondI = dyn_cast<Instruction>(
1286 cast<BranchInst>(InnerLoop->getLoopLatch()->getTerminator())
1287 ->getCondition());
1288 if (CondI)
1289 WorkList.insert(CondI);
1290 MoveInstructions();
1291 WorkList.insert(cast<Instruction>(InnerIndexVar));
1292 MoveInstructions();
Karthik Bhat88db86d2015-03-06 10:11:25 +00001293
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001294 // Splits the inner loops phi nodes out into a separate basic block.
Florian Hahnd8fcf0d2018-06-19 08:03:24 +00001295 BasicBlock *InnerLoopHeader = InnerLoop->getHeader();
1296 SplitBlock(InnerLoopHeader, InnerLoopHeader->getFirstNonPHI(), DT, LI);
1297 LLVM_DEBUG(dbgs() << "splitting InnerLoopHeader done\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +00001298 }
1299
1300 Transformed |= adjustLoopLinks();
1301 if (!Transformed) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001302 LLVM_DEBUG(dbgs() << "adjustLoopLinks failed\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +00001303 return false;
1304 }
1305
Karthik Bhat88db86d2015-03-06 10:11:25 +00001306 return true;
1307}
1308
Florian Hahnd8fcf0d2018-06-19 08:03:24 +00001309/// \brief Move all instructions except the terminator from FromBB right before
Benjamin Kramer79442922015-03-06 18:59:14 +00001310/// InsertBefore
1311static void moveBBContents(BasicBlock *FromBB, Instruction *InsertBefore) {
1312 auto &ToList = InsertBefore->getParent()->getInstList();
1313 auto &FromList = FromBB->getInstList();
1314
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001315 ToList.splice(InsertBefore->getIterator(), FromList, FromList.begin(),
1316 FromBB->getTerminator()->getIterator());
Benjamin Kramer79442922015-03-06 18:59:14 +00001317}
1318
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001319/// Update BI to jump to NewBB instead of OldBB. Records updates to
Florian Hahnc6296fe2018-02-14 13:13:15 +00001320/// the dominator tree in DTUpdates, if DT should be preserved.
1321static void updateSuccessor(BranchInst *BI, BasicBlock *OldBB,
1322 BasicBlock *NewBB,
1323 std::vector<DominatorTree::UpdateType> &DTUpdates) {
Chandler Carruth96fc1de2018-08-26 08:41:15 +00001324 assert(llvm::count_if(successors(BI),
Florian Hahnc6296fe2018-02-14 13:13:15 +00001325 [OldBB](BasicBlock *BB) { return BB == OldBB; }) < 2 &&
1326 "BI must jump to OldBB at most once.");
1327 for (unsigned i = 0, e = BI->getNumSuccessors(); i < e; ++i) {
1328 if (BI->getSuccessor(i) == OldBB) {
1329 BI->setSuccessor(i, NewBB);
1330
1331 DTUpdates.push_back(
1332 {DominatorTree::UpdateKind::Insert, BI->getParent(), NewBB});
1333 DTUpdates.push_back(
1334 {DominatorTree::UpdateKind::Delete, BI->getParent(), OldBB});
1335 break;
1336 }
1337 }
1338}
1339
Florian Hahn6feb6372018-09-26 19:34:25 +00001340// Move Lcssa PHIs to the right place.
Florian Hahn11b2f4f2019-05-26 23:38:25 +00001341static void moveLCSSAPhis(BasicBlock *InnerExit, BasicBlock *InnerHeader,
1342 BasicBlock *InnerLatch, BasicBlock *OuterHeader,
1343 BasicBlock *OuterLatch, BasicBlock *OuterExit) {
1344
1345 // Deal with LCSSA PHI nodes in the exit block of the inner loop, that are
1346 // defined either in the header or latch. Those blocks will become header and
1347 // latch of the new outer loop, and the only possible users can PHI nodes
1348 // in the exit block of the loop nest or the outer loop header (reduction
1349 // PHIs, in that case, the incoming value must be defined in the inner loop
1350 // header). We can just substitute the user with the incoming value and remove
1351 // the PHI.
1352 for (PHINode &P : make_early_inc_range(InnerExit->phis())) {
1353 assert(P.getNumIncomingValues() == 1 &&
1354 "Only loops with a single exit are supported!");
1355
1356 // Incoming values are guaranteed be instructions currently.
1357 auto IncI = cast<Instruction>(P.getIncomingValueForBlock(InnerLatch));
1358 // Skip phis with incoming values from the inner loop body, excluding the
1359 // header and latch.
1360 if (IncI->getParent() != InnerLatch && IncI->getParent() != InnerHeader)
1361 continue;
1362
1363 assert(all_of(P.users(),
1364 [OuterHeader, OuterExit, IncI, InnerHeader](User *U) {
1365 return (cast<PHINode>(U)->getParent() == OuterHeader &&
1366 IncI->getParent() == InnerHeader) ||
1367 cast<PHINode>(U)->getParent() == OuterExit;
1368 }) &&
1369 "Can only replace phis iff the uses are in the loop nest exit or "
1370 "the incoming value is defined in the inner header (it will "
1371 "dominate all loop blocks after interchanging)");
1372 P.replaceAllUsesWith(IncI);
1373 P.eraseFromParent();
1374 }
1375
Florian Hahn6feb6372018-09-26 19:34:25 +00001376 SmallVector<PHINode *, 8> LcssaInnerExit;
1377 for (PHINode &P : InnerExit->phis())
1378 LcssaInnerExit.push_back(&P);
1379
1380 SmallVector<PHINode *, 8> LcssaInnerLatch;
1381 for (PHINode &P : InnerLatch->phis())
1382 LcssaInnerLatch.push_back(&P);
1383
1384 // Lcssa PHIs for values used outside the inner loop are in InnerExit.
1385 // If a PHI node has users outside of InnerExit, it has a use outside the
1386 // interchanged loop and we have to preserve it. We move these to
1387 // InnerLatch, which will become the new exit block for the innermost
Florian Hahn11b2f4f2019-05-26 23:38:25 +00001388 // loop after interchanging.
1389 for (PHINode *P : LcssaInnerExit)
1390 P->moveBefore(InnerLatch->getFirstNonPHI());
Florian Hahn6feb6372018-09-26 19:34:25 +00001391
1392 // If the inner loop latch contains LCSSA PHIs, those come from a child loop
1393 // and we have to move them to the new inner latch.
1394 for (PHINode *P : LcssaInnerLatch)
1395 P->moveBefore(InnerExit->getFirstNonPHI());
1396
Florian Hahn11b2f4f2019-05-26 23:38:25 +00001397 // Deal with LCSSA PHI nodes in the loop nest exit block. For PHIs that have
1398 // incoming values from the outer latch or header, we have to add a new PHI
1399 // in the inner loop latch, which became the exit block of the outer loop,
1400 // after interchanging.
1401 if (OuterExit) {
1402 for (PHINode &P : OuterExit->phis()) {
1403 if (P.getNumIncomingValues() != 1)
1404 continue;
1405 // Skip Phis with incoming values not defined in the outer loop's header
1406 // and latch. Also skip incoming phis defined in the latch. Those should
1407 // already have been updated.
1408 auto I = dyn_cast<Instruction>(P.getIncomingValue(0));
1409 if (!I || ((I->getParent() != OuterLatch || isa<PHINode>(I)) &&
1410 I->getParent() != OuterHeader))
1411 continue;
1412
1413 PHINode *NewPhi = dyn_cast<PHINode>(P.clone());
1414 NewPhi->setIncomingValue(0, P.getIncomingValue(0));
1415 NewPhi->setIncomingBlock(0, OuterLatch);
1416 NewPhi->insertBefore(InnerLatch->getFirstNonPHI());
1417 P.setIncomingValue(0, NewPhi);
1418 }
1419 }
1420
Florian Hahn6feb6372018-09-26 19:34:25 +00001421 // Now adjust the incoming blocks for the LCSSA PHIs.
1422 // For PHIs moved from Inner's exit block, we need to replace Inner's latch
1423 // with the new latch.
Roman Lebedev1a1b9222019-05-05 18:59:39 +00001424 InnerLatch->replacePhiUsesWith(InnerLatch, OuterLatch);
Florian Hahn6feb6372018-09-26 19:34:25 +00001425}
1426
Karthik Bhat88db86d2015-03-06 10:11:25 +00001427bool LoopInterchangeTransform::adjustLoopBranches() {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001428 LLVM_DEBUG(dbgs() << "adjustLoopBranches called\n");
Florian Hahnc6296fe2018-02-14 13:13:15 +00001429 std::vector<DominatorTree::UpdateType> DTUpdates;
1430
Florian Hahn236f6fe2018-09-06 09:57:27 +00001431 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader();
1432 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
1433
1434 assert(OuterLoopPreHeader != OuterLoop->getHeader() &&
1435 InnerLoopPreHeader != InnerLoop->getHeader() && OuterLoopPreHeader &&
1436 InnerLoopPreHeader && "Guaranteed by loop-simplify form");
1437 // Ensure that both preheaders do not contain PHI nodes and have single
1438 // predecessors. This allows us to move them easily. We use
1439 // InsertPreHeaderForLoop to create an 'extra' preheader, if the existing
1440 // preheaders do not satisfy those conditions.
1441 if (isa<PHINode>(OuterLoopPreHeader->begin()) ||
1442 !OuterLoopPreHeader->getUniquePredecessor())
Alina Sbirleaf31eba62019-05-08 17:05:36 +00001443 OuterLoopPreHeader =
1444 InsertPreheaderForLoop(OuterLoop, DT, LI, nullptr, true);
Florian Hahn236f6fe2018-09-06 09:57:27 +00001445 if (InnerLoopPreHeader == OuterLoop->getHeader())
Alina Sbirleaf31eba62019-05-08 17:05:36 +00001446 InnerLoopPreHeader =
1447 InsertPreheaderForLoop(InnerLoop, DT, LI, nullptr, true);
Florian Hahn236f6fe2018-09-06 09:57:27 +00001448
Karthik Bhat88db86d2015-03-06 10:11:25 +00001449 // Adjust the loop preheader
1450 BasicBlock *InnerLoopHeader = InnerLoop->getHeader();
1451 BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
1452 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
1453 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch();
Karthik Bhat88db86d2015-03-06 10:11:25 +00001454 BasicBlock *OuterLoopPredecessor = OuterLoopPreHeader->getUniquePredecessor();
1455 BasicBlock *InnerLoopLatchPredecessor =
1456 InnerLoopLatch->getUniquePredecessor();
1457 BasicBlock *InnerLoopLatchSuccessor;
1458 BasicBlock *OuterLoopLatchSuccessor;
1459
1460 BranchInst *OuterLoopLatchBI =
1461 dyn_cast<BranchInst>(OuterLoopLatch->getTerminator());
1462 BranchInst *InnerLoopLatchBI =
1463 dyn_cast<BranchInst>(InnerLoopLatch->getTerminator());
1464 BranchInst *OuterLoopHeaderBI =
1465 dyn_cast<BranchInst>(OuterLoopHeader->getTerminator());
1466 BranchInst *InnerLoopHeaderBI =
1467 dyn_cast<BranchInst>(InnerLoopHeader->getTerminator());
1468
1469 if (!OuterLoopPredecessor || !InnerLoopLatchPredecessor ||
1470 !OuterLoopLatchBI || !InnerLoopLatchBI || !OuterLoopHeaderBI ||
1471 !InnerLoopHeaderBI)
1472 return false;
1473
1474 BranchInst *InnerLoopLatchPredecessorBI =
1475 dyn_cast<BranchInst>(InnerLoopLatchPredecessor->getTerminator());
1476 BranchInst *OuterLoopPredecessorBI =
1477 dyn_cast<BranchInst>(OuterLoopPredecessor->getTerminator());
1478
1479 if (!OuterLoopPredecessorBI || !InnerLoopLatchPredecessorBI)
1480 return false;
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001481 BasicBlock *InnerLoopHeaderSuccessor = InnerLoopHeader->getUniqueSuccessor();
1482 if (!InnerLoopHeaderSuccessor)
Karthik Bhat88db86d2015-03-06 10:11:25 +00001483 return false;
1484
1485 // Adjust Loop Preheader and headers
Florian Hahnc6296fe2018-02-14 13:13:15 +00001486 updateSuccessor(OuterLoopPredecessorBI, OuterLoopPreHeader,
1487 InnerLoopPreHeader, DTUpdates);
1488 updateSuccessor(OuterLoopHeaderBI, OuterLoopLatch, LoopExit, DTUpdates);
1489 updateSuccessor(OuterLoopHeaderBI, InnerLoopPreHeader,
1490 InnerLoopHeaderSuccessor, DTUpdates);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001491
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001492 // Adjust reduction PHI's now that the incoming block has changed.
Roman Lebedev1a1b9222019-05-05 18:59:39 +00001493 InnerLoopHeaderSuccessor->replacePhiUsesWith(InnerLoopHeader,
1494 OuterLoopHeader);
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001495
Florian Hahnc6296fe2018-02-14 13:13:15 +00001496 updateSuccessor(InnerLoopHeaderBI, InnerLoopHeaderSuccessor,
1497 OuterLoopPreHeader, DTUpdates);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001498
1499 // -------------Adjust loop latches-----------
1500 if (InnerLoopLatchBI->getSuccessor(0) == InnerLoopHeader)
1501 InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(1);
1502 else
1503 InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(0);
1504
Florian Hahnc6296fe2018-02-14 13:13:15 +00001505 updateSuccessor(InnerLoopLatchPredecessorBI, InnerLoopLatch,
1506 InnerLoopLatchSuccessor, DTUpdates);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001507
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001508
Karthik Bhat88db86d2015-03-06 10:11:25 +00001509 if (OuterLoopLatchBI->getSuccessor(0) == OuterLoopHeader)
1510 OuterLoopLatchSuccessor = OuterLoopLatchBI->getSuccessor(1);
1511 else
1512 OuterLoopLatchSuccessor = OuterLoopLatchBI->getSuccessor(0);
1513
Florian Hahnc6296fe2018-02-14 13:13:15 +00001514 updateSuccessor(InnerLoopLatchBI, InnerLoopLatchSuccessor,
1515 OuterLoopLatchSuccessor, DTUpdates);
1516 updateSuccessor(OuterLoopLatchBI, OuterLoopLatchSuccessor, InnerLoopLatch,
1517 DTUpdates);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001518
Florian Hahnc6296fe2018-02-14 13:13:15 +00001519 DT->applyUpdates(DTUpdates);
Florian Hahn831a7572018-04-05 09:48:45 +00001520 restructureLoops(OuterLoop, InnerLoop, InnerLoopPreHeader,
1521 OuterLoopPreHeader);
1522
Florian Hahn11b2f4f2019-05-26 23:38:25 +00001523 moveLCSSAPhis(InnerLoopLatchSuccessor, InnerLoopHeader, InnerLoopLatch,
1524 OuterLoopHeader, OuterLoopLatch, InnerLoop->getExitBlock());
Florian Hahn6feb6372018-09-26 19:34:25 +00001525 // For PHIs in the exit block of the outer loop, outer's latch has been
1526 // replaced by Inners'.
Roman Lebedev1a1b9222019-05-05 18:59:39 +00001527 OuterLoopLatchSuccessor->replacePhiUsesWith(OuterLoopLatch, InnerLoopLatch);
Florian Hahn6feb6372018-09-26 19:34:25 +00001528
Florian Hahna684a992018-11-08 20:44:19 +00001529 // Now update the reduction PHIs in the inner and outer loop headers.
1530 SmallVector<PHINode *, 4> InnerLoopPHIs, OuterLoopPHIs;
1531 for (PHINode &PHI : drop_begin(InnerLoopHeader->phis(), 1))
1532 InnerLoopPHIs.push_back(cast<PHINode>(&PHI));
1533 for (PHINode &PHI : drop_begin(OuterLoopHeader->phis(), 1))
1534 OuterLoopPHIs.push_back(cast<PHINode>(&PHI));
1535
1536 auto &OuterInnerReductions = LIL.getOuterInnerReductions();
1537 (void)OuterInnerReductions;
1538
1539 // Now move the remaining reduction PHIs from outer to inner loop header and
1540 // vice versa. The PHI nodes must be part of a reduction across the inner and
1541 // outer loop and all the remains to do is and updating the incoming blocks.
1542 for (PHINode *PHI : OuterLoopPHIs) {
1543 PHI->moveBefore(InnerLoopHeader->getFirstNonPHI());
1544 assert(OuterInnerReductions.find(PHI) != OuterInnerReductions.end() &&
1545 "Expected a reduction PHI node");
1546 }
1547 for (PHINode *PHI : InnerLoopPHIs) {
1548 PHI->moveBefore(OuterLoopHeader->getFirstNonPHI());
1549 assert(OuterInnerReductions.find(PHI) != OuterInnerReductions.end() &&
1550 "Expected a reduction PHI node");
1551 }
Florian Hahnd8fcf0d2018-06-19 08:03:24 +00001552
1553 // Update the incoming blocks for moved PHI nodes.
Roman Lebedev1a1b9222019-05-05 18:59:39 +00001554 OuterLoopHeader->replacePhiUsesWith(InnerLoopPreHeader, OuterLoopPreHeader);
1555 OuterLoopHeader->replacePhiUsesWith(InnerLoopLatch, OuterLoopLatch);
1556 InnerLoopHeader->replacePhiUsesWith(OuterLoopPreHeader, InnerLoopPreHeader);
1557 InnerLoopHeader->replacePhiUsesWith(OuterLoopLatch, InnerLoopLatch);
Florian Hahnd8fcf0d2018-06-19 08:03:24 +00001558
Karthik Bhat88db86d2015-03-06 10:11:25 +00001559 return true;
1560}
Karthik Bhat88db86d2015-03-06 10:11:25 +00001561
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +00001562void LoopInterchangeTransform::adjustLoopPreheaders() {
Karthik Bhat88db86d2015-03-06 10:11:25 +00001563 // We have interchanged the preheaders so we need to interchange the data in
1564 // the preheader as well.
1565 // This is because the content of inner preheader was previously executed
1566 // inside the outer loop.
1567 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader();
1568 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
1569 BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
1570 BranchInst *InnerTermBI =
1571 cast<BranchInst>(InnerLoopPreHeader->getTerminator());
1572
Karthik Bhat88db86d2015-03-06 10:11:25 +00001573 // These instructions should now be executed inside the loop.
1574 // Move instruction into a new block after outer header.
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001575 moveBBContents(InnerLoopPreHeader, OuterLoopHeader->getTerminator());
Karthik Bhat88db86d2015-03-06 10:11:25 +00001576 // These instructions were not executed previously in the loop so move them to
1577 // the older inner loop preheader.
Benjamin Kramer79442922015-03-06 18:59:14 +00001578 moveBBContents(OuterLoopPreHeader, InnerTermBI);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001579}
1580
1581bool LoopInterchangeTransform::adjustLoopLinks() {
Karthik Bhat88db86d2015-03-06 10:11:25 +00001582 // Adjust all branches in the inner and outer loop.
1583 bool Changed = adjustLoopBranches();
1584 if (Changed)
1585 adjustLoopPreheaders();
1586 return Changed;
1587}
1588
1589char LoopInterchange::ID = 0;
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +00001590
Karthik Bhat88db86d2015-03-06 10:11:25 +00001591INITIALIZE_PASS_BEGIN(LoopInterchange, "loop-interchange",
1592 "Interchanges loops for cache reuse", false, false)
Florian Hahn8600fee2018-10-01 09:59:48 +00001593INITIALIZE_PASS_DEPENDENCY(LoopPass)
Chandler Carruth49c22192016-05-12 22:19:39 +00001594INITIALIZE_PASS_DEPENDENCY(DependenceAnalysisWrapperPass)
Florian Hahnad993522017-07-15 13:13:19 +00001595INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
Karthik Bhat88db86d2015-03-06 10:11:25 +00001596
1597INITIALIZE_PASS_END(LoopInterchange, "loop-interchange",
1598 "Interchanges loops for cache reuse", false, false)
1599
1600Pass *llvm::createLoopInterchangePass() { return new LoopInterchange(); }