blob: dde3a7f34bbfd8ab96fe8e4d9c1e396708782f14 [file] [log] [blame]
Karthik Bhat88db86d2015-03-06 10:11:25 +00001//===- LoopInterchange.cpp - Loop interchange pass------------------------===//
2//
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
16#include "llvm/ADT/SmallVector.h"
17#include "llvm/Analysis/AliasAnalysis.h"
18#include "llvm/Analysis/AliasSetTracker.h"
19#include "llvm/Analysis/AssumptionCache.h"
20#include "llvm/Analysis/BlockFrequencyInfo.h"
21#include "llvm/Analysis/CodeMetrics.h"
22#include "llvm/Analysis/DependenceAnalysis.h"
23#include "llvm/Analysis/LoopInfo.h"
24#include "llvm/Analysis/LoopIterator.h"
25#include "llvm/Analysis/LoopPass.h"
26#include "llvm/Analysis/ScalarEvolution.h"
27#include "llvm/Analysis/ScalarEvolutionExpander.h"
28#include "llvm/Analysis/ScalarEvolutionExpressions.h"
29#include "llvm/Analysis/TargetTransformInfo.h"
30#include "llvm/Analysis/ValueTracking.h"
31#include "llvm/Transforms/Scalar.h"
32#include "llvm/IR/Function.h"
33#include "llvm/IR/IRBuilder.h"
34#include "llvm/IR/IntrinsicInst.h"
35#include "llvm/IR/InstIterator.h"
36#include "llvm/IR/Dominators.h"
37#include "llvm/Pass.h"
38#include "llvm/Support/Debug.h"
39#include "llvm/Transforms/Utils/SSAUpdater.h"
40#include "llvm/Support/raw_ostream.h"
41#include "llvm/Transforms/Utils/LoopUtils.h"
42#include "llvm/Transforms/Utils/BasicBlockUtils.h"
43using namespace llvm;
44
45#define DEBUG_TYPE "loop-interchange"
46
47namespace {
48
49typedef SmallVector<Loop *, 8> LoopVector;
50
51// TODO: Check if we can use a sparse matrix here.
52typedef std::vector<std::vector<char>> CharMatrix;
53
54// Maximum number of dependencies that can be handled in the dependency matrix.
55static const unsigned MaxMemInstrCount = 100;
56
57// Maximum loop depth supported.
58static const unsigned MaxLoopNestDepth = 10;
59
60struct LoopInterchange;
61
62#ifdef DUMP_DEP_MATRICIES
63void printDepMatrix(CharMatrix &DepMatrix) {
64 for (auto I = DepMatrix.begin(), E = DepMatrix.end(); I != E; ++I) {
65 std::vector<char> Vec = *I;
66 for (auto II = Vec.begin(), EE = Vec.end(); II != EE; ++II)
67 DEBUG(dbgs() << *II << " ");
68 DEBUG(dbgs() << "\n");
69 }
70}
71#endif
72
73bool populateDependencyMatrix(CharMatrix &DepMatrix, unsigned Level, Loop *L,
74 DependenceAnalysis *DA) {
75 typedef SmallVector<Value *, 16> ValueVector;
76 ValueVector MemInstr;
77
78 if (Level > MaxLoopNestDepth) {
79 DEBUG(dbgs() << "Cannot handle loops of depth greater than "
80 << MaxLoopNestDepth << "\n");
81 return false;
82 }
83
84 // For each block.
85 for (Loop::block_iterator BB = L->block_begin(), BE = L->block_end();
86 BB != BE; ++BB) {
87 // Scan the BB and collect legal loads and stores.
88 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E;
89 ++I) {
90 Instruction *Ins = dyn_cast<Instruction>(I);
91 if (!Ins)
92 return false;
93 LoadInst *Ld = dyn_cast<LoadInst>(I);
94 StoreInst *St = dyn_cast<StoreInst>(I);
95 if (!St && !Ld)
96 continue;
97 if (Ld && !Ld->isSimple())
98 return false;
99 if (St && !St->isSimple())
100 return false;
101 MemInstr.push_back(I);
102 }
103 }
104
105 DEBUG(dbgs() << "Found " << MemInstr.size()
106 << " Loads and Stores to analyze\n");
107
108 ValueVector::iterator I, IE, J, JE;
109
110 for (I = MemInstr.begin(), IE = MemInstr.end(); I != IE; ++I) {
111 for (J = I, JE = MemInstr.end(); J != JE; ++J) {
112 std::vector<char> Dep;
113 Instruction *Src = dyn_cast<Instruction>(*I);
114 Instruction *Des = dyn_cast<Instruction>(*J);
115 if (Src == Des)
116 continue;
117 if (isa<LoadInst>(Src) && isa<LoadInst>(Des))
118 continue;
119 if (auto D = DA->depends(Src, Des, true)) {
120 DEBUG(dbgs() << "Found Dependency between Src=" << Src << " Des=" << Des
121 << "\n");
122 if (D->isFlow()) {
123 // TODO: Handle Flow dependence.Check if it is sufficient to populate
124 // the Dependence Matrix with the direction reversed.
125 DEBUG(dbgs() << "Flow dependence not handled");
126 return false;
127 }
128 if (D->isAnti()) {
129 DEBUG(dbgs() << "Found Anti dependence \n");
130 unsigned Levels = D->getLevels();
131 char Direction;
132 for (unsigned II = 1; II <= Levels; ++II) {
133 const SCEV *Distance = D->getDistance(II);
134 const SCEVConstant *SCEVConst =
135 dyn_cast_or_null<SCEVConstant>(Distance);
136 if (SCEVConst) {
137 const ConstantInt *CI = SCEVConst->getValue();
138 if (CI->isNegative())
139 Direction = '<';
140 else if (CI->isZero())
141 Direction = '=';
142 else
143 Direction = '>';
144 Dep.push_back(Direction);
145 } else if (D->isScalar(II)) {
146 Direction = 'S';
147 Dep.push_back(Direction);
148 } else {
149 unsigned Dir = D->getDirection(II);
150 if (Dir == Dependence::DVEntry::LT ||
151 Dir == Dependence::DVEntry::LE)
152 Direction = '<';
153 else if (Dir == Dependence::DVEntry::GT ||
154 Dir == Dependence::DVEntry::GE)
155 Direction = '>';
156 else if (Dir == Dependence::DVEntry::EQ)
157 Direction = '=';
158 else
159 Direction = '*';
160 Dep.push_back(Direction);
161 }
162 }
163 while (Dep.size() != Level) {
164 Dep.push_back('I');
165 }
166
167 DepMatrix.push_back(Dep);
168 if (DepMatrix.size() > MaxMemInstrCount) {
169 DEBUG(dbgs() << "Cannot handle more than " << MaxMemInstrCount
170 << " dependencies inside loop\n");
171 return false;
172 }
173 }
174 }
175 }
176 }
177
178 // We don't have a DepMatrix to check legality return false
179 if (DepMatrix.size() == 0)
180 return false;
181 return true;
182}
183
184// A loop is moved from index 'from' to an index 'to'. Update the Dependence
185// matrix by exchanging the two columns.
186void interChangeDepedencies(CharMatrix &DepMatrix, unsigned FromIndx,
187 unsigned ToIndx) {
188 unsigned numRows = DepMatrix.size();
189 for (unsigned i = 0; i < numRows; ++i) {
190 char TmpVal = DepMatrix[i][ToIndx];
191 DepMatrix[i][ToIndx] = DepMatrix[i][FromIndx];
192 DepMatrix[i][FromIndx] = TmpVal;
193 }
194}
195
196// Checks if outermost non '=','S'or'I' dependence in the dependence matrix is
197// '>'
198bool isOuterMostDepPositive(CharMatrix &DepMatrix, unsigned Row,
199 unsigned Column) {
200 for (unsigned i = 0; i <= Column; ++i) {
201 if (DepMatrix[Row][i] == '<')
202 return false;
203 if (DepMatrix[Row][i] == '>')
204 return true;
205 }
206 // All dependencies were '=','S' or 'I'
207 return false;
208}
209
210// Checks if no dependence exist in the dependency matrix in Row before Column.
211bool containsNoDependence(CharMatrix &DepMatrix, unsigned Row,
212 unsigned Column) {
213 for (unsigned i = 0; i < Column; ++i) {
214 if (DepMatrix[Row][i] != '=' || DepMatrix[Row][i] != 'S' ||
215 DepMatrix[Row][i] != 'I')
216 return false;
217 }
218 return true;
219}
220
221bool validDepInterchange(CharMatrix &DepMatrix, unsigned Row,
222 unsigned OuterLoopId, char InnerDep, char OuterDep) {
223
224 if (isOuterMostDepPositive(DepMatrix, Row, OuterLoopId))
225 return false;
226
227 if (InnerDep == OuterDep)
228 return true;
229
230 // It is legal to interchange if and only if after interchange no row has a
231 // '>' direction as the leftmost non-'='.
232
233 if (InnerDep == '=' || InnerDep == 'S' || InnerDep == 'I')
234 return true;
235
236 if (InnerDep == '<')
237 return true;
238
239 if (InnerDep == '>') {
240 // If OuterLoopId represents outermost loop then interchanging will make the
241 // 1st dependency as '>'
242 if (OuterLoopId == 0)
243 return false;
244
245 // If all dependencies before OuterloopId are '=','S'or 'I'. Then
246 // interchanging will result in this row having an outermost non '='
247 // dependency of '>'
248 if (!containsNoDependence(DepMatrix, Row, OuterLoopId))
249 return true;
250 }
251
252 return false;
253}
254
255// Checks if it is legal to interchange 2 loops.
256// [Theorm] A permutation of the loops in a perfect nest is legal if and only if
257// the direction matrix, after the same permutation is applied to its columns,
258// has no ">" direction as the leftmost non-"=" direction in any row.
259bool isLegalToInterChangeLoops(CharMatrix &DepMatrix, unsigned InnerLoopId,
260 unsigned OuterLoopId) {
261
262 unsigned NumRows = DepMatrix.size();
263 // For each row check if it is valid to interchange.
264 for (unsigned Row = 0; Row < NumRows; ++Row) {
265 char InnerDep = DepMatrix[Row][InnerLoopId];
266 char OuterDep = DepMatrix[Row][OuterLoopId];
267 if (InnerDep == '*' || OuterDep == '*')
268 return false;
269 else if (!validDepInterchange(DepMatrix, Row, OuterLoopId, InnerDep,
270 OuterDep))
271 return false;
272 }
273 return true;
274}
275
276static void populateWorklist(Loop &L, SmallVector<LoopVector, 8> &V) {
277
278 DEBUG(dbgs() << "Calling populateWorklist called\n");
279 LoopVector LoopList;
280 Loop *CurrentLoop = &L;
281 std::vector<Loop *> vec = CurrentLoop->getSubLoopsVector();
282 while (vec.size() != 0) {
283 // The current loop has multiple subloops in it hence it is not tightly
284 // nested.
285 // Discard all loops above it added into Worklist.
286 if (vec.size() != 1) {
287 LoopList.clear();
288 return;
289 }
290 LoopList.push_back(CurrentLoop);
291 CurrentLoop = *(vec.begin());
292 vec = CurrentLoop->getSubLoopsVector();
293 }
294 LoopList.push_back(CurrentLoop);
295 V.push_back(LoopList);
296}
297
298static PHINode *getInductionVariable(Loop *L, ScalarEvolution *SE) {
299 PHINode *InnerIndexVar = L->getCanonicalInductionVariable();
300 if (InnerIndexVar)
301 return InnerIndexVar;
302 if (L->getLoopLatch() == nullptr || L->getLoopPredecessor() == nullptr)
303 return nullptr;
304 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
305 PHINode *PhiVar = cast<PHINode>(I);
306 Type *PhiTy = PhiVar->getType();
307 if (!PhiTy->isIntegerTy() && !PhiTy->isFloatingPointTy() &&
308 !PhiTy->isPointerTy())
309 return nullptr;
310 const SCEVAddRecExpr *AddRec =
311 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(PhiVar));
312 if (!AddRec || !AddRec->isAffine())
313 continue;
314 const SCEV *Step = AddRec->getStepRecurrence(*SE);
315 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
316 if (!C)
317 continue;
318 // Found the induction variable.
319 // FIXME: Handle loops with more than one induction variable. Note that,
320 // currently, legality makes sure we have only one induction variable.
321 return PhiVar;
322 }
323 return nullptr;
324}
325
326/// LoopInterchangeLegality checks if it is legal to interchange the loop.
327class LoopInterchangeLegality {
328public:
329 LoopInterchangeLegality(Loop *Outer, Loop *Inner, ScalarEvolution *SE,
330 LoopInterchange *Pass)
331 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), CurrentPass(Pass) {}
332
333 /// Check if the loops can be interchanged.
334 bool canInterchangeLoops(unsigned InnerLoopId, unsigned OuterLoopId,
335 CharMatrix &DepMatrix);
336 /// Check if the loop structure is understood. We do not handle triangular
337 /// loops for now.
338 bool isLoopStructureUnderstood(PHINode *InnerInductionVar);
339
340 bool currentLimitations();
341
342private:
343 bool tightlyNested(Loop *Outer, Loop *Inner);
344
345 Loop *OuterLoop;
346 Loop *InnerLoop;
347
348 /// Scev analysis.
349 ScalarEvolution *SE;
350 LoopInterchange *CurrentPass;
351};
352
353/// LoopInterchangeProfitability checks if it is profitable to interchange the
354/// loop.
355class LoopInterchangeProfitability {
356public:
357 LoopInterchangeProfitability(Loop *Outer, Loop *Inner, ScalarEvolution *SE)
358 : OuterLoop(Outer), InnerLoop(Inner), SE(SE) {}
359
360 /// Check if the loop interchange is profitable
361 bool isProfitable(unsigned InnerLoopId, unsigned OuterLoopId,
362 CharMatrix &DepMatrix);
363
364private:
365 int getInstrOrderCost();
366
367 Loop *OuterLoop;
368 Loop *InnerLoop;
369
370 /// Scev analysis.
371 ScalarEvolution *SE;
372};
373
374/// LoopInterchangeTransform interchanges the loop
375class LoopInterchangeTransform {
376public:
377 LoopInterchangeTransform(Loop *Outer, Loop *Inner, ScalarEvolution *SE,
378 LoopInfo *LI, DominatorTree *DT,
379 LoopInterchange *Pass, BasicBlock *LoopNestExit)
380 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), LI(LI), DT(DT),
381 LoopExit(LoopNestExit) {
382 initialize();
383 }
384
385 /// Interchange OuterLoop and InnerLoop.
386 bool transform();
387 void restructureLoops(Loop *InnerLoop, Loop *OuterLoop);
388 void removeChildLoop(Loop *OuterLoop, Loop *InnerLoop);
389 void initialize();
390
391private:
392 void splitInnerLoopLatch(Instruction *);
393 void splitOuterLoopLatch();
394 void splitInnerLoopHeader();
395 bool adjustLoopLinks();
396 void adjustLoopPreheaders();
397 void adjustOuterLoopPreheader();
398 void adjustInnerLoopPreheader();
399 bool adjustLoopBranches();
400
401 Loop *OuterLoop;
402 Loop *InnerLoop;
403
404 /// Scev analysis.
405 ScalarEvolution *SE;
406 LoopInfo *LI;
407 DominatorTree *DT;
408 BasicBlock *LoopExit;
409};
410
411// Main LoopInterchange Pass
412struct LoopInterchange : public FunctionPass {
413 static char ID;
414 ScalarEvolution *SE;
415 LoopInfo *LI;
416 DependenceAnalysis *DA;
417 DominatorTree *DT;
418 LoopInterchange()
419 : FunctionPass(ID), SE(nullptr), LI(nullptr), DA(nullptr), DT(nullptr) {
420 initializeLoopInterchangePass(*PassRegistry::getPassRegistry());
421 }
422
423 void getAnalysisUsage(AnalysisUsage &AU) const override {
424 AU.addRequired<ScalarEvolution>();
425 AU.addRequired<AliasAnalysis>();
426 AU.addRequired<DominatorTreeWrapperPass>();
427 AU.addRequired<LoopInfoWrapperPass>();
428 AU.addRequired<DependenceAnalysis>();
429 AU.addRequiredID(LoopSimplifyID);
430 AU.addRequiredID(LCSSAID);
431 }
432
433 bool runOnFunction(Function &F) override {
434 SE = &getAnalysis<ScalarEvolution>();
435 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
436 DA = &getAnalysis<DependenceAnalysis>();
437 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
438 DT = DTWP ? &DTWP->getDomTree() : nullptr;
439 // Build up a worklist of loop pairs to analyze.
440 SmallVector<LoopVector, 8> Worklist;
441
442 for (Loop *L : *LI)
443 populateWorklist(*L, Worklist);
444
445 DEBUG(dbgs() << "Worklist size = " << Worklist.size() << "\n");
446 bool Changed = true;
447 while (!Worklist.empty()) {
448 LoopVector LoopList = Worklist.pop_back_val();
449 Changed = processLoopList(LoopList);
450 }
451 return Changed;
452 }
453
454 bool isComputableLoopNest(LoopVector LoopList) {
455 for (auto I = LoopList.begin(), E = LoopList.end(); I != E; ++I) {
456 Loop *L = *I;
457 const SCEV *ExitCountOuter = SE->getBackedgeTakenCount(L);
458 if (ExitCountOuter == SE->getCouldNotCompute()) {
459 DEBUG(dbgs() << "Couldn't compute Backedge count\n");
460 return false;
461 }
462 if (L->getNumBackEdges() != 1) {
463 DEBUG(dbgs() << "NumBackEdges is not equal to 1\n");
464 return false;
465 }
466 if (!L->getExitingBlock()) {
467 DEBUG(dbgs() << "Loop Doesn't have unique exit block\n");
468 return false;
469 }
470 }
471 return true;
472 }
473
474 unsigned selectLoopForInterchange(LoopVector LoopList) {
475 // TODO: Add a better heuristic to select the loop to be interchanged based
476 // on the dependece matrix. Currently we select the innermost loop.
477 return LoopList.size() - 1;
478 }
479
480 bool processLoopList(LoopVector LoopList) {
481 bool Changed = false;
482 bool containsLCSSAPHI = false;
483 CharMatrix DependencyMatrix;
484 if (LoopList.size() < 2) {
485 DEBUG(dbgs() << "Loop doesn't contain minimum nesting level.\n");
486 return false;
487 }
488 if (!isComputableLoopNest(LoopList)) {
489 DEBUG(dbgs() << "Not vaild loop candidate for interchange\n");
490 return false;
491 }
492 Loop *OuterMostLoop = *(LoopList.begin());
493
494 DEBUG(dbgs() << "Processing LoopList of size = " << LoopList.size()
495 << "\n");
496
497 if (!populateDependencyMatrix(DependencyMatrix, LoopList.size(),
498 OuterMostLoop, DA)) {
499 DEBUG(dbgs() << "Populating Dependency matrix failed\n");
500 return false;
501 }
502#ifdef DUMP_DEP_MATRICIES
503 DEBUG(dbgs() << "Dependence before inter change \n");
504 printDepMatrix(DependencyMatrix);
505#endif
506
507 BasicBlock *OuterMostLoopLatch = OuterMostLoop->getLoopLatch();
508 BranchInst *OuterMostLoopLatchBI =
509 dyn_cast<BranchInst>(OuterMostLoopLatch->getTerminator());
510 if (!OuterMostLoopLatchBI)
511 return false;
512
513 // Since we currently do not handle LCSSA PHI's any failure in loop
514 // condition will now branch to LoopNestExit.
515 // TODO: This should be removed once we handle LCSSA PHI nodes.
516
517 // Get the Outermost loop exit.
518 BasicBlock *LoopNestExit;
519 if (OuterMostLoopLatchBI->getSuccessor(0) == OuterMostLoop->getHeader())
520 LoopNestExit = OuterMostLoopLatchBI->getSuccessor(1);
521 else
522 LoopNestExit = OuterMostLoopLatchBI->getSuccessor(0);
523
524 for (auto I = LoopList.begin(), E = LoopList.end(); I != E; ++I) {
525 Loop *L = *I;
526 BasicBlock *Latch = L->getLoopLatch();
527 BasicBlock *Header = L->getHeader();
528 if (Latch && Latch != Header && isa<PHINode>(Latch->begin())) {
529 containsLCSSAPHI = true;
530 break;
531 }
532 }
533
534 // TODO: Handle lcssa PHI's. Currently LCSSA PHI's are not handled. Handle
535 // the same by splitting the loop latch and adjusting loop links
536 // accordingly.
537 if (containsLCSSAPHI)
538 return false;
539
540 unsigned SelecLoopId = selectLoopForInterchange(LoopList);
541 // Move the selected loop outwards to the best posible position.
542 for (unsigned i = SelecLoopId; i > 0; i--) {
543 bool Interchanged =
544 processLoop(LoopList, i, i - 1, LoopNestExit, DependencyMatrix);
545 if (!Interchanged)
546 return Changed;
547 // Loops interchanged reflect the same in LoopList
Benjamin Kramer79442922015-03-06 18:59:14 +0000548 std::swap(LoopList[i - 1], LoopList[i]);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000549
550 // Update the DependencyMatrix
551 interChangeDepedencies(DependencyMatrix, i, i - 1);
552
553#ifdef DUMP_DEP_MATRICIES
554 DEBUG(dbgs() << "Dependence after inter change \n");
555 printDepMatrix(DependencyMatrix);
556#endif
557 Changed |= Interchanged;
558 }
559 return Changed;
560 }
561
562 bool processLoop(LoopVector LoopList, unsigned InnerLoopId,
563 unsigned OuterLoopId, BasicBlock *LoopNestExit,
564 std::vector<std::vector<char>> &DependencyMatrix) {
565
566 DEBUG(dbgs() << "Processing Innder Loop Id = " << InnerLoopId
567 << " and OuterLoopId = " << OuterLoopId << "\n");
568 Loop *InnerLoop = LoopList[InnerLoopId];
569 Loop *OuterLoop = LoopList[OuterLoopId];
570
571 LoopInterchangeLegality LIL(OuterLoop, InnerLoop, SE, this);
572 if (!LIL.canInterchangeLoops(InnerLoopId, OuterLoopId, DependencyMatrix)) {
573 DEBUG(dbgs() << "Not interchanging Loops. Cannot prove legality\n");
574 return false;
575 }
576 DEBUG(dbgs() << "Loops are legal to interchange\n");
577 LoopInterchangeProfitability LIP(OuterLoop, InnerLoop, SE);
578 if (!LIP.isProfitable(InnerLoopId, OuterLoopId, DependencyMatrix)) {
579 DEBUG(dbgs() << "Interchanging Loops not profitable\n");
580 return false;
581 }
582
583 LoopInterchangeTransform LIT(OuterLoop, InnerLoop, SE, LI, DT, this,
584 LoopNestExit);
585 LIT.transform();
586 DEBUG(dbgs() << "Loops interchanged\n");
587 return true;
588 }
589};
590
591} // end of namespace
592
593static bool containsUnsafeInstructions(BasicBlock *BB) {
594 for (auto I = BB->begin(), E = BB->end(); I != E; ++I) {
595 if (I->mayHaveSideEffects() || I->mayReadFromMemory())
596 return true;
597 }
598 return false;
599}
600
601bool LoopInterchangeLegality::tightlyNested(Loop *OuterLoop, Loop *InnerLoop) {
602 BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
603 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
604 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch();
605
606 DEBUG(dbgs() << "Checking if Loops are Tightly Nested\n");
607
608 // A perfectly nested loop will not have any branch in between the outer and
609 // inner block i.e. outer header will branch to either inner preheader and
610 // outerloop latch.
611 BranchInst *outerLoopHeaderBI =
612 dyn_cast<BranchInst>(OuterLoopHeader->getTerminator());
613 if (!outerLoopHeaderBI)
614 return false;
615 unsigned num = outerLoopHeaderBI->getNumSuccessors();
616 for (unsigned i = 0; i < num; i++) {
617 if (outerLoopHeaderBI->getSuccessor(i) != InnerLoopPreHeader &&
618 outerLoopHeaderBI->getSuccessor(i) != OuterLoopLatch)
619 return false;
620 }
621
622 DEBUG(dbgs() << "Checking instructions in Loop header and Loop latch \n");
623 // We do not have any basic block in between now make sure the outer header
624 // and outer loop latch doesnt contain any unsafe instructions.
625 if (containsUnsafeInstructions(OuterLoopHeader) ||
626 containsUnsafeInstructions(OuterLoopLatch))
627 return false;
628
629 DEBUG(dbgs() << "Loops are perfectly nested \n");
630 // We have a perfect loop nest.
631 return true;
632}
633
634static unsigned getPHICount(BasicBlock *BB) {
635 unsigned PhiCount = 0;
636 for (auto I = BB->begin(); isa<PHINode>(I); ++I)
637 PhiCount++;
638 return PhiCount;
639}
640
641bool LoopInterchangeLegality::isLoopStructureUnderstood(
642 PHINode *InnerInduction) {
643
644 unsigned Num = InnerInduction->getNumOperands();
645 BasicBlock *InnerLoopPreheader = InnerLoop->getLoopPreheader();
646 for (unsigned i = 0; i < Num; ++i) {
647 Value *Val = InnerInduction->getOperand(i);
648 if (isa<Constant>(Val))
649 continue;
650 Instruction *I = dyn_cast<Instruction>(Val);
651 if (!I)
652 return false;
653 // TODO: Handle triangular loops.
654 // e.g. for(int i=0;i<N;i++)
655 // for(int j=i;j<N;j++)
656 unsigned IncomBlockIndx = PHINode::getIncomingValueNumForOperand(i);
657 if (InnerInduction->getIncomingBlock(IncomBlockIndx) ==
658 InnerLoopPreheader &&
659 !OuterLoop->isLoopInvariant(I)) {
660 return false;
661 }
662 }
663 return true;
664}
665
666// This function indicates the current limitations in the transform as a result
667// of which we do not proceed.
668bool LoopInterchangeLegality::currentLimitations() {
669
670 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
671 BasicBlock *InnerLoopHeader = InnerLoop->getHeader();
672 BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
673 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
674 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch();
675
676 PHINode *InnerInductionVar;
677 PHINode *OuterInductionVar;
678
679 // We currently handle only 1 induction variable inside the loop. We also do
680 // not handle reductions as of now.
681 if (getPHICount(InnerLoopHeader) > 1)
682 return true;
683
684 if (getPHICount(OuterLoopHeader) > 1)
685 return true;
686
687 InnerInductionVar = getInductionVariable(InnerLoop, SE);
688 OuterInductionVar = getInductionVariable(OuterLoop, SE);
689
690 if (!OuterInductionVar || !InnerInductionVar) {
691 DEBUG(dbgs() << "Induction variable not found\n");
692 return true;
693 }
694
695 // TODO: Triangular loops are not handled for now.
696 if (!isLoopStructureUnderstood(InnerInductionVar)) {
697 DEBUG(dbgs() << "Loop structure not understood by pass\n");
698 return true;
699 }
700
701 // TODO: Loops with LCSSA PHI's are currently not handled.
702 if (isa<PHINode>(OuterLoopLatch->begin())) {
703 DEBUG(dbgs() << "Found and LCSSA PHI in outer loop latch\n");
704 return true;
705 }
706 if (InnerLoopLatch != InnerLoopHeader &&
707 isa<PHINode>(InnerLoopLatch->begin())) {
708 DEBUG(dbgs() << "Found and LCSSA PHI in inner loop latch\n");
709 return true;
710 }
711
712 // TODO: Current limitation: Since we split the inner loop latch at the point
713 // were induction variable is incremented (induction.next); We cannot have
714 // more than 1 user of induction.next since it would result in broken code
715 // after split.
716 // e.g.
717 // for(i=0;i<N;i++) {
718 // for(j = 0;j<M;j++) {
719 // A[j+1][i+2] = A[j][i]+k;
720 // }
721 // }
722 bool FoundInduction = false;
723 Instruction *InnerIndexVarInc = nullptr;
724 if (InnerInductionVar->getIncomingBlock(0) == InnerLoopPreHeader)
725 InnerIndexVarInc =
726 dyn_cast<Instruction>(InnerInductionVar->getIncomingValue(1));
727 else
728 InnerIndexVarInc =
729 dyn_cast<Instruction>(InnerInductionVar->getIncomingValue(0));
730
731 if (!InnerIndexVarInc)
732 return true;
733
734 // Since we split the inner loop latch on this induction variable. Make sure
735 // we do not have any instruction between the induction variable and branch
736 // instruction.
737
738 for (auto I = InnerLoopLatch->rbegin(), E = InnerLoopLatch->rend();
739 I != E && !FoundInduction; ++I) {
740 if (isa<BranchInst>(*I) || isa<CmpInst>(*I) || isa<TruncInst>(*I))
741 continue;
742 const Instruction &Ins = *I;
743 // We found an instruction. If this is not induction variable then it is not
744 // safe to split this loop latch.
745 if (!Ins.isIdenticalTo(InnerIndexVarInc))
746 return true;
747 else
748 FoundInduction = true;
749 }
750 // The loop latch ended and we didnt find the induction variable return as
751 // current limitation.
752 if (!FoundInduction)
753 return true;
754
755 return false;
756}
757
758bool LoopInterchangeLegality::canInterchangeLoops(unsigned InnerLoopId,
759 unsigned OuterLoopId,
760 CharMatrix &DepMatrix) {
761
762 if (!isLegalToInterChangeLoops(DepMatrix, InnerLoopId, OuterLoopId)) {
763 DEBUG(dbgs() << "Failed interchange InnerLoopId = " << InnerLoopId
764 << "and OuterLoopId = " << OuterLoopId
765 << "due to dependence\n");
766 return false;
767 }
768
769 // Create unique Preheaders if we already do not have one.
770 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader();
771 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
772
773 // Create a unique outer preheader -
774 // 1) If OuterLoop preheader is not present.
775 // 2) If OuterLoop Preheader is same as OuterLoop Header
776 // 3) If OuterLoop Preheader is same as Header of the previous loop.
777 // 4) If OuterLoop Preheader is Entry node.
778 if (!OuterLoopPreHeader || OuterLoopPreHeader == OuterLoop->getHeader() ||
779 isa<PHINode>(OuterLoopPreHeader->begin()) ||
780 !OuterLoopPreHeader->getUniquePredecessor()) {
781 OuterLoopPreHeader = InsertPreheaderForLoop(OuterLoop, CurrentPass);
782 }
783
784 if (!InnerLoopPreHeader || InnerLoopPreHeader == InnerLoop->getHeader() ||
785 InnerLoopPreHeader == OuterLoop->getHeader()) {
786 InnerLoopPreHeader = InsertPreheaderForLoop(InnerLoop, CurrentPass);
787 }
788
789 // Check if the loops are tightly nested.
790 if (!tightlyNested(OuterLoop, InnerLoop)) {
791 DEBUG(dbgs() << "Loops not tightly nested\n");
792 return false;
793 }
794
795 // TODO: The loops could not be interchanged due to current limitations in the
796 // transform module.
797 if (currentLimitations()) {
798 DEBUG(dbgs() << "Not legal because of current transform limitation\n");
799 return false;
800 }
801
802 return true;
803}
804
805int LoopInterchangeProfitability::getInstrOrderCost() {
806 unsigned GoodOrder, BadOrder;
807 BadOrder = GoodOrder = 0;
808 for (auto BI = InnerLoop->block_begin(), BE = InnerLoop->block_end();
809 BI != BE; ++BI) {
810 for (auto I = (*BI)->begin(), E = (*BI)->end(); I != E; ++I) {
811 const Instruction &Ins = *I;
812 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Ins)) {
813 unsigned NumOp = GEP->getNumOperands();
814 bool FoundInnerInduction = false;
815 bool FoundOuterInduction = false;
816 for (unsigned i = 0; i < NumOp; ++i) {
817 const SCEV *OperandVal = SE->getSCEV(GEP->getOperand(i));
818 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(OperandVal);
819 if (!AR)
820 continue;
821
822 // If we find the inner induction after an outer induction e.g.
823 // for(int i=0;i<N;i++)
824 // for(int j=0;j<N;j++)
825 // A[i][j] = A[i-1][j-1]+k;
826 // then it is a good order.
827 if (AR->getLoop() == InnerLoop) {
828 // We found an InnerLoop induction after OuterLoop induction. It is
829 // a good order.
830 FoundInnerInduction = true;
831 if (FoundOuterInduction) {
832 GoodOrder++;
833 break;
834 }
835 }
836 // If we find the outer induction after an inner induction e.g.
837 // for(int i=0;i<N;i++)
838 // for(int j=0;j<N;j++)
839 // A[j][i] = A[j-1][i-1]+k;
840 // then it is a bad order.
841 if (AR->getLoop() == OuterLoop) {
842 // We found an OuterLoop induction after InnerLoop induction. It is
843 // a bad order.
844 FoundOuterInduction = true;
845 if (FoundInnerInduction) {
846 BadOrder++;
847 break;
848 }
849 }
850 }
851 }
852 }
853 }
854 return GoodOrder - BadOrder;
855}
856
857bool isProfitabileForVectorization(unsigned InnerLoopId, unsigned OuterLoopId,
858 CharMatrix &DepMatrix) {
859 // TODO: Improve this heuristic to catch more cases.
860 // If the inner loop is loop independent or doesn't carry any dependency it is
861 // profitable to move this to outer position.
862 unsigned Row = DepMatrix.size();
863 for (unsigned i = 0; i < Row; ++i) {
864 if (DepMatrix[i][InnerLoopId] != 'S' && DepMatrix[i][InnerLoopId] != 'I')
865 return false;
866 // TODO: We need to improve this heuristic.
867 if (DepMatrix[i][OuterLoopId] != '=')
868 return false;
869 }
870 // If outer loop has dependence and inner loop is loop independent then it is
871 // profitable to interchange to enable parallelism.
872 return true;
873}
874
875bool LoopInterchangeProfitability::isProfitable(unsigned InnerLoopId,
876 unsigned OuterLoopId,
877 CharMatrix &DepMatrix) {
878
879 // TODO: Add Better Profitibility checks.
880 // e.g
881 // 1) Construct dependency matrix and move the one with no loop carried dep
882 // inside to enable vectorization.
883
884 // This is rough cost estimation algorithm. It counts the good and bad order
885 // of induction variables in the instruction and allows reordering if number
886 // of bad orders is more than good.
887 int Cost = 0;
888 Cost += getInstrOrderCost();
889 DEBUG(dbgs() << "Cost = " << Cost << "\n");
890 if (Cost < 0)
891 return true;
892
893 // It is not profitable as per current cache profitibility model. But check if
894 // we can move this loop outside to improve parallelism.
895 bool ImprovesPar =
896 isProfitabileForVectorization(InnerLoopId, OuterLoopId, DepMatrix);
897 return ImprovesPar;
898}
899
900void LoopInterchangeTransform::removeChildLoop(Loop *OuterLoop,
901 Loop *InnerLoop) {
Daniel Jasper6adbd7a2015-03-06 10:39:14 +0000902 for (Loop::iterator I = OuterLoop->begin(), E = OuterLoop->end(); I != E;
903 ++I) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000904 if (*I == InnerLoop) {
905 OuterLoop->removeChildLoop(I);
906 return;
907 }
908 }
Daniel Jasper6adbd7a2015-03-06 10:39:14 +0000909 assert(false && "Couldn't find loop");
Karthik Bhat88db86d2015-03-06 10:11:25 +0000910}
Daniel Jasper6adbd7a2015-03-06 10:39:14 +0000911
Karthik Bhat88db86d2015-03-06 10:11:25 +0000912void LoopInterchangeTransform::restructureLoops(Loop *InnerLoop,
913 Loop *OuterLoop) {
914 Loop *OuterLoopParent = OuterLoop->getParentLoop();
915 if (OuterLoopParent) {
916 // Remove the loop from its parent loop.
917 removeChildLoop(OuterLoopParent, OuterLoop);
918 removeChildLoop(OuterLoop, InnerLoop);
919 OuterLoopParent->addChildLoop(InnerLoop);
920 } else {
921 removeChildLoop(OuterLoop, InnerLoop);
922 LI->changeTopLevelLoop(OuterLoop, InnerLoop);
923 }
924
925 for (Loop::iterator I = InnerLoop->begin(), E = InnerLoop->end(); I != E; ++I)
926 OuterLoop->addChildLoop(InnerLoop->removeChildLoop(I));
927
928 InnerLoop->addChildLoop(OuterLoop);
929}
930
931bool LoopInterchangeTransform::transform() {
932
933 DEBUG(dbgs() << "transform\n");
934 bool Transformed = false;
935 Instruction *InnerIndexVar;
936
937 if (InnerLoop->getSubLoops().size() == 0) {
938 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
939 DEBUG(dbgs() << "Calling Split Inner Loop\n");
940 PHINode *InductionPHI = getInductionVariable(InnerLoop, SE);
941 if (!InductionPHI) {
942 DEBUG(dbgs() << "Failed to find the point to split loop latch \n");
943 return false;
944 }
945
946 if (InductionPHI->getIncomingBlock(0) == InnerLoopPreHeader)
947 InnerIndexVar = dyn_cast<Instruction>(InductionPHI->getIncomingValue(1));
948 else
949 InnerIndexVar = dyn_cast<Instruction>(InductionPHI->getIncomingValue(0));
950
951 //
952 // Split at the place were the induction variable is
953 // incremented/decremented.
954 // TODO: This splitting logic may not work always. Fix this.
955 splitInnerLoopLatch(InnerIndexVar);
956 DEBUG(dbgs() << "splitInnerLoopLatch Done\n");
957
958 // Splits the inner loops phi nodes out into a seperate basic block.
959 splitInnerLoopHeader();
960 DEBUG(dbgs() << "splitInnerLoopHeader Done\n");
961 }
962
963 Transformed |= adjustLoopLinks();
964 if (!Transformed) {
965 DEBUG(dbgs() << "adjustLoopLinks Failed\n");
966 return false;
967 }
968
969 restructureLoops(InnerLoop, OuterLoop);
970 return true;
971}
972
973void LoopInterchangeTransform::initialize() {}
974
Benjamin Kramer79442922015-03-06 18:59:14 +0000975void LoopInterchangeTransform::splitInnerLoopLatch(Instruction *Inc) {
Karthik Bhat88db86d2015-03-06 10:11:25 +0000976 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
Karthik Bhat88db86d2015-03-06 10:11:25 +0000977 BasicBlock *InnerLoopLatchPred = InnerLoopLatch;
Benjamin Kramer79442922015-03-06 18:59:14 +0000978 InnerLoopLatch = SplitBlock(InnerLoopLatchPred, Inc, DT, LI);
Karthik Bhat88db86d2015-03-06 10:11:25 +0000979}
980
981void LoopInterchangeTransform::splitOuterLoopLatch() {
982 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch();
983 BasicBlock *OuterLatchLcssaPhiBlock = OuterLoopLatch;
984 OuterLoopLatch = SplitBlock(OuterLatchLcssaPhiBlock,
985 OuterLoopLatch->getFirstNonPHI(), DT, LI);
986}
987
988void LoopInterchangeTransform::splitInnerLoopHeader() {
989
990 // Split the inner loop header out.
991 BasicBlock *InnerLoopHeader = InnerLoop->getHeader();
992 SplitBlock(InnerLoopHeader, InnerLoopHeader->getFirstNonPHI(), DT, LI);
993
994 DEBUG(dbgs() << "Output of splitInnerLoopHeader InnerLoopHeaderSucc & "
995 "InnerLoopHeader \n");
996}
997
Benjamin Kramer79442922015-03-06 18:59:14 +0000998/// \brief Move all instructions except the terminator from FromBB right before
999/// InsertBefore
1000static void moveBBContents(BasicBlock *FromBB, Instruction *InsertBefore) {
1001 auto &ToList = InsertBefore->getParent()->getInstList();
1002 auto &FromList = FromBB->getInstList();
1003
1004 ToList.splice(InsertBefore, FromList, FromList.begin(),
1005 FromBB->getTerminator());
1006}
1007
Karthik Bhat88db86d2015-03-06 10:11:25 +00001008void LoopInterchangeTransform::adjustOuterLoopPreheader() {
1009 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader();
Karthik Bhat88db86d2015-03-06 10:11:25 +00001010 BasicBlock *InnerPreHeader = InnerLoop->getLoopPreheader();
Benjamin Kramer79442922015-03-06 18:59:14 +00001011
1012 moveBBContents(OuterLoopPreHeader, InnerPreHeader->getTerminator());
Karthik Bhat88db86d2015-03-06 10:11:25 +00001013}
1014
1015void LoopInterchangeTransform::adjustInnerLoopPreheader() {
Karthik Bhat88db86d2015-03-06 10:11:25 +00001016 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
Karthik Bhat88db86d2015-03-06 10:11:25 +00001017 BasicBlock *OuterHeader = OuterLoop->getHeader();
Benjamin Kramer79442922015-03-06 18:59:14 +00001018
1019 moveBBContents(InnerLoopPreHeader, OuterHeader->getTerminator());
Karthik Bhat88db86d2015-03-06 10:11:25 +00001020}
1021
1022bool LoopInterchangeTransform::adjustLoopBranches() {
1023
1024 DEBUG(dbgs() << "adjustLoopBranches called\n");
1025 // Adjust the loop preheader
1026 BasicBlock *InnerLoopHeader = InnerLoop->getHeader();
1027 BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
1028 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
1029 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch();
1030 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader();
1031 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
1032 BasicBlock *OuterLoopPredecessor = OuterLoopPreHeader->getUniquePredecessor();
1033 BasicBlock *InnerLoopLatchPredecessor =
1034 InnerLoopLatch->getUniquePredecessor();
1035 BasicBlock *InnerLoopLatchSuccessor;
1036 BasicBlock *OuterLoopLatchSuccessor;
1037
1038 BranchInst *OuterLoopLatchBI =
1039 dyn_cast<BranchInst>(OuterLoopLatch->getTerminator());
1040 BranchInst *InnerLoopLatchBI =
1041 dyn_cast<BranchInst>(InnerLoopLatch->getTerminator());
1042 BranchInst *OuterLoopHeaderBI =
1043 dyn_cast<BranchInst>(OuterLoopHeader->getTerminator());
1044 BranchInst *InnerLoopHeaderBI =
1045 dyn_cast<BranchInst>(InnerLoopHeader->getTerminator());
1046
1047 if (!OuterLoopPredecessor || !InnerLoopLatchPredecessor ||
1048 !OuterLoopLatchBI || !InnerLoopLatchBI || !OuterLoopHeaderBI ||
1049 !InnerLoopHeaderBI)
1050 return false;
1051
1052 BranchInst *InnerLoopLatchPredecessorBI =
1053 dyn_cast<BranchInst>(InnerLoopLatchPredecessor->getTerminator());
1054 BranchInst *OuterLoopPredecessorBI =
1055 dyn_cast<BranchInst>(OuterLoopPredecessor->getTerminator());
1056
1057 if (!OuterLoopPredecessorBI || !InnerLoopLatchPredecessorBI)
1058 return false;
1059 BasicBlock *InnerLoopHeaderSucessor = InnerLoopHeader->getUniqueSuccessor();
1060 if (!InnerLoopHeaderSucessor)
1061 return false;
1062
1063 // Adjust Loop Preheader and headers
1064
1065 unsigned NumSucc = OuterLoopPredecessorBI->getNumSuccessors();
1066 for (unsigned i = 0; i < NumSucc; ++i) {
1067 if (OuterLoopPredecessorBI->getSuccessor(i) == OuterLoopPreHeader)
1068 OuterLoopPredecessorBI->setSuccessor(i, InnerLoopPreHeader);
1069 }
1070
1071 NumSucc = OuterLoopHeaderBI->getNumSuccessors();
1072 for (unsigned i = 0; i < NumSucc; ++i) {
1073 if (OuterLoopHeaderBI->getSuccessor(i) == OuterLoopLatch)
1074 OuterLoopHeaderBI->setSuccessor(i, LoopExit);
1075 else if (OuterLoopHeaderBI->getSuccessor(i) == InnerLoopPreHeader)
1076 OuterLoopHeaderBI->setSuccessor(i, InnerLoopHeaderSucessor);
1077 }
1078
1079 BranchInst::Create(OuterLoopPreHeader, InnerLoopHeaderBI);
1080 InnerLoopHeaderBI->eraseFromParent();
1081
1082 // -------------Adjust loop latches-----------
1083 if (InnerLoopLatchBI->getSuccessor(0) == InnerLoopHeader)
1084 InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(1);
1085 else
1086 InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(0);
1087
1088 NumSucc = InnerLoopLatchPredecessorBI->getNumSuccessors();
1089 for (unsigned i = 0; i < NumSucc; ++i) {
1090 if (InnerLoopLatchPredecessorBI->getSuccessor(i) == InnerLoopLatch)
1091 InnerLoopLatchPredecessorBI->setSuccessor(i, InnerLoopLatchSuccessor);
1092 }
1093
1094 if (OuterLoopLatchBI->getSuccessor(0) == OuterLoopHeader)
1095 OuterLoopLatchSuccessor = OuterLoopLatchBI->getSuccessor(1);
1096 else
1097 OuterLoopLatchSuccessor = OuterLoopLatchBI->getSuccessor(0);
1098
1099 if (InnerLoopLatchBI->getSuccessor(1) == InnerLoopLatchSuccessor)
1100 InnerLoopLatchBI->setSuccessor(1, OuterLoopLatchSuccessor);
1101 else
1102 InnerLoopLatchBI->setSuccessor(0, OuterLoopLatchSuccessor);
1103
1104 if (OuterLoopLatchBI->getSuccessor(0) == OuterLoopLatchSuccessor) {
1105 OuterLoopLatchBI->setSuccessor(0, InnerLoopLatch);
1106 } else {
1107 OuterLoopLatchBI->setSuccessor(1, InnerLoopLatch);
1108 }
1109
1110 return true;
1111}
1112void LoopInterchangeTransform::adjustLoopPreheaders() {
1113
1114 // We have interchanged the preheaders so we need to interchange the data in
1115 // the preheader as well.
1116 // This is because the content of inner preheader was previously executed
1117 // inside the outer loop.
1118 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader();
1119 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
1120 BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
1121 BranchInst *InnerTermBI =
1122 cast<BranchInst>(InnerLoopPreHeader->getTerminator());
1123
Karthik Bhat88db86d2015-03-06 10:11:25 +00001124 BasicBlock *HeaderSplit =
1125 SplitBlock(OuterLoopHeader, OuterLoopHeader->getTerminator(), DT, LI);
1126 Instruction *InsPoint = HeaderSplit->getFirstNonPHI();
1127 // These instructions should now be executed inside the loop.
1128 // Move instruction into a new block after outer header.
Benjamin Kramer79442922015-03-06 18:59:14 +00001129 moveBBContents(InnerLoopPreHeader, InsPoint);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001130 // These instructions were not executed previously in the loop so move them to
1131 // the older inner loop preheader.
Benjamin Kramer79442922015-03-06 18:59:14 +00001132 moveBBContents(OuterLoopPreHeader, InnerTermBI);
Karthik Bhat88db86d2015-03-06 10:11:25 +00001133}
1134
1135bool LoopInterchangeTransform::adjustLoopLinks() {
1136
1137 // Adjust all branches in the inner and outer loop.
1138 bool Changed = adjustLoopBranches();
1139 if (Changed)
1140 adjustLoopPreheaders();
1141 return Changed;
1142}
1143
1144char LoopInterchange::ID = 0;
1145INITIALIZE_PASS_BEGIN(LoopInterchange, "loop-interchange",
1146 "Interchanges loops for cache reuse", false, false)
1147INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
1148INITIALIZE_PASS_DEPENDENCY(DependenceAnalysis)
1149INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1150INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1151INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
1152INITIALIZE_PASS_DEPENDENCY(LCSSA)
1153INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
1154
1155INITIALIZE_PASS_END(LoopInterchange, "loop-interchange",
1156 "Interchanges loops for cache reuse", false, false)
1157
1158Pass *llvm::createLoopInterchangePass() { return new LoopInterchange(); }