46 #define DEBUG_TYPE "loop-interchange"
50 cl::desc(
"Interchange if you gain more than this number"));
57 typedef std::vector<std::vector<char>> CharMatrix;
60 static const unsigned MaxMemInstrCount = 100;
63 static const unsigned MaxLoopNestDepth = 10;
65 struct LoopInterchange;
67 #ifdef DUMP_DEP_MATRICIES
68 void printDepMatrix(CharMatrix &DepMatrix) {
69 for (
auto I = DepMatrix.begin(),
E = DepMatrix.end();
I !=
E; ++
I) {
70 std::vector<char> Vec = *
I;
71 for (
auto II = Vec.begin(), EE = Vec.end(); II != EE; ++II)
78 static bool populateDependencyMatrix(CharMatrix &DepMatrix,
unsigned Level,
89 if (!isa<Instruction>(
I))
91 if (
LoadInst *Ld = dyn_cast<LoadInst>(
I)) {
95 }
else if (
StoreInst *St = dyn_cast<StoreInst>(
I)) {
98 MemInstr.push_back(&*
I);
103 DEBUG(
dbgs() <<
"Found " << MemInstr.size()
104 <<
" Loads and Stores to analyze\n");
106 ValueVector::iterator
I,
IE, J, JE;
108 for (I = MemInstr.begin(), IE = MemInstr.end(); I !=
IE; ++
I) {
109 for (J = I, JE = MemInstr.end(); J != JE; ++J) {
110 std::vector<char> Dep;
116 if (isa<LoadInst>(Src) && isa<LoadInst>(Dst))
119 if (
auto D = DI->
depends(Src, Dst,
true)) {
120 assert(
D->isOrdered() &&
"Expected an output, flow or anti dep.");
122 D->isFlow() ?
"flow" :
D->isAnti() ?
"anti" :
"output";
123 dbgs() <<
"Found " << DepType
124 <<
" dependency between Src and Dst\n"
125 <<
" Src:" << *Src <<
"\n Dst:" << *Dst <<
'\n');
126 unsigned Levels =
D->getLevels();
128 for (
unsigned II = 1; II <= Levels; ++II) {
129 const SCEV *Distance =
D->getDistance(II);
131 dyn_cast_or_null<SCEVConstant>(Distance);
140 Dep.push_back(Direction);
141 }
else if (
D->isScalar(II)) {
143 Dep.push_back(Direction);
145 unsigned Dir =
D->getDirection(II);
156 Dep.push_back(Direction);
159 while (Dep.size() !=
Level) {
163 DepMatrix.push_back(Dep);
164 if (DepMatrix.size() > MaxMemInstrCount) {
165 DEBUG(
dbgs() <<
"Cannot handle more than " << MaxMemInstrCount
166 <<
" dependencies inside loop\n");
174 if (DepMatrix.size() == 0)
181 static void interChangeDependencies(CharMatrix &DepMatrix,
unsigned FromIndx,
183 unsigned numRows = DepMatrix.size();
184 for (
unsigned i = 0; i < numRows; ++i) {
185 char TmpVal = DepMatrix[i][ToIndx];
186 DepMatrix[i][ToIndx] = DepMatrix[i][FromIndx];
187 DepMatrix[i][FromIndx] = TmpVal;
193 static bool isOuterMostDepPositive(CharMatrix &DepMatrix,
unsigned Row,
195 for (
unsigned i = 0; i <= Column; ++i) {
196 if (DepMatrix[Row][i] ==
'<')
198 if (DepMatrix[Row][i] ==
'>')
206 static bool containsNoDependence(CharMatrix &DepMatrix,
unsigned Row,
208 for (
unsigned i = 0; i < Column; ++i) {
209 if (DepMatrix[Row][i] !=
'=' && DepMatrix[Row][i] !=
'S' &&
210 DepMatrix[Row][i] !=
'I')
216 static bool validDepInterchange(CharMatrix &DepMatrix,
unsigned Row,
217 unsigned OuterLoopId,
char InnerDep,
220 if (isOuterMostDepPositive(DepMatrix, Row, OuterLoopId))
223 if (InnerDep == OuterDep)
229 if (InnerDep ==
'=' || InnerDep ==
'S' || InnerDep ==
'I')
235 if (InnerDep ==
'>') {
238 if (OuterLoopId == 0)
244 if (!containsNoDependence(DepMatrix, Row, OuterLoopId))
255 static bool isLegalToInterChangeLoops(CharMatrix &DepMatrix,
256 unsigned InnerLoopId,
257 unsigned OuterLoopId) {
259 unsigned NumRows = DepMatrix.size();
261 for (
unsigned Row = 0; Row < NumRows; ++Row) {
262 char InnerDep = DepMatrix[Row][InnerLoopId];
263 char OuterDep = DepMatrix[Row][OuterLoopId];
264 if (InnerDep ==
'*' || OuterDep ==
'*')
266 if (!validDepInterchange(DepMatrix, Row, OuterLoopId, InnerDep, OuterDep))
274 DEBUG(
dbgs() <<
"Calling populateWorklist on Func: "
275 << L.
getHeader()->getParent()->getName() <<
" Loop: %"
278 Loop *CurrentLoop = &
L;
279 const std::vector<Loop *> *Vec = &CurrentLoop->
getSubLoops();
280 while (!Vec->empty()) {
284 if (Vec->size() != 1) {
288 LoopList.push_back(CurrentLoop);
289 CurrentLoop = Vec->front();
292 LoopList.push_back(CurrentLoop);
299 return InnerIndexVar;
305 if (!PhiTy->isIntegerTy() && !PhiTy->isFloatingPointTy() &&
306 !PhiTy->isPointerTy())
313 if (!isa<SCEVConstant>(Step))
324 class LoopInterchangeLegality {
329 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), LI(LI), DT(DT),
330 PreserveLCSSA(PreserveLCSSA), ORE(ORE), InnerLoopHasReduction(
false) {}
333 bool canInterchangeLoops(
unsigned InnerLoopId,
unsigned OuterLoopId,
334 CharMatrix &DepMatrix);
337 bool isLoopStructureUnderstood(
PHINode *InnerInductionVar);
339 bool currentLimitations();
341 bool hasInnerLoopReduction() {
return InnerLoopHasReduction; }
344 bool tightlyNested(
Loop *Outer,
Loop *Inner);
345 bool containsUnsafeInstructionsInHeader(
BasicBlock *BB);
347 bool containsUnsafeInstructionsInLatch(
BasicBlock *BB);
348 bool findInductionAndReductions(
Loop *L,
361 bool InnerLoopHasReduction;
366 class LoopInterchangeProfitability {
370 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), ORE(ORE) {}
373 bool isProfitable(
unsigned InnerLoopId,
unsigned OuterLoopId,
374 CharMatrix &DepMatrix);
377 int getInstrOrderCost();
389 class LoopInterchangeTransform {
394 bool InnerLoopContainsReductions)
395 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), LI(LI), DT(DT),
396 LoopExit(LoopNestExit),
397 InnerLoopHasReduction(InnerLoopContainsReductions) {}
401 void restructureLoops(
Loop *InnerLoop,
Loop *OuterLoop);
402 void removeChildLoop(
Loop *OuterLoop,
Loop *InnerLoop);
406 void splitInnerLoopHeader();
407 bool adjustLoopLinks();
408 void adjustLoopPreheaders();
409 bool adjustLoopBranches();
421 bool InnerLoopHasReduction;
436 :
FunctionPass(
ID), SE(nullptr), LI(nullptr), DI(nullptr), DT(nullptr) {
451 bool runOnFunction(
Function &
F)
override {
455 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
456 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
457 DI = &getAnalysis<DependenceAnalysisWrapperPass>().getDI();
458 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
459 DT = DTWP ? &DTWP->getDomTree() :
nullptr;
460 ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
461 PreserveLCSSA = mustPreserveAnalysisID(
LCSSAID);
467 populateWorklist(*L, Worklist);
469 DEBUG(
dbgs() <<
"Worklist size = " << Worklist.
size() <<
"\n");
471 while (!Worklist.
empty()) {
473 Changed = processLoopList(LoopList, F);
478 bool isComputableLoopNest(LoopVector LoopList) {
479 for (
Loop *L : LoopList) {
482 DEBUG(
dbgs() <<
"Couldn't compute backedge count\n");
486 DEBUG(
dbgs() <<
"NumBackEdges is not equal to 1\n");
490 DEBUG(
dbgs() <<
"Loop doesn't have unique exit block\n");
497 unsigned selectLoopForInterchange(
const LoopVector &LoopList) {
500 return LoopList.size() - 1;
503 bool processLoopList(LoopVector LoopList,
Function &F) {
505 bool Changed =
false;
506 unsigned LoopNestDepth = LoopList.size();
507 if (LoopNestDepth < 2) {
508 DEBUG(
dbgs() <<
"Loop doesn't contain minimum nesting level.\n");
511 if (LoopNestDepth > MaxLoopNestDepth) {
512 DEBUG(
dbgs() <<
"Cannot handle loops of depth greater than "
513 << MaxLoopNestDepth <<
"\n");
516 if (!isComputableLoopNest(LoopList)) {
517 DEBUG(
dbgs() <<
"Not valid loop candidate for interchange\n");
521 DEBUG(
dbgs() <<
"Processing LoopList of size = " << LoopNestDepth <<
"\n");
523 CharMatrix DependencyMatrix;
524 Loop *OuterMostLoop = *(LoopList.begin());
525 if (!populateDependencyMatrix(DependencyMatrix, LoopNestDepth,
526 OuterMostLoop, DI)) {
527 DEBUG(
dbgs() <<
"Populating dependency matrix failed\n");
530 #ifdef DUMP_DEP_MATRICIES
531 DEBUG(
dbgs() <<
"Dependence before interchange\n");
532 printDepMatrix(DependencyMatrix);
538 if (!OuterMostLoopLatchBI)
552 if (isa<PHINode>(LoopNestExit->
begin())) {
553 DEBUG(
dbgs() <<
"PHI Nodes in loop nest exit is not handled for now "
554 "since on failure all loops branch to loop nest exit.\n");
558 unsigned SelecLoopId = selectLoopForInterchange(LoopList);
560 for (
unsigned i = SelecLoopId; i > 0; i--) {
562 processLoop(LoopList, i, i - 1, LoopNestExit, DependencyMatrix);
569 interChangeDependencies(DependencyMatrix, i, i - 1);
571 #ifdef DUMP_DEP_MATRICIES
572 DEBUG(
dbgs() <<
"Dependence after interchange\n");
573 printDepMatrix(DependencyMatrix);
575 Changed |= Interchanged;
580 bool processLoop(LoopVector LoopList,
unsigned InnerLoopId,
581 unsigned OuterLoopId,
BasicBlock *LoopNestExit,
582 std::vector<std::vector<char>> &DependencyMatrix) {
584 DEBUG(
dbgs() <<
"Processing Inner Loop Id = " << InnerLoopId
585 <<
" and OuterLoopId = " << OuterLoopId <<
"\n");
586 Loop *InnerLoop = LoopList[InnerLoopId];
587 Loop *OuterLoop = LoopList[OuterLoopId];
589 LoopInterchangeLegality LIL(OuterLoop, InnerLoop, SE, LI, DT,
591 if (!LIL.canInterchangeLoops(InnerLoopId, OuterLoopId, DependencyMatrix)) {
592 DEBUG(
dbgs() <<
"Not interchanging Loops. Cannot prove legality\n");
595 DEBUG(
dbgs() <<
"Loops are legal to interchange\n");
596 LoopInterchangeProfitability LIP(OuterLoop, InnerLoop, SE, ORE);
597 if (!LIP.isProfitable(InnerLoopId, OuterLoopId, DependencyMatrix)) {
598 DEBUG(
dbgs() <<
"Interchanging loops not profitable\n");
605 <<
"Loop interchanged with enclosing loop.");
607 LoopInterchangeTransform LIT(OuterLoop, InnerLoop, SE, LI, DT,
608 LoopNestExit, LIL.hasInnerLoopReduction());
624 bool LoopInterchangeLegality::containsUnsafeInstructionsInHeader(
626 for (
auto I = BB->
begin(),
E = BB->
end(); I !=
E; ++
I) {
629 if (
LoadInst *L = dyn_cast<LoadInst>(I)) {
630 if (!areAllUsesReductions(L, InnerLoop))
632 }
else if (I->mayHaveSideEffects() || I->mayReadFromMemory())
638 bool LoopInterchangeLegality::containsUnsafeInstructionsInLatch(
640 for (
auto I = BB->
begin(),
E = BB->
end(); I !=
E; ++
I) {
643 if (
StoreInst *L = dyn_cast<StoreInst>(I)) {
644 if (!isa<PHINode>(L->getOperand(0)))
646 }
else if (I->mayHaveSideEffects() || I->mayReadFromMemory())
652 bool LoopInterchangeLegality::tightlyNested(
Loop *OuterLoop,
Loop *InnerLoop) {
657 DEBUG(
dbgs() <<
"Checking if loops are tightly nested\n");
664 if (!OuterLoopHeaderBI)
667 for (
unsigned i = 0, e = OuterLoopHeaderBI->
getNumSuccessors(); i < e; ++i) {
668 if (OuterLoopHeaderBI->
getSuccessor(i) != InnerLoopPreHeader &&
673 DEBUG(
dbgs() <<
"Checking instructions in Loop header and Loop latch\n");
676 if (containsUnsafeInstructionsInHeader(OuterLoopHeader) ||
677 containsUnsafeInstructionsInLatch(OuterLoopLatch))
680 DEBUG(
dbgs() <<
"Loops are perfectly nested\n");
686 bool LoopInterchangeLegality::isLoopStructureUnderstood(
691 for (
unsigned i = 0; i < Num; ++i) {
693 if (isa<Constant>(Val))
703 InnerLoopPreheader &&
711 bool LoopInterchangeLegality::findInductionAndReductions(
726 dbgs() <<
"Failed to recognize PHI as an induction or reduction.\n");
734 for (
auto I = Block->
begin(); isa<PHINode>(
I); ++
I) {
744 if (!isa<PHINode>(Ins) && isOuterLoopExitBlock)
753 unsigned Num = BI->getNumSuccessors();
755 for (
unsigned i = 0; i < Num; ++i) {
756 if (BI->getSuccessor(i) == LoopHeader)
758 return BI->getSuccessor(i);
766 bool LoopInterchangeLegality::currentLimitations() {
777 if (!findInductionAndReductions(InnerLoop, Inductions, Reductions)) {
778 DEBUG(
dbgs() <<
"Only inner loops with induction or reduction PHI nodes "
779 <<
"are supported currently.\n");
781 "UnsupportedPHIInner",
784 <<
"Only inner loops with induction or reduction PHI nodes can be"
785 " interchange currently.");
790 if (Inductions.
size() != 1) {
791 DEBUG(
dbgs() <<
"We currently only support loops with 1 induction variable."
792 <<
"Failed to interchange due to current limitation\n");
794 "MultiInductionInner",
797 <<
"Only inner loops with 1 induction variable can be "
798 "interchanged currently.");
801 if (Reductions.
size() > 0)
802 InnerLoopHasReduction =
true;
806 if (!findInductionAndReductions(OuterLoop, Inductions, Reductions)) {
807 DEBUG(
dbgs() <<
"Only outer loops with induction or reduction PHI nodes "
808 <<
"are supported currently.\n");
810 "UnsupportedPHIOuter",
813 <<
"Only outer loops with induction or reduction PHI nodes can be"
814 " interchanged currently.");
820 if (!Reductions.
empty()) {
821 DEBUG(
dbgs() <<
"Outer loops with reductions are not supported "
827 <<
"Outer loops with reductions cannot be interchangeed "
832 if (Inductions.
size() != 1) {
833 DEBUG(
dbgs() <<
"Loops with more than 1 induction variables are not "
834 <<
"supported currently.\n");
836 "MultiIndutionOuter",
839 <<
"Only outer loops with 1 induction variable can be "
840 "interchanged currently.");
845 if (!isLoopStructureUnderstood(InnerInductionVar)) {
846 DEBUG(
dbgs() <<
"Loop structure not understood by pass\n");
848 "UnsupportedStructureInner",
851 <<
"Inner loop structure not understood currently.");
859 DEBUG(
dbgs() <<
"Can only handle LCSSA PHIs in outer loops currently.\n");
864 <<
"Only outer loops with LCSSA PHIs can be interchange "
871 DEBUG(
dbgs() <<
"Can only handle LCSSA PHIs in inner loops currently.\n");
873 "NoLCSSAPHIOuterInner",
876 <<
"Only inner loops with LCSSA PHIs can be interchange "
899 if (!InnerIndexVarInc) {
900 DEBUG(
dbgs() <<
"Did not find an instruction to increment the induction "
903 "NoIncrementInInner",
906 <<
"The inner loop does not increment the induction variable.");
914 bool FoundInduction =
false;
916 if (isa<BranchInst>(I) || isa<CmpInst>(
I) || isa<TruncInst>(I))
922 DEBUG(
dbgs() <<
"Found unsupported instructions between induction "
923 <<
"variable increment and branch.\n");
925 "UnsupportedInsBetweenInduction",
928 <<
"Found unsupported instruction between induction variable "
929 "increment and branch.");
933 FoundInduction =
true;
938 if (!FoundInduction) {
939 DEBUG(
dbgs() <<
"Did not find the induction variable.\n");
941 "NoIndutionVariable",
944 <<
"Did not find the induction variable.");
950 bool LoopInterchangeLegality::canInterchangeLoops(
unsigned InnerLoopId,
951 unsigned OuterLoopId,
952 CharMatrix &DepMatrix) {
954 if (!isLegalToInterChangeLoops(DepMatrix, InnerLoopId, OuterLoopId)) {
955 DEBUG(
dbgs() <<
"Failed interchange InnerLoopId = " << InnerLoopId
956 <<
" and OuterLoopId = " << OuterLoopId
957 <<
" due to dependence\n");
962 <<
"Cannot interchange loops due to dependences.");
975 if (!OuterLoopPreHeader || OuterLoopPreHeader == OuterLoop->
getHeader() ||
976 isa<PHINode>(OuterLoopPreHeader->
begin()) ||
982 if (!InnerLoopPreHeader || InnerLoopPreHeader == InnerLoop->
getHeader() ||
983 InnerLoopPreHeader == OuterLoop->
getHeader()) {
990 if (currentLimitations()) {
991 DEBUG(
dbgs() <<
"Not legal because of current transform limitation\n");
996 if (!tightlyNested(OuterLoop, InnerLoop)) {
997 DEBUG(
dbgs() <<
"Loops not tightly nested\n");
1002 <<
"Cannot interchange loops because they are not tightly "
1010 int LoopInterchangeProfitability::getInstrOrderCost() {
1011 unsigned GoodOrder, BadOrder;
1012 BadOrder = GoodOrder = 0;
1017 unsigned NumOp =
GEP->getNumOperands();
1018 bool FoundInnerInduction =
false;
1019 bool FoundOuterInduction =
false;
1020 for (
unsigned i = 0; i < NumOp; ++i) {
1031 if (AR->
getLoop() == InnerLoop) {
1034 FoundInnerInduction =
true;
1035 if (FoundOuterInduction) {
1045 if (AR->
getLoop() == OuterLoop) {
1048 FoundOuterInduction =
true;
1049 if (FoundInnerInduction) {
1058 return GoodOrder - BadOrder;
1062 unsigned OuterLoopId,
1063 CharMatrix &DepMatrix) {
1067 unsigned Row = DepMatrix.size();
1068 for (
unsigned i = 0; i < Row; ++i) {
1069 if (DepMatrix[i][InnerLoopId] !=
'S' && DepMatrix[i][InnerLoopId] !=
'I')
1072 if (DepMatrix[i][OuterLoopId] !=
'=')
1080 bool LoopInterchangeProfitability::isProfitable(
unsigned InnerLoopId,
1081 unsigned OuterLoopId,
1082 CharMatrix &DepMatrix) {
1092 int Cost = getInstrOrderCost();
1093 DEBUG(
dbgs() <<
"Cost = " << Cost <<
"\n");
1103 "InterchangeNotProfitable",
1106 <<
"Interchanging loops is too costly (cost="
1107 <<
ore::NV(
"Cost", Cost) <<
", threshold="
1109 ") and it does not improve parallelism.");
1113 void LoopInterchangeTransform::removeChildLoop(
Loop *OuterLoop,
1117 if (*I == InnerLoop) {
1125 void LoopInterchangeTransform::restructureLoops(
Loop *InnerLoop,
1128 if (OuterLoopParent) {
1130 removeChildLoop(OuterLoopParent, OuterLoop);
1131 removeChildLoop(OuterLoop, InnerLoop);
1134 removeChildLoop(OuterLoop, InnerLoop);
1135 LI->changeTopLevelLoop(OuterLoop, InnerLoop);
1138 while (!InnerLoop->
empty())
1145 bool Transformed =
false;
1150 DEBUG(
dbgs() <<
"Calling Split Inner Loop\n");
1151 PHINode *InductionPHI = getInductionVariable(InnerLoop, SE);
1152 if (!InductionPHI) {
1153 DEBUG(
dbgs() <<
"Failed to find the point to split loop latch \n");
1166 splitInnerLoopLatch(InnerIndexVar);
1167 DEBUG(
dbgs() <<
"splitInnerLoopLatch done\n");
1170 splitInnerLoopHeader();
1171 DEBUG(
dbgs() <<
"splitInnerLoopHeader done\n");
1174 Transformed |= adjustLoopLinks();
1176 DEBUG(
dbgs() <<
"adjustLoopLinks failed\n");
1180 restructureLoops(InnerLoop, OuterLoop);
1184 void LoopInterchangeTransform::splitInnerLoopLatch(
Instruction *Inc) {
1186 BasicBlock *InnerLoopLatchPred = InnerLoopLatch;
1187 InnerLoopLatch =
SplitBlock(InnerLoopLatchPred, Inc, DT, LI);
1190 void LoopInterchangeTransform::splitInnerLoopHeader() {
1196 if (InnerLoopHasReduction) {
1199 ++(InnerLoopHeader->
begin()), InnerLoopHeader->
getName() +
".split");
1201 if (
Loop *L = LI->getLoopFor(InnerLoopHeader))
1206 for (
auto I = New->
begin(); isa<PHINode>(
I); ++
I) {
1213 P->eraseFromParent();
1219 DEBUG(
dbgs() <<
"Output of splitInnerLoopHeader InnerLoopHeaderSucc & "
1220 "InnerLoopHeader\n");
1233 void LoopInterchangeTransform::updateIncomingBlock(
BasicBlock *CurrBlock,
1236 for (
auto I = CurrBlock->
begin(); isa<PHINode>(
I); ++
I) {
1239 for (
unsigned i = 0; i < Num; ++i) {
1246 bool LoopInterchangeTransform::adjustLoopBranches() {
1248 DEBUG(
dbgs() <<
"adjustLoopBranches called\n");
1271 if (!OuterLoopPredecessor || !InnerLoopLatchPredecessor ||
1272 !OuterLoopLatchBI || !InnerLoopLatchBI || !OuterLoopHeaderBI ||
1281 if (!OuterLoopPredecessorBI || !InnerLoopLatchPredecessorBI)
1284 if (!InnerLoopHeaderSuccessor)
1289 unsigned NumSucc = OuterLoopPredecessorBI->getNumSuccessors();
1290 for (
unsigned i = 0; i < NumSucc; ++i) {
1291 if (OuterLoopPredecessorBI->getSuccessor(i) == OuterLoopPreHeader)
1292 OuterLoopPredecessorBI->setSuccessor(i, InnerLoopPreHeader);
1295 NumSucc = OuterLoopHeaderBI->getNumSuccessors();
1296 for (
unsigned i = 0; i < NumSucc; ++i) {
1297 if (OuterLoopHeaderBI->getSuccessor(i) == OuterLoopLatch)
1298 OuterLoopHeaderBI->setSuccessor(i, LoopExit);
1299 else if (OuterLoopHeaderBI->getSuccessor(i) == InnerLoopPreHeader)
1300 OuterLoopHeaderBI->setSuccessor(i, InnerLoopHeaderSuccessor);
1304 updateIncomingBlock(InnerLoopHeaderSuccessor, InnerLoopHeader,
1308 InnerLoopHeaderBI->eraseFromParent();
1311 if (InnerLoopLatchBI->getSuccessor(0) == InnerLoopHeader)
1312 InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(1);
1314 InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(0);
1317 for (
unsigned i = 0; i < NumSucc; ++i) {
1318 if (InnerLoopLatchPredecessorBI->
getSuccessor(i) == InnerLoopLatch)
1319 InnerLoopLatchPredecessorBI->
setSuccessor(i, InnerLoopLatchSuccessor);
1325 for (
auto I = InnerLoopLatchSuccessor->
begin(); isa<PHINode>(
I); ++
I) {
1326 PHINode *LcssaPhi = cast<PHINode>(
I);
1330 Value *Incoming =
P->getIncomingValueForBlock(InnerLoopLatch);
1331 P->replaceAllUsesWith(Incoming);
1332 P->eraseFromParent();
1335 if (OuterLoopLatchBI->
getSuccessor(0) == OuterLoopHeader)
1336 OuterLoopLatchSuccessor = OuterLoopLatchBI->
getSuccessor(1);
1338 OuterLoopLatchSuccessor = OuterLoopLatchBI->
getSuccessor(0);
1340 if (InnerLoopLatchBI->getSuccessor(1) == InnerLoopLatchSuccessor)
1341 InnerLoopLatchBI->setSuccessor(1, OuterLoopLatchSuccessor);
1343 InnerLoopLatchBI->setSuccessor(0, OuterLoopLatchSuccessor);
1345 updateIncomingBlock(OuterLoopLatchSuccessor, OuterLoopLatch, InnerLoopLatch);
1347 if (OuterLoopLatchBI->
getSuccessor(0) == OuterLoopLatchSuccessor) {
1355 void LoopInterchangeTransform::adjustLoopPreheaders() {
1375 bool LoopInterchangeTransform::adjustLoopLinks() {
1378 bool Changed = adjustLoopBranches();
1380 adjustLoopPreheaders();
1386 "Interchanges loops for cache reuse",
false,
false)
unsigned getNumBackEdges() const
Calculate the number of back edges to the loop header.
Pass interface - Implemented by all 'passes'.
loop Interchanges loops for cache false
void push_back(const T &Elt)
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
DiagnosticInfoOptimizationBase::Argument NV
BasicBlock * SplitBlock(BasicBlock *Old, Instruction *SplitPt, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr)
Split the specified block at the specified instruction - everything before SplitPt stays in Old and e...
DebugLoc getStartLoc() const
Return the debug location of the start of this loop.
Legacy pass manager pass to access dependence information.
unsigned getNumOperands() const
static bool isProfitableForVectorization(unsigned InnerLoopId, unsigned OuterLoopId, CharMatrix &DepMatrix)
The main scalar evolution driver.
static bool isReductionPHI(PHINode *Phi, Loop *TheLoop, RecurrenceDescriptor &RedDes)
Returns true if Phi is a reduction in TheLoop.
BasicBlock * InsertPreheaderForLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, bool PreserveLCSSA)
InsertPreheaderForLoop - Once we discover that a loop doesn't have a preheader, this method is called...
const SCEV * getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
LoopT * getParentLoop() const
An instruction for reading from memory.
DependenceInfo - This class is the main dependence-analysis driver.
BlockT * getHeader() const
LoopT * removeChildLoop(iterator I)
This removes the specified child from being a subloop of this loop.
StringRef getName() const
Return a constant reference to the value's name.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
iterator begin()
Instruction iterator methods.
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
bool isIdenticalTo(const Instruction *I) const
Return true if the specified instruction is exactly identical to the current one. ...
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly...
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
LLVM_NODISCARD bool empty() const
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
static cl::opt< int > LoopInterchangeCostThreshold("loop-interchange-threshold", cl::init(0), cl::Hidden, cl::desc("Interchange if you gain more than this number"))
static BasicBlock * getLoopLatchExitBlock(BasicBlock *LatchBlock, BasicBlock *LoopHeader)
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
This method is used by other analyses to update loop information.
This node represents a polynomial recurrence on the trip count of the specified loop.
void addChildLoop(LoopT *NewChild)
Add the specified loop to be a child of this loop.
BasicBlock * getSuccessor(unsigned i) const
An instruction for storing to memory.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
unsigned getNumIncomingValues() const
Return the number of incoming edges.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
const SCEV * getCouldNotCompute()
initializer< Ty > init(const Ty &Val)
std::unique_ptr< Dependence > depends(Instruction *Src, Instruction *Dst, bool PossiblyLoopIndependent)
depends - Tests for a dependence between the Src and Dst instructions.
bool isAffine() const
Return true if this represents an expression A + B*x where A and B are loop invariant values...
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
Conditional or Unconditional Branch instruction.
loop Interchanges loops for cache reuse
Represent the analysis usage information of a pass.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
void splice(iterator where, iplist_impl &L2)
const InstListType & getInstList() const
Return the underlying instruction list container.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
for(unsigned i=0, e=MI->getNumOperands();i!=e;++i)
FunctionPass class - This class is used to implement most global optimizations.
BlockT * getExitingBlock() const
If getExitingBlocks would return exactly one block, return that block.
Value * getOperand(unsigned i) const
self_iterator getIterator()
const BasicBlock * getUniqueSuccessor() const
Return the successor of this block if it has a unique successor.
Used in the streaming interface as the general argument type.
static unsigned getIncomingValueNumForOperand(unsigned i)
void initializeLoopInterchangePass(PassRegistry &)
void setSuccessor(unsigned idx, BasicBlock *NewSucc)
The RecurrenceDescriptor is used to identify recurrences variables in a loop.
INITIALIZE_PASS_BEGIN(LoopInterchange,"loop-interchange","Interchanges loops for cache reuse", false, false) INITIALIZE_PASS_END(LoopInterchange
Iterator for intrusive lists based on ilist_node.
static bool containsSafePHI(BasicBlock *Block, bool isOuterLoopExitBlock)
This is the shared class of boolean and integer constants.
A struct for saving information about induction variables.
void setIncomingBlock(unsigned i, BasicBlock *BB)
Pass * createLoopInterchangePass()
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
AnalysisUsage & addRequiredID(const void *ID)
static void moveBBContents(BasicBlock *FromBB, Instruction *InsertBefore)
Move all instructions except the terminator from FromBB right before InsertBefore.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Module.h This file contains the declarations for the Module class.
Type * getType() const
All values are typed, get the type of this value.
LLVM_NODISCARD T pop_back_val()
PHINode * getCanonicalInductionVariable() const
Check to see if the loop has a canonical induction variable: an integer recurrence that starts at 0 a...
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
ConstantInt * getValue() const
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Value * getIncomingValueForBlock(const BasicBlock *BB) const
iterator_range< user_iterator > users()
std::vector< BlockT * >::const_iterator block_iterator
llvm_unreachable("Unknown RegBank!")
block_iterator block_end() const
This class represents an analyzed expression in the program.
unsigned getNumSuccessors() const
Represents a single loop in the control flow graph.
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
BlockT * getLoopPredecessor() const
If the given loop's header has exactly one unique predecessor outside the loop, return it...
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
const Loop * getLoop() const
BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
OutputIt transform(R &&Range, OutputIt d_first, UnaryPredicate P)
Wrapper function around std::transform to apply a function to a range and store the result elsewhere...
const SCEV * getBackedgeTakenCount(const Loop *L)
If the specified loop has a predictable backedge-taken count, return it, otherwise return a SCEVCould...
const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
const std::vector< LoopT * > & getSubLoops() const
Return the loops contained entirely within this loop.
block_iterator block_begin() const
The legacy pass manager's analysis pass to compute loop information.
StringRef - Represent a constant reference to a string, i.e.
Legacy analysis pass which computes a DominatorTree.
std::vector< LoopT * >::const_iterator iterator
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
const Instruction * getFirstNonPHI() const
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
const BasicBlock * getParent() const
static bool isInductionPHI(PHINode *Phi, const Loop *L, ScalarEvolution *SE, InductionDescriptor &D, const SCEV *Expr=nullptr)
Returns true if Phi is an induction in the loop L.
This class represents a constant integer value.