1 //===- LoopInterchange.cpp - Loop interchange pass------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This Pass handles loop interchange transform.
11 // This pass interchanges loops to provide a more cache-friendly memory access
14 //===----------------------------------------------------------------------===//
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/IR/Dominators.h"
32 #include "llvm/IR/Function.h"
33 #include "llvm/IR/IRBuilder.h"
34 #include "llvm/IR/InstIterator.h"
35 #include "llvm/IR/IntrinsicInst.h"
36 #include "llvm/Pass.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/Transforms/Scalar.h"
40 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
41 #include "llvm/Transforms/Utils/LoopUtils.h"
42 #include "llvm/Transforms/Utils/SSAUpdater.h"
45 #define DEBUG_TYPE "loop-interchange"
49 typedef SmallVector<Loop *, 8> LoopVector;
51 // TODO: Check if we can use a sparse matrix here.
52 typedef std::vector<std::vector<char>> CharMatrix;
54 // Maximum number of dependencies that can be handled in the dependency matrix.
55 static const unsigned MaxMemInstrCount = 100;
57 // Maximum loop depth supported.
58 static const unsigned MaxLoopNestDepth = 10;
60 struct LoopInterchange;
62 #ifdef DUMP_DEP_MATRICIES
63 void 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");
73 bool populateDependencyMatrix(CharMatrix &DepMatrix, unsigned Level, Loop *L,
74 DependenceAnalysis *DA) {
75 typedef SmallVector<Value *, 16> ValueVector;
78 if (Level > MaxLoopNestDepth) {
79 DEBUG(dbgs() << "Cannot handle loops of depth greater than "
80 << MaxLoopNestDepth << "\n");
85 for (Loop::block_iterator BB = L->block_begin(), BE = L->block_end();
87 // Scan the BB and collect legal loads and stores.
88 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E;
90 Instruction *Ins = dyn_cast<Instruction>(I);
93 LoadInst *Ld = dyn_cast<LoadInst>(I);
94 StoreInst *St = dyn_cast<StoreInst>(I);
97 if (Ld && !Ld->isSimple())
99 if (St && !St->isSimple())
101 MemInstr.push_back(I);
105 DEBUG(dbgs() << "Found " << MemInstr.size()
106 << " Loads and Stores to analyze\n");
108 ValueVector::iterator I, IE, J, JE;
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);
117 if (isa<LoadInst>(Src) && isa<LoadInst>(Des))
119 if (auto D = DA->depends(Src, Des, true)) {
120 DEBUG(dbgs() << "Found Dependency between Src=" << Src << " Des=" << Des
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");
129 DEBUG(dbgs() << "Found Anti dependence \n");
130 unsigned Levels = D->getLevels();
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);
137 const ConstantInt *CI = SCEVConst->getValue();
138 if (CI->isNegative())
140 else if (CI->isZero())
144 Dep.push_back(Direction);
145 } else if (D->isScalar(II)) {
147 Dep.push_back(Direction);
149 unsigned Dir = D->getDirection(II);
150 if (Dir == Dependence::DVEntry::LT ||
151 Dir == Dependence::DVEntry::LE)
153 else if (Dir == Dependence::DVEntry::GT ||
154 Dir == Dependence::DVEntry::GE)
156 else if (Dir == Dependence::DVEntry::EQ)
160 Dep.push_back(Direction);
163 while (Dep.size() != Level) {
167 DepMatrix.push_back(Dep);
168 if (DepMatrix.size() > MaxMemInstrCount) {
169 DEBUG(dbgs() << "Cannot handle more than " << MaxMemInstrCount
170 << " dependencies inside loop\n");
178 // We don't have a DepMatrix to check legality return false
179 if (DepMatrix.size() == 0)
184 // A loop is moved from index 'from' to an index 'to'. Update the Dependence
185 // matrix by exchanging the two columns.
186 void interChangeDepedencies(CharMatrix &DepMatrix, unsigned FromIndx,
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;
196 // Checks if outermost non '=','S'or'I' dependence in the dependence matrix is
198 bool isOuterMostDepPositive(CharMatrix &DepMatrix, unsigned Row,
200 for (unsigned i = 0; i <= Column; ++i) {
201 if (DepMatrix[Row][i] == '<')
203 if (DepMatrix[Row][i] == '>')
206 // All dependencies were '=','S' or 'I'
210 // Checks if no dependence exist in the dependency matrix in Row before Column.
211 bool containsNoDependence(CharMatrix &DepMatrix, unsigned Row,
213 for (unsigned i = 0; i < Column; ++i) {
214 if (DepMatrix[Row][i] != '=' || DepMatrix[Row][i] != 'S' ||
215 DepMatrix[Row][i] != 'I')
221 bool validDepInterchange(CharMatrix &DepMatrix, unsigned Row,
222 unsigned OuterLoopId, char InnerDep, char OuterDep) {
224 if (isOuterMostDepPositive(DepMatrix, Row, OuterLoopId))
227 if (InnerDep == OuterDep)
230 // It is legal to interchange if and only if after interchange no row has a
231 // '>' direction as the leftmost non-'='.
233 if (InnerDep == '=' || InnerDep == 'S' || InnerDep == 'I')
239 if (InnerDep == '>') {
240 // If OuterLoopId represents outermost loop then interchanging will make the
241 // 1st dependency as '>'
242 if (OuterLoopId == 0)
245 // If all dependencies before OuterloopId are '=','S'or 'I'. Then
246 // interchanging will result in this row having an outermost non '='
248 if (!containsNoDependence(DepMatrix, Row, OuterLoopId))
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.
259 bool isLegalToInterChangeLoops(CharMatrix &DepMatrix, unsigned InnerLoopId,
260 unsigned OuterLoopId) {
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 == '*')
269 else if (!validDepInterchange(DepMatrix, Row, OuterLoopId, InnerDep,
276 static void populateWorklist(Loop &L, SmallVector<LoopVector, 8> &V) {
278 DEBUG(dbgs() << "Calling populateWorklist called\n");
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
285 // Discard all loops above it added into Worklist.
286 if (vec.size() != 1) {
290 LoopList.push_back(CurrentLoop);
291 CurrentLoop = *(vec.begin());
292 vec = CurrentLoop->getSubLoopsVector();
294 LoopList.push_back(CurrentLoop);
295 V.push_back(LoopList);
298 static PHINode *getInductionVariable(Loop *L, ScalarEvolution *SE) {
299 PHINode *InnerIndexVar = L->getCanonicalInductionVariable();
301 return InnerIndexVar;
302 if (L->getLoopLatch() == nullptr || L->getLoopPredecessor() == 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())
310 const SCEVAddRecExpr *AddRec =
311 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(PhiVar));
312 if (!AddRec || !AddRec->isAffine())
314 const SCEV *Step = AddRec->getStepRecurrence(*SE);
315 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
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.
326 /// LoopInterchangeLegality checks if it is legal to interchange the loop.
327 class LoopInterchangeLegality {
329 LoopInterchangeLegality(Loop *Outer, Loop *Inner, ScalarEvolution *SE,
330 LoopInterchange *Pass)
331 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), CurrentPass(Pass) {}
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
338 bool isLoopStructureUnderstood(PHINode *InnerInductionVar);
340 bool currentLimitations();
343 bool tightlyNested(Loop *Outer, Loop *Inner);
350 LoopInterchange *CurrentPass;
353 /// LoopInterchangeProfitability checks if it is profitable to interchange the
355 class LoopInterchangeProfitability {
357 LoopInterchangeProfitability(Loop *Outer, Loop *Inner, ScalarEvolution *SE)
358 : OuterLoop(Outer), InnerLoop(Inner), SE(SE) {}
360 /// Check if the loop interchange is profitable
361 bool isProfitable(unsigned InnerLoopId, unsigned OuterLoopId,
362 CharMatrix &DepMatrix);
365 int getInstrOrderCost();
374 /// LoopInterchangeTransform interchanges the loop
375 class LoopInterchangeTransform {
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) {}
383 /// Interchange OuterLoop and InnerLoop.
385 void restructureLoops(Loop *InnerLoop, Loop *OuterLoop);
386 void removeChildLoop(Loop *OuterLoop, Loop *InnerLoop);
389 void splitInnerLoopLatch(Instruction *);
390 void splitOuterLoopLatch();
391 void splitInnerLoopHeader();
392 bool adjustLoopLinks();
393 void adjustLoopPreheaders();
394 void adjustOuterLoopPreheader();
395 void adjustInnerLoopPreheader();
396 bool adjustLoopBranches();
405 BasicBlock *LoopExit;
408 // Main LoopInterchange Pass
409 struct LoopInterchange : public FunctionPass {
413 DependenceAnalysis *DA;
416 : FunctionPass(ID), SE(nullptr), LI(nullptr), DA(nullptr), DT(nullptr) {
417 initializeLoopInterchangePass(*PassRegistry::getPassRegistry());
420 void getAnalysisUsage(AnalysisUsage &AU) const override {
421 AU.addRequired<ScalarEvolution>();
422 AU.addRequired<AliasAnalysis>();
423 AU.addRequired<DominatorTreeWrapperPass>();
424 AU.addRequired<LoopInfoWrapperPass>();
425 AU.addRequired<DependenceAnalysis>();
426 AU.addRequiredID(LoopSimplifyID);
427 AU.addRequiredID(LCSSAID);
430 bool runOnFunction(Function &F) override {
431 SE = &getAnalysis<ScalarEvolution>();
432 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
433 DA = &getAnalysis<DependenceAnalysis>();
434 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
435 DT = DTWP ? &DTWP->getDomTree() : nullptr;
436 // Build up a worklist of loop pairs to analyze.
437 SmallVector<LoopVector, 8> Worklist;
440 populateWorklist(*L, Worklist);
442 DEBUG(dbgs() << "Worklist size = " << Worklist.size() << "\n");
444 while (!Worklist.empty()) {
445 LoopVector LoopList = Worklist.pop_back_val();
446 Changed = processLoopList(LoopList);
451 bool isComputableLoopNest(LoopVector LoopList) {
452 for (auto I = LoopList.begin(), E = LoopList.end(); I != E; ++I) {
454 const SCEV *ExitCountOuter = SE->getBackedgeTakenCount(L);
455 if (ExitCountOuter == SE->getCouldNotCompute()) {
456 DEBUG(dbgs() << "Couldn't compute Backedge count\n");
459 if (L->getNumBackEdges() != 1) {
460 DEBUG(dbgs() << "NumBackEdges is not equal to 1\n");
463 if (!L->getExitingBlock()) {
464 DEBUG(dbgs() << "Loop Doesn't have unique exit block\n");
471 unsigned selectLoopForInterchange(LoopVector LoopList) {
472 // TODO: Add a better heuristic to select the loop to be interchanged based
473 // on the dependece matrix. Currently we select the innermost loop.
474 return LoopList.size() - 1;
477 bool processLoopList(LoopVector LoopList) {
478 bool Changed = false;
479 bool containsLCSSAPHI = false;
480 CharMatrix DependencyMatrix;
481 if (LoopList.size() < 2) {
482 DEBUG(dbgs() << "Loop doesn't contain minimum nesting level.\n");
485 if (!isComputableLoopNest(LoopList)) {
486 DEBUG(dbgs() << "Not vaild loop candidate for interchange\n");
489 Loop *OuterMostLoop = *(LoopList.begin());
491 DEBUG(dbgs() << "Processing LoopList of size = " << LoopList.size()
494 if (!populateDependencyMatrix(DependencyMatrix, LoopList.size(),
495 OuterMostLoop, DA)) {
496 DEBUG(dbgs() << "Populating Dependency matrix failed\n");
499 #ifdef DUMP_DEP_MATRICIES
500 DEBUG(dbgs() << "Dependence before inter change \n");
501 printDepMatrix(DependencyMatrix);
504 BasicBlock *OuterMostLoopLatch = OuterMostLoop->getLoopLatch();
505 BranchInst *OuterMostLoopLatchBI =
506 dyn_cast<BranchInst>(OuterMostLoopLatch->getTerminator());
507 if (!OuterMostLoopLatchBI)
510 // Since we currently do not handle LCSSA PHI's any failure in loop
511 // condition will now branch to LoopNestExit.
512 // TODO: This should be removed once we handle LCSSA PHI nodes.
514 // Get the Outermost loop exit.
515 BasicBlock *LoopNestExit;
516 if (OuterMostLoopLatchBI->getSuccessor(0) == OuterMostLoop->getHeader())
517 LoopNestExit = OuterMostLoopLatchBI->getSuccessor(1);
519 LoopNestExit = OuterMostLoopLatchBI->getSuccessor(0);
521 for (auto I = LoopList.begin(), E = LoopList.end(); I != E; ++I) {
523 BasicBlock *Latch = L->getLoopLatch();
524 BasicBlock *Header = L->getHeader();
525 if (Latch && Latch != Header && isa<PHINode>(Latch->begin())) {
526 containsLCSSAPHI = true;
531 // TODO: Handle lcssa PHI's. Currently LCSSA PHI's are not handled. Handle
532 // the same by splitting the loop latch and adjusting loop links
534 if (containsLCSSAPHI)
537 unsigned SelecLoopId = selectLoopForInterchange(LoopList);
538 // Move the selected loop outwards to the best posible position.
539 for (unsigned i = SelecLoopId; i > 0; i--) {
541 processLoop(LoopList, i, i - 1, LoopNestExit, DependencyMatrix);
544 // Loops interchanged reflect the same in LoopList
545 std::swap(LoopList[i - 1], LoopList[i]);
547 // Update the DependencyMatrix
548 interChangeDepedencies(DependencyMatrix, i, i - 1);
550 #ifdef DUMP_DEP_MATRICIES
551 DEBUG(dbgs() << "Dependence after inter change \n");
552 printDepMatrix(DependencyMatrix);
554 Changed |= Interchanged;
559 bool processLoop(LoopVector LoopList, unsigned InnerLoopId,
560 unsigned OuterLoopId, BasicBlock *LoopNestExit,
561 std::vector<std::vector<char>> &DependencyMatrix) {
563 DEBUG(dbgs() << "Processing Innder Loop Id = " << InnerLoopId
564 << " and OuterLoopId = " << OuterLoopId << "\n");
565 Loop *InnerLoop = LoopList[InnerLoopId];
566 Loop *OuterLoop = LoopList[OuterLoopId];
568 LoopInterchangeLegality LIL(OuterLoop, InnerLoop, SE, this);
569 if (!LIL.canInterchangeLoops(InnerLoopId, OuterLoopId, DependencyMatrix)) {
570 DEBUG(dbgs() << "Not interchanging Loops. Cannot prove legality\n");
573 DEBUG(dbgs() << "Loops are legal to interchange\n");
574 LoopInterchangeProfitability LIP(OuterLoop, InnerLoop, SE);
575 if (!LIP.isProfitable(InnerLoopId, OuterLoopId, DependencyMatrix)) {
576 DEBUG(dbgs() << "Interchanging Loops not profitable\n");
580 LoopInterchangeTransform LIT(OuterLoop, InnerLoop, SE, LI, DT, this,
583 DEBUG(dbgs() << "Loops interchanged\n");
588 } // end of namespace
590 static bool containsUnsafeInstructions(BasicBlock *BB) {
591 for (auto I = BB->begin(), E = BB->end(); I != E; ++I) {
592 if (I->mayHaveSideEffects() || I->mayReadFromMemory())
598 bool LoopInterchangeLegality::tightlyNested(Loop *OuterLoop, Loop *InnerLoop) {
599 BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
600 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
601 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch();
603 DEBUG(dbgs() << "Checking if Loops are Tightly Nested\n");
605 // A perfectly nested loop will not have any branch in between the outer and
606 // inner block i.e. outer header will branch to either inner preheader and
608 BranchInst *outerLoopHeaderBI =
609 dyn_cast<BranchInst>(OuterLoopHeader->getTerminator());
610 if (!outerLoopHeaderBI)
612 unsigned num = outerLoopHeaderBI->getNumSuccessors();
613 for (unsigned i = 0; i < num; i++) {
614 if (outerLoopHeaderBI->getSuccessor(i) != InnerLoopPreHeader &&
615 outerLoopHeaderBI->getSuccessor(i) != OuterLoopLatch)
619 DEBUG(dbgs() << "Checking instructions in Loop header and Loop latch \n");
620 // We do not have any basic block in between now make sure the outer header
621 // and outer loop latch doesnt contain any unsafe instructions.
622 if (containsUnsafeInstructions(OuterLoopHeader) ||
623 containsUnsafeInstructions(OuterLoopLatch))
626 DEBUG(dbgs() << "Loops are perfectly nested \n");
627 // We have a perfect loop nest.
631 static unsigned getPHICount(BasicBlock *BB) {
632 unsigned PhiCount = 0;
633 for (auto I = BB->begin(); isa<PHINode>(I); ++I)
638 bool LoopInterchangeLegality::isLoopStructureUnderstood(
639 PHINode *InnerInduction) {
641 unsigned Num = InnerInduction->getNumOperands();
642 BasicBlock *InnerLoopPreheader = InnerLoop->getLoopPreheader();
643 for (unsigned i = 0; i < Num; ++i) {
644 Value *Val = InnerInduction->getOperand(i);
645 if (isa<Constant>(Val))
647 Instruction *I = dyn_cast<Instruction>(Val);
650 // TODO: Handle triangular loops.
651 // e.g. for(int i=0;i<N;i++)
652 // for(int j=i;j<N;j++)
653 unsigned IncomBlockIndx = PHINode::getIncomingValueNumForOperand(i);
654 if (InnerInduction->getIncomingBlock(IncomBlockIndx) ==
655 InnerLoopPreheader &&
656 !OuterLoop->isLoopInvariant(I)) {
663 // This function indicates the current limitations in the transform as a result
664 // of which we do not proceed.
665 bool LoopInterchangeLegality::currentLimitations() {
667 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
668 BasicBlock *InnerLoopHeader = InnerLoop->getHeader();
669 BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
670 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
671 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch();
673 PHINode *InnerInductionVar;
674 PHINode *OuterInductionVar;
676 // We currently handle only 1 induction variable inside the loop. We also do
677 // not handle reductions as of now.
678 if (getPHICount(InnerLoopHeader) > 1)
681 if (getPHICount(OuterLoopHeader) > 1)
684 InnerInductionVar = getInductionVariable(InnerLoop, SE);
685 OuterInductionVar = getInductionVariable(OuterLoop, SE);
687 if (!OuterInductionVar || !InnerInductionVar) {
688 DEBUG(dbgs() << "Induction variable not found\n");
692 // TODO: Triangular loops are not handled for now.
693 if (!isLoopStructureUnderstood(InnerInductionVar)) {
694 DEBUG(dbgs() << "Loop structure not understood by pass\n");
698 // TODO: Loops with LCSSA PHI's are currently not handled.
699 if (isa<PHINode>(OuterLoopLatch->begin())) {
700 DEBUG(dbgs() << "Found and LCSSA PHI in outer loop latch\n");
703 if (InnerLoopLatch != InnerLoopHeader &&
704 isa<PHINode>(InnerLoopLatch->begin())) {
705 DEBUG(dbgs() << "Found and LCSSA PHI in inner loop latch\n");
709 // TODO: Current limitation: Since we split the inner loop latch at the point
710 // were induction variable is incremented (induction.next); We cannot have
711 // more than 1 user of induction.next since it would result in broken code
714 // for(i=0;i<N;i++) {
715 // for(j = 0;j<M;j++) {
716 // A[j+1][i+2] = A[j][i]+k;
719 bool FoundInduction = false;
720 Instruction *InnerIndexVarInc = nullptr;
721 if (InnerInductionVar->getIncomingBlock(0) == InnerLoopPreHeader)
723 dyn_cast<Instruction>(InnerInductionVar->getIncomingValue(1));
726 dyn_cast<Instruction>(InnerInductionVar->getIncomingValue(0));
728 if (!InnerIndexVarInc)
731 // Since we split the inner loop latch on this induction variable. Make sure
732 // we do not have any instruction between the induction variable and branch
735 for (auto I = InnerLoopLatch->rbegin(), E = InnerLoopLatch->rend();
736 I != E && !FoundInduction; ++I) {
737 if (isa<BranchInst>(*I) || isa<CmpInst>(*I) || isa<TruncInst>(*I))
739 const Instruction &Ins = *I;
740 // We found an instruction. If this is not induction variable then it is not
741 // safe to split this loop latch.
742 if (!Ins.isIdenticalTo(InnerIndexVarInc))
745 FoundInduction = true;
747 // The loop latch ended and we didnt find the induction variable return as
748 // current limitation.
755 bool LoopInterchangeLegality::canInterchangeLoops(unsigned InnerLoopId,
756 unsigned OuterLoopId,
757 CharMatrix &DepMatrix) {
759 if (!isLegalToInterChangeLoops(DepMatrix, InnerLoopId, OuterLoopId)) {
760 DEBUG(dbgs() << "Failed interchange InnerLoopId = " << InnerLoopId
761 << "and OuterLoopId = " << OuterLoopId
762 << "due to dependence\n");
766 // Create unique Preheaders if we already do not have one.
767 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader();
768 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
770 // Create a unique outer preheader -
771 // 1) If OuterLoop preheader is not present.
772 // 2) If OuterLoop Preheader is same as OuterLoop Header
773 // 3) If OuterLoop Preheader is same as Header of the previous loop.
774 // 4) If OuterLoop Preheader is Entry node.
775 if (!OuterLoopPreHeader || OuterLoopPreHeader == OuterLoop->getHeader() ||
776 isa<PHINode>(OuterLoopPreHeader->begin()) ||
777 !OuterLoopPreHeader->getUniquePredecessor()) {
778 OuterLoopPreHeader = InsertPreheaderForLoop(OuterLoop, CurrentPass);
781 if (!InnerLoopPreHeader || InnerLoopPreHeader == InnerLoop->getHeader() ||
782 InnerLoopPreHeader == OuterLoop->getHeader()) {
783 InnerLoopPreHeader = InsertPreheaderForLoop(InnerLoop, CurrentPass);
786 // Check if the loops are tightly nested.
787 if (!tightlyNested(OuterLoop, InnerLoop)) {
788 DEBUG(dbgs() << "Loops not tightly nested\n");
792 // TODO: The loops could not be interchanged due to current limitations in the
794 if (currentLimitations()) {
795 DEBUG(dbgs() << "Not legal because of current transform limitation\n");
802 int LoopInterchangeProfitability::getInstrOrderCost() {
803 unsigned GoodOrder, BadOrder;
804 BadOrder = GoodOrder = 0;
805 for (auto BI = InnerLoop->block_begin(), BE = InnerLoop->block_end();
807 for (auto I = (*BI)->begin(), E = (*BI)->end(); I != E; ++I) {
808 const Instruction &Ins = *I;
809 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Ins)) {
810 unsigned NumOp = GEP->getNumOperands();
811 bool FoundInnerInduction = false;
812 bool FoundOuterInduction = false;
813 for (unsigned i = 0; i < NumOp; ++i) {
814 const SCEV *OperandVal = SE->getSCEV(GEP->getOperand(i));
815 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(OperandVal);
819 // If we find the inner induction after an outer induction e.g.
820 // for(int i=0;i<N;i++)
821 // for(int j=0;j<N;j++)
822 // A[i][j] = A[i-1][j-1]+k;
823 // then it is a good order.
824 if (AR->getLoop() == InnerLoop) {
825 // We found an InnerLoop induction after OuterLoop induction. It is
827 FoundInnerInduction = true;
828 if (FoundOuterInduction) {
833 // If we find the outer induction after an inner induction e.g.
834 // for(int i=0;i<N;i++)
835 // for(int j=0;j<N;j++)
836 // A[j][i] = A[j-1][i-1]+k;
837 // then it is a bad order.
838 if (AR->getLoop() == OuterLoop) {
839 // We found an OuterLoop induction after InnerLoop induction. It is
841 FoundOuterInduction = true;
842 if (FoundInnerInduction) {
851 return GoodOrder - BadOrder;
854 static bool isProfitabileForVectorization(unsigned InnerLoopId,
855 unsigned OuterLoopId,
856 CharMatrix &DepMatrix) {
857 // TODO: Improve this heuristic to catch more cases.
858 // If the inner loop is loop independent or doesn't carry any dependency it is
859 // profitable to move this to outer position.
860 unsigned Row = DepMatrix.size();
861 for (unsigned i = 0; i < Row; ++i) {
862 if (DepMatrix[i][InnerLoopId] != 'S' && DepMatrix[i][InnerLoopId] != 'I')
864 // TODO: We need to improve this heuristic.
865 if (DepMatrix[i][OuterLoopId] != '=')
868 // If outer loop has dependence and inner loop is loop independent then it is
869 // profitable to interchange to enable parallelism.
873 bool LoopInterchangeProfitability::isProfitable(unsigned InnerLoopId,
874 unsigned OuterLoopId,
875 CharMatrix &DepMatrix) {
877 // TODO: Add Better Profitibility checks.
879 // 1) Construct dependency matrix and move the one with no loop carried dep
880 // inside to enable vectorization.
882 // This is rough cost estimation algorithm. It counts the good and bad order
883 // of induction variables in the instruction and allows reordering if number
884 // of bad orders is more than good.
886 Cost += getInstrOrderCost();
887 DEBUG(dbgs() << "Cost = " << Cost << "\n");
891 // It is not profitable as per current cache profitibility model. But check if
892 // we can move this loop outside to improve parallelism.
894 isProfitabileForVectorization(InnerLoopId, OuterLoopId, DepMatrix);
898 void LoopInterchangeTransform::removeChildLoop(Loop *OuterLoop,
900 for (Loop::iterator I = OuterLoop->begin(), E = OuterLoop->end(); I != E;
902 if (*I == InnerLoop) {
903 OuterLoop->removeChildLoop(I);
907 assert(false && "Couldn't find loop");
910 void LoopInterchangeTransform::restructureLoops(Loop *InnerLoop,
912 Loop *OuterLoopParent = OuterLoop->getParentLoop();
913 if (OuterLoopParent) {
914 // Remove the loop from its parent loop.
915 removeChildLoop(OuterLoopParent, OuterLoop);
916 removeChildLoop(OuterLoop, InnerLoop);
917 OuterLoopParent->addChildLoop(InnerLoop);
919 removeChildLoop(OuterLoop, InnerLoop);
920 LI->changeTopLevelLoop(OuterLoop, InnerLoop);
923 for (Loop::iterator I = InnerLoop->begin(), E = InnerLoop->end(); I != E; ++I)
924 OuterLoop->addChildLoop(InnerLoop->removeChildLoop(I));
926 InnerLoop->addChildLoop(OuterLoop);
929 bool LoopInterchangeTransform::transform() {
931 DEBUG(dbgs() << "transform\n");
932 bool Transformed = false;
933 Instruction *InnerIndexVar;
935 if (InnerLoop->getSubLoops().size() == 0) {
936 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
937 DEBUG(dbgs() << "Calling Split Inner Loop\n");
938 PHINode *InductionPHI = getInductionVariable(InnerLoop, SE);
940 DEBUG(dbgs() << "Failed to find the point to split loop latch \n");
944 if (InductionPHI->getIncomingBlock(0) == InnerLoopPreHeader)
945 InnerIndexVar = dyn_cast<Instruction>(InductionPHI->getIncomingValue(1));
947 InnerIndexVar = dyn_cast<Instruction>(InductionPHI->getIncomingValue(0));
950 // Split at the place were the induction variable is
951 // incremented/decremented.
952 // TODO: This splitting logic may not work always. Fix this.
953 splitInnerLoopLatch(InnerIndexVar);
954 DEBUG(dbgs() << "splitInnerLoopLatch Done\n");
956 // Splits the inner loops phi nodes out into a seperate basic block.
957 splitInnerLoopHeader();
958 DEBUG(dbgs() << "splitInnerLoopHeader Done\n");
961 Transformed |= adjustLoopLinks();
963 DEBUG(dbgs() << "adjustLoopLinks Failed\n");
967 restructureLoops(InnerLoop, OuterLoop);
971 void LoopInterchangeTransform::splitInnerLoopLatch(Instruction *Inc) {
972 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
973 BasicBlock *InnerLoopLatchPred = InnerLoopLatch;
974 InnerLoopLatch = SplitBlock(InnerLoopLatchPred, Inc, DT, LI);
977 void LoopInterchangeTransform::splitOuterLoopLatch() {
978 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch();
979 BasicBlock *OuterLatchLcssaPhiBlock = OuterLoopLatch;
980 OuterLoopLatch = SplitBlock(OuterLatchLcssaPhiBlock,
981 OuterLoopLatch->getFirstNonPHI(), DT, LI);
984 void LoopInterchangeTransform::splitInnerLoopHeader() {
986 // Split the inner loop header out.
987 BasicBlock *InnerLoopHeader = InnerLoop->getHeader();
988 SplitBlock(InnerLoopHeader, InnerLoopHeader->getFirstNonPHI(), DT, LI);
990 DEBUG(dbgs() << "Output of splitInnerLoopHeader InnerLoopHeaderSucc & "
991 "InnerLoopHeader \n");
994 /// \brief Move all instructions except the terminator from FromBB right before
996 static void moveBBContents(BasicBlock *FromBB, Instruction *InsertBefore) {
997 auto &ToList = InsertBefore->getParent()->getInstList();
998 auto &FromList = FromBB->getInstList();
1000 ToList.splice(InsertBefore, FromList, FromList.begin(),
1001 FromBB->getTerminator());
1004 void LoopInterchangeTransform::adjustOuterLoopPreheader() {
1005 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader();
1006 BasicBlock *InnerPreHeader = InnerLoop->getLoopPreheader();
1008 moveBBContents(OuterLoopPreHeader, InnerPreHeader->getTerminator());
1011 void LoopInterchangeTransform::adjustInnerLoopPreheader() {
1012 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
1013 BasicBlock *OuterHeader = OuterLoop->getHeader();
1015 moveBBContents(InnerLoopPreHeader, OuterHeader->getTerminator());
1018 bool LoopInterchangeTransform::adjustLoopBranches() {
1020 DEBUG(dbgs() << "adjustLoopBranches called\n");
1021 // Adjust the loop preheader
1022 BasicBlock *InnerLoopHeader = InnerLoop->getHeader();
1023 BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
1024 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
1025 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch();
1026 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader();
1027 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
1028 BasicBlock *OuterLoopPredecessor = OuterLoopPreHeader->getUniquePredecessor();
1029 BasicBlock *InnerLoopLatchPredecessor =
1030 InnerLoopLatch->getUniquePredecessor();
1031 BasicBlock *InnerLoopLatchSuccessor;
1032 BasicBlock *OuterLoopLatchSuccessor;
1034 BranchInst *OuterLoopLatchBI =
1035 dyn_cast<BranchInst>(OuterLoopLatch->getTerminator());
1036 BranchInst *InnerLoopLatchBI =
1037 dyn_cast<BranchInst>(InnerLoopLatch->getTerminator());
1038 BranchInst *OuterLoopHeaderBI =
1039 dyn_cast<BranchInst>(OuterLoopHeader->getTerminator());
1040 BranchInst *InnerLoopHeaderBI =
1041 dyn_cast<BranchInst>(InnerLoopHeader->getTerminator());
1043 if (!OuterLoopPredecessor || !InnerLoopLatchPredecessor ||
1044 !OuterLoopLatchBI || !InnerLoopLatchBI || !OuterLoopHeaderBI ||
1048 BranchInst *InnerLoopLatchPredecessorBI =
1049 dyn_cast<BranchInst>(InnerLoopLatchPredecessor->getTerminator());
1050 BranchInst *OuterLoopPredecessorBI =
1051 dyn_cast<BranchInst>(OuterLoopPredecessor->getTerminator());
1053 if (!OuterLoopPredecessorBI || !InnerLoopLatchPredecessorBI)
1055 BasicBlock *InnerLoopHeaderSucessor = InnerLoopHeader->getUniqueSuccessor();
1056 if (!InnerLoopHeaderSucessor)
1059 // Adjust Loop Preheader and headers
1061 unsigned NumSucc = OuterLoopPredecessorBI->getNumSuccessors();
1062 for (unsigned i = 0; i < NumSucc; ++i) {
1063 if (OuterLoopPredecessorBI->getSuccessor(i) == OuterLoopPreHeader)
1064 OuterLoopPredecessorBI->setSuccessor(i, InnerLoopPreHeader);
1067 NumSucc = OuterLoopHeaderBI->getNumSuccessors();
1068 for (unsigned i = 0; i < NumSucc; ++i) {
1069 if (OuterLoopHeaderBI->getSuccessor(i) == OuterLoopLatch)
1070 OuterLoopHeaderBI->setSuccessor(i, LoopExit);
1071 else if (OuterLoopHeaderBI->getSuccessor(i) == InnerLoopPreHeader)
1072 OuterLoopHeaderBI->setSuccessor(i, InnerLoopHeaderSucessor);
1075 BranchInst::Create(OuterLoopPreHeader, InnerLoopHeaderBI);
1076 InnerLoopHeaderBI->eraseFromParent();
1078 // -------------Adjust loop latches-----------
1079 if (InnerLoopLatchBI->getSuccessor(0) == InnerLoopHeader)
1080 InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(1);
1082 InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(0);
1084 NumSucc = InnerLoopLatchPredecessorBI->getNumSuccessors();
1085 for (unsigned i = 0; i < NumSucc; ++i) {
1086 if (InnerLoopLatchPredecessorBI->getSuccessor(i) == InnerLoopLatch)
1087 InnerLoopLatchPredecessorBI->setSuccessor(i, InnerLoopLatchSuccessor);
1090 if (OuterLoopLatchBI->getSuccessor(0) == OuterLoopHeader)
1091 OuterLoopLatchSuccessor = OuterLoopLatchBI->getSuccessor(1);
1093 OuterLoopLatchSuccessor = OuterLoopLatchBI->getSuccessor(0);
1095 if (InnerLoopLatchBI->getSuccessor(1) == InnerLoopLatchSuccessor)
1096 InnerLoopLatchBI->setSuccessor(1, OuterLoopLatchSuccessor);
1098 InnerLoopLatchBI->setSuccessor(0, OuterLoopLatchSuccessor);
1100 if (OuterLoopLatchBI->getSuccessor(0) == OuterLoopLatchSuccessor) {
1101 OuterLoopLatchBI->setSuccessor(0, InnerLoopLatch);
1103 OuterLoopLatchBI->setSuccessor(1, InnerLoopLatch);
1108 void LoopInterchangeTransform::adjustLoopPreheaders() {
1110 // We have interchanged the preheaders so we need to interchange the data in
1111 // the preheader as well.
1112 // This is because the content of inner preheader was previously executed
1113 // inside the outer loop.
1114 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader();
1115 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
1116 BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
1117 BranchInst *InnerTermBI =
1118 cast<BranchInst>(InnerLoopPreHeader->getTerminator());
1120 BasicBlock *HeaderSplit =
1121 SplitBlock(OuterLoopHeader, OuterLoopHeader->getTerminator(), DT, LI);
1122 Instruction *InsPoint = HeaderSplit->getFirstNonPHI();
1123 // These instructions should now be executed inside the loop.
1124 // Move instruction into a new block after outer header.
1125 moveBBContents(InnerLoopPreHeader, InsPoint);
1126 // These instructions were not executed previously in the loop so move them to
1127 // the older inner loop preheader.
1128 moveBBContents(OuterLoopPreHeader, InnerTermBI);
1131 bool LoopInterchangeTransform::adjustLoopLinks() {
1133 // Adjust all branches in the inner and outer loop.
1134 bool Changed = adjustLoopBranches();
1136 adjustLoopPreheaders();
1140 char LoopInterchange::ID = 0;
1141 INITIALIZE_PASS_BEGIN(LoopInterchange, "loop-interchange",
1142 "Interchanges loops for cache reuse", false, false)
1143 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
1144 INITIALIZE_PASS_DEPENDENCY(DependenceAnalysis)
1145 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1146 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1147 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
1148 INITIALIZE_PASS_DEPENDENCY(LCSSA)
1149 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
1151 INITIALIZE_PASS_END(LoopInterchange, "loop-interchange",
1152 "Interchanges loops for cache reuse", false, false)
1154 Pass *llvm::createLoopInterchangePass() { return new LoopInterchange(); }