blob: 4cda6ed4b8764811d94724fef3db1560eb3467a6 [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
Vikram TV74b41112015-12-09 05:16:24 +0000176 // We don't have a DepMatrix to check legality return false.
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000177 if (DepMatrix.empty())
Karthik Bhat88db86d2015-03-06 10:11:25 +0000178 return false;
179 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
273static void populateWorklist(Loop &L, SmallVector<LoopVector, 8> &V) {
Chad Rosierf5814f52016-09-07 15:56:59 +0000274 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.
Benjamin Kramere448b5b2015-07-13 17:21:14 +0000284 if (Vec->size() != 1) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000285 LoopList.clear();
286 return;
287 }
288 LoopList.push_back(CurrentLoop);
Benjamin Kramere448b5b2015-07-13 17:21:14 +0000289 CurrentLoop = Vec->front();
290 Vec = &CurrentLoop->getSubLoops();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000291 }
292 LoopList.push_back(CurrentLoop);
Benjamin Kramere448b5b2015-07-13 17:21:14 +0000293 V.push_back(std::move(LoopList));
Karthik Bhat88db86d2015-03-06 10:11:25 +0000294}
295
296static PHINode *getInductionVariable(Loop *L, ScalarEvolution *SE) {
297 PHINode *InnerIndexVar = L->getCanonicalInductionVariable();
298 if (InnerIndexVar)
299 return InnerIndexVar;
300 if (L->getLoopLatch() == nullptr || L->getLoopPredecessor() == nullptr)
301 return nullptr;
302 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
303 PHINode *PhiVar = cast<PHINode>(I);
304 Type *PhiTy = PhiVar->getType();
305 if (!PhiTy->isIntegerTy() && !PhiTy->isFloatingPointTy() &&
306 !PhiTy->isPointerTy())
307 return nullptr;
308 const SCEVAddRecExpr *AddRec =
309 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(PhiVar));
310 if (!AddRec || !AddRec->isAffine())
311 continue;
312 const SCEV *Step = AddRec->getStepRecurrence(*SE);
Chad Rosierf7c76f92016-09-21 13:28:41 +0000313 if (!isa<SCEVConstant>(Step))
Karthik Bhat88db86d2015-03-06 10:11:25 +0000314 continue;
315 // Found the induction variable.
316 // FIXME: Handle loops with more than one induction variable. Note that,
317 // currently, legality makes sure we have only one induction variable.
318 return PhiVar;
319 }
320 return nullptr;
321}
322
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000323namespace {
324
Karthik Bhat88db86d2015-03-06 10:11:25 +0000325/// LoopInterchangeLegality checks if it is legal to interchange the loop.
326class LoopInterchangeLegality {
327public:
328 LoopInterchangeLegality(Loop *Outer, Loop *Inner, ScalarEvolution *SE,
Florian Hahnad993522017-07-15 13:13:19 +0000329 LoopInfo *LI, DominatorTree *DT, bool PreserveLCSSA,
330 OptimizationRemarkEmitter *ORE)
Justin Bogner843fb202015-12-15 19:40:57 +0000331 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), LI(LI), DT(DT),
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000332 PreserveLCSSA(PreserveLCSSA), ORE(ORE) {}
Karthik Bhat88db86d2015-03-06 10:11:25 +0000333
334 /// Check if the loops can be interchanged.
335 bool canInterchangeLoops(unsigned InnerLoopId, unsigned OuterLoopId,
336 CharMatrix &DepMatrix);
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000337
Karthik Bhat88db86d2015-03-06 10:11:25 +0000338 /// Check if the loop structure is understood. We do not handle triangular
339 /// loops for now.
340 bool isLoopStructureUnderstood(PHINode *InnerInductionVar);
341
342 bool currentLimitations();
343
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000344 bool hasInnerLoopReduction() { return InnerLoopHasReduction; }
345
Karthik Bhat88db86d2015-03-06 10:11:25 +0000346private:
347 bool tightlyNested(Loop *Outer, Loop *Inner);
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000348 bool containsUnsafeInstructionsInHeader(BasicBlock *BB);
349 bool areAllUsesReductions(Instruction *Ins, Loop *L);
350 bool containsUnsafeInstructionsInLatch(BasicBlock *BB);
351 bool findInductionAndReductions(Loop *L,
352 SmallVector<PHINode *, 8> &Inductions,
353 SmallVector<PHINode *, 8> &Reductions);
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000354
Karthik Bhat88db86d2015-03-06 10:11:25 +0000355 Loop *OuterLoop;
356 Loop *InnerLoop;
357
Karthik Bhat88db86d2015-03-06 10:11:25 +0000358 ScalarEvolution *SE;
Justin Bogner843fb202015-12-15 19:40:57 +0000359 LoopInfo *LI;
360 DominatorTree *DT;
361 bool PreserveLCSSA;
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000362
Florian Hahnad993522017-07-15 13:13:19 +0000363 /// Interface to emit optimization remarks.
364 OptimizationRemarkEmitter *ORE;
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000365
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000366 bool InnerLoopHasReduction = false;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000367};
368
369/// LoopInterchangeProfitability checks if it is profitable to interchange the
370/// loop.
371class LoopInterchangeProfitability {
372public:
Florian Hahnad993522017-07-15 13:13:19 +0000373 LoopInterchangeProfitability(Loop *Outer, Loop *Inner, ScalarEvolution *SE,
374 OptimizationRemarkEmitter *ORE)
375 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), ORE(ORE) {}
Karthik Bhat88db86d2015-03-06 10:11:25 +0000376
Vikram TV74b41112015-12-09 05:16:24 +0000377 /// Check if the loop interchange is profitable.
Karthik Bhat88db86d2015-03-06 10:11:25 +0000378 bool isProfitable(unsigned InnerLoopId, unsigned OuterLoopId,
379 CharMatrix &DepMatrix);
380
381private:
382 int getInstrOrderCost();
383
384 Loop *OuterLoop;
385 Loop *InnerLoop;
386
387 /// Scev analysis.
388 ScalarEvolution *SE;
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000389
Florian Hahnad993522017-07-15 13:13:19 +0000390 /// Interface to emit optimization remarks.
391 OptimizationRemarkEmitter *ORE;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000392};
393
Vikram TV74b41112015-12-09 05:16:24 +0000394/// LoopInterchangeTransform interchanges the loop.
Karthik Bhat88db86d2015-03-06 10:11:25 +0000395class LoopInterchangeTransform {
396public:
397 LoopInterchangeTransform(Loop *Outer, Loop *Inner, ScalarEvolution *SE,
398 LoopInfo *LI, DominatorTree *DT,
Justin Bogner843fb202015-12-15 19:40:57 +0000399 BasicBlock *LoopNestExit,
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000400 bool InnerLoopContainsReductions)
Karthik Bhat88db86d2015-03-06 10:11:25 +0000401 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), LI(LI), DT(DT),
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000402 LoopExit(LoopNestExit),
403 InnerLoopHasReduction(InnerLoopContainsReductions) {}
Karthik Bhat88db86d2015-03-06 10:11:25 +0000404
405 /// Interchange OuterLoop and InnerLoop.
406 bool transform();
407 void restructureLoops(Loop *InnerLoop, Loop *OuterLoop);
408 void removeChildLoop(Loop *OuterLoop, Loop *InnerLoop);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000409
410private:
411 void splitInnerLoopLatch(Instruction *);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000412 void splitInnerLoopHeader();
413 bool adjustLoopLinks();
414 void adjustLoopPreheaders();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000415 bool adjustLoopBranches();
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000416 void updateIncomingBlock(BasicBlock *CurrBlock, BasicBlock *OldPred,
417 BasicBlock *NewPred);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000418
419 Loop *OuterLoop;
420 Loop *InnerLoop;
421
422 /// Scev analysis.
423 ScalarEvolution *SE;
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000424
Karthik Bhat88db86d2015-03-06 10:11:25 +0000425 LoopInfo *LI;
426 DominatorTree *DT;
427 BasicBlock *LoopExit;
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000428 bool InnerLoopHasReduction;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000429};
430
Vikram TV74b41112015-12-09 05:16:24 +0000431// Main LoopInterchange Pass.
Karthik Bhat88db86d2015-03-06 10:11:25 +0000432struct LoopInterchange : public FunctionPass {
433 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;
Justin Bogner843fb202015-12-15 19:40:57 +0000438 bool PreserveLCSSA;
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000439
Florian Hahnad993522017-07-15 13:13:19 +0000440 /// Interface to emit optimization remarks.
441 OptimizationRemarkEmitter *ORE;
442
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000443 LoopInterchange() : FunctionPass(ID) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000444 initializeLoopInterchangePass(*PassRegistry::getPassRegistry());
445 }
446
447 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000448 AU.addRequired<ScalarEvolutionWrapperPass>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000449 AU.addRequired<AAResultsWrapperPass>();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000450 AU.addRequired<DominatorTreeWrapperPass>();
451 AU.addRequired<LoopInfoWrapperPass>();
Chandler Carruth49c22192016-05-12 22:19:39 +0000452 AU.addRequired<DependenceAnalysisWrapperPass>();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000453 AU.addRequiredID(LoopSimplifyID);
454 AU.addRequiredID(LCSSAID);
Florian Hahnad993522017-07-15 13:13:19 +0000455 AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000456 }
457
458 bool runOnFunction(Function &F) override {
Andrew Kaylor50271f72016-05-03 22:32:30 +0000459 if (skipFunction(F))
460 return false;
461
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000462 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000463 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Chandler Carruth49c22192016-05-12 22:19:39 +0000464 DI = &getAnalysis<DependenceAnalysisWrapperPass>().getDI();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000465 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
466 DT = DTWP ? &DTWP->getDomTree() : nullptr;
Florian Hahnad993522017-07-15 13:13:19 +0000467 ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
Justin Bogner843fb202015-12-15 19:40:57 +0000468 PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
469
Karthik Bhat88db86d2015-03-06 10:11:25 +0000470 // Build up a worklist of loop pairs to analyze.
471 SmallVector<LoopVector, 8> Worklist;
472
473 for (Loop *L : *LI)
474 populateWorklist(*L, Worklist);
475
Chad Rosiera4c42462016-09-12 13:24:47 +0000476 DEBUG(dbgs() << "Worklist size = " << Worklist.size() << "\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000477 bool Changed = true;
478 while (!Worklist.empty()) {
479 LoopVector LoopList = Worklist.pop_back_val();
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000480 Changed = processLoopList(LoopList, F);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000481 }
482 return Changed;
483 }
484
485 bool isComputableLoopNest(LoopVector LoopList) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000486 for (Loop *L : LoopList) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000487 const SCEV *ExitCountOuter = SE->getBackedgeTakenCount(L);
488 if (ExitCountOuter == SE->getCouldNotCompute()) {
Chad Rosierf7c76f92016-09-21 13:28:41 +0000489 DEBUG(dbgs() << "Couldn't compute backedge count\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000490 return false;
491 }
492 if (L->getNumBackEdges() != 1) {
493 DEBUG(dbgs() << "NumBackEdges is not equal to 1\n");
494 return false;
495 }
496 if (!L->getExitingBlock()) {
Chad Rosierf7c76f92016-09-21 13:28:41 +0000497 DEBUG(dbgs() << "Loop doesn't have unique exit block\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000498 return false;
499 }
500 }
501 return true;
502 }
503
Benjamin Kramerc321e532016-06-08 19:09:22 +0000504 unsigned selectLoopForInterchange(const LoopVector &LoopList) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000505 // TODO: Add a better heuristic to select the loop to be interchanged based
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000506 // on the dependence matrix. Currently we select the innermost loop.
Karthik Bhat88db86d2015-03-06 10:11:25 +0000507 return LoopList.size() - 1;
508 }
509
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000510 bool processLoopList(LoopVector LoopList, Function &F) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000511 bool Changed = false;
Chad Rosier7ea0d392016-09-13 13:30:30 +0000512 unsigned LoopNestDepth = LoopList.size();
513 if (LoopNestDepth < 2) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000514 DEBUG(dbgs() << "Loop doesn't contain minimum nesting level.\n");
515 return false;
516 }
Chad Rosier7ea0d392016-09-13 13:30:30 +0000517 if (LoopNestDepth > MaxLoopNestDepth) {
518 DEBUG(dbgs() << "Cannot handle loops of depth greater than "
519 << MaxLoopNestDepth << "\n");
520 return false;
521 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000522 if (!isComputableLoopNest(LoopList)) {
Chad Rosiera4c42462016-09-12 13:24:47 +0000523 DEBUG(dbgs() << "Not valid loop candidate for interchange\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000524 return false;
525 }
Chad Rosier7ea0d392016-09-13 13:30:30 +0000526
527 DEBUG(dbgs() << "Processing LoopList of size = " << LoopNestDepth << "\n");
528
529 CharMatrix DependencyMatrix;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000530 Loop *OuterMostLoop = *(LoopList.begin());
Chad Rosier7ea0d392016-09-13 13:30:30 +0000531 if (!populateDependencyMatrix(DependencyMatrix, LoopNestDepth,
Chandler Carruth49c22192016-05-12 22:19:39 +0000532 OuterMostLoop, DI)) {
Chad Rosierf7c76f92016-09-21 13:28:41 +0000533 DEBUG(dbgs() << "Populating dependency matrix failed\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000534 return false;
535 }
536#ifdef DUMP_DEP_MATRICIES
Chad Rosier58ede272016-09-14 16:43:19 +0000537 DEBUG(dbgs() << "Dependence before interchange\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000538 printDepMatrix(DependencyMatrix);
539#endif
540
541 BasicBlock *OuterMostLoopLatch = OuterMostLoop->getLoopLatch();
542 BranchInst *OuterMostLoopLatchBI =
543 dyn_cast<BranchInst>(OuterMostLoopLatch->getTerminator());
Florian Hahn1f95ef12018-02-13 10:02:52 +0000544 if (!OuterMostLoopLatchBI || OuterMostLoopLatchBI->getNumSuccessors() != 2)
Karthik Bhat88db86d2015-03-06 10:11:25 +0000545 return false;
546
547 // Since we currently do not handle LCSSA PHI's any failure in loop
548 // condition will now branch to LoopNestExit.
549 // TODO: This should be removed once we handle LCSSA PHI nodes.
550
551 // Get the Outermost loop exit.
552 BasicBlock *LoopNestExit;
553 if (OuterMostLoopLatchBI->getSuccessor(0) == OuterMostLoop->getHeader())
554 LoopNestExit = OuterMostLoopLatchBI->getSuccessor(1);
555 else
556 LoopNestExit = OuterMostLoopLatchBI->getSuccessor(0);
557
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000558 if (isa<PHINode>(LoopNestExit->begin())) {
559 DEBUG(dbgs() << "PHI Nodes in loop nest exit is not handled for now "
560 "since on failure all loops branch to loop nest exit.\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000561 return false;
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000562 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000563
564 unsigned SelecLoopId = selectLoopForInterchange(LoopList);
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000565 // Move the selected loop outwards to the best possible position.
Karthik Bhat88db86d2015-03-06 10:11:25 +0000566 for (unsigned i = SelecLoopId; i > 0; i--) {
567 bool Interchanged =
568 processLoop(LoopList, i, i - 1, LoopNestExit, DependencyMatrix);
569 if (!Interchanged)
570 return Changed;
571 // Loops interchanged reflect the same in LoopList
Benjamin Kramer79442922015-03-06 18:59:14 +0000572 std::swap(LoopList[i - 1], LoopList[i]);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000573
574 // Update the DependencyMatrix
Chad Rosierd18ea062016-09-13 13:00:29 +0000575 interChangeDependencies(DependencyMatrix, i, i - 1);
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000576 DT->recalculate(F);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000577#ifdef DUMP_DEP_MATRICIES
Chad Rosier58ede272016-09-14 16:43:19 +0000578 DEBUG(dbgs() << "Dependence after interchange\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000579 printDepMatrix(DependencyMatrix);
580#endif
581 Changed |= Interchanged;
582 }
583 return Changed;
584 }
585
586 bool processLoop(LoopVector LoopList, unsigned InnerLoopId,
587 unsigned OuterLoopId, BasicBlock *LoopNestExit,
588 std::vector<std::vector<char>> &DependencyMatrix) {
Chad Rosier13bc0d192016-09-07 18:15:12 +0000589 DEBUG(dbgs() << "Processing Inner Loop Id = " << InnerLoopId
Karthik Bhat88db86d2015-03-06 10:11:25 +0000590 << " and OuterLoopId = " << OuterLoopId << "\n");
591 Loop *InnerLoop = LoopList[InnerLoopId];
592 Loop *OuterLoop = LoopList[OuterLoopId];
593
Justin Bogner843fb202015-12-15 19:40:57 +0000594 LoopInterchangeLegality LIL(OuterLoop, InnerLoop, SE, LI, DT,
Florian Hahnad993522017-07-15 13:13:19 +0000595 PreserveLCSSA, ORE);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000596 if (!LIL.canInterchangeLoops(InnerLoopId, OuterLoopId, DependencyMatrix)) {
597 DEBUG(dbgs() << "Not interchanging Loops. Cannot prove legality\n");
598 return false;
599 }
600 DEBUG(dbgs() << "Loops are legal to interchange\n");
Florian Hahnad993522017-07-15 13:13:19 +0000601 LoopInterchangeProfitability LIP(OuterLoop, InnerLoop, SE, ORE);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000602 if (!LIP.isProfitable(InnerLoopId, OuterLoopId, DependencyMatrix)) {
Chad Rosierf7c76f92016-09-21 13:28:41 +0000603 DEBUG(dbgs() << "Interchanging loops not profitable\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000604 return false;
605 }
606
Vivek Pandya95906582017-10-11 17:12:59 +0000607 ORE->emit([&]() {
608 return OptimizationRemark(DEBUG_TYPE, "Interchanged",
609 InnerLoop->getStartLoc(),
610 InnerLoop->getHeader())
611 << "Loop interchanged with enclosing loop.";
612 });
Florian Hahnad993522017-07-15 13:13:19 +0000613
Justin Bogner843fb202015-12-15 19:40:57 +0000614 LoopInterchangeTransform LIT(OuterLoop, InnerLoop, SE, LI, DT,
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000615 LoopNestExit, LIL.hasInnerLoopReduction());
Karthik Bhat88db86d2015-03-06 10:11:25 +0000616 LIT.transform();
617 DEBUG(dbgs() << "Loops interchanged\n");
618 return true;
619 }
620};
621
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000622} // end anonymous namespace
623
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000624bool LoopInterchangeLegality::areAllUsesReductions(Instruction *Ins, Loop *L) {
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000625 return llvm::none_of(Ins->users(), [=](User *U) -> bool {
David Majnemer0a16c222016-08-11 21:15:00 +0000626 auto *UserIns = dyn_cast<PHINode>(U);
Tyler Nowicki0a913102015-06-16 18:07:34 +0000627 RecurrenceDescriptor RD;
628 return !UserIns || !RecurrenceDescriptor::isReductionPHI(UserIns, L, RD);
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000629 });
630}
Karthik Bhat88db86d2015-03-06 10:11:25 +0000631
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000632bool LoopInterchangeLegality::containsUnsafeInstructionsInHeader(
633 BasicBlock *BB) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000634 for (auto I = BB->begin(), E = BB->end(); I != E; ++I) {
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000635 // Load corresponding to reduction PHI's are safe while concluding if
636 // tightly nested.
637 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
638 if (!areAllUsesReductions(L, InnerLoop))
639 return true;
640 } else if (I->mayHaveSideEffects() || I->mayReadFromMemory())
641 return true;
642 }
643 return false;
644}
645
646bool LoopInterchangeLegality::containsUnsafeInstructionsInLatch(
647 BasicBlock *BB) {
648 for (auto I = BB->begin(), E = BB->end(); I != E; ++I) {
649 // Stores corresponding to reductions are safe while concluding if tightly
650 // nested.
651 if (StoreInst *L = dyn_cast<StoreInst>(I)) {
Chad Rosierf7c76f92016-09-21 13:28:41 +0000652 if (!isa<PHINode>(L->getOperand(0)))
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000653 return true;
654 } else if (I->mayHaveSideEffects() || I->mayReadFromMemory())
Karthik Bhat88db86d2015-03-06 10:11:25 +0000655 return true;
656 }
657 return false;
658}
659
660bool LoopInterchangeLegality::tightlyNested(Loop *OuterLoop, Loop *InnerLoop) {
661 BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
662 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
663 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch();
664
Chad Rosierf7c76f92016-09-21 13:28:41 +0000665 DEBUG(dbgs() << "Checking if loops are tightly nested\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000666
667 // A perfectly nested loop will not have any branch in between the outer and
668 // inner block i.e. outer header will branch to either inner preheader and
669 // outerloop latch.
Chad Rosierf7c76f92016-09-21 13:28:41 +0000670 BranchInst *OuterLoopHeaderBI =
Karthik Bhat88db86d2015-03-06 10:11:25 +0000671 dyn_cast<BranchInst>(OuterLoopHeader->getTerminator());
Chad Rosierf7c76f92016-09-21 13:28:41 +0000672 if (!OuterLoopHeaderBI)
Karthik Bhat88db86d2015-03-06 10:11:25 +0000673 return false;
Chad Rosierf7c76f92016-09-21 13:28:41 +0000674
Florian Hahnf66efd62017-07-24 11:41:30 +0000675 for (BasicBlock *Succ : OuterLoopHeaderBI->successors())
676 if (Succ != InnerLoopPreHeader && Succ != OuterLoopLatch)
Karthik Bhat88db86d2015-03-06 10:11:25 +0000677 return false;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000678
Chad Rosierf7c76f92016-09-21 13:28:41 +0000679 DEBUG(dbgs() << "Checking instructions in Loop header and Loop latch\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000680 // We do not have any basic block in between now make sure the outer header
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000681 // and outer loop latch doesn't contain any unsafe instructions.
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000682 if (containsUnsafeInstructionsInHeader(OuterLoopHeader) ||
683 containsUnsafeInstructionsInLatch(OuterLoopLatch))
Karthik Bhat88db86d2015-03-06 10:11:25 +0000684 return false;
685
Chad Rosierf7c76f92016-09-21 13:28:41 +0000686 DEBUG(dbgs() << "Loops are perfectly nested\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000687 // We have a perfect loop nest.
688 return true;
689}
690
Karthik Bhat88db86d2015-03-06 10:11:25 +0000691bool LoopInterchangeLegality::isLoopStructureUnderstood(
692 PHINode *InnerInduction) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000693 unsigned Num = InnerInduction->getNumOperands();
694 BasicBlock *InnerLoopPreheader = InnerLoop->getLoopPreheader();
695 for (unsigned i = 0; i < Num; ++i) {
696 Value *Val = InnerInduction->getOperand(i);
697 if (isa<Constant>(Val))
698 continue;
699 Instruction *I = dyn_cast<Instruction>(Val);
700 if (!I)
701 return false;
702 // TODO: Handle triangular loops.
703 // e.g. for(int i=0;i<N;i++)
704 // for(int j=i;j<N;j++)
705 unsigned IncomBlockIndx = PHINode::getIncomingValueNumForOperand(i);
706 if (InnerInduction->getIncomingBlock(IncomBlockIndx) ==
707 InnerLoopPreheader &&
708 !OuterLoop->isLoopInvariant(I)) {
709 return false;
710 }
711 }
712 return true;
713}
714
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000715bool LoopInterchangeLegality::findInductionAndReductions(
716 Loop *L, SmallVector<PHINode *, 8> &Inductions,
717 SmallVector<PHINode *, 8> &Reductions) {
718 if (!L->getLoopLatch() || !L->getLoopPredecessor())
719 return false;
720 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
Tyler Nowicki0a913102015-06-16 18:07:34 +0000721 RecurrenceDescriptor RD;
James Molloy1bbf15c2015-08-27 09:53:00 +0000722 InductionDescriptor ID;
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000723 PHINode *PHI = cast<PHINode>(I);
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000724 if (InductionDescriptor::isInductionPHI(PHI, L, SE, ID))
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000725 Inductions.push_back(PHI);
Tyler Nowicki0a913102015-06-16 18:07:34 +0000726 else if (RecurrenceDescriptor::isReductionPHI(PHI, L, RD))
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000727 Reductions.push_back(PHI);
728 else {
729 DEBUG(
730 dbgs() << "Failed to recognize PHI as an induction or reduction.\n");
731 return false;
732 }
733 }
734 return true;
735}
736
737static bool containsSafePHI(BasicBlock *Block, bool isOuterLoopExitBlock) {
738 for (auto I = Block->begin(); isa<PHINode>(I); ++I) {
739 PHINode *PHI = cast<PHINode>(I);
740 // Reduction lcssa phi will have only 1 incoming block that from loop latch.
741 if (PHI->getNumIncomingValues() > 1)
742 return false;
743 Instruction *Ins = dyn_cast<Instruction>(PHI->getIncomingValue(0));
744 if (!Ins)
745 return false;
746 // Incoming value for lcssa phi's in outer loop exit can only be inner loop
747 // exits lcssa phi else it would not be tightly nested.
748 if (!isa<PHINode>(Ins) && isOuterLoopExitBlock)
749 return false;
750 }
751 return true;
752}
753
754static BasicBlock *getLoopLatchExitBlock(BasicBlock *LatchBlock,
755 BasicBlock *LoopHeader) {
756 if (BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator())) {
Florian Hahnf66efd62017-07-24 11:41:30 +0000757 assert(BI->getNumSuccessors() == 2 &&
758 "Branch leaving loop latch must have 2 successors");
759 for (BasicBlock *Succ : BI->successors()) {
760 if (Succ == LoopHeader)
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000761 continue;
Florian Hahnf66efd62017-07-24 11:41:30 +0000762 return Succ;
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000763 }
764 }
765 return nullptr;
766}
767
Karthik Bhat88db86d2015-03-06 10:11:25 +0000768// This function indicates the current limitations in the transform as a result
769// of which we do not proceed.
770bool LoopInterchangeLegality::currentLimitations() {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000771 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
772 BasicBlock *InnerLoopHeader = InnerLoop->getHeader();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000773 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
774 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch();
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000775 BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000776
777 PHINode *InnerInductionVar;
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000778 SmallVector<PHINode *, 8> Inductions;
779 SmallVector<PHINode *, 8> Reductions;
Florian Hahn4eeff392017-07-03 15:32:00 +0000780 if (!findInductionAndReductions(InnerLoop, Inductions, Reductions)) {
781 DEBUG(dbgs() << "Only inner loops with induction or reduction PHI nodes "
782 << "are supported currently.\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000783 ORE->emit([&]() {
784 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedPHIInner",
785 InnerLoop->getStartLoc(),
786 InnerLoop->getHeader())
787 << "Only inner loops with induction or reduction PHI nodes can be"
788 " interchange currently.";
789 });
Karthik Bhat88db86d2015-03-06 10:11:25 +0000790 return true;
Florian Hahn4eeff392017-07-03 15:32:00 +0000791 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000792
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000793 // TODO: Currently we handle only loops with 1 induction variable.
794 if (Inductions.size() != 1) {
795 DEBUG(dbgs() << "We currently only support loops with 1 induction variable."
796 << "Failed to interchange due to current limitation\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000797 ORE->emit([&]() {
798 return OptimizationRemarkMissed(DEBUG_TYPE, "MultiInductionInner",
799 InnerLoop->getStartLoc(),
800 InnerLoop->getHeader())
801 << "Only inner loops with 1 induction variable can be "
802 "interchanged currently.";
803 });
Karthik Bhat88db86d2015-03-06 10:11:25 +0000804 return true;
805 }
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000806 if (Reductions.size() > 0)
807 InnerLoopHasReduction = true;
808
809 InnerInductionVar = Inductions.pop_back_val();
810 Reductions.clear();
Florian Hahn4eeff392017-07-03 15:32:00 +0000811 if (!findInductionAndReductions(OuterLoop, Inductions, Reductions)) {
812 DEBUG(dbgs() << "Only outer loops with induction or reduction PHI nodes "
813 << "are supported currently.\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000814 ORE->emit([&]() {
815 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedPHIOuter",
816 OuterLoop->getStartLoc(),
817 OuterLoop->getHeader())
818 << "Only outer loops with induction or reduction PHI nodes can be"
819 " interchanged currently.";
820 });
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000821 return true;
Florian Hahn4eeff392017-07-03 15:32:00 +0000822 }
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000823
824 // Outer loop cannot have reduction because then loops will not be tightly
825 // nested.
Florian Hahn4eeff392017-07-03 15:32:00 +0000826 if (!Reductions.empty()) {
827 DEBUG(dbgs() << "Outer loops with reductions are not supported "
828 << "currently.\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000829 ORE->emit([&]() {
830 return OptimizationRemarkMissed(DEBUG_TYPE, "ReductionsOuter",
831 OuterLoop->getStartLoc(),
832 OuterLoop->getHeader())
833 << "Outer loops with reductions cannot be interchangeed "
834 "currently.";
835 });
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000836 return true;
Florian Hahn4eeff392017-07-03 15:32:00 +0000837 }
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000838 // TODO: Currently we handle only loops with 1 induction variable.
Florian Hahn4eeff392017-07-03 15:32:00 +0000839 if (Inductions.size() != 1) {
840 DEBUG(dbgs() << "Loops with more than 1 induction variables are not "
841 << "supported currently.\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000842 ORE->emit([&]() {
843 return OptimizationRemarkMissed(DEBUG_TYPE, "MultiIndutionOuter",
844 OuterLoop->getStartLoc(),
845 OuterLoop->getHeader())
846 << "Only outer loops with 1 induction variable can be "
847 "interchanged currently.";
848 });
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000849 return true;
Florian Hahn4eeff392017-07-03 15:32:00 +0000850 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000851
852 // TODO: Triangular loops are not handled for now.
853 if (!isLoopStructureUnderstood(InnerInductionVar)) {
854 DEBUG(dbgs() << "Loop structure not understood by pass\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000855 ORE->emit([&]() {
856 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedStructureInner",
857 InnerLoop->getStartLoc(),
858 InnerLoop->getHeader())
859 << "Inner loop structure not understood currently.";
860 });
Karthik Bhat88db86d2015-03-06 10:11:25 +0000861 return true;
862 }
863
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000864 // TODO: We only handle LCSSA PHI's corresponding to reduction for now.
865 BasicBlock *LoopExitBlock =
866 getLoopLatchExitBlock(OuterLoopLatch, OuterLoopHeader);
Florian Hahn4eeff392017-07-03 15:32:00 +0000867 if (!LoopExitBlock || !containsSafePHI(LoopExitBlock, true)) {
868 DEBUG(dbgs() << "Can only handle LCSSA PHIs in outer loops currently.\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000869 ORE->emit([&]() {
870 return OptimizationRemarkMissed(DEBUG_TYPE, "NoLCSSAPHIOuter",
871 OuterLoop->getStartLoc(),
872 OuterLoop->getHeader())
873 << "Only outer loops with LCSSA PHIs can be interchange "
874 "currently.";
875 });
Karthik Bhat88db86d2015-03-06 10:11:25 +0000876 return true;
Florian Hahn4eeff392017-07-03 15:32:00 +0000877 }
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000878
879 LoopExitBlock = getLoopLatchExitBlock(InnerLoopLatch, InnerLoopHeader);
Florian Hahn4eeff392017-07-03 15:32:00 +0000880 if (!LoopExitBlock || !containsSafePHI(LoopExitBlock, false)) {
881 DEBUG(dbgs() << "Can only handle LCSSA PHIs in inner loops currently.\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000882 ORE->emit([&]() {
883 return OptimizationRemarkMissed(DEBUG_TYPE, "NoLCSSAPHIOuterInner",
884 InnerLoop->getStartLoc(),
885 InnerLoop->getHeader())
886 << "Only inner loops with LCSSA PHIs can be interchange "
887 "currently.";
888 });
Karthik Bhat88db86d2015-03-06 10:11:25 +0000889 return true;
Florian Hahn4eeff392017-07-03 15:32:00 +0000890 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000891
892 // TODO: Current limitation: Since we split the inner loop latch at the point
893 // were induction variable is incremented (induction.next); We cannot have
894 // more than 1 user of induction.next since it would result in broken code
895 // after split.
896 // e.g.
897 // for(i=0;i<N;i++) {
898 // for(j = 0;j<M;j++) {
899 // A[j+1][i+2] = A[j][i]+k;
900 // }
901 // }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000902 Instruction *InnerIndexVarInc = nullptr;
903 if (InnerInductionVar->getIncomingBlock(0) == InnerLoopPreHeader)
904 InnerIndexVarInc =
905 dyn_cast<Instruction>(InnerInductionVar->getIncomingValue(1));
906 else
907 InnerIndexVarInc =
908 dyn_cast<Instruction>(InnerInductionVar->getIncomingValue(0));
909
Florian Hahn4eeff392017-07-03 15:32:00 +0000910 if (!InnerIndexVarInc) {
911 DEBUG(dbgs() << "Did not find an instruction to increment the induction "
912 << "variable.\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000913 ORE->emit([&]() {
914 return OptimizationRemarkMissed(DEBUG_TYPE, "NoIncrementInInner",
915 InnerLoop->getStartLoc(),
916 InnerLoop->getHeader())
917 << "The inner loop does not increment the induction variable.";
918 });
Pete Cooper11bd9582015-07-27 18:37:58 +0000919 return true;
Florian Hahn4eeff392017-07-03 15:32:00 +0000920 }
Pete Cooper11bd9582015-07-27 18:37:58 +0000921
Karthik Bhat88db86d2015-03-06 10:11:25 +0000922 // Since we split the inner loop latch on this induction variable. Make sure
923 // we do not have any instruction between the induction variable and branch
924 // instruction.
925
David Majnemerd7708772016-06-24 04:05:21 +0000926 bool FoundInduction = false;
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000927 for (const Instruction &I : llvm::reverse(*InnerLoopLatch)) {
Florian Hahncd783452017-08-25 16:52:29 +0000928 if (isa<BranchInst>(I) || isa<CmpInst>(I) || isa<TruncInst>(I) ||
929 isa<ZExtInst>(I))
Karthik Bhat88db86d2015-03-06 10:11:25 +0000930 continue;
Florian Hahn4eeff392017-07-03 15:32:00 +0000931
Karthik Bhat88db86d2015-03-06 10:11:25 +0000932 // We found an instruction. If this is not induction variable then it is not
933 // safe to split this loop latch.
Florian Hahn4eeff392017-07-03 15:32:00 +0000934 if (!I.isIdenticalTo(InnerIndexVarInc)) {
935 DEBUG(dbgs() << "Found unsupported instructions between induction "
936 << "variable increment and branch.\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000937 ORE->emit([&]() {
938 return OptimizationRemarkMissed(
939 DEBUG_TYPE, "UnsupportedInsBetweenInduction",
940 InnerLoop->getStartLoc(), InnerLoop->getHeader())
941 << "Found unsupported instruction between induction variable "
942 "increment and branch.";
943 });
Karthik Bhat88db86d2015-03-06 10:11:25 +0000944 return true;
Florian Hahn4eeff392017-07-03 15:32:00 +0000945 }
David Majnemerd7708772016-06-24 04:05:21 +0000946
947 FoundInduction = true;
948 break;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000949 }
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000950 // The loop latch ended and we didn't find the induction variable return as
Karthik Bhat88db86d2015-03-06 10:11:25 +0000951 // current limitation.
Florian Hahn4eeff392017-07-03 15:32:00 +0000952 if (!FoundInduction) {
953 DEBUG(dbgs() << "Did not find the induction variable.\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000954 ORE->emit([&]() {
955 return OptimizationRemarkMissed(DEBUG_TYPE, "NoIndutionVariable",
956 InnerLoop->getStartLoc(),
957 InnerLoop->getHeader())
958 << "Did not find the induction variable.";
959 });
Karthik Bhat88db86d2015-03-06 10:11:25 +0000960 return true;
Florian Hahn4eeff392017-07-03 15:32:00 +0000961 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000962 return false;
963}
964
965bool LoopInterchangeLegality::canInterchangeLoops(unsigned InnerLoopId,
966 unsigned OuterLoopId,
967 CharMatrix &DepMatrix) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000968 if (!isLegalToInterChangeLoops(DepMatrix, InnerLoopId, OuterLoopId)) {
969 DEBUG(dbgs() << "Failed interchange InnerLoopId = " << InnerLoopId
Chad Rosier58ede272016-09-14 16:43:19 +0000970 << " and OuterLoopId = " << OuterLoopId
971 << " due to dependence\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000972 ORE->emit([&]() {
973 return OptimizationRemarkMissed(DEBUG_TYPE, "Dependence",
974 InnerLoop->getStartLoc(),
975 InnerLoop->getHeader())
976 << "Cannot interchange loops due to dependences.";
977 });
Karthik Bhat88db86d2015-03-06 10:11:25 +0000978 return false;
979 }
980
Florian Hahn42840492017-07-31 09:00:52 +0000981 // Check if outer and inner loop contain legal instructions only.
982 for (auto *BB : OuterLoop->blocks())
983 for (Instruction &I : *BB)
984 if (CallInst *CI = dyn_cast<CallInst>(&I)) {
985 // readnone functions do not prevent interchanging.
986 if (CI->doesNotReadMemory())
987 continue;
988 DEBUG(dbgs() << "Loops with call instructions cannot be interchanged "
989 << "safely.");
990 return false;
991 }
992
Karthik Bhat88db86d2015-03-06 10:11:25 +0000993 // Create unique Preheaders if we already do not have one.
994 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader();
995 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
996
997 // Create a unique outer preheader -
998 // 1) If OuterLoop preheader is not present.
999 // 2) If OuterLoop Preheader is same as OuterLoop Header
1000 // 3) If OuterLoop Preheader is same as Header of the previous loop.
1001 // 4) If OuterLoop Preheader is Entry node.
1002 if (!OuterLoopPreHeader || OuterLoopPreHeader == OuterLoop->getHeader() ||
1003 isa<PHINode>(OuterLoopPreHeader->begin()) ||
1004 !OuterLoopPreHeader->getUniquePredecessor()) {
Justin Bogner843fb202015-12-15 19:40:57 +00001005 OuterLoopPreHeader =
1006 InsertPreheaderForLoop(OuterLoop, DT, LI, PreserveLCSSA);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001007 }
1008
1009 if (!InnerLoopPreHeader || InnerLoopPreHeader == InnerLoop->getHeader() ||
1010 InnerLoopPreHeader == OuterLoop->getHeader()) {
Justin Bogner843fb202015-12-15 19:40:57 +00001011 InnerLoopPreHeader =
1012 InsertPreheaderForLoop(InnerLoop, DT, LI, PreserveLCSSA);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001013 }
1014
Karthik Bhat88db86d2015-03-06 10:11:25 +00001015 // TODO: The loops could not be interchanged due to current limitations in the
1016 // transform module.
1017 if (currentLimitations()) {
1018 DEBUG(dbgs() << "Not legal because of current transform limitation\n");
1019 return false;
1020 }
1021
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001022 // Check if the loops are tightly nested.
1023 if (!tightlyNested(OuterLoop, InnerLoop)) {
1024 DEBUG(dbgs() << "Loops not tightly nested\n");
Vivek Pandya95906582017-10-11 17:12:59 +00001025 ORE->emit([&]() {
1026 return OptimizationRemarkMissed(DEBUG_TYPE, "NotTightlyNested",
1027 InnerLoop->getStartLoc(),
1028 InnerLoop->getHeader())
1029 << "Cannot interchange loops because they are not tightly "
1030 "nested.";
1031 });
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001032 return false;
1033 }
1034
Karthik Bhat88db86d2015-03-06 10:11:25 +00001035 return true;
1036}
1037
1038int LoopInterchangeProfitability::getInstrOrderCost() {
1039 unsigned GoodOrder, BadOrder;
1040 BadOrder = GoodOrder = 0;
Florian Hahnf66efd62017-07-24 11:41:30 +00001041 for (BasicBlock *BB : InnerLoop->blocks()) {
1042 for (Instruction &Ins : *BB) {
Karthik Bhat88db86d2015-03-06 10:11:25 +00001043 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Ins)) {
1044 unsigned NumOp = GEP->getNumOperands();
1045 bool FoundInnerInduction = false;
1046 bool FoundOuterInduction = false;
1047 for (unsigned i = 0; i < NumOp; ++i) {
1048 const SCEV *OperandVal = SE->getSCEV(GEP->getOperand(i));
1049 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(OperandVal);
1050 if (!AR)
1051 continue;
1052
1053 // If we find the inner induction after an outer induction e.g.
1054 // for(int i=0;i<N;i++)
1055 // for(int j=0;j<N;j++)
1056 // A[i][j] = A[i-1][j-1]+k;
1057 // then it is a good order.
1058 if (AR->getLoop() == InnerLoop) {
1059 // We found an InnerLoop induction after OuterLoop induction. It is
1060 // a good order.
1061 FoundInnerInduction = true;
1062 if (FoundOuterInduction) {
1063 GoodOrder++;
1064 break;
1065 }
1066 }
1067 // If we find the outer induction after an inner induction e.g.
1068 // for(int i=0;i<N;i++)
1069 // for(int j=0;j<N;j++)
1070 // A[j][i] = A[j-1][i-1]+k;
1071 // then it is a bad order.
1072 if (AR->getLoop() == OuterLoop) {
1073 // We found an OuterLoop induction after InnerLoop induction. It is
1074 // a bad order.
1075 FoundOuterInduction = true;
1076 if (FoundInnerInduction) {
1077 BadOrder++;
1078 break;
1079 }
1080 }
1081 }
1082 }
1083 }
1084 }
1085 return GoodOrder - BadOrder;
1086}
1087
Chad Rosiere6b3a632016-09-14 17:12:30 +00001088static bool isProfitableForVectorization(unsigned InnerLoopId,
1089 unsigned OuterLoopId,
1090 CharMatrix &DepMatrix) {
Karthik Bhat88db86d2015-03-06 10:11:25 +00001091 // TODO: Improve this heuristic to catch more cases.
1092 // If the inner loop is loop independent or doesn't carry any dependency it is
1093 // profitable to move this to outer position.
Florian Hahnf66efd62017-07-24 11:41:30 +00001094 for (auto &Row : DepMatrix) {
1095 if (Row[InnerLoopId] != 'S' && Row[InnerLoopId] != 'I')
Karthik Bhat88db86d2015-03-06 10:11:25 +00001096 return false;
1097 // TODO: We need to improve this heuristic.
Florian Hahnf66efd62017-07-24 11:41:30 +00001098 if (Row[OuterLoopId] != '=')
Karthik Bhat88db86d2015-03-06 10:11:25 +00001099 return false;
1100 }
1101 // If outer loop has dependence and inner loop is loop independent then it is
1102 // profitable to interchange to enable parallelism.
1103 return true;
1104}
1105
1106bool LoopInterchangeProfitability::isProfitable(unsigned InnerLoopId,
1107 unsigned OuterLoopId,
1108 CharMatrix &DepMatrix) {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001109 // TODO: Add better profitability checks.
Karthik Bhat88db86d2015-03-06 10:11:25 +00001110 // e.g
1111 // 1) Construct dependency matrix and move the one with no loop carried dep
1112 // inside to enable vectorization.
1113
1114 // This is rough cost estimation algorithm. It counts the good and bad order
1115 // of induction variables in the instruction and allows reordering if number
1116 // of bad orders is more than good.
Chad Rosier72431892016-09-14 17:07:13 +00001117 int Cost = getInstrOrderCost();
Karthik Bhat88db86d2015-03-06 10:11:25 +00001118 DEBUG(dbgs() << "Cost = " << Cost << "\n");
Chad Rosier72431892016-09-14 17:07:13 +00001119 if (Cost < -LoopInterchangeCostThreshold)
Karthik Bhat88db86d2015-03-06 10:11:25 +00001120 return true;
1121
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001122 // It is not profitable as per current cache profitability model. But check if
Karthik Bhat88db86d2015-03-06 10:11:25 +00001123 // we can move this loop outside to improve parallelism.
Florian Hahnad993522017-07-15 13:13:19 +00001124 if (isProfitableForVectorization(InnerLoopId, OuterLoopId, DepMatrix))
1125 return true;
1126
Vivek Pandya95906582017-10-11 17:12:59 +00001127 ORE->emit([&]() {
1128 return OptimizationRemarkMissed(DEBUG_TYPE, "InterchangeNotProfitable",
1129 InnerLoop->getStartLoc(),
1130 InnerLoop->getHeader())
1131 << "Interchanging loops is too costly (cost="
1132 << ore::NV("Cost", Cost) << ", threshold="
1133 << ore::NV("Threshold", LoopInterchangeCostThreshold)
1134 << ") and it does not improve parallelism.";
1135 });
Florian Hahnad993522017-07-15 13:13:19 +00001136 return false;
Karthik Bhat88db86d2015-03-06 10:11:25 +00001137}
1138
1139void LoopInterchangeTransform::removeChildLoop(Loop *OuterLoop,
1140 Loop *InnerLoop) {
Daniel Jasper6adbd7a2015-03-06 10:39:14 +00001141 for (Loop::iterator I = OuterLoop->begin(), E = OuterLoop->end(); I != E;
1142 ++I) {
Karthik Bhat88db86d2015-03-06 10:11:25 +00001143 if (*I == InnerLoop) {
1144 OuterLoop->removeChildLoop(I);
1145 return;
1146 }
1147 }
Benjamin Kramer8ceb3232015-10-25 22:28:27 +00001148 llvm_unreachable("Couldn't find loop");
Karthik Bhat88db86d2015-03-06 10:11:25 +00001149}
Daniel Jasper6adbd7a2015-03-06 10:39:14 +00001150
Karthik Bhat88db86d2015-03-06 10:11:25 +00001151void LoopInterchangeTransform::restructureLoops(Loop *InnerLoop,
1152 Loop *OuterLoop) {
1153 Loop *OuterLoopParent = OuterLoop->getParentLoop();
1154 if (OuterLoopParent) {
1155 // Remove the loop from its parent loop.
1156 removeChildLoop(OuterLoopParent, OuterLoop);
1157 removeChildLoop(OuterLoop, InnerLoop);
1158 OuterLoopParent->addChildLoop(InnerLoop);
1159 } else {
1160 removeChildLoop(OuterLoop, InnerLoop);
1161 LI->changeTopLevelLoop(OuterLoop, InnerLoop);
1162 }
1163
Andrew Kaylor08c5f1e2015-04-24 17:39:16 +00001164 while (!InnerLoop->empty())
1165 OuterLoop->addChildLoop(InnerLoop->removeChildLoop(InnerLoop->begin()));
Karthik Bhat88db86d2015-03-06 10:11:25 +00001166
1167 InnerLoop->addChildLoop(OuterLoop);
1168}
1169
1170bool LoopInterchangeTransform::transform() {
Karthik Bhat88db86d2015-03-06 10:11:25 +00001171 bool Transformed = false;
1172 Instruction *InnerIndexVar;
1173
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +00001174 if (InnerLoop->getSubLoops().empty()) {
Karthik Bhat88db86d2015-03-06 10:11:25 +00001175 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
1176 DEBUG(dbgs() << "Calling Split Inner Loop\n");
1177 PHINode *InductionPHI = getInductionVariable(InnerLoop, SE);
1178 if (!InductionPHI) {
1179 DEBUG(dbgs() << "Failed to find the point to split loop latch \n");
1180 return false;
1181 }
1182
1183 if (InductionPHI->getIncomingBlock(0) == InnerLoopPreHeader)
1184 InnerIndexVar = dyn_cast<Instruction>(InductionPHI->getIncomingValue(1));
1185 else
1186 InnerIndexVar = dyn_cast<Instruction>(InductionPHI->getIncomingValue(0));
1187
David Green907b60f2017-10-21 13:58:37 +00001188 // Ensure that InductionPHI is the first Phi node as required by
1189 // splitInnerLoopHeader
1190 if (&InductionPHI->getParent()->front() != InductionPHI)
1191 InductionPHI->moveBefore(&InductionPHI->getParent()->front());
1192
Karthik Bhat88db86d2015-03-06 10:11:25 +00001193 // Split at the place were the induction variable is
1194 // incremented/decremented.
1195 // TODO: This splitting logic may not work always. Fix this.
1196 splitInnerLoopLatch(InnerIndexVar);
Chad Rosierf7c76f92016-09-21 13:28:41 +00001197 DEBUG(dbgs() << "splitInnerLoopLatch done\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +00001198
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001199 // Splits the inner loops phi nodes out into a separate basic block.
Karthik Bhat88db86d2015-03-06 10:11:25 +00001200 splitInnerLoopHeader();
Chad Rosierf7c76f92016-09-21 13:28:41 +00001201 DEBUG(dbgs() << "splitInnerLoopHeader done\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +00001202 }
1203
1204 Transformed |= adjustLoopLinks();
1205 if (!Transformed) {
Chad Rosierf7c76f92016-09-21 13:28:41 +00001206 DEBUG(dbgs() << "adjustLoopLinks failed\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +00001207 return false;
1208 }
1209
1210 restructureLoops(InnerLoop, OuterLoop);
1211 return true;
1212}
1213
Benjamin Kramer79442922015-03-06 18:59:14 +00001214void LoopInterchangeTransform::splitInnerLoopLatch(Instruction *Inc) {
Karthik Bhat88db86d2015-03-06 10:11:25 +00001215 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
Karthik Bhat88db86d2015-03-06 10:11:25 +00001216 BasicBlock *InnerLoopLatchPred = InnerLoopLatch;
Benjamin Kramer79442922015-03-06 18:59:14 +00001217 InnerLoopLatch = SplitBlock(InnerLoopLatchPred, Inc, DT, LI);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001218}
1219
Karthik Bhat88db86d2015-03-06 10:11:25 +00001220void LoopInterchangeTransform::splitInnerLoopHeader() {
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001221 // Split the inner loop header out. Here make sure that the reduction PHI's
1222 // stay in the innerloop body.
Karthik Bhat88db86d2015-03-06 10:11:25 +00001223 BasicBlock *InnerLoopHeader = InnerLoop->getHeader();
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001224 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
Florian Hahne54a20e2018-02-12 11:10:58 +00001225 SplitBlock(InnerLoopHeader, InnerLoopHeader->getFirstNonPHI(), DT, LI);
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001226 if (InnerLoopHasReduction) {
Florian Hahne54a20e2018-02-12 11:10:58 +00001227 // Adjust Reduction PHI's in the block. The induction PHI must be the first
1228 // PHI in InnerLoopHeader for this to work.
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001229 SmallVector<PHINode *, 8> PHIVec;
Florian Hahne54a20e2018-02-12 11:10:58 +00001230 for (auto I = std::next(InnerLoopHeader->begin()); isa<PHINode>(I); ++I) {
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001231 PHINode *PHI = dyn_cast<PHINode>(I);
1232 Value *V = PHI->getIncomingValueForBlock(InnerLoopPreHeader);
1233 PHI->replaceAllUsesWith(V);
1234 PHIVec.push_back((PHI));
1235 }
Benjamin Kramer135f7352016-06-26 12:28:59 +00001236 for (PHINode *P : PHIVec) {
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001237 P->eraseFromParent();
1238 }
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001239 }
Karthik Bhat88db86d2015-03-06 10:11:25 +00001240
1241 DEBUG(dbgs() << "Output of splitInnerLoopHeader InnerLoopHeaderSucc & "
Chad Rosierf7c76f92016-09-21 13:28:41 +00001242 "InnerLoopHeader\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +00001243}
1244
Benjamin Kramer79442922015-03-06 18:59:14 +00001245/// \brief Move all instructions except the terminator from FromBB right before
1246/// InsertBefore
1247static void moveBBContents(BasicBlock *FromBB, Instruction *InsertBefore) {
1248 auto &ToList = InsertBefore->getParent()->getInstList();
1249 auto &FromList = FromBB->getInstList();
1250
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001251 ToList.splice(InsertBefore->getIterator(), FromList, FromList.begin(),
1252 FromBB->getTerminator()->getIterator());
Benjamin Kramer79442922015-03-06 18:59:14 +00001253}
1254
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001255void LoopInterchangeTransform::updateIncomingBlock(BasicBlock *CurrBlock,
1256 BasicBlock *OldPred,
1257 BasicBlock *NewPred) {
1258 for (auto I = CurrBlock->begin(); isa<PHINode>(I); ++I) {
1259 PHINode *PHI = cast<PHINode>(I);
1260 unsigned Num = PHI->getNumIncomingValues();
1261 for (unsigned i = 0; i < Num; ++i) {
1262 if (PHI->getIncomingBlock(i) == OldPred)
1263 PHI->setIncomingBlock(i, NewPred);
1264 }
1265 }
1266}
1267
Karthik Bhat88db86d2015-03-06 10:11:25 +00001268bool LoopInterchangeTransform::adjustLoopBranches() {
Karthik Bhat88db86d2015-03-06 10:11:25 +00001269 DEBUG(dbgs() << "adjustLoopBranches called\n");
1270 // Adjust the loop preheader
1271 BasicBlock *InnerLoopHeader = InnerLoop->getHeader();
1272 BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
1273 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
1274 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch();
1275 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader();
1276 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
1277 BasicBlock *OuterLoopPredecessor = OuterLoopPreHeader->getUniquePredecessor();
1278 BasicBlock *InnerLoopLatchPredecessor =
1279 InnerLoopLatch->getUniquePredecessor();
1280 BasicBlock *InnerLoopLatchSuccessor;
1281 BasicBlock *OuterLoopLatchSuccessor;
1282
1283 BranchInst *OuterLoopLatchBI =
1284 dyn_cast<BranchInst>(OuterLoopLatch->getTerminator());
1285 BranchInst *InnerLoopLatchBI =
1286 dyn_cast<BranchInst>(InnerLoopLatch->getTerminator());
1287 BranchInst *OuterLoopHeaderBI =
1288 dyn_cast<BranchInst>(OuterLoopHeader->getTerminator());
1289 BranchInst *InnerLoopHeaderBI =
1290 dyn_cast<BranchInst>(InnerLoopHeader->getTerminator());
1291
1292 if (!OuterLoopPredecessor || !InnerLoopLatchPredecessor ||
1293 !OuterLoopLatchBI || !InnerLoopLatchBI || !OuterLoopHeaderBI ||
1294 !InnerLoopHeaderBI)
1295 return false;
1296
1297 BranchInst *InnerLoopLatchPredecessorBI =
1298 dyn_cast<BranchInst>(InnerLoopLatchPredecessor->getTerminator());
1299 BranchInst *OuterLoopPredecessorBI =
1300 dyn_cast<BranchInst>(OuterLoopPredecessor->getTerminator());
1301
1302 if (!OuterLoopPredecessorBI || !InnerLoopLatchPredecessorBI)
1303 return false;
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001304 BasicBlock *InnerLoopHeaderSuccessor = InnerLoopHeader->getUniqueSuccessor();
1305 if (!InnerLoopHeaderSuccessor)
Karthik Bhat88db86d2015-03-06 10:11:25 +00001306 return false;
1307
1308 // Adjust Loop Preheader and headers
1309
1310 unsigned NumSucc = OuterLoopPredecessorBI->getNumSuccessors();
1311 for (unsigned i = 0; i < NumSucc; ++i) {
1312 if (OuterLoopPredecessorBI->getSuccessor(i) == OuterLoopPreHeader)
1313 OuterLoopPredecessorBI->setSuccessor(i, InnerLoopPreHeader);
1314 }
1315
1316 NumSucc = OuterLoopHeaderBI->getNumSuccessors();
1317 for (unsigned i = 0; i < NumSucc; ++i) {
1318 if (OuterLoopHeaderBI->getSuccessor(i) == OuterLoopLatch)
1319 OuterLoopHeaderBI->setSuccessor(i, LoopExit);
1320 else if (OuterLoopHeaderBI->getSuccessor(i) == InnerLoopPreHeader)
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001321 OuterLoopHeaderBI->setSuccessor(i, InnerLoopHeaderSuccessor);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001322 }
1323
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001324 // Adjust reduction PHI's now that the incoming block has changed.
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001325 updateIncomingBlock(InnerLoopHeaderSuccessor, InnerLoopHeader,
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001326 OuterLoopHeader);
1327
Karthik Bhat88db86d2015-03-06 10:11:25 +00001328 BranchInst::Create(OuterLoopPreHeader, InnerLoopHeaderBI);
1329 InnerLoopHeaderBI->eraseFromParent();
1330
1331 // -------------Adjust loop latches-----------
1332 if (InnerLoopLatchBI->getSuccessor(0) == InnerLoopHeader)
1333 InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(1);
1334 else
1335 InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(0);
1336
1337 NumSucc = InnerLoopLatchPredecessorBI->getNumSuccessors();
1338 for (unsigned i = 0; i < NumSucc; ++i) {
1339 if (InnerLoopLatchPredecessorBI->getSuccessor(i) == InnerLoopLatch)
1340 InnerLoopLatchPredecessorBI->setSuccessor(i, InnerLoopLatchSuccessor);
1341 }
1342
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001343 // Adjust PHI nodes in InnerLoopLatchSuccessor. Update all uses of PHI with
1344 // the value and remove this PHI node from inner loop.
1345 SmallVector<PHINode *, 8> LcssaVec;
1346 for (auto I = InnerLoopLatchSuccessor->begin(); isa<PHINode>(I); ++I) {
1347 PHINode *LcssaPhi = cast<PHINode>(I);
1348 LcssaVec.push_back(LcssaPhi);
1349 }
Benjamin Kramer135f7352016-06-26 12:28:59 +00001350 for (PHINode *P : LcssaVec) {
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001351 Value *Incoming = P->getIncomingValueForBlock(InnerLoopLatch);
1352 P->replaceAllUsesWith(Incoming);
1353 P->eraseFromParent();
1354 }
1355
Karthik Bhat88db86d2015-03-06 10:11:25 +00001356 if (OuterLoopLatchBI->getSuccessor(0) == OuterLoopHeader)
1357 OuterLoopLatchSuccessor = OuterLoopLatchBI->getSuccessor(1);
1358 else
1359 OuterLoopLatchSuccessor = OuterLoopLatchBI->getSuccessor(0);
1360
1361 if (InnerLoopLatchBI->getSuccessor(1) == InnerLoopLatchSuccessor)
1362 InnerLoopLatchBI->setSuccessor(1, OuterLoopLatchSuccessor);
1363 else
1364 InnerLoopLatchBI->setSuccessor(0, OuterLoopLatchSuccessor);
1365
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001366 updateIncomingBlock(OuterLoopLatchSuccessor, OuterLoopLatch, InnerLoopLatch);
1367
Karthik Bhat88db86d2015-03-06 10:11:25 +00001368 if (OuterLoopLatchBI->getSuccessor(0) == OuterLoopLatchSuccessor) {
1369 OuterLoopLatchBI->setSuccessor(0, InnerLoopLatch);
1370 } else {
1371 OuterLoopLatchBI->setSuccessor(1, InnerLoopLatch);
1372 }
1373
1374 return true;
1375}
Karthik Bhat88db86d2015-03-06 10:11:25 +00001376
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +00001377void LoopInterchangeTransform::adjustLoopPreheaders() {
Karthik Bhat88db86d2015-03-06 10:11:25 +00001378 // We have interchanged the preheaders so we need to interchange the data in
1379 // the preheader as well.
1380 // This is because the content of inner preheader was previously executed
1381 // inside the outer loop.
1382 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader();
1383 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
1384 BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
1385 BranchInst *InnerTermBI =
1386 cast<BranchInst>(InnerLoopPreHeader->getTerminator());
1387
Karthik Bhat88db86d2015-03-06 10:11:25 +00001388 // These instructions should now be executed inside the loop.
1389 // Move instruction into a new block after outer header.
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001390 moveBBContents(InnerLoopPreHeader, OuterLoopHeader->getTerminator());
Karthik Bhat88db86d2015-03-06 10:11:25 +00001391 // These instructions were not executed previously in the loop so move them to
1392 // the older inner loop preheader.
Benjamin Kramer79442922015-03-06 18:59:14 +00001393 moveBBContents(OuterLoopPreHeader, InnerTermBI);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001394}
1395
1396bool LoopInterchangeTransform::adjustLoopLinks() {
Karthik Bhat88db86d2015-03-06 10:11:25 +00001397 // Adjust all branches in the inner and outer loop.
1398 bool Changed = adjustLoopBranches();
1399 if (Changed)
1400 adjustLoopPreheaders();
1401 return Changed;
1402}
1403
1404char LoopInterchange::ID = 0;
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +00001405
Karthik Bhat88db86d2015-03-06 10:11:25 +00001406INITIALIZE_PASS_BEGIN(LoopInterchange, "loop-interchange",
1407 "Interchanges loops for cache reuse", false, false)
Chandler Carruth7b560d42015-09-09 17:55:00 +00001408INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Chandler Carruth49c22192016-05-12 22:19:39 +00001409INITIALIZE_PASS_DEPENDENCY(DependenceAnalysisWrapperPass)
Karthik Bhat88db86d2015-03-06 10:11:25 +00001410INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001411INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
Karthik Bhat88db86d2015-03-06 10:11:25 +00001412INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
Easwaran Ramane12c4872016-06-09 19:44:46 +00001413INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass)
Karthik Bhat88db86d2015-03-06 10:11:25 +00001414INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Florian Hahnad993522017-07-15 13:13:19 +00001415INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
Karthik Bhat88db86d2015-03-06 10:11:25 +00001416
1417INITIALIZE_PASS_END(LoopInterchange, "loop-interchange",
1418 "Interchanges loops for cache reuse", false, false)
1419
1420Pass *llvm::createLoopInterchangePass() { return new LoopInterchange(); }