blob: c8678ddb266b826949f729fb92644a0d0f6b05b6 [file] [log] [blame]
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +00001//===- LoopInterchange.cpp - Loop interchange pass-------------------------===//
Karthik Bhat88db86d2015-03-06 10:11:25 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This Pass handles loop interchange transform.
11// This pass interchanges loops to provide a more cache-friendly memory access
12// patterns.
13//
14//===----------------------------------------------------------------------===//
15
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000016#include "llvm/ADT/STLExtras.h"
Karthik Bhat88db86d2015-03-06 10:11:25 +000017#include "llvm/ADT/SmallVector.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/AliasAnalysis.h"
Karthik Bhat88db86d2015-03-06 10:11:25 +000020#include "llvm/Analysis/DependenceAnalysis.h"
21#include "llvm/Analysis/LoopInfo.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"
Karthik Bhat88db86d2015-03-06 10:11:25 +000043#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000044#include "llvm/Transforms/Utils/LoopUtils.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000045#include <cassert>
46#include <utility>
47#include <vector>
Davide Italiano9d8f6f82017-01-29 01:55:24 +000048
Karthik Bhat88db86d2015-03-06 10:11:25 +000049using namespace llvm;
50
51#define DEBUG_TYPE "loop-interchange"
52
Chad Rosier72431892016-09-14 17:07:13 +000053static cl::opt<int> LoopInterchangeCostThreshold(
54 "loop-interchange-threshold", cl::init(0), cl::Hidden,
55 cl::desc("Interchange if you gain more than this number"));
56
Karthik Bhat88db86d2015-03-06 10:11:25 +000057namespace {
58
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000059using LoopVector = SmallVector<Loop *, 8>;
Karthik Bhat88db86d2015-03-06 10:11:25 +000060
61// TODO: Check if we can use a sparse matrix here.
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000062using CharMatrix = std::vector<std::vector<char>>;
63
64} // end anonymous namespace
Karthik Bhat88db86d2015-03-06 10:11:25 +000065
66// Maximum number of dependencies that can be handled in the dependency matrix.
67static const unsigned MaxMemInstrCount = 100;
68
69// Maximum loop depth supported.
70static const unsigned MaxLoopNestDepth = 10;
71
Karthik Bhat88db86d2015-03-06 10:11:25 +000072#ifdef DUMP_DEP_MATRICIES
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000073static void printDepMatrix(CharMatrix &DepMatrix) {
Florian Hahnf66efd62017-07-24 11:41:30 +000074 for (auto &Row : DepMatrix) {
75 for (auto D : Row)
76 DEBUG(dbgs() << D << " ");
Karthik Bhat88db86d2015-03-06 10:11:25 +000077 DEBUG(dbgs() << "\n");
78 }
79}
80#endif
81
Karthik Bhat8210fdf2015-04-23 04:51:44 +000082static bool populateDependencyMatrix(CharMatrix &DepMatrix, unsigned Level,
Chandler Carruth49c22192016-05-12 22:19:39 +000083 Loop *L, DependenceInfo *DI) {
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000084 using ValueVector = SmallVector<Value *, 16>;
85
Karthik Bhat88db86d2015-03-06 10:11:25 +000086 ValueVector MemInstr;
87
Karthik Bhat88db86d2015-03-06 10:11:25 +000088 // For each block.
Florian Hahnf66efd62017-07-24 11:41:30 +000089 for (BasicBlock *BB : L->blocks()) {
Karthik Bhat88db86d2015-03-06 10:11:25 +000090 // Scan the BB and collect legal loads and stores.
Florian Hahnf66efd62017-07-24 11:41:30 +000091 for (Instruction &I : *BB) {
Chad Rosier09c11092016-09-13 12:56:04 +000092 if (!isa<Instruction>(I))
Karthik Bhat88db86d2015-03-06 10:11:25 +000093 return false;
Florian Hahnf66efd62017-07-24 11:41:30 +000094 if (auto *Ld = dyn_cast<LoadInst>(&I)) {
Chad Rosier09c11092016-09-13 12:56:04 +000095 if (!Ld->isSimple())
96 return false;
Florian Hahnf66efd62017-07-24 11:41:30 +000097 MemInstr.push_back(&I);
98 } else if (auto *St = dyn_cast<StoreInst>(&I)) {
Chad Rosier09c11092016-09-13 12:56:04 +000099 if (!St->isSimple())
100 return false;
Florian Hahnf66efd62017-07-24 11:41:30 +0000101 MemInstr.push_back(&I);
Chad Rosier09c11092016-09-13 12:56:04 +0000102 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000103 }
104 }
105
106 DEBUG(dbgs() << "Found " << MemInstr.size()
107 << " Loads and Stores to analyze\n");
108
109 ValueVector::iterator I, IE, J, JE;
110
111 for (I = MemInstr.begin(), IE = MemInstr.end(); I != IE; ++I) {
112 for (J = I, JE = MemInstr.end(); J != JE; ++J) {
113 std::vector<char> Dep;
Chad Rosier09c11092016-09-13 12:56:04 +0000114 Instruction *Src = cast<Instruction>(*I);
115 Instruction *Dst = cast<Instruction>(*J);
Chad Rosier90bcb912016-09-07 16:07:17 +0000116 if (Src == Dst)
Karthik Bhat88db86d2015-03-06 10:11:25 +0000117 continue;
Chad Rosier00eb8db2016-09-21 19:16:47 +0000118 // Ignore Input dependencies.
Chad Rosier90bcb912016-09-07 16:07:17 +0000119 if (isa<LoadInst>(Src) && isa<LoadInst>(Dst))
Karthik Bhat88db86d2015-03-06 10:11:25 +0000120 continue;
Chad Rosier00eb8db2016-09-21 19:16:47 +0000121 // Track Output, Flow, and Anti dependencies.
Chad Rosier90bcb912016-09-07 16:07:17 +0000122 if (auto D = DI->depends(Src, Dst, true)) {
Chad Rosier00eb8db2016-09-21 19:16:47 +0000123 assert(D->isOrdered() && "Expected an output, flow or anti dep.");
124 DEBUG(StringRef DepType =
125 D->isFlow() ? "flow" : D->isAnti() ? "anti" : "output";
126 dbgs() << "Found " << DepType
127 << " dependency between Src and Dst\n"
Chad Rosier90bcb912016-09-07 16:07:17 +0000128 << " Src:" << *Src << "\n Dst:" << *Dst << '\n');
Chad Rosier00eb8db2016-09-21 19:16:47 +0000129 unsigned Levels = D->getLevels();
130 char Direction;
131 for (unsigned II = 1; II <= Levels; ++II) {
132 const SCEV *Distance = D->getDistance(II);
133 const SCEVConstant *SCEVConst =
134 dyn_cast_or_null<SCEVConstant>(Distance);
135 if (SCEVConst) {
136 const ConstantInt *CI = SCEVConst->getValue();
137 if (CI->isNegative())
138 Direction = '<';
139 else if (CI->isZero())
140 Direction = '=';
141 else
142 Direction = '>';
143 Dep.push_back(Direction);
144 } else if (D->isScalar(II)) {
145 Direction = 'S';
146 Dep.push_back(Direction);
147 } else {
148 unsigned Dir = D->getDirection(II);
149 if (Dir == Dependence::DVEntry::LT ||
150 Dir == Dependence::DVEntry::LE)
151 Direction = '<';
152 else if (Dir == Dependence::DVEntry::GT ||
153 Dir == Dependence::DVEntry::GE)
154 Direction = '>';
155 else if (Dir == Dependence::DVEntry::EQ)
156 Direction = '=';
157 else
158 Direction = '*';
159 Dep.push_back(Direction);
160 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000161 }
Chad Rosier00eb8db2016-09-21 19:16:47 +0000162 while (Dep.size() != Level) {
163 Dep.push_back('I');
164 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000165
Chad Rosier00eb8db2016-09-21 19:16:47 +0000166 DepMatrix.push_back(Dep);
167 if (DepMatrix.size() > MaxMemInstrCount) {
168 DEBUG(dbgs() << "Cannot handle more than " << MaxMemInstrCount
169 << " dependencies inside loop\n");
170 return false;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000171 }
172 }
173 }
174 }
175
Karthik Bhat88db86d2015-03-06 10:11:25 +0000176 return true;
177}
178
179// A loop is moved from index 'from' to an index 'to'. Update the Dependence
180// matrix by exchanging the two columns.
Chad Rosierd18ea062016-09-13 13:00:29 +0000181static void interChangeDependencies(CharMatrix &DepMatrix, unsigned FromIndx,
182 unsigned ToIndx) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000183 unsigned numRows = DepMatrix.size();
184 for (unsigned i = 0; i < numRows; ++i) {
185 char TmpVal = DepMatrix[i][ToIndx];
186 DepMatrix[i][ToIndx] = DepMatrix[i][FromIndx];
187 DepMatrix[i][FromIndx] = TmpVal;
188 }
189}
190
191// Checks if outermost non '=','S'or'I' dependence in the dependence matrix is
192// '>'
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000193static bool isOuterMostDepPositive(CharMatrix &DepMatrix, unsigned Row,
194 unsigned Column) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000195 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.
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000206static bool containsNoDependence(CharMatrix &DepMatrix, unsigned Row,
207 unsigned Column) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000208 for (unsigned i = 0; i < Column; ++i) {
Chandler Carruthfca1ff02016-11-03 16:39:25 +0000209 if (DepMatrix[Row][i] != '=' && DepMatrix[Row][i] != 'S' &&
Karthik Bhat88db86d2015-03-06 10:11:25 +0000210 DepMatrix[Row][i] != 'I')
211 return false;
212 }
213 return true;
214}
215
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000216static bool validDepInterchange(CharMatrix &DepMatrix, unsigned Row,
217 unsigned OuterLoopId, char InnerDep,
218 char OuterDep) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000219 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.
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000251// [Theorem] A permutation of the loops in a perfect nest is legal if and only
Chad Rosier61683a22016-09-13 13:08:53 +0000252// 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.
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000254static bool isLegalToInterChangeLoops(CharMatrix &DepMatrix,
255 unsigned InnerLoopId,
256 unsigned OuterLoopId) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000257 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;
Chad Rosier61683a22016-09-13 13:08:53 +0000264 if (!validDepInterchange(DepMatrix, Row, OuterLoopId, InnerDep, OuterDep))
Karthik Bhat88db86d2015-03-06 10:11:25 +0000265 return false;
266 }
267 return true;
268}
269
270static void populateWorklist(Loop &L, SmallVector<LoopVector, 8> &V) {
Chad Rosierf5814f52016-09-07 15:56:59 +0000271 DEBUG(dbgs() << "Calling populateWorklist on Func: "
272 << L.getHeader()->getParent()->getName() << " Loop: %"
273 << L.getHeader()->getName() << '\n');
Karthik Bhat88db86d2015-03-06 10:11:25 +0000274 LoopVector LoopList;
275 Loop *CurrentLoop = &L;
Benjamin Kramere448b5b2015-07-13 17:21:14 +0000276 const std::vector<Loop *> *Vec = &CurrentLoop->getSubLoops();
277 while (!Vec->empty()) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000278 // The current loop has multiple subloops in it hence it is not tightly
279 // nested.
280 // Discard all loops above it added into Worklist.
Benjamin Kramere448b5b2015-07-13 17:21:14 +0000281 if (Vec->size() != 1) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000282 LoopList.clear();
283 return;
284 }
285 LoopList.push_back(CurrentLoop);
Benjamin Kramere448b5b2015-07-13 17:21:14 +0000286 CurrentLoop = Vec->front();
287 Vec = &CurrentLoop->getSubLoops();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000288 }
289 LoopList.push_back(CurrentLoop);
Benjamin Kramere448b5b2015-07-13 17:21:14 +0000290 V.push_back(std::move(LoopList));
Karthik Bhat88db86d2015-03-06 10:11:25 +0000291}
292
293static PHINode *getInductionVariable(Loop *L, ScalarEvolution *SE) {
294 PHINode *InnerIndexVar = L->getCanonicalInductionVariable();
295 if (InnerIndexVar)
296 return InnerIndexVar;
297 if (L->getLoopLatch() == nullptr || L->getLoopPredecessor() == nullptr)
298 return nullptr;
299 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
300 PHINode *PhiVar = cast<PHINode>(I);
301 Type *PhiTy = PhiVar->getType();
302 if (!PhiTy->isIntegerTy() && !PhiTy->isFloatingPointTy() &&
303 !PhiTy->isPointerTy())
304 return nullptr;
305 const SCEVAddRecExpr *AddRec =
306 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(PhiVar));
307 if (!AddRec || !AddRec->isAffine())
308 continue;
309 const SCEV *Step = AddRec->getStepRecurrence(*SE);
Chad Rosierf7c76f92016-09-21 13:28:41 +0000310 if (!isa<SCEVConstant>(Step))
Karthik Bhat88db86d2015-03-06 10:11:25 +0000311 continue;
312 // Found the induction variable.
313 // FIXME: Handle loops with more than one induction variable. Note that,
314 // currently, legality makes sure we have only one induction variable.
315 return PhiVar;
316 }
317 return nullptr;
318}
319
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000320namespace {
321
Karthik Bhat88db86d2015-03-06 10:11:25 +0000322/// LoopInterchangeLegality checks if it is legal to interchange the loop.
323class LoopInterchangeLegality {
324public:
325 LoopInterchangeLegality(Loop *Outer, Loop *Inner, ScalarEvolution *SE,
Florian Hahnad993522017-07-15 13:13:19 +0000326 LoopInfo *LI, DominatorTree *DT, bool PreserveLCSSA,
327 OptimizationRemarkEmitter *ORE)
Justin Bogner843fb202015-12-15 19:40:57 +0000328 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), LI(LI), DT(DT),
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000329 PreserveLCSSA(PreserveLCSSA), 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
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000341 bool hasInnerLoopReduction() { return InnerLoopHasReduction; }
342
Karthik Bhat88db86d2015-03-06 10:11:25 +0000343private:
344 bool tightlyNested(Loop *Outer, Loop *Inner);
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000345 bool containsUnsafeInstructionsInHeader(BasicBlock *BB);
346 bool areAllUsesReductions(Instruction *Ins, Loop *L);
347 bool containsUnsafeInstructionsInLatch(BasicBlock *BB);
348 bool findInductionAndReductions(Loop *L,
349 SmallVector<PHINode *, 8> &Inductions,
350 SmallVector<PHINode *, 8> &Reductions);
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000351
Karthik Bhat88db86d2015-03-06 10:11:25 +0000352 Loop *OuterLoop;
353 Loop *InnerLoop;
354
Karthik Bhat88db86d2015-03-06 10:11:25 +0000355 ScalarEvolution *SE;
Justin Bogner843fb202015-12-15 19:40:57 +0000356 LoopInfo *LI;
357 DominatorTree *DT;
358 bool PreserveLCSSA;
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000359
Florian Hahnad993522017-07-15 13:13:19 +0000360 /// Interface to emit optimization remarks.
361 OptimizationRemarkEmitter *ORE;
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000362
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000363 bool InnerLoopHasReduction = false;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000364};
365
366/// LoopInterchangeProfitability checks if it is profitable to interchange the
367/// loop.
368class LoopInterchangeProfitability {
369public:
Florian Hahnad993522017-07-15 13:13:19 +0000370 LoopInterchangeProfitability(Loop *Outer, Loop *Inner, ScalarEvolution *SE,
371 OptimizationRemarkEmitter *ORE)
372 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), ORE(ORE) {}
Karthik Bhat88db86d2015-03-06 10:11:25 +0000373
Vikram TV74b41112015-12-09 05:16:24 +0000374 /// Check if the loop interchange is profitable.
Karthik Bhat88db86d2015-03-06 10:11:25 +0000375 bool isProfitable(unsigned InnerLoopId, unsigned OuterLoopId,
376 CharMatrix &DepMatrix);
377
378private:
379 int getInstrOrderCost();
380
381 Loop *OuterLoop;
382 Loop *InnerLoop;
383
384 /// Scev analysis.
385 ScalarEvolution *SE;
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000386
Florian Hahnad993522017-07-15 13:13:19 +0000387 /// Interface to emit optimization remarks.
388 OptimizationRemarkEmitter *ORE;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000389};
390
Vikram TV74b41112015-12-09 05:16:24 +0000391/// LoopInterchangeTransform interchanges the loop.
Karthik Bhat88db86d2015-03-06 10:11:25 +0000392class LoopInterchangeTransform {
393public:
394 LoopInterchangeTransform(Loop *Outer, Loop *Inner, ScalarEvolution *SE,
395 LoopInfo *LI, DominatorTree *DT,
Justin Bogner843fb202015-12-15 19:40:57 +0000396 BasicBlock *LoopNestExit,
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000397 bool InnerLoopContainsReductions)
Karthik Bhat88db86d2015-03-06 10:11:25 +0000398 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), LI(LI), DT(DT),
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000399 LoopExit(LoopNestExit),
400 InnerLoopHasReduction(InnerLoopContainsReductions) {}
Karthik Bhat88db86d2015-03-06 10:11:25 +0000401
402 /// Interchange OuterLoop and InnerLoop.
403 bool transform();
404 void restructureLoops(Loop *InnerLoop, Loop *OuterLoop);
405 void removeChildLoop(Loop *OuterLoop, Loop *InnerLoop);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000406
407private:
408 void splitInnerLoopLatch(Instruction *);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000409 void splitInnerLoopHeader();
410 bool adjustLoopLinks();
411 void adjustLoopPreheaders();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000412 bool adjustLoopBranches();
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000413 void updateIncomingBlock(BasicBlock *CurrBlock, BasicBlock *OldPred,
414 BasicBlock *NewPred);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000415
416 Loop *OuterLoop;
417 Loop *InnerLoop;
418
419 /// Scev analysis.
420 ScalarEvolution *SE;
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000421
Karthik Bhat88db86d2015-03-06 10:11:25 +0000422 LoopInfo *LI;
423 DominatorTree *DT;
424 BasicBlock *LoopExit;
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000425 bool InnerLoopHasReduction;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000426};
427
Vikram TV74b41112015-12-09 05:16:24 +0000428// Main LoopInterchange Pass.
Karthik Bhat88db86d2015-03-06 10:11:25 +0000429struct LoopInterchange : public FunctionPass {
430 static char ID;
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000431 ScalarEvolution *SE = nullptr;
432 LoopInfo *LI = nullptr;
433 DependenceInfo *DI = nullptr;
434 DominatorTree *DT = nullptr;
Justin Bogner843fb202015-12-15 19:40:57 +0000435 bool PreserveLCSSA;
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000436
Florian Hahnad993522017-07-15 13:13:19 +0000437 /// Interface to emit optimization remarks.
438 OptimizationRemarkEmitter *ORE;
439
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000440 LoopInterchange() : FunctionPass(ID) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000441 initializeLoopInterchangePass(*PassRegistry::getPassRegistry());
442 }
443
444 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000445 AU.addRequired<ScalarEvolutionWrapperPass>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000446 AU.addRequired<AAResultsWrapperPass>();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000447 AU.addRequired<DominatorTreeWrapperPass>();
448 AU.addRequired<LoopInfoWrapperPass>();
Chandler Carruth49c22192016-05-12 22:19:39 +0000449 AU.addRequired<DependenceAnalysisWrapperPass>();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000450 AU.addRequiredID(LoopSimplifyID);
451 AU.addRequiredID(LCSSAID);
Florian Hahnad993522017-07-15 13:13:19 +0000452 AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
Florian Hahnc6296fe2018-02-14 13:13:15 +0000453
454 AU.addPreserved<DominatorTreeWrapperPass>();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000455 }
456
457 bool runOnFunction(Function &F) override {
Andrew Kaylor50271f72016-05-03 22:32:30 +0000458 if (skipFunction(F))
459 return false;
460
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000461 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000462 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Chandler Carruth49c22192016-05-12 22:19:39 +0000463 DI = &getAnalysis<DependenceAnalysisWrapperPass>().getDI();
Florian Hahnc6296fe2018-02-14 13:13:15 +0000464 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Florian Hahnad993522017-07-15 13:13:19 +0000465 ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
Justin Bogner843fb202015-12-15 19:40:57 +0000466 PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
467
Karthik Bhat88db86d2015-03-06 10:11:25 +0000468 // Build up a worklist of loop pairs to analyze.
469 SmallVector<LoopVector, 8> Worklist;
470
471 for (Loop *L : *LI)
472 populateWorklist(*L, Worklist);
473
Chad Rosiera4c42462016-09-12 13:24:47 +0000474 DEBUG(dbgs() << "Worklist size = " << Worklist.size() << "\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000475 bool Changed = true;
476 while (!Worklist.empty()) {
477 LoopVector LoopList = Worklist.pop_back_val();
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000478 Changed = processLoopList(LoopList, F);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000479 }
480 return Changed;
481 }
482
483 bool isComputableLoopNest(LoopVector LoopList) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000484 for (Loop *L : LoopList) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000485 const SCEV *ExitCountOuter = SE->getBackedgeTakenCount(L);
486 if (ExitCountOuter == SE->getCouldNotCompute()) {
Chad Rosierf7c76f92016-09-21 13:28:41 +0000487 DEBUG(dbgs() << "Couldn't compute backedge count\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000488 return false;
489 }
490 if (L->getNumBackEdges() != 1) {
491 DEBUG(dbgs() << "NumBackEdges is not equal to 1\n");
492 return false;
493 }
494 if (!L->getExitingBlock()) {
Chad Rosierf7c76f92016-09-21 13:28:41 +0000495 DEBUG(dbgs() << "Loop doesn't have unique exit block\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000496 return false;
497 }
498 }
499 return true;
500 }
501
Benjamin Kramerc321e532016-06-08 19:09:22 +0000502 unsigned selectLoopForInterchange(const LoopVector &LoopList) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000503 // TODO: Add a better heuristic to select the loop to be interchanged based
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000504 // on the dependence matrix. Currently we select the innermost loop.
Karthik Bhat88db86d2015-03-06 10:11:25 +0000505 return LoopList.size() - 1;
506 }
507
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000508 bool processLoopList(LoopVector LoopList, Function &F) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000509 bool Changed = false;
Chad Rosier7ea0d392016-09-13 13:30:30 +0000510 unsigned LoopNestDepth = LoopList.size();
511 if (LoopNestDepth < 2) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000512 DEBUG(dbgs() << "Loop doesn't contain minimum nesting level.\n");
513 return false;
514 }
Chad Rosier7ea0d392016-09-13 13:30:30 +0000515 if (LoopNestDepth > MaxLoopNestDepth) {
516 DEBUG(dbgs() << "Cannot handle loops of depth greater than "
517 << MaxLoopNestDepth << "\n");
518 return false;
519 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000520 if (!isComputableLoopNest(LoopList)) {
Chad Rosiera4c42462016-09-12 13:24:47 +0000521 DEBUG(dbgs() << "Not valid loop candidate for interchange\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000522 return false;
523 }
Chad Rosier7ea0d392016-09-13 13:30:30 +0000524
525 DEBUG(dbgs() << "Processing LoopList of size = " << LoopNestDepth << "\n");
526
527 CharMatrix DependencyMatrix;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000528 Loop *OuterMostLoop = *(LoopList.begin());
Chad Rosier7ea0d392016-09-13 13:30:30 +0000529 if (!populateDependencyMatrix(DependencyMatrix, LoopNestDepth,
Chandler Carruth49c22192016-05-12 22:19:39 +0000530 OuterMostLoop, DI)) {
Chad Rosierf7c76f92016-09-21 13:28:41 +0000531 DEBUG(dbgs() << "Populating dependency matrix failed\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000532 return false;
533 }
534#ifdef DUMP_DEP_MATRICIES
Chad Rosier58ede272016-09-14 16:43:19 +0000535 DEBUG(dbgs() << "Dependence before interchange\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000536 printDepMatrix(DependencyMatrix);
537#endif
538
539 BasicBlock *OuterMostLoopLatch = OuterMostLoop->getLoopLatch();
540 BranchInst *OuterMostLoopLatchBI =
541 dyn_cast<BranchInst>(OuterMostLoopLatch->getTerminator());
Florian Hahn1f95ef12018-02-13 10:02:52 +0000542 if (!OuterMostLoopLatchBI || OuterMostLoopLatchBI->getNumSuccessors() != 2)
Karthik Bhat88db86d2015-03-06 10:11:25 +0000543 return false;
544
545 // Since we currently do not handle LCSSA PHI's any failure in loop
546 // condition will now branch to LoopNestExit.
547 // TODO: This should be removed once we handle LCSSA PHI nodes.
548
549 // Get the Outermost loop exit.
550 BasicBlock *LoopNestExit;
551 if (OuterMostLoopLatchBI->getSuccessor(0) == OuterMostLoop->getHeader())
552 LoopNestExit = OuterMostLoopLatchBI->getSuccessor(1);
553 else
554 LoopNestExit = OuterMostLoopLatchBI->getSuccessor(0);
555
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000556 if (isa<PHINode>(LoopNestExit->begin())) {
557 DEBUG(dbgs() << "PHI Nodes in loop nest exit is not handled for now "
558 "since on failure all loops branch to loop nest exit.\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000559 return false;
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000560 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000561
562 unsigned SelecLoopId = selectLoopForInterchange(LoopList);
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000563 // Move the selected loop outwards to the best possible position.
Karthik Bhat88db86d2015-03-06 10:11:25 +0000564 for (unsigned i = SelecLoopId; i > 0; i--) {
565 bool Interchanged =
566 processLoop(LoopList, i, i - 1, LoopNestExit, DependencyMatrix);
567 if (!Interchanged)
568 return Changed;
569 // Loops interchanged reflect the same in LoopList
Benjamin Kramer79442922015-03-06 18:59:14 +0000570 std::swap(LoopList[i - 1], LoopList[i]);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000571
572 // Update the DependencyMatrix
Chad Rosierd18ea062016-09-13 13:00:29 +0000573 interChangeDependencies(DependencyMatrix, i, i - 1);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000574#ifdef DUMP_DEP_MATRICIES
Chad Rosier58ede272016-09-14 16:43:19 +0000575 DEBUG(dbgs() << "Dependence after interchange\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000576 printDepMatrix(DependencyMatrix);
577#endif
578 Changed |= Interchanged;
579 }
580 return Changed;
581 }
582
583 bool processLoop(LoopVector LoopList, unsigned InnerLoopId,
584 unsigned OuterLoopId, BasicBlock *LoopNestExit,
585 std::vector<std::vector<char>> &DependencyMatrix) {
Chad Rosier13bc0d192016-09-07 18:15:12 +0000586 DEBUG(dbgs() << "Processing Inner Loop Id = " << InnerLoopId
Karthik Bhat88db86d2015-03-06 10:11:25 +0000587 << " and OuterLoopId = " << OuterLoopId << "\n");
588 Loop *InnerLoop = LoopList[InnerLoopId];
589 Loop *OuterLoop = LoopList[OuterLoopId];
590
Justin Bogner843fb202015-12-15 19:40:57 +0000591 LoopInterchangeLegality LIL(OuterLoop, InnerLoop, SE, LI, DT,
Florian Hahnad993522017-07-15 13:13:19 +0000592 PreserveLCSSA, ORE);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000593 if (!LIL.canInterchangeLoops(InnerLoopId, OuterLoopId, DependencyMatrix)) {
594 DEBUG(dbgs() << "Not interchanging Loops. Cannot prove legality\n");
595 return false;
596 }
597 DEBUG(dbgs() << "Loops are legal to interchange\n");
Florian Hahnad993522017-07-15 13:13:19 +0000598 LoopInterchangeProfitability LIP(OuterLoop, InnerLoop, SE, ORE);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000599 if (!LIP.isProfitable(InnerLoopId, OuterLoopId, DependencyMatrix)) {
Chad Rosierf7c76f92016-09-21 13:28:41 +0000600 DEBUG(dbgs() << "Interchanging loops not profitable\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000601 return false;
602 }
603
Vivek Pandya95906582017-10-11 17:12:59 +0000604 ORE->emit([&]() {
605 return OptimizationRemark(DEBUG_TYPE, "Interchanged",
606 InnerLoop->getStartLoc(),
607 InnerLoop->getHeader())
608 << "Loop interchanged with enclosing loop.";
609 });
Florian Hahnad993522017-07-15 13:13:19 +0000610
Justin Bogner843fb202015-12-15 19:40:57 +0000611 LoopInterchangeTransform LIT(OuterLoop, InnerLoop, SE, LI, DT,
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000612 LoopNestExit, LIL.hasInnerLoopReduction());
Karthik Bhat88db86d2015-03-06 10:11:25 +0000613 LIT.transform();
614 DEBUG(dbgs() << "Loops interchanged\n");
615 return true;
616 }
617};
618
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000619} // end anonymous namespace
620
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000621bool LoopInterchangeLegality::areAllUsesReductions(Instruction *Ins, Loop *L) {
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000622 return llvm::none_of(Ins->users(), [=](User *U) -> bool {
David Majnemer0a16c222016-08-11 21:15:00 +0000623 auto *UserIns = dyn_cast<PHINode>(U);
Tyler Nowicki0a913102015-06-16 18:07:34 +0000624 RecurrenceDescriptor RD;
625 return !UserIns || !RecurrenceDescriptor::isReductionPHI(UserIns, L, RD);
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000626 });
627}
Karthik Bhat88db86d2015-03-06 10:11:25 +0000628
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000629bool LoopInterchangeLegality::containsUnsafeInstructionsInHeader(
630 BasicBlock *BB) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000631 for (auto I = BB->begin(), E = BB->end(); I != E; ++I) {
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000632 // Load corresponding to reduction PHI's are safe while concluding if
633 // tightly nested.
634 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
635 if (!areAllUsesReductions(L, InnerLoop))
636 return true;
637 } else if (I->mayHaveSideEffects() || I->mayReadFromMemory())
638 return true;
639 }
640 return false;
641}
642
643bool LoopInterchangeLegality::containsUnsafeInstructionsInLatch(
644 BasicBlock *BB) {
645 for (auto I = BB->begin(), E = BB->end(); I != E; ++I) {
646 // Stores corresponding to reductions are safe while concluding if tightly
647 // nested.
648 if (StoreInst *L = dyn_cast<StoreInst>(I)) {
Chad Rosierf7c76f92016-09-21 13:28:41 +0000649 if (!isa<PHINode>(L->getOperand(0)))
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000650 return true;
651 } else if (I->mayHaveSideEffects() || I->mayReadFromMemory())
Karthik Bhat88db86d2015-03-06 10:11:25 +0000652 return true;
653 }
654 return false;
655}
656
657bool LoopInterchangeLegality::tightlyNested(Loop *OuterLoop, Loop *InnerLoop) {
658 BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
659 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
660 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch();
661
Chad Rosierf7c76f92016-09-21 13:28:41 +0000662 DEBUG(dbgs() << "Checking if loops are tightly nested\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000663
664 // A perfectly nested loop will not have any branch in between the outer and
665 // inner block i.e. outer header will branch to either inner preheader and
666 // outerloop latch.
Chad Rosierf7c76f92016-09-21 13:28:41 +0000667 BranchInst *OuterLoopHeaderBI =
Karthik Bhat88db86d2015-03-06 10:11:25 +0000668 dyn_cast<BranchInst>(OuterLoopHeader->getTerminator());
Chad Rosierf7c76f92016-09-21 13:28:41 +0000669 if (!OuterLoopHeaderBI)
Karthik Bhat88db86d2015-03-06 10:11:25 +0000670 return false;
Chad Rosierf7c76f92016-09-21 13:28:41 +0000671
Florian Hahnf66efd62017-07-24 11:41:30 +0000672 for (BasicBlock *Succ : OuterLoopHeaderBI->successors())
673 if (Succ != InnerLoopPreHeader && Succ != OuterLoopLatch)
Karthik Bhat88db86d2015-03-06 10:11:25 +0000674 return false;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000675
Chad Rosierf7c76f92016-09-21 13:28:41 +0000676 DEBUG(dbgs() << "Checking instructions in Loop header and Loop latch\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000677 // We do not have any basic block in between now make sure the outer header
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000678 // and outer loop latch doesn't contain any unsafe instructions.
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000679 if (containsUnsafeInstructionsInHeader(OuterLoopHeader) ||
680 containsUnsafeInstructionsInLatch(OuterLoopLatch))
Karthik Bhat88db86d2015-03-06 10:11:25 +0000681 return false;
682
Chad Rosierf7c76f92016-09-21 13:28:41 +0000683 DEBUG(dbgs() << "Loops are perfectly nested\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000684 // We have a perfect loop nest.
685 return true;
686}
687
Karthik Bhat88db86d2015-03-06 10:11:25 +0000688bool LoopInterchangeLegality::isLoopStructureUnderstood(
689 PHINode *InnerInduction) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000690 unsigned Num = InnerInduction->getNumOperands();
691 BasicBlock *InnerLoopPreheader = InnerLoop->getLoopPreheader();
692 for (unsigned i = 0; i < Num; ++i) {
693 Value *Val = InnerInduction->getOperand(i);
694 if (isa<Constant>(Val))
695 continue;
696 Instruction *I = dyn_cast<Instruction>(Val);
697 if (!I)
698 return false;
699 // TODO: Handle triangular loops.
700 // e.g. for(int i=0;i<N;i++)
701 // for(int j=i;j<N;j++)
702 unsigned IncomBlockIndx = PHINode::getIncomingValueNumForOperand(i);
703 if (InnerInduction->getIncomingBlock(IncomBlockIndx) ==
704 InnerLoopPreheader &&
705 !OuterLoop->isLoopInvariant(I)) {
706 return false;
707 }
708 }
709 return true;
710}
711
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000712bool LoopInterchangeLegality::findInductionAndReductions(
713 Loop *L, SmallVector<PHINode *, 8> &Inductions,
714 SmallVector<PHINode *, 8> &Reductions) {
715 if (!L->getLoopLatch() || !L->getLoopPredecessor())
716 return false;
717 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
Tyler Nowicki0a913102015-06-16 18:07:34 +0000718 RecurrenceDescriptor RD;
James Molloy1bbf15c2015-08-27 09:53:00 +0000719 InductionDescriptor ID;
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000720 PHINode *PHI = cast<PHINode>(I);
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000721 if (InductionDescriptor::isInductionPHI(PHI, L, SE, ID))
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000722 Inductions.push_back(PHI);
Tyler Nowicki0a913102015-06-16 18:07:34 +0000723 else if (RecurrenceDescriptor::isReductionPHI(PHI, L, RD))
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000724 Reductions.push_back(PHI);
725 else {
726 DEBUG(
727 dbgs() << "Failed to recognize PHI as an induction or reduction.\n");
728 return false;
729 }
730 }
731 return true;
732}
733
734static bool containsSafePHI(BasicBlock *Block, bool isOuterLoopExitBlock) {
735 for (auto I = Block->begin(); isa<PHINode>(I); ++I) {
736 PHINode *PHI = cast<PHINode>(I);
737 // Reduction lcssa phi will have only 1 incoming block that from loop latch.
738 if (PHI->getNumIncomingValues() > 1)
739 return false;
740 Instruction *Ins = dyn_cast<Instruction>(PHI->getIncomingValue(0));
741 if (!Ins)
742 return false;
743 // Incoming value for lcssa phi's in outer loop exit can only be inner loop
744 // exits lcssa phi else it would not be tightly nested.
745 if (!isa<PHINode>(Ins) && isOuterLoopExitBlock)
746 return false;
747 }
748 return true;
749}
750
751static BasicBlock *getLoopLatchExitBlock(BasicBlock *LatchBlock,
752 BasicBlock *LoopHeader) {
753 if (BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator())) {
Florian Hahnf66efd62017-07-24 11:41:30 +0000754 assert(BI->getNumSuccessors() == 2 &&
755 "Branch leaving loop latch must have 2 successors");
756 for (BasicBlock *Succ : BI->successors()) {
757 if (Succ == LoopHeader)
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000758 continue;
Florian Hahnf66efd62017-07-24 11:41:30 +0000759 return Succ;
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000760 }
761 }
762 return nullptr;
763}
764
Karthik Bhat88db86d2015-03-06 10:11:25 +0000765// This function indicates the current limitations in the transform as a result
766// of which we do not proceed.
767bool LoopInterchangeLegality::currentLimitations() {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000768 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
769 BasicBlock *InnerLoopHeader = InnerLoop->getHeader();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000770 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
771 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch();
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000772 BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000773
774 PHINode *InnerInductionVar;
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000775 SmallVector<PHINode *, 8> Inductions;
776 SmallVector<PHINode *, 8> Reductions;
Florian Hahn4eeff392017-07-03 15:32:00 +0000777 if (!findInductionAndReductions(InnerLoop, Inductions, Reductions)) {
778 DEBUG(dbgs() << "Only inner loops with induction or reduction PHI nodes "
779 << "are supported currently.\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000780 ORE->emit([&]() {
781 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedPHIInner",
782 InnerLoop->getStartLoc(),
783 InnerLoop->getHeader())
784 << "Only inner loops with induction or reduction PHI nodes can be"
785 " interchange currently.";
786 });
Karthik Bhat88db86d2015-03-06 10:11:25 +0000787 return true;
Florian Hahn4eeff392017-07-03 15:32:00 +0000788 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000789
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000790 // TODO: Currently we handle only loops with 1 induction variable.
791 if (Inductions.size() != 1) {
792 DEBUG(dbgs() << "We currently only support loops with 1 induction variable."
793 << "Failed to interchange due to current limitation\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000794 ORE->emit([&]() {
795 return OptimizationRemarkMissed(DEBUG_TYPE, "MultiInductionInner",
796 InnerLoop->getStartLoc(),
797 InnerLoop->getHeader())
798 << "Only inner loops with 1 induction variable can be "
799 "interchanged currently.";
800 });
Karthik Bhat88db86d2015-03-06 10:11:25 +0000801 return true;
802 }
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000803 if (Reductions.size() > 0)
804 InnerLoopHasReduction = true;
805
806 InnerInductionVar = Inductions.pop_back_val();
807 Reductions.clear();
Florian Hahn4eeff392017-07-03 15:32:00 +0000808 if (!findInductionAndReductions(OuterLoop, Inductions, Reductions)) {
809 DEBUG(dbgs() << "Only outer loops with induction or reduction PHI nodes "
810 << "are supported currently.\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000811 ORE->emit([&]() {
812 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedPHIOuter",
813 OuterLoop->getStartLoc(),
814 OuterLoop->getHeader())
815 << "Only outer loops with induction or reduction PHI nodes can be"
816 " interchanged currently.";
817 });
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000818 return true;
Florian Hahn4eeff392017-07-03 15:32:00 +0000819 }
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000820
821 // Outer loop cannot have reduction because then loops will not be tightly
822 // nested.
Florian Hahn4eeff392017-07-03 15:32:00 +0000823 if (!Reductions.empty()) {
824 DEBUG(dbgs() << "Outer loops with reductions are not supported "
825 << "currently.\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000826 ORE->emit([&]() {
827 return OptimizationRemarkMissed(DEBUG_TYPE, "ReductionsOuter",
828 OuterLoop->getStartLoc(),
829 OuterLoop->getHeader())
830 << "Outer loops with reductions cannot be interchangeed "
831 "currently.";
832 });
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000833 return true;
Florian Hahn4eeff392017-07-03 15:32:00 +0000834 }
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000835 // TODO: Currently we handle only loops with 1 induction variable.
Florian Hahn4eeff392017-07-03 15:32:00 +0000836 if (Inductions.size() != 1) {
837 DEBUG(dbgs() << "Loops with more than 1 induction variables are not "
838 << "supported currently.\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000839 ORE->emit([&]() {
840 return OptimizationRemarkMissed(DEBUG_TYPE, "MultiIndutionOuter",
841 OuterLoop->getStartLoc(),
842 OuterLoop->getHeader())
843 << "Only outer loops with 1 induction variable can be "
844 "interchanged currently.";
845 });
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000846 return true;
Florian Hahn4eeff392017-07-03 15:32:00 +0000847 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000848
849 // TODO: Triangular loops are not handled for now.
850 if (!isLoopStructureUnderstood(InnerInductionVar)) {
851 DEBUG(dbgs() << "Loop structure not understood by pass\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000852 ORE->emit([&]() {
853 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedStructureInner",
854 InnerLoop->getStartLoc(),
855 InnerLoop->getHeader())
856 << "Inner loop structure not understood currently.";
857 });
Karthik Bhat88db86d2015-03-06 10:11:25 +0000858 return true;
859 }
860
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000861 // TODO: We only handle LCSSA PHI's corresponding to reduction for now.
862 BasicBlock *LoopExitBlock =
863 getLoopLatchExitBlock(OuterLoopLatch, OuterLoopHeader);
Florian Hahn4eeff392017-07-03 15:32:00 +0000864 if (!LoopExitBlock || !containsSafePHI(LoopExitBlock, true)) {
865 DEBUG(dbgs() << "Can only handle LCSSA PHIs in outer loops currently.\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000866 ORE->emit([&]() {
867 return OptimizationRemarkMissed(DEBUG_TYPE, "NoLCSSAPHIOuter",
868 OuterLoop->getStartLoc(),
869 OuterLoop->getHeader())
870 << "Only outer loops with LCSSA PHIs can be interchange "
871 "currently.";
872 });
Karthik Bhat88db86d2015-03-06 10:11:25 +0000873 return true;
Florian Hahn4eeff392017-07-03 15:32:00 +0000874 }
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000875
876 LoopExitBlock = getLoopLatchExitBlock(InnerLoopLatch, InnerLoopHeader);
Florian Hahn4eeff392017-07-03 15:32:00 +0000877 if (!LoopExitBlock || !containsSafePHI(LoopExitBlock, false)) {
878 DEBUG(dbgs() << "Can only handle LCSSA PHIs in inner loops currently.\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000879 ORE->emit([&]() {
880 return OptimizationRemarkMissed(DEBUG_TYPE, "NoLCSSAPHIOuterInner",
881 InnerLoop->getStartLoc(),
882 InnerLoop->getHeader())
883 << "Only inner loops with LCSSA PHIs can be interchange "
884 "currently.";
885 });
Karthik Bhat88db86d2015-03-06 10:11:25 +0000886 return true;
Florian Hahn4eeff392017-07-03 15:32:00 +0000887 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000888
889 // TODO: Current limitation: Since we split the inner loop latch at the point
890 // were induction variable is incremented (induction.next); We cannot have
891 // more than 1 user of induction.next since it would result in broken code
892 // after split.
893 // e.g.
894 // for(i=0;i<N;i++) {
895 // for(j = 0;j<M;j++) {
896 // A[j+1][i+2] = A[j][i]+k;
897 // }
898 // }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000899 Instruction *InnerIndexVarInc = nullptr;
900 if (InnerInductionVar->getIncomingBlock(0) == InnerLoopPreHeader)
901 InnerIndexVarInc =
902 dyn_cast<Instruction>(InnerInductionVar->getIncomingValue(1));
903 else
904 InnerIndexVarInc =
905 dyn_cast<Instruction>(InnerInductionVar->getIncomingValue(0));
906
Florian Hahn4eeff392017-07-03 15:32:00 +0000907 if (!InnerIndexVarInc) {
908 DEBUG(dbgs() << "Did not find an instruction to increment the induction "
909 << "variable.\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000910 ORE->emit([&]() {
911 return OptimizationRemarkMissed(DEBUG_TYPE, "NoIncrementInInner",
912 InnerLoop->getStartLoc(),
913 InnerLoop->getHeader())
914 << "The inner loop does not increment the induction variable.";
915 });
Pete Cooper11bd9582015-07-27 18:37:58 +0000916 return true;
Florian Hahn4eeff392017-07-03 15:32:00 +0000917 }
Pete Cooper11bd9582015-07-27 18:37:58 +0000918
Karthik Bhat88db86d2015-03-06 10:11:25 +0000919 // Since we split the inner loop latch on this induction variable. Make sure
920 // we do not have any instruction between the induction variable and branch
921 // instruction.
922
David Majnemerd7708772016-06-24 04:05:21 +0000923 bool FoundInduction = false;
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000924 for (const Instruction &I : llvm::reverse(*InnerLoopLatch)) {
Florian Hahncd783452017-08-25 16:52:29 +0000925 if (isa<BranchInst>(I) || isa<CmpInst>(I) || isa<TruncInst>(I) ||
926 isa<ZExtInst>(I))
Karthik Bhat88db86d2015-03-06 10:11:25 +0000927 continue;
Florian Hahn4eeff392017-07-03 15:32:00 +0000928
Karthik Bhat88db86d2015-03-06 10:11:25 +0000929 // We found an instruction. If this is not induction variable then it is not
930 // safe to split this loop latch.
Florian Hahn4eeff392017-07-03 15:32:00 +0000931 if (!I.isIdenticalTo(InnerIndexVarInc)) {
932 DEBUG(dbgs() << "Found unsupported instructions between induction "
933 << "variable increment and branch.\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000934 ORE->emit([&]() {
935 return OptimizationRemarkMissed(
936 DEBUG_TYPE, "UnsupportedInsBetweenInduction",
937 InnerLoop->getStartLoc(), InnerLoop->getHeader())
938 << "Found unsupported instruction between induction variable "
939 "increment and branch.";
940 });
Karthik Bhat88db86d2015-03-06 10:11:25 +0000941 return true;
Florian Hahn4eeff392017-07-03 15:32:00 +0000942 }
David Majnemerd7708772016-06-24 04:05:21 +0000943
944 FoundInduction = true;
945 break;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000946 }
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000947 // The loop latch ended and we didn't find the induction variable return as
Karthik Bhat88db86d2015-03-06 10:11:25 +0000948 // current limitation.
Florian Hahn4eeff392017-07-03 15:32:00 +0000949 if (!FoundInduction) {
950 DEBUG(dbgs() << "Did not find the induction variable.\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000951 ORE->emit([&]() {
952 return OptimizationRemarkMissed(DEBUG_TYPE, "NoIndutionVariable",
953 InnerLoop->getStartLoc(),
954 InnerLoop->getHeader())
955 << "Did not find the induction variable.";
956 });
Karthik Bhat88db86d2015-03-06 10:11:25 +0000957 return true;
Florian Hahn4eeff392017-07-03 15:32:00 +0000958 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000959 return false;
960}
961
962bool LoopInterchangeLegality::canInterchangeLoops(unsigned InnerLoopId,
963 unsigned OuterLoopId,
964 CharMatrix &DepMatrix) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000965 if (!isLegalToInterChangeLoops(DepMatrix, InnerLoopId, OuterLoopId)) {
966 DEBUG(dbgs() << "Failed interchange InnerLoopId = " << InnerLoopId
Chad Rosier58ede272016-09-14 16:43:19 +0000967 << " and OuterLoopId = " << OuterLoopId
968 << " due to dependence\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000969 ORE->emit([&]() {
970 return OptimizationRemarkMissed(DEBUG_TYPE, "Dependence",
971 InnerLoop->getStartLoc(),
972 InnerLoop->getHeader())
973 << "Cannot interchange loops due to dependences.";
974 });
Karthik Bhat88db86d2015-03-06 10:11:25 +0000975 return false;
976 }
977
Florian Hahn42840492017-07-31 09:00:52 +0000978 // Check if outer and inner loop contain legal instructions only.
979 for (auto *BB : OuterLoop->blocks())
980 for (Instruction &I : *BB)
981 if (CallInst *CI = dyn_cast<CallInst>(&I)) {
982 // readnone functions do not prevent interchanging.
983 if (CI->doesNotReadMemory())
984 continue;
985 DEBUG(dbgs() << "Loops with call instructions cannot be interchanged "
986 << "safely.");
987 return false;
988 }
989
Karthik Bhat88db86d2015-03-06 10:11:25 +0000990 // Create unique Preheaders if we already do not have one.
991 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader();
992 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
993
994 // Create a unique outer preheader -
995 // 1) If OuterLoop preheader is not present.
996 // 2) If OuterLoop Preheader is same as OuterLoop Header
997 // 3) If OuterLoop Preheader is same as Header of the previous loop.
998 // 4) If OuterLoop Preheader is Entry node.
999 if (!OuterLoopPreHeader || OuterLoopPreHeader == OuterLoop->getHeader() ||
1000 isa<PHINode>(OuterLoopPreHeader->begin()) ||
1001 !OuterLoopPreHeader->getUniquePredecessor()) {
Justin Bogner843fb202015-12-15 19:40:57 +00001002 OuterLoopPreHeader =
1003 InsertPreheaderForLoop(OuterLoop, DT, LI, PreserveLCSSA);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001004 }
1005
1006 if (!InnerLoopPreHeader || InnerLoopPreHeader == InnerLoop->getHeader() ||
1007 InnerLoopPreHeader == OuterLoop->getHeader()) {
Justin Bogner843fb202015-12-15 19:40:57 +00001008 InnerLoopPreHeader =
1009 InsertPreheaderForLoop(InnerLoop, DT, LI, PreserveLCSSA);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001010 }
1011
Karthik Bhat88db86d2015-03-06 10:11:25 +00001012 // TODO: The loops could not be interchanged due to current limitations in the
1013 // transform module.
1014 if (currentLimitations()) {
1015 DEBUG(dbgs() << "Not legal because of current transform limitation\n");
1016 return false;
1017 }
1018
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001019 // Check if the loops are tightly nested.
1020 if (!tightlyNested(OuterLoop, InnerLoop)) {
1021 DEBUG(dbgs() << "Loops not tightly nested\n");
Vivek Pandya95906582017-10-11 17:12:59 +00001022 ORE->emit([&]() {
1023 return OptimizationRemarkMissed(DEBUG_TYPE, "NotTightlyNested",
1024 InnerLoop->getStartLoc(),
1025 InnerLoop->getHeader())
1026 << "Cannot interchange loops because they are not tightly "
1027 "nested.";
1028 });
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001029 return false;
1030 }
1031
Karthik Bhat88db86d2015-03-06 10:11:25 +00001032 return true;
1033}
1034
1035int LoopInterchangeProfitability::getInstrOrderCost() {
1036 unsigned GoodOrder, BadOrder;
1037 BadOrder = GoodOrder = 0;
Florian Hahnf66efd62017-07-24 11:41:30 +00001038 for (BasicBlock *BB : InnerLoop->blocks()) {
1039 for (Instruction &Ins : *BB) {
Karthik Bhat88db86d2015-03-06 10:11:25 +00001040 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Ins)) {
1041 unsigned NumOp = GEP->getNumOperands();
1042 bool FoundInnerInduction = false;
1043 bool FoundOuterInduction = false;
1044 for (unsigned i = 0; i < NumOp; ++i) {
1045 const SCEV *OperandVal = SE->getSCEV(GEP->getOperand(i));
1046 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(OperandVal);
1047 if (!AR)
1048 continue;
1049
1050 // If we find the inner induction after an outer induction e.g.
1051 // for(int i=0;i<N;i++)
1052 // for(int j=0;j<N;j++)
1053 // A[i][j] = A[i-1][j-1]+k;
1054 // then it is a good order.
1055 if (AR->getLoop() == InnerLoop) {
1056 // We found an InnerLoop induction after OuterLoop induction. It is
1057 // a good order.
1058 FoundInnerInduction = true;
1059 if (FoundOuterInduction) {
1060 GoodOrder++;
1061 break;
1062 }
1063 }
1064 // If we find the outer induction after an inner induction e.g.
1065 // for(int i=0;i<N;i++)
1066 // for(int j=0;j<N;j++)
1067 // A[j][i] = A[j-1][i-1]+k;
1068 // then it is a bad order.
1069 if (AR->getLoop() == OuterLoop) {
1070 // We found an OuterLoop induction after InnerLoop induction. It is
1071 // a bad order.
1072 FoundOuterInduction = true;
1073 if (FoundInnerInduction) {
1074 BadOrder++;
1075 break;
1076 }
1077 }
1078 }
1079 }
1080 }
1081 }
1082 return GoodOrder - BadOrder;
1083}
1084
Chad Rosiere6b3a632016-09-14 17:12:30 +00001085static bool isProfitableForVectorization(unsigned InnerLoopId,
1086 unsigned OuterLoopId,
1087 CharMatrix &DepMatrix) {
Karthik Bhat88db86d2015-03-06 10:11:25 +00001088 // TODO: Improve this heuristic to catch more cases.
1089 // If the inner loop is loop independent or doesn't carry any dependency it is
1090 // profitable to move this to outer position.
Florian Hahnf66efd62017-07-24 11:41:30 +00001091 for (auto &Row : DepMatrix) {
1092 if (Row[InnerLoopId] != 'S' && Row[InnerLoopId] != 'I')
Karthik Bhat88db86d2015-03-06 10:11:25 +00001093 return false;
1094 // TODO: We need to improve this heuristic.
Florian Hahnf66efd62017-07-24 11:41:30 +00001095 if (Row[OuterLoopId] != '=')
Karthik Bhat88db86d2015-03-06 10:11:25 +00001096 return false;
1097 }
1098 // If outer loop has dependence and inner loop is loop independent then it is
1099 // profitable to interchange to enable parallelism.
1100 return true;
1101}
1102
1103bool LoopInterchangeProfitability::isProfitable(unsigned InnerLoopId,
1104 unsigned OuterLoopId,
1105 CharMatrix &DepMatrix) {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001106 // TODO: Add better profitability checks.
Karthik Bhat88db86d2015-03-06 10:11:25 +00001107 // e.g
1108 // 1) Construct dependency matrix and move the one with no loop carried dep
1109 // inside to enable vectorization.
1110
1111 // This is rough cost estimation algorithm. It counts the good and bad order
1112 // of induction variables in the instruction and allows reordering if number
1113 // of bad orders is more than good.
Chad Rosier72431892016-09-14 17:07:13 +00001114 int Cost = getInstrOrderCost();
Karthik Bhat88db86d2015-03-06 10:11:25 +00001115 DEBUG(dbgs() << "Cost = " << Cost << "\n");
Chad Rosier72431892016-09-14 17:07:13 +00001116 if (Cost < -LoopInterchangeCostThreshold)
Karthik Bhat88db86d2015-03-06 10:11:25 +00001117 return true;
1118
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001119 // It is not profitable as per current cache profitability model. But check if
Karthik Bhat88db86d2015-03-06 10:11:25 +00001120 // we can move this loop outside to improve parallelism.
Florian Hahnad993522017-07-15 13:13:19 +00001121 if (isProfitableForVectorization(InnerLoopId, OuterLoopId, DepMatrix))
1122 return true;
1123
Vivek Pandya95906582017-10-11 17:12:59 +00001124 ORE->emit([&]() {
1125 return OptimizationRemarkMissed(DEBUG_TYPE, "InterchangeNotProfitable",
1126 InnerLoop->getStartLoc(),
1127 InnerLoop->getHeader())
1128 << "Interchanging loops is too costly (cost="
1129 << ore::NV("Cost", Cost) << ", threshold="
1130 << ore::NV("Threshold", LoopInterchangeCostThreshold)
1131 << ") and it does not improve parallelism.";
1132 });
Florian Hahnad993522017-07-15 13:13:19 +00001133 return false;
Karthik Bhat88db86d2015-03-06 10:11:25 +00001134}
1135
1136void LoopInterchangeTransform::removeChildLoop(Loop *OuterLoop,
1137 Loop *InnerLoop) {
Daniel Jasper6adbd7a2015-03-06 10:39:14 +00001138 for (Loop::iterator I = OuterLoop->begin(), E = OuterLoop->end(); I != E;
1139 ++I) {
Karthik Bhat88db86d2015-03-06 10:11:25 +00001140 if (*I == InnerLoop) {
1141 OuterLoop->removeChildLoop(I);
1142 return;
1143 }
1144 }
Benjamin Kramer8ceb3232015-10-25 22:28:27 +00001145 llvm_unreachable("Couldn't find loop");
Karthik Bhat88db86d2015-03-06 10:11:25 +00001146}
Daniel Jasper6adbd7a2015-03-06 10:39:14 +00001147
Karthik Bhat88db86d2015-03-06 10:11:25 +00001148void LoopInterchangeTransform::restructureLoops(Loop *InnerLoop,
1149 Loop *OuterLoop) {
1150 Loop *OuterLoopParent = OuterLoop->getParentLoop();
1151 if (OuterLoopParent) {
1152 // Remove the loop from its parent loop.
1153 removeChildLoop(OuterLoopParent, OuterLoop);
1154 removeChildLoop(OuterLoop, InnerLoop);
1155 OuterLoopParent->addChildLoop(InnerLoop);
1156 } else {
1157 removeChildLoop(OuterLoop, InnerLoop);
1158 LI->changeTopLevelLoop(OuterLoop, InnerLoop);
1159 }
1160
Andrew Kaylor08c5f1e2015-04-24 17:39:16 +00001161 while (!InnerLoop->empty())
1162 OuterLoop->addChildLoop(InnerLoop->removeChildLoop(InnerLoop->begin()));
Karthik Bhat88db86d2015-03-06 10:11:25 +00001163
1164 InnerLoop->addChildLoop(OuterLoop);
1165}
1166
1167bool LoopInterchangeTransform::transform() {
Karthik Bhat88db86d2015-03-06 10:11:25 +00001168 bool Transformed = false;
1169 Instruction *InnerIndexVar;
1170
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +00001171 if (InnerLoop->getSubLoops().empty()) {
Karthik Bhat88db86d2015-03-06 10:11:25 +00001172 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
1173 DEBUG(dbgs() << "Calling Split Inner Loop\n");
1174 PHINode *InductionPHI = getInductionVariable(InnerLoop, SE);
1175 if (!InductionPHI) {
1176 DEBUG(dbgs() << "Failed to find the point to split loop latch \n");
1177 return false;
1178 }
1179
1180 if (InductionPHI->getIncomingBlock(0) == InnerLoopPreHeader)
1181 InnerIndexVar = dyn_cast<Instruction>(InductionPHI->getIncomingValue(1));
1182 else
1183 InnerIndexVar = dyn_cast<Instruction>(InductionPHI->getIncomingValue(0));
1184
David Green907b60f2017-10-21 13:58:37 +00001185 // Ensure that InductionPHI is the first Phi node as required by
1186 // splitInnerLoopHeader
1187 if (&InductionPHI->getParent()->front() != InductionPHI)
1188 InductionPHI->moveBefore(&InductionPHI->getParent()->front());
1189
Karthik Bhat88db86d2015-03-06 10:11:25 +00001190 // Split at the place were the induction variable is
1191 // incremented/decremented.
1192 // TODO: This splitting logic may not work always. Fix this.
1193 splitInnerLoopLatch(InnerIndexVar);
Chad Rosierf7c76f92016-09-21 13:28:41 +00001194 DEBUG(dbgs() << "splitInnerLoopLatch done\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +00001195
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001196 // Splits the inner loops phi nodes out into a separate basic block.
Karthik Bhat88db86d2015-03-06 10:11:25 +00001197 splitInnerLoopHeader();
Chad Rosierf7c76f92016-09-21 13:28:41 +00001198 DEBUG(dbgs() << "splitInnerLoopHeader done\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +00001199 }
1200
1201 Transformed |= adjustLoopLinks();
1202 if (!Transformed) {
Chad Rosierf7c76f92016-09-21 13:28:41 +00001203 DEBUG(dbgs() << "adjustLoopLinks failed\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +00001204 return false;
1205 }
1206
1207 restructureLoops(InnerLoop, OuterLoop);
1208 return true;
1209}
1210
Benjamin Kramer79442922015-03-06 18:59:14 +00001211void LoopInterchangeTransform::splitInnerLoopLatch(Instruction *Inc) {
Karthik Bhat88db86d2015-03-06 10:11:25 +00001212 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
Karthik Bhat88db86d2015-03-06 10:11:25 +00001213 BasicBlock *InnerLoopLatchPred = InnerLoopLatch;
Benjamin Kramer79442922015-03-06 18:59:14 +00001214 InnerLoopLatch = SplitBlock(InnerLoopLatchPred, Inc, DT, LI);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001215}
1216
Karthik Bhat88db86d2015-03-06 10:11:25 +00001217void LoopInterchangeTransform::splitInnerLoopHeader() {
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001218 // Split the inner loop header out. Here make sure that the reduction PHI's
1219 // stay in the innerloop body.
Karthik Bhat88db86d2015-03-06 10:11:25 +00001220 BasicBlock *InnerLoopHeader = InnerLoop->getHeader();
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001221 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
Florian Hahne54a20e2018-02-12 11:10:58 +00001222 SplitBlock(InnerLoopHeader, InnerLoopHeader->getFirstNonPHI(), DT, LI);
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001223 if (InnerLoopHasReduction) {
Florian Hahne54a20e2018-02-12 11:10:58 +00001224 // Adjust Reduction PHI's in the block. The induction PHI must be the first
1225 // PHI in InnerLoopHeader for this to work.
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001226 SmallVector<PHINode *, 8> PHIVec;
Florian Hahne54a20e2018-02-12 11:10:58 +00001227 for (auto I = std::next(InnerLoopHeader->begin()); isa<PHINode>(I); ++I) {
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001228 PHINode *PHI = dyn_cast<PHINode>(I);
1229 Value *V = PHI->getIncomingValueForBlock(InnerLoopPreHeader);
1230 PHI->replaceAllUsesWith(V);
1231 PHIVec.push_back((PHI));
1232 }
Benjamin Kramer135f7352016-06-26 12:28:59 +00001233 for (PHINode *P : PHIVec) {
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001234 P->eraseFromParent();
1235 }
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001236 }
Karthik Bhat88db86d2015-03-06 10:11:25 +00001237
1238 DEBUG(dbgs() << "Output of splitInnerLoopHeader InnerLoopHeaderSucc & "
Chad Rosierf7c76f92016-09-21 13:28:41 +00001239 "InnerLoopHeader\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +00001240}
1241
Benjamin Kramer79442922015-03-06 18:59:14 +00001242/// \brief Move all instructions except the terminator from FromBB right before
1243/// InsertBefore
1244static void moveBBContents(BasicBlock *FromBB, Instruction *InsertBefore) {
1245 auto &ToList = InsertBefore->getParent()->getInstList();
1246 auto &FromList = FromBB->getInstList();
1247
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001248 ToList.splice(InsertBefore->getIterator(), FromList, FromList.begin(),
1249 FromBB->getTerminator()->getIterator());
Benjamin Kramer79442922015-03-06 18:59:14 +00001250}
1251
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001252void LoopInterchangeTransform::updateIncomingBlock(BasicBlock *CurrBlock,
1253 BasicBlock *OldPred,
1254 BasicBlock *NewPred) {
1255 for (auto I = CurrBlock->begin(); isa<PHINode>(I); ++I) {
1256 PHINode *PHI = cast<PHINode>(I);
1257 unsigned Num = PHI->getNumIncomingValues();
1258 for (unsigned i = 0; i < Num; ++i) {
1259 if (PHI->getIncomingBlock(i) == OldPred)
1260 PHI->setIncomingBlock(i, NewPred);
1261 }
1262 }
1263}
1264
Florian Hahnc6296fe2018-02-14 13:13:15 +00001265/// \brief Update BI to jump to NewBB instead of OldBB. Records updates to
1266/// the dominator tree in DTUpdates, if DT should be preserved.
1267static void updateSuccessor(BranchInst *BI, BasicBlock *OldBB,
1268 BasicBlock *NewBB,
1269 std::vector<DominatorTree::UpdateType> &DTUpdates) {
1270 assert(llvm::count_if(BI->successors(),
1271 [OldBB](BasicBlock *BB) { return BB == OldBB; }) < 2 &&
1272 "BI must jump to OldBB at most once.");
1273 for (unsigned i = 0, e = BI->getNumSuccessors(); i < e; ++i) {
1274 if (BI->getSuccessor(i) == OldBB) {
1275 BI->setSuccessor(i, NewBB);
1276
1277 DTUpdates.push_back(
1278 {DominatorTree::UpdateKind::Insert, BI->getParent(), NewBB});
1279 DTUpdates.push_back(
1280 {DominatorTree::UpdateKind::Delete, BI->getParent(), OldBB});
1281 break;
1282 }
1283 }
1284}
1285
Karthik Bhat88db86d2015-03-06 10:11:25 +00001286bool LoopInterchangeTransform::adjustLoopBranches() {
Karthik Bhat88db86d2015-03-06 10:11:25 +00001287 DEBUG(dbgs() << "adjustLoopBranches called\n");
Florian Hahnc6296fe2018-02-14 13:13:15 +00001288 std::vector<DominatorTree::UpdateType> DTUpdates;
1289
Karthik Bhat88db86d2015-03-06 10:11:25 +00001290 // Adjust the loop preheader
1291 BasicBlock *InnerLoopHeader = InnerLoop->getHeader();
1292 BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
1293 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
1294 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch();
1295 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader();
1296 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
1297 BasicBlock *OuterLoopPredecessor = OuterLoopPreHeader->getUniquePredecessor();
1298 BasicBlock *InnerLoopLatchPredecessor =
1299 InnerLoopLatch->getUniquePredecessor();
1300 BasicBlock *InnerLoopLatchSuccessor;
1301 BasicBlock *OuterLoopLatchSuccessor;
1302
1303 BranchInst *OuterLoopLatchBI =
1304 dyn_cast<BranchInst>(OuterLoopLatch->getTerminator());
1305 BranchInst *InnerLoopLatchBI =
1306 dyn_cast<BranchInst>(InnerLoopLatch->getTerminator());
1307 BranchInst *OuterLoopHeaderBI =
1308 dyn_cast<BranchInst>(OuterLoopHeader->getTerminator());
1309 BranchInst *InnerLoopHeaderBI =
1310 dyn_cast<BranchInst>(InnerLoopHeader->getTerminator());
1311
1312 if (!OuterLoopPredecessor || !InnerLoopLatchPredecessor ||
1313 !OuterLoopLatchBI || !InnerLoopLatchBI || !OuterLoopHeaderBI ||
1314 !InnerLoopHeaderBI)
1315 return false;
1316
1317 BranchInst *InnerLoopLatchPredecessorBI =
1318 dyn_cast<BranchInst>(InnerLoopLatchPredecessor->getTerminator());
1319 BranchInst *OuterLoopPredecessorBI =
1320 dyn_cast<BranchInst>(OuterLoopPredecessor->getTerminator());
1321
1322 if (!OuterLoopPredecessorBI || !InnerLoopLatchPredecessorBI)
1323 return false;
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001324 BasicBlock *InnerLoopHeaderSuccessor = InnerLoopHeader->getUniqueSuccessor();
1325 if (!InnerLoopHeaderSuccessor)
Karthik Bhat88db86d2015-03-06 10:11:25 +00001326 return false;
1327
1328 // Adjust Loop Preheader and headers
Florian Hahnc6296fe2018-02-14 13:13:15 +00001329 updateSuccessor(OuterLoopPredecessorBI, OuterLoopPreHeader,
1330 InnerLoopPreHeader, DTUpdates);
1331 updateSuccessor(OuterLoopHeaderBI, OuterLoopLatch, LoopExit, DTUpdates);
1332 updateSuccessor(OuterLoopHeaderBI, InnerLoopPreHeader,
1333 InnerLoopHeaderSuccessor, DTUpdates);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001334
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001335 // Adjust reduction PHI's now that the incoming block has changed.
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001336 updateIncomingBlock(InnerLoopHeaderSuccessor, InnerLoopHeader,
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001337 OuterLoopHeader);
1338
Florian Hahnc6296fe2018-02-14 13:13:15 +00001339 updateSuccessor(InnerLoopHeaderBI, InnerLoopHeaderSuccessor,
1340 OuterLoopPreHeader, DTUpdates);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001341
1342 // -------------Adjust loop latches-----------
1343 if (InnerLoopLatchBI->getSuccessor(0) == InnerLoopHeader)
1344 InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(1);
1345 else
1346 InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(0);
1347
Florian Hahnc6296fe2018-02-14 13:13:15 +00001348 updateSuccessor(InnerLoopLatchPredecessorBI, InnerLoopLatch,
1349 InnerLoopLatchSuccessor, DTUpdates);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001350
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001351 // Adjust PHI nodes in InnerLoopLatchSuccessor. Update all uses of PHI with
1352 // the value and remove this PHI node from inner loop.
1353 SmallVector<PHINode *, 8> LcssaVec;
1354 for (auto I = InnerLoopLatchSuccessor->begin(); isa<PHINode>(I); ++I) {
1355 PHINode *LcssaPhi = cast<PHINode>(I);
1356 LcssaVec.push_back(LcssaPhi);
1357 }
Benjamin Kramer135f7352016-06-26 12:28:59 +00001358 for (PHINode *P : LcssaVec) {
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001359 Value *Incoming = P->getIncomingValueForBlock(InnerLoopLatch);
1360 P->replaceAllUsesWith(Incoming);
1361 P->eraseFromParent();
1362 }
1363
Karthik Bhat88db86d2015-03-06 10:11:25 +00001364 if (OuterLoopLatchBI->getSuccessor(0) == OuterLoopHeader)
1365 OuterLoopLatchSuccessor = OuterLoopLatchBI->getSuccessor(1);
1366 else
1367 OuterLoopLatchSuccessor = OuterLoopLatchBI->getSuccessor(0);
1368
Florian Hahnc6296fe2018-02-14 13:13:15 +00001369 updateSuccessor(InnerLoopLatchBI, InnerLoopLatchSuccessor,
1370 OuterLoopLatchSuccessor, DTUpdates);
1371 updateSuccessor(OuterLoopLatchBI, OuterLoopLatchSuccessor, InnerLoopLatch,
1372 DTUpdates);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001373
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001374 updateIncomingBlock(OuterLoopLatchSuccessor, OuterLoopLatch, InnerLoopLatch);
1375
Florian Hahnc6296fe2018-02-14 13:13:15 +00001376 DT->applyUpdates(DTUpdates);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001377 return true;
1378}
Karthik Bhat88db86d2015-03-06 10:11:25 +00001379
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +00001380void LoopInterchangeTransform::adjustLoopPreheaders() {
Karthik Bhat88db86d2015-03-06 10:11:25 +00001381 // We have interchanged the preheaders so we need to interchange the data in
1382 // the preheader as well.
1383 // This is because the content of inner preheader was previously executed
1384 // inside the outer loop.
1385 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader();
1386 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
1387 BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
1388 BranchInst *InnerTermBI =
1389 cast<BranchInst>(InnerLoopPreHeader->getTerminator());
1390
Karthik Bhat88db86d2015-03-06 10:11:25 +00001391 // These instructions should now be executed inside the loop.
1392 // Move instruction into a new block after outer header.
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001393 moveBBContents(InnerLoopPreHeader, OuterLoopHeader->getTerminator());
Karthik Bhat88db86d2015-03-06 10:11:25 +00001394 // These instructions were not executed previously in the loop so move them to
1395 // the older inner loop preheader.
Benjamin Kramer79442922015-03-06 18:59:14 +00001396 moveBBContents(OuterLoopPreHeader, InnerTermBI);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001397}
1398
1399bool LoopInterchangeTransform::adjustLoopLinks() {
Karthik Bhat88db86d2015-03-06 10:11:25 +00001400 // Adjust all branches in the inner and outer loop.
1401 bool Changed = adjustLoopBranches();
1402 if (Changed)
1403 adjustLoopPreheaders();
1404 return Changed;
1405}
1406
1407char LoopInterchange::ID = 0;
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +00001408
Karthik Bhat88db86d2015-03-06 10:11:25 +00001409INITIALIZE_PASS_BEGIN(LoopInterchange, "loop-interchange",
1410 "Interchanges loops for cache reuse", false, false)
Chandler Carruth7b560d42015-09-09 17:55:00 +00001411INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Chandler Carruth49c22192016-05-12 22:19:39 +00001412INITIALIZE_PASS_DEPENDENCY(DependenceAnalysisWrapperPass)
Karthik Bhat88db86d2015-03-06 10:11:25 +00001413INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001414INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
Karthik Bhat88db86d2015-03-06 10:11:25 +00001415INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
Easwaran Ramane12c4872016-06-09 19:44:46 +00001416INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass)
Karthik Bhat88db86d2015-03-06 10:11:25 +00001417INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Florian Hahnad993522017-07-15 13:13:19 +00001418INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
Karthik Bhat88db86d2015-03-06 10:11:25 +00001419
1420INITIALIZE_PASS_END(LoopInterchange, "loop-interchange",
1421 "Interchanges loops for cache reuse", false, false)
1422
1423Pass *llvm::createLoopInterchangePass() { return new LoopInterchange(); }