blob: cab6acce771909e6259d449b580418af0f7c4eed [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"
Florian Hahn6e004332018-04-05 10:39:23 +000018#include "llvm/ADT/Statistic.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000019#include "llvm/ADT/StringRef.h"
Karthik Bhat88db86d2015-03-06 10:11:25 +000020#include "llvm/Analysis/AliasAnalysis.h"
Karthik Bhat88db86d2015-03-06 10:11:25 +000021#include "llvm/Analysis/DependenceAnalysis.h"
22#include "llvm/Analysis/LoopInfo.h"
Adam Nemet0965da22017-10-09 23:19:02 +000023#include "llvm/Analysis/OptimizationRemarkEmitter.h"
Karthik Bhat88db86d2015-03-06 10:11:25 +000024#include "llvm/Analysis/ScalarEvolution.h"
Karthik Bhat88db86d2015-03-06 10:11:25 +000025#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000026#include "llvm/IR/BasicBlock.h"
27#include "llvm/IR/Constants.h"
28#include "llvm/IR/DiagnosticInfo.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000029#include "llvm/IR/Dominators.h"
Karthik Bhat88db86d2015-03-06 10:11:25 +000030#include "llvm/IR/Function.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000031#include "llvm/IR/InstrTypes.h"
32#include "llvm/IR/Instruction.h"
33#include "llvm/IR/Instructions.h"
34#include "llvm/IR/Type.h"
35#include "llvm/IR/User.h"
36#include "llvm/IR/Value.h"
Karthik Bhat88db86d2015-03-06 10:11:25 +000037#include "llvm/Pass.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000038#include "llvm/Support/Casting.h"
39#include "llvm/Support/CommandLine.h"
Karthik Bhat88db86d2015-03-06 10:11:25 +000040#include "llvm/Support/Debug.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000041#include "llvm/Support/ErrorHandling.h"
Karthik Bhat88db86d2015-03-06 10:11:25 +000042#include "llvm/Support/raw_ostream.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000043#include "llvm/Transforms/Scalar.h"
David Blaikiea373d182018-03-28 17:44:36 +000044#include "llvm/Transforms/Utils.h"
Karthik Bhat88db86d2015-03-06 10:11:25 +000045#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000046#include "llvm/Transforms/Utils/LoopUtils.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000047#include <cassert>
48#include <utility>
49#include <vector>
Davide Italiano9d8f6f82017-01-29 01:55:24 +000050
Karthik Bhat88db86d2015-03-06 10:11:25 +000051using namespace llvm;
52
53#define DEBUG_TYPE "loop-interchange"
54
Florian Hahn6e004332018-04-05 10:39:23 +000055STATISTIC(LoopsInterchanged, "Number of loops interchanged");
56
Chad Rosier72431892016-09-14 17:07:13 +000057static cl::opt<int> LoopInterchangeCostThreshold(
58 "loop-interchange-threshold", cl::init(0), cl::Hidden,
59 cl::desc("Interchange if you gain more than this number"));
60
Karthik Bhat88db86d2015-03-06 10:11:25 +000061namespace {
62
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000063using LoopVector = SmallVector<Loop *, 8>;
Karthik Bhat88db86d2015-03-06 10:11:25 +000064
65// TODO: Check if we can use a sparse matrix here.
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000066using CharMatrix = std::vector<std::vector<char>>;
67
68} // end anonymous namespace
Karthik Bhat88db86d2015-03-06 10:11:25 +000069
70// Maximum number of dependencies that can be handled in the dependency matrix.
71static const unsigned MaxMemInstrCount = 100;
72
73// Maximum loop depth supported.
74static const unsigned MaxLoopNestDepth = 10;
75
Karthik Bhat88db86d2015-03-06 10:11:25 +000076#ifdef DUMP_DEP_MATRICIES
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000077static void printDepMatrix(CharMatrix &DepMatrix) {
Florian Hahnf66efd62017-07-24 11:41:30 +000078 for (auto &Row : DepMatrix) {
79 for (auto D : Row)
80 DEBUG(dbgs() << D << " ");
Karthik Bhat88db86d2015-03-06 10:11:25 +000081 DEBUG(dbgs() << "\n");
82 }
83}
84#endif
85
Karthik Bhat8210fdf2015-04-23 04:51:44 +000086static bool populateDependencyMatrix(CharMatrix &DepMatrix, unsigned Level,
Chandler Carruth49c22192016-05-12 22:19:39 +000087 Loop *L, DependenceInfo *DI) {
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000088 using ValueVector = SmallVector<Value *, 16>;
89
Karthik Bhat88db86d2015-03-06 10:11:25 +000090 ValueVector MemInstr;
91
Karthik Bhat88db86d2015-03-06 10:11:25 +000092 // For each block.
Florian Hahnf66efd62017-07-24 11:41:30 +000093 for (BasicBlock *BB : L->blocks()) {
Karthik Bhat88db86d2015-03-06 10:11:25 +000094 // Scan the BB and collect legal loads and stores.
Florian Hahnf66efd62017-07-24 11:41:30 +000095 for (Instruction &I : *BB) {
Chad Rosier09c11092016-09-13 12:56:04 +000096 if (!isa<Instruction>(I))
Karthik Bhat88db86d2015-03-06 10:11:25 +000097 return false;
Florian Hahnf66efd62017-07-24 11:41:30 +000098 if (auto *Ld = dyn_cast<LoadInst>(&I)) {
Chad Rosier09c11092016-09-13 12:56:04 +000099 if (!Ld->isSimple())
100 return false;
Florian Hahnf66efd62017-07-24 11:41:30 +0000101 MemInstr.push_back(&I);
102 } else if (auto *St = dyn_cast<StoreInst>(&I)) {
Chad Rosier09c11092016-09-13 12:56:04 +0000103 if (!St->isSimple())
104 return false;
Florian Hahnf66efd62017-07-24 11:41:30 +0000105 MemInstr.push_back(&I);
Chad Rosier09c11092016-09-13 12:56:04 +0000106 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000107 }
108 }
109
110 DEBUG(dbgs() << "Found " << MemInstr.size()
111 << " Loads and Stores to analyze\n");
112
113 ValueVector::iterator I, IE, J, JE;
114
115 for (I = MemInstr.begin(), IE = MemInstr.end(); I != IE; ++I) {
116 for (J = I, JE = MemInstr.end(); J != JE; ++J) {
117 std::vector<char> Dep;
Chad Rosier09c11092016-09-13 12:56:04 +0000118 Instruction *Src = cast<Instruction>(*I);
119 Instruction *Dst = cast<Instruction>(*J);
Chad Rosier90bcb912016-09-07 16:07:17 +0000120 if (Src == Dst)
Karthik Bhat88db86d2015-03-06 10:11:25 +0000121 continue;
Chad Rosier00eb8db2016-09-21 19:16:47 +0000122 // Ignore Input dependencies.
Chad Rosier90bcb912016-09-07 16:07:17 +0000123 if (isa<LoadInst>(Src) && isa<LoadInst>(Dst))
Karthik Bhat88db86d2015-03-06 10:11:25 +0000124 continue;
Chad Rosier00eb8db2016-09-21 19:16:47 +0000125 // Track Output, Flow, and Anti dependencies.
Chad Rosier90bcb912016-09-07 16:07:17 +0000126 if (auto D = DI->depends(Src, Dst, true)) {
Chad Rosier00eb8db2016-09-21 19:16:47 +0000127 assert(D->isOrdered() && "Expected an output, flow or anti dep.");
128 DEBUG(StringRef DepType =
129 D->isFlow() ? "flow" : D->isAnti() ? "anti" : "output";
130 dbgs() << "Found " << DepType
131 << " dependency between Src and Dst\n"
Chad Rosier90bcb912016-09-07 16:07:17 +0000132 << " Src:" << *Src << "\n Dst:" << *Dst << '\n');
Chad Rosier00eb8db2016-09-21 19:16:47 +0000133 unsigned Levels = D->getLevels();
134 char Direction;
135 for (unsigned II = 1; II <= Levels; ++II) {
136 const SCEV *Distance = D->getDistance(II);
137 const SCEVConstant *SCEVConst =
138 dyn_cast_or_null<SCEVConstant>(Distance);
139 if (SCEVConst) {
140 const ConstantInt *CI = SCEVConst->getValue();
141 if (CI->isNegative())
142 Direction = '<';
143 else if (CI->isZero())
144 Direction = '=';
145 else
146 Direction = '>';
147 Dep.push_back(Direction);
148 } else if (D->isScalar(II)) {
149 Direction = 'S';
150 Dep.push_back(Direction);
151 } else {
152 unsigned Dir = D->getDirection(II);
153 if (Dir == Dependence::DVEntry::LT ||
154 Dir == Dependence::DVEntry::LE)
155 Direction = '<';
156 else if (Dir == Dependence::DVEntry::GT ||
157 Dir == Dependence::DVEntry::GE)
158 Direction = '>';
159 else if (Dir == Dependence::DVEntry::EQ)
160 Direction = '=';
161 else
162 Direction = '*';
163 Dep.push_back(Direction);
164 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000165 }
Chad Rosier00eb8db2016-09-21 19:16:47 +0000166 while (Dep.size() != Level) {
167 Dep.push_back('I');
168 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000169
Chad Rosier00eb8db2016-09-21 19:16:47 +0000170 DepMatrix.push_back(Dep);
171 if (DepMatrix.size() > MaxMemInstrCount) {
172 DEBUG(dbgs() << "Cannot handle more than " << MaxMemInstrCount
173 << " dependencies inside loop\n");
174 return false;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000175 }
176 }
177 }
178 }
179
Karthik Bhat88db86d2015-03-06 10:11:25 +0000180 return true;
181}
182
183// A loop is moved from index 'from' to an index 'to'. Update the Dependence
184// matrix by exchanging the two columns.
Chad Rosierd18ea062016-09-13 13:00:29 +0000185static void interChangeDependencies(CharMatrix &DepMatrix, unsigned FromIndx,
186 unsigned ToIndx) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000187 unsigned numRows = DepMatrix.size();
188 for (unsigned i = 0; i < numRows; ++i) {
189 char TmpVal = DepMatrix[i][ToIndx];
190 DepMatrix[i][ToIndx] = DepMatrix[i][FromIndx];
191 DepMatrix[i][FromIndx] = TmpVal;
192 }
193}
194
195// Checks if outermost non '=','S'or'I' dependence in the dependence matrix is
196// '>'
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000197static bool isOuterMostDepPositive(CharMatrix &DepMatrix, unsigned Row,
198 unsigned Column) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000199 for (unsigned i = 0; i <= Column; ++i) {
200 if (DepMatrix[Row][i] == '<')
201 return false;
202 if (DepMatrix[Row][i] == '>')
203 return true;
204 }
205 // All dependencies were '=','S' or 'I'
206 return false;
207}
208
209// Checks if no dependence exist in the dependency matrix in Row before Column.
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000210static bool containsNoDependence(CharMatrix &DepMatrix, unsigned Row,
211 unsigned Column) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000212 for (unsigned i = 0; i < Column; ++i) {
Chandler Carruthfca1ff02016-11-03 16:39:25 +0000213 if (DepMatrix[Row][i] != '=' && DepMatrix[Row][i] != 'S' &&
Karthik Bhat88db86d2015-03-06 10:11:25 +0000214 DepMatrix[Row][i] != 'I')
215 return false;
216 }
217 return true;
218}
219
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000220static bool validDepInterchange(CharMatrix &DepMatrix, unsigned Row,
221 unsigned OuterLoopId, char InnerDep,
222 char OuterDep) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000223 if (isOuterMostDepPositive(DepMatrix, Row, OuterLoopId))
224 return false;
225
226 if (InnerDep == OuterDep)
227 return true;
228
229 // It is legal to interchange if and only if after interchange no row has a
230 // '>' direction as the leftmost non-'='.
231
232 if (InnerDep == '=' || InnerDep == 'S' || InnerDep == 'I')
233 return true;
234
235 if (InnerDep == '<')
236 return true;
237
238 if (InnerDep == '>') {
239 // If OuterLoopId represents outermost loop then interchanging will make the
240 // 1st dependency as '>'
241 if (OuterLoopId == 0)
242 return false;
243
244 // If all dependencies before OuterloopId are '=','S'or 'I'. Then
245 // interchanging will result in this row having an outermost non '='
246 // dependency of '>'
247 if (!containsNoDependence(DepMatrix, Row, OuterLoopId))
248 return true;
249 }
250
251 return false;
252}
253
254// Checks if it is legal to interchange 2 loops.
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000255// [Theorem] A permutation of the loops in a perfect nest is legal if and only
Chad Rosier61683a22016-09-13 13:08:53 +0000256// if the direction matrix, after the same permutation is applied to its
257// columns, has no ">" direction as the leftmost non-"=" direction in any row.
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000258static bool isLegalToInterChangeLoops(CharMatrix &DepMatrix,
259 unsigned InnerLoopId,
260 unsigned OuterLoopId) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000261 unsigned NumRows = DepMatrix.size();
262 // For each row check if it is valid to interchange.
263 for (unsigned Row = 0; Row < NumRows; ++Row) {
264 char InnerDep = DepMatrix[Row][InnerLoopId];
265 char OuterDep = DepMatrix[Row][OuterLoopId];
266 if (InnerDep == '*' || OuterDep == '*')
267 return false;
Chad Rosier61683a22016-09-13 13:08:53 +0000268 if (!validDepInterchange(DepMatrix, Row, OuterLoopId, InnerDep, OuterDep))
Karthik Bhat88db86d2015-03-06 10:11:25 +0000269 return false;
270 }
271 return true;
272}
273
274static void populateWorklist(Loop &L, SmallVector<LoopVector, 8> &V) {
Chad Rosierf5814f52016-09-07 15:56:59 +0000275 DEBUG(dbgs() << "Calling populateWorklist on Func: "
276 << L.getHeader()->getParent()->getName() << " Loop: %"
277 << L.getHeader()->getName() << '\n');
Karthik Bhat88db86d2015-03-06 10:11:25 +0000278 LoopVector LoopList;
279 Loop *CurrentLoop = &L;
Benjamin Kramere448b5b2015-07-13 17:21:14 +0000280 const std::vector<Loop *> *Vec = &CurrentLoop->getSubLoops();
281 while (!Vec->empty()) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000282 // The current loop has multiple subloops in it hence it is not tightly
283 // nested.
284 // Discard all loops above it added into Worklist.
Benjamin Kramere448b5b2015-07-13 17:21:14 +0000285 if (Vec->size() != 1) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000286 LoopList.clear();
287 return;
288 }
289 LoopList.push_back(CurrentLoop);
Benjamin Kramere448b5b2015-07-13 17:21:14 +0000290 CurrentLoop = Vec->front();
291 Vec = &CurrentLoop->getSubLoops();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000292 }
293 LoopList.push_back(CurrentLoop);
Benjamin Kramere448b5b2015-07-13 17:21:14 +0000294 V.push_back(std::move(LoopList));
Karthik Bhat88db86d2015-03-06 10:11:25 +0000295}
296
297static PHINode *getInductionVariable(Loop *L, ScalarEvolution *SE) {
298 PHINode *InnerIndexVar = L->getCanonicalInductionVariable();
299 if (InnerIndexVar)
300 return InnerIndexVar;
301 if (L->getLoopLatch() == nullptr || L->getLoopPredecessor() == nullptr)
302 return nullptr;
303 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
304 PHINode *PhiVar = cast<PHINode>(I);
305 Type *PhiTy = PhiVar->getType();
306 if (!PhiTy->isIntegerTy() && !PhiTy->isFloatingPointTy() &&
307 !PhiTy->isPointerTy())
308 return nullptr;
309 const SCEVAddRecExpr *AddRec =
310 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(PhiVar));
311 if (!AddRec || !AddRec->isAffine())
312 continue;
313 const SCEV *Step = AddRec->getStepRecurrence(*SE);
Chad Rosierf7c76f92016-09-21 13:28:41 +0000314 if (!isa<SCEVConstant>(Step))
Karthik Bhat88db86d2015-03-06 10:11:25 +0000315 continue;
316 // Found the induction variable.
317 // FIXME: Handle loops with more than one induction variable. Note that,
318 // currently, legality makes sure we have only one induction variable.
319 return PhiVar;
320 }
321 return nullptr;
322}
323
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000324namespace {
325
Karthik Bhat88db86d2015-03-06 10:11:25 +0000326/// LoopInterchangeLegality checks if it is legal to interchange the loop.
327class LoopInterchangeLegality {
328public:
329 LoopInterchangeLegality(Loop *Outer, Loop *Inner, ScalarEvolution *SE,
Florian Hahnad993522017-07-15 13:13:19 +0000330 LoopInfo *LI, DominatorTree *DT, bool PreserveLCSSA,
331 OptimizationRemarkEmitter *ORE)
Justin Bogner843fb202015-12-15 19:40:57 +0000332 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), LI(LI), DT(DT),
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000333 PreserveLCSSA(PreserveLCSSA), ORE(ORE) {}
Karthik Bhat88db86d2015-03-06 10:11:25 +0000334
335 /// Check if the loops can be interchanged.
336 bool canInterchangeLoops(unsigned InnerLoopId, unsigned OuterLoopId,
337 CharMatrix &DepMatrix);
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000338
Karthik Bhat88db86d2015-03-06 10:11:25 +0000339 /// Check if the loop structure is understood. We do not handle triangular
340 /// loops for now.
341 bool isLoopStructureUnderstood(PHINode *InnerInductionVar);
342
343 bool currentLimitations();
344
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000345 bool hasInnerLoopReduction() { return InnerLoopHasReduction; }
346
Karthik Bhat88db86d2015-03-06 10:11:25 +0000347private:
348 bool tightlyNested(Loop *Outer, Loop *Inner);
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000349 bool containsUnsafeInstructionsInHeader(BasicBlock *BB);
350 bool areAllUsesReductions(Instruction *Ins, Loop *L);
351 bool containsUnsafeInstructionsInLatch(BasicBlock *BB);
352 bool findInductionAndReductions(Loop *L,
353 SmallVector<PHINode *, 8> &Inductions,
354 SmallVector<PHINode *, 8> &Reductions);
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000355
Karthik Bhat88db86d2015-03-06 10:11:25 +0000356 Loop *OuterLoop;
357 Loop *InnerLoop;
358
Karthik Bhat88db86d2015-03-06 10:11:25 +0000359 ScalarEvolution *SE;
Justin Bogner843fb202015-12-15 19:40:57 +0000360 LoopInfo *LI;
361 DominatorTree *DT;
362 bool PreserveLCSSA;
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000363
Florian Hahnad993522017-07-15 13:13:19 +0000364 /// Interface to emit optimization remarks.
365 OptimizationRemarkEmitter *ORE;
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000366
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000367 bool InnerLoopHasReduction = false;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000368};
369
370/// LoopInterchangeProfitability checks if it is profitable to interchange the
371/// loop.
372class LoopInterchangeProfitability {
373public:
Florian Hahnad993522017-07-15 13:13:19 +0000374 LoopInterchangeProfitability(Loop *Outer, Loop *Inner, ScalarEvolution *SE,
375 OptimizationRemarkEmitter *ORE)
376 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), ORE(ORE) {}
Karthik Bhat88db86d2015-03-06 10:11:25 +0000377
Vikram TV74b41112015-12-09 05:16:24 +0000378 /// Check if the loop interchange is profitable.
Karthik Bhat88db86d2015-03-06 10:11:25 +0000379 bool isProfitable(unsigned InnerLoopId, unsigned OuterLoopId,
380 CharMatrix &DepMatrix);
381
382private:
383 int getInstrOrderCost();
384
385 Loop *OuterLoop;
386 Loop *InnerLoop;
387
388 /// Scev analysis.
389 ScalarEvolution *SE;
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000390
Florian Hahnad993522017-07-15 13:13:19 +0000391 /// Interface to emit optimization remarks.
392 OptimizationRemarkEmitter *ORE;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000393};
394
Vikram TV74b41112015-12-09 05:16:24 +0000395/// LoopInterchangeTransform interchanges the loop.
Karthik Bhat88db86d2015-03-06 10:11:25 +0000396class LoopInterchangeTransform {
397public:
398 LoopInterchangeTransform(Loop *Outer, Loop *Inner, ScalarEvolution *SE,
399 LoopInfo *LI, DominatorTree *DT,
Justin Bogner843fb202015-12-15 19:40:57 +0000400 BasicBlock *LoopNestExit,
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000401 bool InnerLoopContainsReductions)
Karthik Bhat88db86d2015-03-06 10:11:25 +0000402 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), LI(LI), DT(DT),
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000403 LoopExit(LoopNestExit),
404 InnerLoopHasReduction(InnerLoopContainsReductions) {}
Karthik Bhat88db86d2015-03-06 10:11:25 +0000405
406 /// Interchange OuterLoop and InnerLoop.
407 bool transform();
Florian Hahn831a7572018-04-05 09:48:45 +0000408 void restructureLoops(Loop *NewInner, Loop *NewOuter,
409 BasicBlock *OrigInnerPreHeader,
410 BasicBlock *OrigOuterPreHeader);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000411 void removeChildLoop(Loop *OuterLoop, Loop *InnerLoop);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000412
413private:
414 void splitInnerLoopLatch(Instruction *);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000415 void splitInnerLoopHeader();
416 bool adjustLoopLinks();
417 void adjustLoopPreheaders();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000418 bool adjustLoopBranches();
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000419 void updateIncomingBlock(BasicBlock *CurrBlock, BasicBlock *OldPred,
420 BasicBlock *NewPred);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000421
422 Loop *OuterLoop;
423 Loop *InnerLoop;
424
425 /// Scev analysis.
426 ScalarEvolution *SE;
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000427
Karthik Bhat88db86d2015-03-06 10:11:25 +0000428 LoopInfo *LI;
429 DominatorTree *DT;
430 BasicBlock *LoopExit;
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000431 bool InnerLoopHasReduction;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000432};
433
Vikram TV74b41112015-12-09 05:16:24 +0000434// Main LoopInterchange Pass.
Karthik Bhat88db86d2015-03-06 10:11:25 +0000435struct LoopInterchange : public FunctionPass {
436 static char ID;
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000437 ScalarEvolution *SE = nullptr;
438 LoopInfo *LI = nullptr;
439 DependenceInfo *DI = nullptr;
440 DominatorTree *DT = nullptr;
Justin Bogner843fb202015-12-15 19:40:57 +0000441 bool PreserveLCSSA;
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000442
Florian Hahnad993522017-07-15 13:13:19 +0000443 /// Interface to emit optimization remarks.
444 OptimizationRemarkEmitter *ORE;
445
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000446 LoopInterchange() : FunctionPass(ID) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000447 initializeLoopInterchangePass(*PassRegistry::getPassRegistry());
448 }
449
450 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000451 AU.addRequired<ScalarEvolutionWrapperPass>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000452 AU.addRequired<AAResultsWrapperPass>();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000453 AU.addRequired<DominatorTreeWrapperPass>();
454 AU.addRequired<LoopInfoWrapperPass>();
Chandler Carruth49c22192016-05-12 22:19:39 +0000455 AU.addRequired<DependenceAnalysisWrapperPass>();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000456 AU.addRequiredID(LoopSimplifyID);
457 AU.addRequiredID(LCSSAID);
Florian Hahnad993522017-07-15 13:13:19 +0000458 AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
Florian Hahnc6296fe2018-02-14 13:13:15 +0000459
460 AU.addPreserved<DominatorTreeWrapperPass>();
Florian Hahn831a7572018-04-05 09:48:45 +0000461 AU.addPreserved<LoopInfoWrapperPass>();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000462 }
463
464 bool runOnFunction(Function &F) override {
Andrew Kaylor50271f72016-05-03 22:32:30 +0000465 if (skipFunction(F))
466 return false;
467
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000468 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000469 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Chandler Carruth49c22192016-05-12 22:19:39 +0000470 DI = &getAnalysis<DependenceAnalysisWrapperPass>().getDI();
Florian Hahnc6296fe2018-02-14 13:13:15 +0000471 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Florian Hahnad993522017-07-15 13:13:19 +0000472 ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
Justin Bogner843fb202015-12-15 19:40:57 +0000473 PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
474
Karthik Bhat88db86d2015-03-06 10:11:25 +0000475 // Build up a worklist of loop pairs to analyze.
476 SmallVector<LoopVector, 8> Worklist;
477
478 for (Loop *L : *LI)
479 populateWorklist(*L, Worklist);
480
Chad Rosiera4c42462016-09-12 13:24:47 +0000481 DEBUG(dbgs() << "Worklist size = " << Worklist.size() << "\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000482 bool Changed = true;
483 while (!Worklist.empty()) {
484 LoopVector LoopList = Worklist.pop_back_val();
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000485 Changed = processLoopList(LoopList, F);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000486 }
487 return Changed;
488 }
489
490 bool isComputableLoopNest(LoopVector LoopList) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000491 for (Loop *L : LoopList) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000492 const SCEV *ExitCountOuter = SE->getBackedgeTakenCount(L);
493 if (ExitCountOuter == SE->getCouldNotCompute()) {
Chad Rosierf7c76f92016-09-21 13:28:41 +0000494 DEBUG(dbgs() << "Couldn't compute backedge count\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000495 return false;
496 }
497 if (L->getNumBackEdges() != 1) {
498 DEBUG(dbgs() << "NumBackEdges is not equal to 1\n");
499 return false;
500 }
501 if (!L->getExitingBlock()) {
Chad Rosierf7c76f92016-09-21 13:28:41 +0000502 DEBUG(dbgs() << "Loop doesn't have unique exit block\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000503 return false;
504 }
505 }
506 return true;
507 }
508
Benjamin Kramerc321e532016-06-08 19:09:22 +0000509 unsigned selectLoopForInterchange(const LoopVector &LoopList) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000510 // TODO: Add a better heuristic to select the loop to be interchanged based
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000511 // on the dependence matrix. Currently we select the innermost loop.
Karthik Bhat88db86d2015-03-06 10:11:25 +0000512 return LoopList.size() - 1;
513 }
514
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000515 bool processLoopList(LoopVector LoopList, Function &F) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000516 bool Changed = false;
Chad Rosier7ea0d392016-09-13 13:30:30 +0000517 unsigned LoopNestDepth = LoopList.size();
518 if (LoopNestDepth < 2) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000519 DEBUG(dbgs() << "Loop doesn't contain minimum nesting level.\n");
520 return false;
521 }
Chad Rosier7ea0d392016-09-13 13:30:30 +0000522 if (LoopNestDepth > MaxLoopNestDepth) {
523 DEBUG(dbgs() << "Cannot handle loops of depth greater than "
524 << MaxLoopNestDepth << "\n");
525 return false;
526 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000527 if (!isComputableLoopNest(LoopList)) {
Chad Rosiera4c42462016-09-12 13:24:47 +0000528 DEBUG(dbgs() << "Not valid loop candidate for interchange\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000529 return false;
530 }
Chad Rosier7ea0d392016-09-13 13:30:30 +0000531
532 DEBUG(dbgs() << "Processing LoopList of size = " << LoopNestDepth << "\n");
533
534 CharMatrix DependencyMatrix;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000535 Loop *OuterMostLoop = *(LoopList.begin());
Chad Rosier7ea0d392016-09-13 13:30:30 +0000536 if (!populateDependencyMatrix(DependencyMatrix, LoopNestDepth,
Chandler Carruth49c22192016-05-12 22:19:39 +0000537 OuterMostLoop, DI)) {
Chad Rosierf7c76f92016-09-21 13:28:41 +0000538 DEBUG(dbgs() << "Populating dependency matrix failed\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000539 return false;
540 }
541#ifdef DUMP_DEP_MATRICIES
Chad Rosier58ede272016-09-14 16:43:19 +0000542 DEBUG(dbgs() << "Dependence before interchange\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000543 printDepMatrix(DependencyMatrix);
544#endif
545
546 BasicBlock *OuterMostLoopLatch = OuterMostLoop->getLoopLatch();
547 BranchInst *OuterMostLoopLatchBI =
548 dyn_cast<BranchInst>(OuterMostLoopLatch->getTerminator());
Florian Hahn1f95ef12018-02-13 10:02:52 +0000549 if (!OuterMostLoopLatchBI || OuterMostLoopLatchBI->getNumSuccessors() != 2)
Karthik Bhat88db86d2015-03-06 10:11:25 +0000550 return false;
551
552 // Since we currently do not handle LCSSA PHI's any failure in loop
553 // condition will now branch to LoopNestExit.
554 // TODO: This should be removed once we handle LCSSA PHI nodes.
555
556 // Get the Outermost loop exit.
557 BasicBlock *LoopNestExit;
558 if (OuterMostLoopLatchBI->getSuccessor(0) == OuterMostLoop->getHeader())
559 LoopNestExit = OuterMostLoopLatchBI->getSuccessor(1);
560 else
561 LoopNestExit = OuterMostLoopLatchBI->getSuccessor(0);
562
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000563 if (isa<PHINode>(LoopNestExit->begin())) {
564 DEBUG(dbgs() << "PHI Nodes in loop nest exit is not handled for now "
565 "since on failure all loops branch to loop nest exit.\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000566 return false;
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000567 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000568
569 unsigned SelecLoopId = selectLoopForInterchange(LoopList);
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000570 // Move the selected loop outwards to the best possible position.
Karthik Bhat88db86d2015-03-06 10:11:25 +0000571 for (unsigned i = SelecLoopId; i > 0; i--) {
572 bool Interchanged =
573 processLoop(LoopList, i, i - 1, LoopNestExit, DependencyMatrix);
574 if (!Interchanged)
575 return Changed;
576 // Loops interchanged reflect the same in LoopList
Benjamin Kramer79442922015-03-06 18:59:14 +0000577 std::swap(LoopList[i - 1], LoopList[i]);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000578
579 // Update the DependencyMatrix
Chad Rosierd18ea062016-09-13 13:00:29 +0000580 interChangeDependencies(DependencyMatrix, i, i - 1);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000581#ifdef DUMP_DEP_MATRICIES
Chad Rosier58ede272016-09-14 16:43:19 +0000582 DEBUG(dbgs() << "Dependence after interchange\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000583 printDepMatrix(DependencyMatrix);
584#endif
585 Changed |= Interchanged;
586 }
587 return Changed;
588 }
589
590 bool processLoop(LoopVector LoopList, unsigned InnerLoopId,
591 unsigned OuterLoopId, BasicBlock *LoopNestExit,
592 std::vector<std::vector<char>> &DependencyMatrix) {
Chad Rosier13bc0d192016-09-07 18:15:12 +0000593 DEBUG(dbgs() << "Processing Inner Loop Id = " << InnerLoopId
Karthik Bhat88db86d2015-03-06 10:11:25 +0000594 << " and OuterLoopId = " << OuterLoopId << "\n");
595 Loop *InnerLoop = LoopList[InnerLoopId];
596 Loop *OuterLoop = LoopList[OuterLoopId];
597
Justin Bogner843fb202015-12-15 19:40:57 +0000598 LoopInterchangeLegality LIL(OuterLoop, InnerLoop, SE, LI, DT,
Florian Hahnad993522017-07-15 13:13:19 +0000599 PreserveLCSSA, ORE);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000600 if (!LIL.canInterchangeLoops(InnerLoopId, OuterLoopId, DependencyMatrix)) {
Sebastian Popbf6e1c22018-03-06 21:55:59 +0000601 DEBUG(dbgs() << "Not interchanging loops. Cannot prove legality.\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000602 return false;
603 }
604 DEBUG(dbgs() << "Loops are legal to interchange\n");
Florian Hahnad993522017-07-15 13:13:19 +0000605 LoopInterchangeProfitability LIP(OuterLoop, InnerLoop, SE, ORE);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000606 if (!LIP.isProfitable(InnerLoopId, OuterLoopId, DependencyMatrix)) {
Sebastian Popbf6e1c22018-03-06 21:55:59 +0000607 DEBUG(dbgs() << "Interchanging loops not profitable.\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000608 return false;
609 }
610
Vivek Pandya95906582017-10-11 17:12:59 +0000611 ORE->emit([&]() {
612 return OptimizationRemark(DEBUG_TYPE, "Interchanged",
613 InnerLoop->getStartLoc(),
614 InnerLoop->getHeader())
615 << "Loop interchanged with enclosing loop.";
616 });
Florian Hahnad993522017-07-15 13:13:19 +0000617
Justin Bogner843fb202015-12-15 19:40:57 +0000618 LoopInterchangeTransform LIT(OuterLoop, InnerLoop, SE, LI, DT,
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000619 LoopNestExit, LIL.hasInnerLoopReduction());
Karthik Bhat88db86d2015-03-06 10:11:25 +0000620 LIT.transform();
Sebastian Popbf6e1c22018-03-06 21:55:59 +0000621 DEBUG(dbgs() << "Loops interchanged.\n");
Florian Hahn6e004332018-04-05 10:39:23 +0000622 LoopsInterchanged++;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000623 return true;
624 }
625};
626
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000627} // end anonymous namespace
628
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000629bool LoopInterchangeLegality::areAllUsesReductions(Instruction *Ins, Loop *L) {
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000630 return llvm::none_of(Ins->users(), [=](User *U) -> bool {
David Majnemer0a16c222016-08-11 21:15:00 +0000631 auto *UserIns = dyn_cast<PHINode>(U);
Tyler Nowicki0a913102015-06-16 18:07:34 +0000632 RecurrenceDescriptor RD;
633 return !UserIns || !RecurrenceDescriptor::isReductionPHI(UserIns, L, RD);
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000634 });
635}
Karthik Bhat88db86d2015-03-06 10:11:25 +0000636
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000637bool LoopInterchangeLegality::containsUnsafeInstructionsInHeader(
638 BasicBlock *BB) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000639 for (auto I = BB->begin(), E = BB->end(); I != E; ++I) {
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000640 // Load corresponding to reduction PHI's are safe while concluding if
641 // tightly nested.
642 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
643 if (!areAllUsesReductions(L, InnerLoop))
644 return true;
645 } else if (I->mayHaveSideEffects() || I->mayReadFromMemory())
646 return true;
647 }
648 return false;
649}
650
651bool LoopInterchangeLegality::containsUnsafeInstructionsInLatch(
652 BasicBlock *BB) {
653 for (auto I = BB->begin(), E = BB->end(); I != E; ++I) {
654 // Stores corresponding to reductions are safe while concluding if tightly
655 // nested.
656 if (StoreInst *L = dyn_cast<StoreInst>(I)) {
Chad Rosierf7c76f92016-09-21 13:28:41 +0000657 if (!isa<PHINode>(L->getOperand(0)))
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000658 return true;
659 } else if (I->mayHaveSideEffects() || I->mayReadFromMemory())
Karthik Bhat88db86d2015-03-06 10:11:25 +0000660 return true;
661 }
662 return false;
663}
664
665bool LoopInterchangeLegality::tightlyNested(Loop *OuterLoop, Loop *InnerLoop) {
666 BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
667 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
668 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch();
669
Chad Rosierf7c76f92016-09-21 13:28:41 +0000670 DEBUG(dbgs() << "Checking if loops are tightly nested\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000671
672 // A perfectly nested loop will not have any branch in between the outer and
673 // inner block i.e. outer header will branch to either inner preheader and
674 // outerloop latch.
Chad Rosierf7c76f92016-09-21 13:28:41 +0000675 BranchInst *OuterLoopHeaderBI =
Karthik Bhat88db86d2015-03-06 10:11:25 +0000676 dyn_cast<BranchInst>(OuterLoopHeader->getTerminator());
Chad Rosierf7c76f92016-09-21 13:28:41 +0000677 if (!OuterLoopHeaderBI)
Karthik Bhat88db86d2015-03-06 10:11:25 +0000678 return false;
Chad Rosierf7c76f92016-09-21 13:28:41 +0000679
Florian Hahnf66efd62017-07-24 11:41:30 +0000680 for (BasicBlock *Succ : OuterLoopHeaderBI->successors())
681 if (Succ != InnerLoopPreHeader && Succ != OuterLoopLatch)
Karthik Bhat88db86d2015-03-06 10:11:25 +0000682 return false;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000683
Chad Rosierf7c76f92016-09-21 13:28:41 +0000684 DEBUG(dbgs() << "Checking instructions in Loop header and Loop latch\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000685 // We do not have any basic block in between now make sure the outer header
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000686 // and outer loop latch doesn't contain any unsafe instructions.
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000687 if (containsUnsafeInstructionsInHeader(OuterLoopHeader) ||
688 containsUnsafeInstructionsInLatch(OuterLoopLatch))
Karthik Bhat88db86d2015-03-06 10:11:25 +0000689 return false;
690
Chad Rosierf7c76f92016-09-21 13:28:41 +0000691 DEBUG(dbgs() << "Loops are perfectly nested\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000692 // We have a perfect loop nest.
693 return true;
694}
695
Karthik Bhat88db86d2015-03-06 10:11:25 +0000696bool LoopInterchangeLegality::isLoopStructureUnderstood(
697 PHINode *InnerInduction) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000698 unsigned Num = InnerInduction->getNumOperands();
699 BasicBlock *InnerLoopPreheader = InnerLoop->getLoopPreheader();
700 for (unsigned i = 0; i < Num; ++i) {
701 Value *Val = InnerInduction->getOperand(i);
702 if (isa<Constant>(Val))
703 continue;
704 Instruction *I = dyn_cast<Instruction>(Val);
705 if (!I)
706 return false;
707 // TODO: Handle triangular loops.
708 // e.g. for(int i=0;i<N;i++)
709 // for(int j=i;j<N;j++)
710 unsigned IncomBlockIndx = PHINode::getIncomingValueNumForOperand(i);
711 if (InnerInduction->getIncomingBlock(IncomBlockIndx) ==
712 InnerLoopPreheader &&
713 !OuterLoop->isLoopInvariant(I)) {
714 return false;
715 }
716 }
717 return true;
718}
719
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000720bool LoopInterchangeLegality::findInductionAndReductions(
721 Loop *L, SmallVector<PHINode *, 8> &Inductions,
722 SmallVector<PHINode *, 8> &Reductions) {
723 if (!L->getLoopLatch() || !L->getLoopPredecessor())
724 return false;
725 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
Tyler Nowicki0a913102015-06-16 18:07:34 +0000726 RecurrenceDescriptor RD;
James Molloy1bbf15c2015-08-27 09:53:00 +0000727 InductionDescriptor ID;
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000728 PHINode *PHI = cast<PHINode>(I);
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000729 if (InductionDescriptor::isInductionPHI(PHI, L, SE, ID))
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000730 Inductions.push_back(PHI);
Tyler Nowicki0a913102015-06-16 18:07:34 +0000731 else if (RecurrenceDescriptor::isReductionPHI(PHI, L, RD))
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000732 Reductions.push_back(PHI);
733 else {
734 DEBUG(
735 dbgs() << "Failed to recognize PHI as an induction or reduction.\n");
736 return false;
737 }
738 }
739 return true;
740}
741
742static bool containsSafePHI(BasicBlock *Block, bool isOuterLoopExitBlock) {
743 for (auto I = Block->begin(); isa<PHINode>(I); ++I) {
744 PHINode *PHI = cast<PHINode>(I);
745 // Reduction lcssa phi will have only 1 incoming block that from loop latch.
746 if (PHI->getNumIncomingValues() > 1)
747 return false;
748 Instruction *Ins = dyn_cast<Instruction>(PHI->getIncomingValue(0));
749 if (!Ins)
750 return false;
751 // Incoming value for lcssa phi's in outer loop exit can only be inner loop
752 // exits lcssa phi else it would not be tightly nested.
753 if (!isa<PHINode>(Ins) && isOuterLoopExitBlock)
754 return false;
755 }
756 return true;
757}
758
759static BasicBlock *getLoopLatchExitBlock(BasicBlock *LatchBlock,
760 BasicBlock *LoopHeader) {
761 if (BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator())) {
Florian Hahnf66efd62017-07-24 11:41:30 +0000762 assert(BI->getNumSuccessors() == 2 &&
763 "Branch leaving loop latch must have 2 successors");
764 for (BasicBlock *Succ : BI->successors()) {
765 if (Succ == LoopHeader)
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000766 continue;
Florian Hahnf66efd62017-07-24 11:41:30 +0000767 return Succ;
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000768 }
769 }
770 return nullptr;
771}
772
Karthik Bhat88db86d2015-03-06 10:11:25 +0000773// This function indicates the current limitations in the transform as a result
774// of which we do not proceed.
775bool LoopInterchangeLegality::currentLimitations() {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000776 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
777 BasicBlock *InnerLoopHeader = InnerLoop->getHeader();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000778 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
779 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch();
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000780 BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000781
782 PHINode *InnerInductionVar;
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000783 SmallVector<PHINode *, 8> Inductions;
784 SmallVector<PHINode *, 8> Reductions;
Florian Hahn4eeff392017-07-03 15:32:00 +0000785 if (!findInductionAndReductions(InnerLoop, Inductions, Reductions)) {
786 DEBUG(dbgs() << "Only inner loops with induction or reduction PHI nodes "
787 << "are supported currently.\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000788 ORE->emit([&]() {
789 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedPHIInner",
790 InnerLoop->getStartLoc(),
791 InnerLoop->getHeader())
792 << "Only inner loops with induction or reduction PHI nodes can be"
793 " interchange currently.";
794 });
Karthik Bhat88db86d2015-03-06 10:11:25 +0000795 return true;
Florian Hahn4eeff392017-07-03 15:32:00 +0000796 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000797
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000798 // TODO: Currently we handle only loops with 1 induction variable.
799 if (Inductions.size() != 1) {
800 DEBUG(dbgs() << "We currently only support loops with 1 induction variable."
801 << "Failed to interchange due to current limitation\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000802 ORE->emit([&]() {
803 return OptimizationRemarkMissed(DEBUG_TYPE, "MultiInductionInner",
804 InnerLoop->getStartLoc(),
805 InnerLoop->getHeader())
806 << "Only inner loops with 1 induction variable can be "
807 "interchanged currently.";
808 });
Karthik Bhat88db86d2015-03-06 10:11:25 +0000809 return true;
810 }
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000811 if (Reductions.size() > 0)
812 InnerLoopHasReduction = true;
813
814 InnerInductionVar = Inductions.pop_back_val();
815 Reductions.clear();
Florian Hahn4eeff392017-07-03 15:32:00 +0000816 if (!findInductionAndReductions(OuterLoop, Inductions, Reductions)) {
817 DEBUG(dbgs() << "Only outer loops with induction or reduction PHI nodes "
818 << "are supported currently.\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000819 ORE->emit([&]() {
820 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedPHIOuter",
821 OuterLoop->getStartLoc(),
822 OuterLoop->getHeader())
823 << "Only outer loops with induction or reduction PHI nodes can be"
824 " interchanged currently.";
825 });
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000826 return true;
Florian Hahn4eeff392017-07-03 15:32:00 +0000827 }
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000828
829 // Outer loop cannot have reduction because then loops will not be tightly
830 // nested.
Florian Hahn4eeff392017-07-03 15:32:00 +0000831 if (!Reductions.empty()) {
832 DEBUG(dbgs() << "Outer loops with reductions are not supported "
833 << "currently.\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000834 ORE->emit([&]() {
835 return OptimizationRemarkMissed(DEBUG_TYPE, "ReductionsOuter",
836 OuterLoop->getStartLoc(),
837 OuterLoop->getHeader())
838 << "Outer loops with reductions cannot be interchangeed "
839 "currently.";
840 });
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000841 return true;
Florian Hahn4eeff392017-07-03 15:32:00 +0000842 }
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000843 // TODO: Currently we handle only loops with 1 induction variable.
Florian Hahn4eeff392017-07-03 15:32:00 +0000844 if (Inductions.size() != 1) {
845 DEBUG(dbgs() << "Loops with more than 1 induction variables are not "
846 << "supported currently.\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000847 ORE->emit([&]() {
848 return OptimizationRemarkMissed(DEBUG_TYPE, "MultiIndutionOuter",
849 OuterLoop->getStartLoc(),
850 OuterLoop->getHeader())
851 << "Only outer loops with 1 induction variable can be "
852 "interchanged currently.";
853 });
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000854 return true;
Florian Hahn4eeff392017-07-03 15:32:00 +0000855 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000856
857 // TODO: Triangular loops are not handled for now.
858 if (!isLoopStructureUnderstood(InnerInductionVar)) {
859 DEBUG(dbgs() << "Loop structure not understood by pass\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000860 ORE->emit([&]() {
861 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedStructureInner",
862 InnerLoop->getStartLoc(),
863 InnerLoop->getHeader())
864 << "Inner loop structure not understood currently.";
865 });
Karthik Bhat88db86d2015-03-06 10:11:25 +0000866 return true;
867 }
868
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000869 // TODO: We only handle LCSSA PHI's corresponding to reduction for now.
870 BasicBlock *LoopExitBlock =
871 getLoopLatchExitBlock(OuterLoopLatch, OuterLoopHeader);
Florian Hahn4eeff392017-07-03 15:32:00 +0000872 if (!LoopExitBlock || !containsSafePHI(LoopExitBlock, true)) {
873 DEBUG(dbgs() << "Can only handle LCSSA PHIs in outer loops currently.\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000874 ORE->emit([&]() {
875 return OptimizationRemarkMissed(DEBUG_TYPE, "NoLCSSAPHIOuter",
876 OuterLoop->getStartLoc(),
877 OuterLoop->getHeader())
878 << "Only outer loops with LCSSA PHIs can be interchange "
879 "currently.";
880 });
Karthik Bhat88db86d2015-03-06 10:11:25 +0000881 return true;
Florian Hahn4eeff392017-07-03 15:32:00 +0000882 }
Karthik Bhat8210fdf2015-04-23 04:51:44 +0000883
884 LoopExitBlock = getLoopLatchExitBlock(InnerLoopLatch, InnerLoopHeader);
Florian Hahn4eeff392017-07-03 15:32:00 +0000885 if (!LoopExitBlock || !containsSafePHI(LoopExitBlock, false)) {
886 DEBUG(dbgs() << "Can only handle LCSSA PHIs in inner loops currently.\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000887 ORE->emit([&]() {
888 return OptimizationRemarkMissed(DEBUG_TYPE, "NoLCSSAPHIOuterInner",
889 InnerLoop->getStartLoc(),
890 InnerLoop->getHeader())
891 << "Only inner loops with LCSSA PHIs can be interchange "
892 "currently.";
893 });
Karthik Bhat88db86d2015-03-06 10:11:25 +0000894 return true;
Florian Hahn4eeff392017-07-03 15:32:00 +0000895 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000896
897 // TODO: Current limitation: Since we split the inner loop latch at the point
898 // were induction variable is incremented (induction.next); We cannot have
899 // more than 1 user of induction.next since it would result in broken code
900 // after split.
901 // e.g.
902 // for(i=0;i<N;i++) {
903 // for(j = 0;j<M;j++) {
904 // A[j+1][i+2] = A[j][i]+k;
905 // }
906 // }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000907 Instruction *InnerIndexVarInc = nullptr;
908 if (InnerInductionVar->getIncomingBlock(0) == InnerLoopPreHeader)
909 InnerIndexVarInc =
910 dyn_cast<Instruction>(InnerInductionVar->getIncomingValue(1));
911 else
912 InnerIndexVarInc =
913 dyn_cast<Instruction>(InnerInductionVar->getIncomingValue(0));
914
Florian Hahn4eeff392017-07-03 15:32:00 +0000915 if (!InnerIndexVarInc) {
916 DEBUG(dbgs() << "Did not find an instruction to increment the induction "
917 << "variable.\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000918 ORE->emit([&]() {
919 return OptimizationRemarkMissed(DEBUG_TYPE, "NoIncrementInInner",
920 InnerLoop->getStartLoc(),
921 InnerLoop->getHeader())
922 << "The inner loop does not increment the induction variable.";
923 });
Pete Cooper11bd9582015-07-27 18:37:58 +0000924 return true;
Florian Hahn4eeff392017-07-03 15:32:00 +0000925 }
Pete Cooper11bd9582015-07-27 18:37:58 +0000926
Karthik Bhat88db86d2015-03-06 10:11:25 +0000927 // Since we split the inner loop latch on this induction variable. Make sure
928 // we do not have any instruction between the induction variable and branch
929 // instruction.
930
David Majnemerd7708772016-06-24 04:05:21 +0000931 bool FoundInduction = false;
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000932 for (const Instruction &I : llvm::reverse(*InnerLoopLatch)) {
Florian Hahncd783452017-08-25 16:52:29 +0000933 if (isa<BranchInst>(I) || isa<CmpInst>(I) || isa<TruncInst>(I) ||
934 isa<ZExtInst>(I))
Karthik Bhat88db86d2015-03-06 10:11:25 +0000935 continue;
Florian Hahn4eeff392017-07-03 15:32:00 +0000936
Karthik Bhat88db86d2015-03-06 10:11:25 +0000937 // We found an instruction. If this is not induction variable then it is not
938 // safe to split this loop latch.
Florian Hahn4eeff392017-07-03 15:32:00 +0000939 if (!I.isIdenticalTo(InnerIndexVarInc)) {
940 DEBUG(dbgs() << "Found unsupported instructions between induction "
941 << "variable increment and branch.\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000942 ORE->emit([&]() {
943 return OptimizationRemarkMissed(
944 DEBUG_TYPE, "UnsupportedInsBetweenInduction",
945 InnerLoop->getStartLoc(), InnerLoop->getHeader())
946 << "Found unsupported instruction between induction variable "
947 "increment and branch.";
948 });
Karthik Bhat88db86d2015-03-06 10:11:25 +0000949 return true;
Florian Hahn4eeff392017-07-03 15:32:00 +0000950 }
David Majnemerd7708772016-06-24 04:05:21 +0000951
952 FoundInduction = true;
953 break;
Karthik Bhat88db86d2015-03-06 10:11:25 +0000954 }
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000955 // The loop latch ended and we didn't find the induction variable return as
Karthik Bhat88db86d2015-03-06 10:11:25 +0000956 // current limitation.
Florian Hahn4eeff392017-07-03 15:32:00 +0000957 if (!FoundInduction) {
958 DEBUG(dbgs() << "Did not find the induction variable.\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000959 ORE->emit([&]() {
960 return OptimizationRemarkMissed(DEBUG_TYPE, "NoIndutionVariable",
961 InnerLoop->getStartLoc(),
962 InnerLoop->getHeader())
963 << "Did not find the induction variable.";
964 });
Karthik Bhat88db86d2015-03-06 10:11:25 +0000965 return true;
Florian Hahn4eeff392017-07-03 15:32:00 +0000966 }
Karthik Bhat88db86d2015-03-06 10:11:25 +0000967 return false;
968}
969
970bool LoopInterchangeLegality::canInterchangeLoops(unsigned InnerLoopId,
971 unsigned OuterLoopId,
972 CharMatrix &DepMatrix) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000973 if (!isLegalToInterChangeLoops(DepMatrix, InnerLoopId, OuterLoopId)) {
974 DEBUG(dbgs() << "Failed interchange InnerLoopId = " << InnerLoopId
Chad Rosier58ede272016-09-14 16:43:19 +0000975 << " and OuterLoopId = " << OuterLoopId
976 << " due to dependence\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000977 ORE->emit([&]() {
978 return OptimizationRemarkMissed(DEBUG_TYPE, "Dependence",
979 InnerLoop->getStartLoc(),
980 InnerLoop->getHeader())
981 << "Cannot interchange loops due to dependences.";
982 });
Karthik Bhat88db86d2015-03-06 10:11:25 +0000983 return false;
984 }
985
Florian Hahn42840492017-07-31 09:00:52 +0000986 // Check if outer and inner loop contain legal instructions only.
987 for (auto *BB : OuterLoop->blocks())
988 for (Instruction &I : *BB)
989 if (CallInst *CI = dyn_cast<CallInst>(&I)) {
990 // readnone functions do not prevent interchanging.
991 if (CI->doesNotReadMemory())
992 continue;
993 DEBUG(dbgs() << "Loops with call instructions cannot be interchanged "
994 << "safely.");
Florian Hahn9467ccf2018-04-03 20:54:04 +0000995 ORE->emit([&]() {
996 return OptimizationRemarkMissed(DEBUG_TYPE, "CallInst",
997 CI->getDebugLoc(),
998 CI->getParent())
999 << "Cannot interchange loops due to call instruction.";
1000 });
1001
Florian Hahn42840492017-07-31 09:00:52 +00001002 return false;
1003 }
1004
Karthik Bhat88db86d2015-03-06 10:11:25 +00001005 // Create unique Preheaders if we already do not have one.
1006 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader();
1007 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
1008
1009 // Create a unique outer preheader -
1010 // 1) If OuterLoop preheader is not present.
1011 // 2) If OuterLoop Preheader is same as OuterLoop Header
1012 // 3) If OuterLoop Preheader is same as Header of the previous loop.
1013 // 4) If OuterLoop Preheader is Entry node.
1014 if (!OuterLoopPreHeader || OuterLoopPreHeader == OuterLoop->getHeader() ||
1015 isa<PHINode>(OuterLoopPreHeader->begin()) ||
1016 !OuterLoopPreHeader->getUniquePredecessor()) {
Justin Bogner843fb202015-12-15 19:40:57 +00001017 OuterLoopPreHeader =
1018 InsertPreheaderForLoop(OuterLoop, DT, LI, PreserveLCSSA);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001019 }
1020
1021 if (!InnerLoopPreHeader || InnerLoopPreHeader == InnerLoop->getHeader() ||
1022 InnerLoopPreHeader == OuterLoop->getHeader()) {
Justin Bogner843fb202015-12-15 19:40:57 +00001023 InnerLoopPreHeader =
1024 InsertPreheaderForLoop(InnerLoop, DT, LI, PreserveLCSSA);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001025 }
1026
Karthik Bhat88db86d2015-03-06 10:11:25 +00001027 // TODO: The loops could not be interchanged due to current limitations in the
1028 // transform module.
1029 if (currentLimitations()) {
1030 DEBUG(dbgs() << "Not legal because of current transform limitation\n");
1031 return false;
1032 }
1033
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001034 // Check if the loops are tightly nested.
1035 if (!tightlyNested(OuterLoop, InnerLoop)) {
1036 DEBUG(dbgs() << "Loops not tightly nested\n");
Vivek Pandya95906582017-10-11 17:12:59 +00001037 ORE->emit([&]() {
1038 return OptimizationRemarkMissed(DEBUG_TYPE, "NotTightlyNested",
1039 InnerLoop->getStartLoc(),
1040 InnerLoop->getHeader())
1041 << "Cannot interchange loops because they are not tightly "
1042 "nested.";
1043 });
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001044 return false;
1045 }
1046
Karthik Bhat88db86d2015-03-06 10:11:25 +00001047 return true;
1048}
1049
1050int LoopInterchangeProfitability::getInstrOrderCost() {
1051 unsigned GoodOrder, BadOrder;
1052 BadOrder = GoodOrder = 0;
Florian Hahnf66efd62017-07-24 11:41:30 +00001053 for (BasicBlock *BB : InnerLoop->blocks()) {
1054 for (Instruction &Ins : *BB) {
Karthik Bhat88db86d2015-03-06 10:11:25 +00001055 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Ins)) {
1056 unsigned NumOp = GEP->getNumOperands();
1057 bool FoundInnerInduction = false;
1058 bool FoundOuterInduction = false;
1059 for (unsigned i = 0; i < NumOp; ++i) {
1060 const SCEV *OperandVal = SE->getSCEV(GEP->getOperand(i));
1061 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(OperandVal);
1062 if (!AR)
1063 continue;
1064
1065 // If we find the inner induction after an outer induction e.g.
1066 // for(int i=0;i<N;i++)
1067 // for(int j=0;j<N;j++)
1068 // A[i][j] = A[i-1][j-1]+k;
1069 // then it is a good order.
1070 if (AR->getLoop() == InnerLoop) {
1071 // We found an InnerLoop induction after OuterLoop induction. It is
1072 // a good order.
1073 FoundInnerInduction = true;
1074 if (FoundOuterInduction) {
1075 GoodOrder++;
1076 break;
1077 }
1078 }
1079 // If we find the outer induction after an inner induction e.g.
1080 // for(int i=0;i<N;i++)
1081 // for(int j=0;j<N;j++)
1082 // A[j][i] = A[j-1][i-1]+k;
1083 // then it is a bad order.
1084 if (AR->getLoop() == OuterLoop) {
1085 // We found an OuterLoop induction after InnerLoop induction. It is
1086 // a bad order.
1087 FoundOuterInduction = true;
1088 if (FoundInnerInduction) {
1089 BadOrder++;
1090 break;
1091 }
1092 }
1093 }
1094 }
1095 }
1096 }
1097 return GoodOrder - BadOrder;
1098}
1099
Chad Rosiere6b3a632016-09-14 17:12:30 +00001100static bool isProfitableForVectorization(unsigned InnerLoopId,
1101 unsigned OuterLoopId,
1102 CharMatrix &DepMatrix) {
Karthik Bhat88db86d2015-03-06 10:11:25 +00001103 // TODO: Improve this heuristic to catch more cases.
1104 // If the inner loop is loop independent or doesn't carry any dependency it is
1105 // profitable to move this to outer position.
Florian Hahnf66efd62017-07-24 11:41:30 +00001106 for (auto &Row : DepMatrix) {
1107 if (Row[InnerLoopId] != 'S' && Row[InnerLoopId] != 'I')
Karthik Bhat88db86d2015-03-06 10:11:25 +00001108 return false;
1109 // TODO: We need to improve this heuristic.
Florian Hahnf66efd62017-07-24 11:41:30 +00001110 if (Row[OuterLoopId] != '=')
Karthik Bhat88db86d2015-03-06 10:11:25 +00001111 return false;
1112 }
1113 // If outer loop has dependence and inner loop is loop independent then it is
1114 // profitable to interchange to enable parallelism.
1115 return true;
1116}
1117
1118bool LoopInterchangeProfitability::isProfitable(unsigned InnerLoopId,
1119 unsigned OuterLoopId,
1120 CharMatrix &DepMatrix) {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001121 // TODO: Add better profitability checks.
Karthik Bhat88db86d2015-03-06 10:11:25 +00001122 // e.g
1123 // 1) Construct dependency matrix and move the one with no loop carried dep
1124 // inside to enable vectorization.
1125
1126 // This is rough cost estimation algorithm. It counts the good and bad order
1127 // of induction variables in the instruction and allows reordering if number
1128 // of bad orders is more than good.
Chad Rosier72431892016-09-14 17:07:13 +00001129 int Cost = getInstrOrderCost();
Karthik Bhat88db86d2015-03-06 10:11:25 +00001130 DEBUG(dbgs() << "Cost = " << Cost << "\n");
Chad Rosier72431892016-09-14 17:07:13 +00001131 if (Cost < -LoopInterchangeCostThreshold)
Karthik Bhat88db86d2015-03-06 10:11:25 +00001132 return true;
1133
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001134 // It is not profitable as per current cache profitability model. But check if
Karthik Bhat88db86d2015-03-06 10:11:25 +00001135 // we can move this loop outside to improve parallelism.
Florian Hahnad993522017-07-15 13:13:19 +00001136 if (isProfitableForVectorization(InnerLoopId, OuterLoopId, DepMatrix))
1137 return true;
1138
Vivek Pandya95906582017-10-11 17:12:59 +00001139 ORE->emit([&]() {
1140 return OptimizationRemarkMissed(DEBUG_TYPE, "InterchangeNotProfitable",
1141 InnerLoop->getStartLoc(),
1142 InnerLoop->getHeader())
1143 << "Interchanging loops is too costly (cost="
1144 << ore::NV("Cost", Cost) << ", threshold="
1145 << ore::NV("Threshold", LoopInterchangeCostThreshold)
1146 << ") and it does not improve parallelism.";
1147 });
Florian Hahnad993522017-07-15 13:13:19 +00001148 return false;
Karthik Bhat88db86d2015-03-06 10:11:25 +00001149}
1150
1151void LoopInterchangeTransform::removeChildLoop(Loop *OuterLoop,
1152 Loop *InnerLoop) {
Daniel Jasper6adbd7a2015-03-06 10:39:14 +00001153 for (Loop::iterator I = OuterLoop->begin(), E = OuterLoop->end(); I != E;
1154 ++I) {
Karthik Bhat88db86d2015-03-06 10:11:25 +00001155 if (*I == InnerLoop) {
1156 OuterLoop->removeChildLoop(I);
1157 return;
1158 }
1159 }
Benjamin Kramer8ceb3232015-10-25 22:28:27 +00001160 llvm_unreachable("Couldn't find loop");
Karthik Bhat88db86d2015-03-06 10:11:25 +00001161}
Daniel Jasper6adbd7a2015-03-06 10:39:14 +00001162
Florian Hahn831a7572018-04-05 09:48:45 +00001163/// Update LoopInfo, after interchanging. NewInner and NewOuter refer to the
1164/// new inner and outer loop after interchanging: NewInner is the original
1165/// outer loop and NewOuter is the original inner loop.
1166///
1167/// Before interchanging, we have the following structure
1168/// Outer preheader
1169// Outer header
1170// Inner preheader
1171// Inner header
1172// Inner body
1173// Inner latch
1174// outer bbs
1175// Outer latch
1176//
1177// After interchanging:
1178// Inner preheader
1179// Inner header
1180// Outer preheader
1181// Outer header
1182// Inner body
1183// outer bbs
1184// Outer latch
1185// Inner latch
1186void LoopInterchangeTransform::restructureLoops(
1187 Loop *NewInner, Loop *NewOuter, BasicBlock *OrigInnerPreHeader,
1188 BasicBlock *OrigOuterPreHeader) {
Karthik Bhat88db86d2015-03-06 10:11:25 +00001189 Loop *OuterLoopParent = OuterLoop->getParentLoop();
Florian Hahn831a7572018-04-05 09:48:45 +00001190 // The original inner loop preheader moves from the new inner loop to
1191 // the parent loop, if there is one.
1192 NewInner->removeBlockFromLoop(OrigInnerPreHeader);
1193 LI->changeLoopFor(OrigInnerPreHeader, OuterLoopParent);
1194
1195 // Switch the loop levels.
Karthik Bhat88db86d2015-03-06 10:11:25 +00001196 if (OuterLoopParent) {
1197 // Remove the loop from its parent loop.
Florian Hahn831a7572018-04-05 09:48:45 +00001198 removeChildLoop(OuterLoopParent, NewInner);
1199 removeChildLoop(NewInner, NewOuter);
1200 OuterLoopParent->addChildLoop(NewOuter);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001201 } else {
Florian Hahn831a7572018-04-05 09:48:45 +00001202 removeChildLoop(NewInner, NewOuter);
1203 LI->changeTopLevelLoop(NewInner, NewOuter);
1204 }
1205 while (!NewOuter->empty())
1206 NewInner->addChildLoop(NewOuter->removeChildLoop(NewOuter->begin()));
1207 NewOuter->addChildLoop(NewInner);
1208
1209 // BBs from the original inner loop.
1210 SmallVector<BasicBlock *, 8> OrigInnerBBs(NewOuter->blocks());
1211
1212 // Add BBs from the original outer loop to the original inner loop (excluding
1213 // BBs already in inner loop)
1214 for (BasicBlock *BB : NewInner->blocks())
1215 if (LI->getLoopFor(BB) == NewInner)
1216 NewOuter->addBlockEntry(BB);
1217
1218 // Now remove inner loop header and latch from the new inner loop and move
1219 // other BBs (the loop body) to the new inner loop.
1220 BasicBlock *OuterHeader = NewOuter->getHeader();
1221 BasicBlock *OuterLatch = NewOuter->getLoopLatch();
1222 for (BasicBlock *BB : OrigInnerBBs) {
1223 // Remove the new outer loop header and latch from the new inner loop.
1224 if (BB == OuterHeader || BB == OuterLatch)
1225 NewInner->removeBlockFromLoop(BB);
1226 else
1227 LI->changeLoopFor(BB, NewInner);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001228 }
1229
Florian Hahn831a7572018-04-05 09:48:45 +00001230 // The preheader of the original outer loop becomes part of the new
1231 // outer loop.
1232 NewOuter->addBlockEntry(OrigOuterPreHeader);
1233 LI->changeLoopFor(OrigOuterPreHeader, NewOuter);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001234}
1235
1236bool LoopInterchangeTransform::transform() {
Karthik Bhat88db86d2015-03-06 10:11:25 +00001237 bool Transformed = false;
1238 Instruction *InnerIndexVar;
1239
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +00001240 if (InnerLoop->getSubLoops().empty()) {
Karthik Bhat88db86d2015-03-06 10:11:25 +00001241 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
1242 DEBUG(dbgs() << "Calling Split Inner Loop\n");
1243 PHINode *InductionPHI = getInductionVariable(InnerLoop, SE);
1244 if (!InductionPHI) {
1245 DEBUG(dbgs() << "Failed to find the point to split loop latch \n");
1246 return false;
1247 }
1248
1249 if (InductionPHI->getIncomingBlock(0) == InnerLoopPreHeader)
1250 InnerIndexVar = dyn_cast<Instruction>(InductionPHI->getIncomingValue(1));
1251 else
1252 InnerIndexVar = dyn_cast<Instruction>(InductionPHI->getIncomingValue(0));
1253
David Green907b60f2017-10-21 13:58:37 +00001254 // Ensure that InductionPHI is the first Phi node as required by
1255 // splitInnerLoopHeader
1256 if (&InductionPHI->getParent()->front() != InductionPHI)
1257 InductionPHI->moveBefore(&InductionPHI->getParent()->front());
1258
Karthik Bhat88db86d2015-03-06 10:11:25 +00001259 // Split at the place were the induction variable is
1260 // incremented/decremented.
1261 // TODO: This splitting logic may not work always. Fix this.
1262 splitInnerLoopLatch(InnerIndexVar);
Chad Rosierf7c76f92016-09-21 13:28:41 +00001263 DEBUG(dbgs() << "splitInnerLoopLatch done\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +00001264
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001265 // Splits the inner loops phi nodes out into a separate basic block.
Karthik Bhat88db86d2015-03-06 10:11:25 +00001266 splitInnerLoopHeader();
Chad Rosierf7c76f92016-09-21 13:28:41 +00001267 DEBUG(dbgs() << "splitInnerLoopHeader done\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +00001268 }
1269
1270 Transformed |= adjustLoopLinks();
1271 if (!Transformed) {
Chad Rosierf7c76f92016-09-21 13:28:41 +00001272 DEBUG(dbgs() << "adjustLoopLinks failed\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +00001273 return false;
1274 }
1275
Karthik Bhat88db86d2015-03-06 10:11:25 +00001276 return true;
1277}
1278
Benjamin Kramer79442922015-03-06 18:59:14 +00001279void LoopInterchangeTransform::splitInnerLoopLatch(Instruction *Inc) {
Karthik Bhat88db86d2015-03-06 10:11:25 +00001280 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
Karthik Bhat88db86d2015-03-06 10:11:25 +00001281 BasicBlock *InnerLoopLatchPred = InnerLoopLatch;
Benjamin Kramer79442922015-03-06 18:59:14 +00001282 InnerLoopLatch = SplitBlock(InnerLoopLatchPred, Inc, DT, LI);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001283}
1284
Karthik Bhat88db86d2015-03-06 10:11:25 +00001285void LoopInterchangeTransform::splitInnerLoopHeader() {
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001286 // Split the inner loop header out. Here make sure that the reduction PHI's
1287 // stay in the innerloop body.
Karthik Bhat88db86d2015-03-06 10:11:25 +00001288 BasicBlock *InnerLoopHeader = InnerLoop->getHeader();
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001289 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
Florian Hahne54a20e2018-02-12 11:10:58 +00001290 SplitBlock(InnerLoopHeader, InnerLoopHeader->getFirstNonPHI(), DT, LI);
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001291 if (InnerLoopHasReduction) {
Florian Hahne54a20e2018-02-12 11:10:58 +00001292 // Adjust Reduction PHI's in the block. The induction PHI must be the first
1293 // PHI in InnerLoopHeader for this to work.
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001294 SmallVector<PHINode *, 8> PHIVec;
Florian Hahne54a20e2018-02-12 11:10:58 +00001295 for (auto I = std::next(InnerLoopHeader->begin()); isa<PHINode>(I); ++I) {
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001296 PHINode *PHI = dyn_cast<PHINode>(I);
1297 Value *V = PHI->getIncomingValueForBlock(InnerLoopPreHeader);
1298 PHI->replaceAllUsesWith(V);
1299 PHIVec.push_back((PHI));
1300 }
Benjamin Kramer135f7352016-06-26 12:28:59 +00001301 for (PHINode *P : PHIVec) {
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001302 P->eraseFromParent();
1303 }
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001304 }
Karthik Bhat88db86d2015-03-06 10:11:25 +00001305
1306 DEBUG(dbgs() << "Output of splitInnerLoopHeader InnerLoopHeaderSucc & "
Chad Rosierf7c76f92016-09-21 13:28:41 +00001307 "InnerLoopHeader\n");
Karthik Bhat88db86d2015-03-06 10:11:25 +00001308}
1309
Benjamin Kramer79442922015-03-06 18:59:14 +00001310/// \brief Move all instructions except the terminator from FromBB right before
1311/// InsertBefore
1312static void moveBBContents(BasicBlock *FromBB, Instruction *InsertBefore) {
1313 auto &ToList = InsertBefore->getParent()->getInstList();
1314 auto &FromList = FromBB->getInstList();
1315
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001316 ToList.splice(InsertBefore->getIterator(), FromList, FromList.begin(),
1317 FromBB->getTerminator()->getIterator());
Benjamin Kramer79442922015-03-06 18:59:14 +00001318}
1319
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001320void LoopInterchangeTransform::updateIncomingBlock(BasicBlock *CurrBlock,
1321 BasicBlock *OldPred,
1322 BasicBlock *NewPred) {
1323 for (auto I = CurrBlock->begin(); isa<PHINode>(I); ++I) {
1324 PHINode *PHI = cast<PHINode>(I);
1325 unsigned Num = PHI->getNumIncomingValues();
1326 for (unsigned i = 0; i < Num; ++i) {
1327 if (PHI->getIncomingBlock(i) == OldPred)
1328 PHI->setIncomingBlock(i, NewPred);
1329 }
1330 }
1331}
1332
Florian Hahnc6296fe2018-02-14 13:13:15 +00001333/// \brief Update BI to jump to NewBB instead of OldBB. Records updates to
1334/// the dominator tree in DTUpdates, if DT should be preserved.
1335static void updateSuccessor(BranchInst *BI, BasicBlock *OldBB,
1336 BasicBlock *NewBB,
1337 std::vector<DominatorTree::UpdateType> &DTUpdates) {
1338 assert(llvm::count_if(BI->successors(),
1339 [OldBB](BasicBlock *BB) { return BB == OldBB; }) < 2 &&
1340 "BI must jump to OldBB at most once.");
1341 for (unsigned i = 0, e = BI->getNumSuccessors(); i < e; ++i) {
1342 if (BI->getSuccessor(i) == OldBB) {
1343 BI->setSuccessor(i, NewBB);
1344
1345 DTUpdates.push_back(
1346 {DominatorTree::UpdateKind::Insert, BI->getParent(), NewBB});
1347 DTUpdates.push_back(
1348 {DominatorTree::UpdateKind::Delete, BI->getParent(), OldBB});
1349 break;
1350 }
1351 }
1352}
1353
Karthik Bhat88db86d2015-03-06 10:11:25 +00001354bool LoopInterchangeTransform::adjustLoopBranches() {
Karthik Bhat88db86d2015-03-06 10:11:25 +00001355 DEBUG(dbgs() << "adjustLoopBranches called\n");
Florian Hahnc6296fe2018-02-14 13:13:15 +00001356 std::vector<DominatorTree::UpdateType> DTUpdates;
1357
Karthik Bhat88db86d2015-03-06 10:11:25 +00001358 // Adjust the loop preheader
1359 BasicBlock *InnerLoopHeader = InnerLoop->getHeader();
1360 BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
1361 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
1362 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch();
1363 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader();
1364 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
1365 BasicBlock *OuterLoopPredecessor = OuterLoopPreHeader->getUniquePredecessor();
1366 BasicBlock *InnerLoopLatchPredecessor =
1367 InnerLoopLatch->getUniquePredecessor();
1368 BasicBlock *InnerLoopLatchSuccessor;
1369 BasicBlock *OuterLoopLatchSuccessor;
1370
1371 BranchInst *OuterLoopLatchBI =
1372 dyn_cast<BranchInst>(OuterLoopLatch->getTerminator());
1373 BranchInst *InnerLoopLatchBI =
1374 dyn_cast<BranchInst>(InnerLoopLatch->getTerminator());
1375 BranchInst *OuterLoopHeaderBI =
1376 dyn_cast<BranchInst>(OuterLoopHeader->getTerminator());
1377 BranchInst *InnerLoopHeaderBI =
1378 dyn_cast<BranchInst>(InnerLoopHeader->getTerminator());
1379
1380 if (!OuterLoopPredecessor || !InnerLoopLatchPredecessor ||
1381 !OuterLoopLatchBI || !InnerLoopLatchBI || !OuterLoopHeaderBI ||
1382 !InnerLoopHeaderBI)
1383 return false;
1384
1385 BranchInst *InnerLoopLatchPredecessorBI =
1386 dyn_cast<BranchInst>(InnerLoopLatchPredecessor->getTerminator());
1387 BranchInst *OuterLoopPredecessorBI =
1388 dyn_cast<BranchInst>(OuterLoopPredecessor->getTerminator());
1389
1390 if (!OuterLoopPredecessorBI || !InnerLoopLatchPredecessorBI)
1391 return false;
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001392 BasicBlock *InnerLoopHeaderSuccessor = InnerLoopHeader->getUniqueSuccessor();
1393 if (!InnerLoopHeaderSuccessor)
Karthik Bhat88db86d2015-03-06 10:11:25 +00001394 return false;
1395
1396 // Adjust Loop Preheader and headers
Florian Hahnc6296fe2018-02-14 13:13:15 +00001397 updateSuccessor(OuterLoopPredecessorBI, OuterLoopPreHeader,
1398 InnerLoopPreHeader, DTUpdates);
1399 updateSuccessor(OuterLoopHeaderBI, OuterLoopLatch, LoopExit, DTUpdates);
1400 updateSuccessor(OuterLoopHeaderBI, InnerLoopPreHeader,
1401 InnerLoopHeaderSuccessor, DTUpdates);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001402
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001403 // Adjust reduction PHI's now that the incoming block has changed.
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001404 updateIncomingBlock(InnerLoopHeaderSuccessor, InnerLoopHeader,
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001405 OuterLoopHeader);
1406
Florian Hahnc6296fe2018-02-14 13:13:15 +00001407 updateSuccessor(InnerLoopHeaderBI, InnerLoopHeaderSuccessor,
1408 OuterLoopPreHeader, DTUpdates);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001409
1410 // -------------Adjust loop latches-----------
1411 if (InnerLoopLatchBI->getSuccessor(0) == InnerLoopHeader)
1412 InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(1);
1413 else
1414 InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(0);
1415
Florian Hahnc6296fe2018-02-14 13:13:15 +00001416 updateSuccessor(InnerLoopLatchPredecessorBI, InnerLoopLatch,
1417 InnerLoopLatchSuccessor, DTUpdates);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001418
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001419 // Adjust PHI nodes in InnerLoopLatchSuccessor. Update all uses of PHI with
1420 // the value and remove this PHI node from inner loop.
1421 SmallVector<PHINode *, 8> LcssaVec;
1422 for (auto I = InnerLoopLatchSuccessor->begin(); isa<PHINode>(I); ++I) {
1423 PHINode *LcssaPhi = cast<PHINode>(I);
1424 LcssaVec.push_back(LcssaPhi);
1425 }
Benjamin Kramer135f7352016-06-26 12:28:59 +00001426 for (PHINode *P : LcssaVec) {
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001427 Value *Incoming = P->getIncomingValueForBlock(InnerLoopLatch);
1428 P->replaceAllUsesWith(Incoming);
1429 P->eraseFromParent();
1430 }
1431
Karthik Bhat88db86d2015-03-06 10:11:25 +00001432 if (OuterLoopLatchBI->getSuccessor(0) == OuterLoopHeader)
1433 OuterLoopLatchSuccessor = OuterLoopLatchBI->getSuccessor(1);
1434 else
1435 OuterLoopLatchSuccessor = OuterLoopLatchBI->getSuccessor(0);
1436
Florian Hahnc6296fe2018-02-14 13:13:15 +00001437 updateSuccessor(InnerLoopLatchBI, InnerLoopLatchSuccessor,
1438 OuterLoopLatchSuccessor, DTUpdates);
1439 updateSuccessor(OuterLoopLatchBI, OuterLoopLatchSuccessor, InnerLoopLatch,
1440 DTUpdates);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001441
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001442 updateIncomingBlock(OuterLoopLatchSuccessor, OuterLoopLatch, InnerLoopLatch);
1443
Florian Hahnc6296fe2018-02-14 13:13:15 +00001444 DT->applyUpdates(DTUpdates);
Florian Hahn831a7572018-04-05 09:48:45 +00001445 restructureLoops(OuterLoop, InnerLoop, InnerLoopPreHeader,
1446 OuterLoopPreHeader);
1447
Karthik Bhat88db86d2015-03-06 10:11:25 +00001448 return true;
1449}
Karthik Bhat88db86d2015-03-06 10:11:25 +00001450
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +00001451void LoopInterchangeTransform::adjustLoopPreheaders() {
Karthik Bhat88db86d2015-03-06 10:11:25 +00001452 // We have interchanged the preheaders so we need to interchange the data in
1453 // the preheader as well.
1454 // This is because the content of inner preheader was previously executed
1455 // inside the outer loop.
1456 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader();
1457 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
1458 BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
1459 BranchInst *InnerTermBI =
1460 cast<BranchInst>(InnerLoopPreHeader->getTerminator());
1461
Karthik Bhat88db86d2015-03-06 10:11:25 +00001462 // These instructions should now be executed inside the loop.
1463 // Move instruction into a new block after outer header.
Karthik Bhat8210fdf2015-04-23 04:51:44 +00001464 moveBBContents(InnerLoopPreHeader, OuterLoopHeader->getTerminator());
Karthik Bhat88db86d2015-03-06 10:11:25 +00001465 // These instructions were not executed previously in the loop so move them to
1466 // the older inner loop preheader.
Benjamin Kramer79442922015-03-06 18:59:14 +00001467 moveBBContents(OuterLoopPreHeader, InnerTermBI);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001468}
1469
1470bool LoopInterchangeTransform::adjustLoopLinks() {
Karthik Bhat88db86d2015-03-06 10:11:25 +00001471 // Adjust all branches in the inner and outer loop.
1472 bool Changed = adjustLoopBranches();
1473 if (Changed)
1474 adjustLoopPreheaders();
1475 return Changed;
1476}
1477
1478char LoopInterchange::ID = 0;
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +00001479
Karthik Bhat88db86d2015-03-06 10:11:25 +00001480INITIALIZE_PASS_BEGIN(LoopInterchange, "loop-interchange",
1481 "Interchanges loops for cache reuse", false, false)
Chandler Carruth7b560d42015-09-09 17:55:00 +00001482INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Chandler Carruth49c22192016-05-12 22:19:39 +00001483INITIALIZE_PASS_DEPENDENCY(DependenceAnalysisWrapperPass)
Karthik Bhat88db86d2015-03-06 10:11:25 +00001484INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001485INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
Karthik Bhat88db86d2015-03-06 10:11:25 +00001486INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
Easwaran Ramane12c4872016-06-09 19:44:46 +00001487INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass)
Karthik Bhat88db86d2015-03-06 10:11:25 +00001488INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Florian Hahnad993522017-07-15 13:13:19 +00001489INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
Karthik Bhat88db86d2015-03-06 10:11:25 +00001490
1491INITIALIZE_PASS_END(LoopInterchange, "loop-interchange",
1492 "Interchanges loops for cache reuse", false, false)
1493
1494Pass *llvm::createLoopInterchangePass() { return new LoopInterchange(); }