53 #define DEBUG_TYPE "loop-interchange" 55 STATISTIC(LoopsInterchanged,
"Number of loops interchanged");
59 cl::desc(
"Interchange if you gain more than this number"));
66 using CharMatrix = std::vector<std::vector<char>>;
76 #ifdef DUMP_DEP_MATRICIES 77 static void printDepMatrix(CharMatrix &DepMatrix) {
78 for (
auto &Row : DepMatrix) {
96 if (!isa<Instruction>(
I))
98 if (
auto *Ld = dyn_cast<LoadInst>(&
I)) {
102 }
else if (
auto *St = dyn_cast<StoreInst>(&
I)) {
105 MemInstr.push_back(&
I);
111 <<
" Loads and Stores to analyze\n");
113 ValueVector::iterator
I,
IE, J, JE;
115 for (I = MemInstr.begin(), IE = MemInstr.end(); I !=
IE; ++
I) {
116 for (J = I, JE = MemInstr.end(); J != JE; ++J) {
117 std::vector<char> Dep;
123 if (isa<LoadInst>(Src) && isa<LoadInst>(Dst))
126 if (
auto D = DI->
depends(Src, Dst,
true)) {
127 assert(
D->isOrdered() &&
"Expected an output, flow or anti dep.");
129 D->isFlow() ?
"flow" :
D->isAnti() ?
"anti" :
"output";
130 dbgs() <<
"Found " << DepType
131 <<
" dependency between Src and Dst\n" 132 <<
" Src:" << *Src <<
"\n Dst:" << *Dst <<
'\n');
133 unsigned Levels =
D->getLevels();
135 for (
unsigned II = 1; II <= Levels; ++II) {
136 const SCEV *Distance =
D->getDistance(II);
138 dyn_cast_or_null<SCEVConstant>(Distance);
147 Dep.push_back(Direction);
148 }
else if (
D->isScalar(II)) {
150 Dep.push_back(Direction);
152 unsigned Dir =
D->getDirection(II);
163 Dep.push_back(Direction);
166 while (Dep.size() !=
Level) {
170 DepMatrix.push_back(Dep);
172 LLVM_DEBUG(
dbgs() <<
"Cannot handle more than " << MaxMemInstrCount
173 <<
" dependencies inside loop\n");
187 unsigned numRows = DepMatrix.size();
188 for (
unsigned i = 0; i < numRows; ++i) {
189 char TmpVal = DepMatrix[i][ToIndx];
190 DepMatrix[i][ToIndx] = DepMatrix[i][FromIndx];
191 DepMatrix[i][FromIndx] = TmpVal;
199 for (
unsigned i = 0; i <= Column; ++i) {
200 if (DepMatrix[Row][i] ==
'<')
202 if (DepMatrix[Row][i] ==
'>')
212 for (
unsigned i = 0; i < Column; ++i) {
213 if (DepMatrix[Row][i] !=
'=' && DepMatrix[Row][i] !=
'S' &&
214 DepMatrix[Row][i] !=
'I')
221 unsigned OuterLoopId,
char InnerDep,
226 if (InnerDep == OuterDep)
232 if (InnerDep ==
'=' || InnerDep ==
'S' || InnerDep ==
'I')
238 if (InnerDep ==
'>') {
241 if (OuterLoopId == 0)
259 unsigned InnerLoopId,
260 unsigned OuterLoopId) {
261 unsigned NumRows = DepMatrix.size();
263 for (
unsigned Row = 0; Row < NumRows; ++Row) {
264 char InnerDep = DepMatrix[Row][InnerLoopId];
265 char OuterDep = DepMatrix[Row][OuterLoopId];
266 if (InnerDep ==
'*' || OuterDep ==
'*')
279 Loop *CurrentLoop = &L;
280 const std::vector<Loop *> *Vec = &CurrentLoop->
getSubLoops();
281 while (!Vec->empty()) {
285 if (Vec->size() != 1) {
289 LoopList.push_back(CurrentLoop);
290 CurrentLoop = Vec->front();
293 LoopList.push_back(CurrentLoop);
300 return InnerIndexVar;
306 if (!PhiTy->isIntegerTy() && !PhiTy->isFloatingPointTy() &&
307 !PhiTy->isPointerTy())
314 if (!isa<SCEVConstant>(Step))
327 class LoopInterchangeLegality {
332 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), LI(LI), DT(DT),
333 PreserveLCSSA(PreserveLCSSA), ORE(ORE) {}
336 bool canInterchangeLoops(
unsigned InnerLoopId,
unsigned OuterLoopId,
337 CharMatrix &DepMatrix);
341 bool isLoopStructureUnderstood(
PHINode *InnerInductionVar);
343 bool currentLimitations();
345 bool hasInnerLoopReduction() {
return InnerLoopHasReduction; }
348 bool tightlyNested(
Loop *Outer,
Loop *Inner);
349 bool containsUnsafeInstructionsInHeader(
BasicBlock *BB);
351 bool containsUnsafeInstructionsInLatch(
BasicBlock *BB);
352 bool findInductionAndReductions(
Loop *L,
367 bool InnerLoopHasReduction =
false;
372 class LoopInterchangeProfitability {
376 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), ORE(ORE) {}
379 bool isProfitable(
unsigned InnerLoopId,
unsigned OuterLoopId,
380 CharMatrix &DepMatrix);
383 int getInstrOrderCost();
396 class LoopInterchangeTransform {
401 bool InnerLoopContainsReductions)
402 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), LI(LI), DT(DT),
403 LoopExit(LoopNestExit),
404 InnerLoopHasReduction(InnerLoopContainsReductions) {}
408 void restructureLoops(
Loop *NewInner,
Loop *NewOuter,
411 void removeChildLoop(
Loop *OuterLoop,
Loop *InnerLoop);
415 void splitInnerLoopHeader();
416 bool adjustLoopLinks();
417 void adjustLoopPreheaders();
418 bool adjustLoopBranches();
431 bool InnerLoopHasReduction;
468 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
469 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
470 DI = &getAnalysis<DependenceAnalysisWrapperPass>().getDI();
471 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
472 ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
473 PreserveLCSSA = mustPreserveAnalysisID(
LCSSAID);
483 while (!Worklist.
empty()) {
485 Changed = processLoopList(LoopList, F);
490 bool isComputableLoopNest(LoopVector LoopList) {
491 for (
Loop *L : LoopList) {
497 if (L->getNumBackEdges() != 1) {
501 if (!L->getExitingBlock()) {
509 unsigned selectLoopForInterchange(
const LoopVector &LoopList) {
512 return LoopList.size() - 1;
515 bool processLoopList(LoopVector LoopList,
Function &F) {
516 bool Changed =
false;
517 unsigned LoopNestDepth = LoopList.size();
518 if (LoopNestDepth < 2) {
519 LLVM_DEBUG(
dbgs() <<
"Loop doesn't contain minimum nesting level.\n");
522 if (LoopNestDepth > MaxLoopNestDepth) {
524 << MaxLoopNestDepth <<
"\n");
527 if (!isComputableLoopNest(LoopList)) {
528 LLVM_DEBUG(
dbgs() <<
"Not valid loop candidate for interchange\n");
532 LLVM_DEBUG(
dbgs() <<
"Processing LoopList of size = " << LoopNestDepth
535 CharMatrix DependencyMatrix;
536 Loop *OuterMostLoop = *(LoopList.begin());
538 OuterMostLoop, DI)) {
542 #ifdef DUMP_DEP_MATRICIES 544 printDepMatrix(DependencyMatrix);
554 unsigned SelecLoopId = selectLoopForInterchange(LoopList);
556 for (
unsigned i = SelecLoopId; i > 0; i--) {
558 processLoop(LoopList, i, i - 1, LoopNestExit, DependencyMatrix);
566 #ifdef DUMP_DEP_MATRICIES 568 printDepMatrix(DependencyMatrix);
570 Changed |= Interchanged;
575 bool processLoop(LoopVector LoopList,
unsigned InnerLoopId,
576 unsigned OuterLoopId,
BasicBlock *LoopNestExit,
577 std::vector<std::vector<char>> &DependencyMatrix) {
579 <<
" and OuterLoopId = " << OuterLoopId <<
"\n");
580 Loop *InnerLoop = LoopList[InnerLoopId];
581 Loop *OuterLoop = LoopList[OuterLoopId];
583 LoopInterchangeLegality LIL(OuterLoop, InnerLoop, SE, LI, DT,
585 if (!LIL.canInterchangeLoops(InnerLoopId, OuterLoopId, DependencyMatrix)) {
586 LLVM_DEBUG(
dbgs() <<
"Not interchanging loops. Cannot prove legality.\n");
590 LoopInterchangeProfitability LIP(OuterLoop, InnerLoop, SE, ORE);
591 if (!LIP.isProfitable(InnerLoopId, OuterLoopId, DependencyMatrix)) {
600 <<
"Loop interchanged with enclosing loop.";
603 LoopInterchangeTransform LIT(OuterLoop, InnerLoop, SE, LI, DT,
604 LoopNestExit, LIL.hasInnerLoopReduction());
622 bool LoopInterchangeLegality::containsUnsafeInstructionsInHeader(
627 if (
LoadInst *L = dyn_cast<LoadInst>(&
I)) {
628 if (!areAllUsesReductions(L, InnerLoop))
630 }
else if (
I.mayHaveSideEffects() ||
I.mayReadFromMemory())
636 bool LoopInterchangeLegality::containsUnsafeInstructionsInLatch(
642 if (!isa<PHINode>(L->getOperand(0)))
644 }
else if (
I.mayHaveSideEffects() ||
I.mayReadFromMemory())
650 bool LoopInterchangeLegality::tightlyNested(
Loop *OuterLoop,
Loop *InnerLoop) {
662 if (!OuterLoopHeaderBI)
666 if (Succ != InnerLoopPreHeader && Succ != OuterLoopLatch)
669 LLVM_DEBUG(
dbgs() <<
"Checking instructions in Loop header and Loop latch\n");
672 if (containsUnsafeInstructionsInHeader(OuterLoopHeader) ||
673 containsUnsafeInstructionsInLatch(OuterLoopLatch))
681 bool LoopInterchangeLegality::isLoopStructureUnderstood(
685 for (
unsigned i = 0; i < Num; ++i) {
687 if (isa<Constant>(Val))
697 InnerLoopPreheader &&
705 bool LoopInterchangeLegality::findInductionAndReductions(
719 dbgs() <<
"Failed to recognize PHI as an induction or reduction.\n");
729 if (PHI.getNumIncomingValues() > 1)
736 if (!isa<PHINode>(Ins) && isOuterLoopExitBlock)
744 bool LoopInterchangeLegality::currentLimitations() {
755 dbgs() <<
"Loops where the latch is not the exiting block are not" 756 <<
" supported currently.\n");
761 <<
"Loops where the latch is not the exiting block cannot be" 762 " interchange currently.";
770 if (!findInductionAndReductions(InnerLoop, Inductions, Reductions)) {
772 dbgs() <<
"Only inner loops with induction or reduction PHI nodes " 773 <<
"are supported currently.\n");
778 <<
"Only inner loops with induction or reduction PHI nodes can be" 779 " interchange currently.";
785 if (Inductions.
size() != 1) {
787 dbgs() <<
"We currently only support loops with 1 induction variable." 788 <<
"Failed to interchange due to current limitation\n");
793 <<
"Only inner loops with 1 induction variable can be " 794 "interchanged currently.";
798 if (Reductions.
size() > 0)
799 InnerLoopHasReduction =
true;
803 if (!findInductionAndReductions(OuterLoop, Inductions, Reductions)) {
805 dbgs() <<
"Only outer loops with induction or reduction PHI nodes " 806 <<
"are supported currently.\n");
811 <<
"Only outer loops with induction or reduction PHI nodes can be" 812 " interchanged currently.";
819 if (!Reductions.
empty()) {
820 LLVM_DEBUG(
dbgs() <<
"Outer loops with reductions are not supported " 826 <<
"Outer loops with reductions cannot be interchangeed " 832 if (Inductions.
size() != 1) {
833 LLVM_DEBUG(
dbgs() <<
"Loops with more than 1 induction variables are not " 834 <<
"supported currently.\n");
839 <<
"Only outer loops with 1 induction variable can be " 840 "interchanged currently.";
846 if (!isLoopStructureUnderstood(InnerInductionVar)) {
852 <<
"Inner loop structure not understood currently.";
861 dbgs() <<
"Can only handle LCSSA PHIs in inner loops currently.\n");
866 <<
"Only inner loops with LCSSA PHIs can be interchange " 890 if (!InnerIndexVarInc) {
892 dbgs() <<
"Did not find an instruction to increment the induction " 898 <<
"The inner loop does not increment the induction variable.";
907 bool FoundInduction =
false;
910 if (isa<BranchInst>(
I) || isa<CmpInst>(
I) || isa<TruncInst>(
I) ||
916 if (!
I.isIdenticalTo(InnerIndexVarInc)) {
917 LLVM_DEBUG(
dbgs() <<
"Found unsupported instructions between induction " 918 <<
"variable increment and branch.\n");
923 <<
"Found unsupported instruction between induction variable " 924 "increment and branch.";
929 FoundInduction =
true;
934 if (!FoundInduction) {
940 <<
"Did not find the induction variable.";
960 if (PHI.getType()->isFloatingPointTy())
962 for (
unsigned i = 0; i < PHI.getNumIncomingValues(); i++) {
984 bool LoopInterchangeLegality::canInterchangeLoops(
unsigned InnerLoopId,
985 unsigned OuterLoopId,
986 CharMatrix &DepMatrix) {
988 LLVM_DEBUG(
dbgs() <<
"Failed interchange InnerLoopId = " << InnerLoopId
989 <<
" and OuterLoopId = " << OuterLoopId
990 <<
" due to dependence\n");
995 <<
"Cannot interchange loops due to dependences.";
1000 for (
auto *BB : OuterLoop->
blocks())
1002 if (
CallInst *CI = dyn_cast<CallInst>(&
I)) {
1004 if (CI->doesNotReadMemory())
1007 dbgs() <<
"Loops with call instructions cannot be interchanged " 1013 <<
"Cannot interchange loops due to call instruction.";
1028 if (!OuterLoopPreHeader || OuterLoopPreHeader == OuterLoop->
getHeader() ||
1029 isa<PHINode>(OuterLoopPreHeader->
begin()) ||
1031 OuterLoopPreHeader =
1035 if (!InnerLoopPreHeader || InnerLoopPreHeader == InnerLoop->
getHeader() ||
1036 InnerLoopPreHeader == OuterLoop->
getHeader()) {
1037 InnerLoopPreHeader =
1043 if (currentLimitations()) {
1044 LLVM_DEBUG(
dbgs() <<
"Not legal because of current transform limitation\n");
1049 if (!tightlyNested(OuterLoop, InnerLoop)) {
1055 <<
"Cannot interchange loops because they are not tightly " 1062 LLVM_DEBUG(
dbgs() <<
"Found unsupported PHI nodes in outer loop exit.\n");
1067 <<
"Found unsupported PHI node in loop exit.";
1075 int LoopInterchangeProfitability::getInstrOrderCost() {
1076 unsigned GoodOrder, BadOrder;
1077 BadOrder = GoodOrder = 0;
1081 unsigned NumOp =
GEP->getNumOperands();
1082 bool FoundInnerInduction =
false;
1083 bool FoundOuterInduction =
false;
1084 for (
unsigned i = 0; i < NumOp; ++i) {
1085 const SCEV *OperandVal = SE->getSCEV(
GEP->getOperand(i));
1095 if (AR->
getLoop() == InnerLoop) {
1098 FoundInnerInduction =
true;
1099 if (FoundOuterInduction) {
1109 if (AR->
getLoop() == OuterLoop) {
1112 FoundOuterInduction =
true;
1113 if (FoundInnerInduction) {
1122 return GoodOrder - BadOrder;
1126 unsigned OuterLoopId,
1127 CharMatrix &DepMatrix) {
1131 for (
auto &Row : DepMatrix) {
1132 if (Row[InnerLoopId] !=
'S' && Row[InnerLoopId] !=
'I')
1135 if (Row[OuterLoopId] !=
'=')
1141 return !DepMatrix.empty();
1144 bool LoopInterchangeProfitability::isProfitable(
unsigned InnerLoopId,
1145 unsigned OuterLoopId,
1146 CharMatrix &DepMatrix) {
1155 int Cost = getInstrOrderCost();
1169 <<
"Interchanging loops is too costly (cost=" 1170 <<
ore::NV(
"Cost", Cost) <<
", threshold=" 1172 <<
") and it does not improve parallelism.";
1177 void LoopInterchangeTransform::removeChildLoop(
Loop *OuterLoop,
1179 for (
Loop *L : *OuterLoop)
1180 if (L == InnerLoop) {
1181 OuterLoop->removeChildLoop(L);
1210 void LoopInterchangeTransform::restructureLoops(
1217 LI->changeLoopFor(OrigInnerPreHeader, OuterLoopParent);
1220 if (OuterLoopParent) {
1222 removeChildLoop(OuterLoopParent, NewInner);
1223 removeChildLoop(NewInner, NewOuter);
1226 removeChildLoop(NewInner, NewOuter);
1227 LI->changeTopLevelLoop(NewInner, NewOuter);
1229 while (!NewOuter->
empty())
1239 if (LI->getLoopFor(BB) == NewInner)
1248 if (LI->getLoopFor(BB) != NewOuter)
1251 if (BB == OuterHeader || BB == OuterLatch)
1254 LI->changeLoopFor(BB, NewInner);
1260 LI->changeLoopFor(OrigOuterPreHeader, NewOuter);
1264 bool Transformed =
false;
1271 if (!InductionPHI) {
1272 LLVM_DEBUG(
dbgs() <<
"Failed to find the point to split loop latch \n");
1288 splitInnerLoopLatch(InnerIndexVar);
1297 Transformed |= adjustLoopLinks();
1306 void LoopInterchangeTransform::splitInnerLoopLatch(
Instruction *Inc) {
1308 BasicBlock *InnerLoopLatchPred = InnerLoopLatch;
1309 InnerLoopLatch =
SplitBlock(InnerLoopLatchPred, Inc, DT, LI);
1322 void LoopInterchangeTransform::updateIncomingBlock(
BasicBlock *CurrBlock,
1326 unsigned Num = PHI.getNumIncomingValues();
1327 for (
unsigned i = 0; i < Num; ++i) {
1328 if (PHI.getIncomingBlock(i) == OldPred)
1329 PHI.setIncomingBlock(i, NewPred);
1338 std::vector<DominatorTree::UpdateType> &DTUpdates) {
1340 [OldBB](
BasicBlock *BB) {
return BB == OldBB; }) < 2 &&
1341 "BI must jump to OldBB at most once.");
1346 DTUpdates.push_back(
1348 DTUpdates.push_back(
1355 bool LoopInterchangeTransform::adjustLoopBranches() {
1357 std::vector<DominatorTree::UpdateType> DTUpdates;
1381 if (!OuterLoopPredecessor || !InnerLoopLatchPredecessor ||
1382 !OuterLoopLatchBI || !InnerLoopLatchBI || !OuterLoopHeaderBI ||
1391 if (!OuterLoopPredecessorBI || !InnerLoopLatchPredecessorBI)
1394 if (!InnerLoopHeaderSuccessor)
1399 InnerLoopPreHeader, DTUpdates);
1400 updateSuccessor(OuterLoopHeaderBI, OuterLoopLatch, LoopExit, DTUpdates);
1402 InnerLoopHeaderSuccessor, DTUpdates);
1405 updateIncomingBlock(InnerLoopHeaderSuccessor, InnerLoopHeader,
1409 OuterLoopPreHeader, DTUpdates);
1412 if (InnerLoopLatchBI->getSuccessor(0) == InnerLoopHeader)
1413 InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(1);
1415 InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(0);
1418 InnerLoopLatchSuccessor, DTUpdates);
1427 Value *Incoming =
P->getIncomingValueForBlock(InnerLoopLatch);
1428 P->replaceAllUsesWith(Incoming);
1429 P->eraseFromParent();
1432 if (OuterLoopLatchBI->
getSuccessor(0) == OuterLoopHeader)
1433 OuterLoopLatchSuccessor = OuterLoopLatchBI->
getSuccessor(1);
1435 OuterLoopLatchSuccessor = OuterLoopLatchBI->
getSuccessor(0);
1438 OuterLoopLatchSuccessor, DTUpdates);
1439 updateSuccessor(OuterLoopLatchBI, OuterLoopLatchSuccessor, InnerLoopLatch,
1442 updateIncomingBlock(OuterLoopLatchSuccessor, OuterLoopLatch, InnerLoopLatch);
1444 DT->applyUpdates(DTUpdates);
1445 restructureLoops(OuterLoop, InnerLoop, InnerLoopPreHeader,
1446 OuterLoopPreHeader);
1451 InnerLoopPHIs.
push_back(cast<PHINode>(&PHI));
1453 OuterLoopPHIs.
push_back(cast<PHINode>(&PHI));
1455 for (
PHINode *PHI : OuterLoopPHIs)
1462 for (
PHINode *PHI : InnerLoopPHIs) {
1468 assert(!isa<PHINode>(PHI->getIncomingValueForBlock(InBB)) &&
1469 "Unexpected incoming PHI node, reductions in outer loop are not " 1471 PHI->replaceAllUsesWith(PHI->getIncomingValueForBlock(InBB));
1472 PHI->eraseFromParent();
1478 updateIncomingBlock(OuterLoopHeader, InnerLoopPreHeader, OuterLoopPreHeader);
1479 updateIncomingBlock(OuterLoopHeader, InnerLoopLatch, OuterLoopLatch);
1480 updateIncomingBlock(InnerLoopHeader, OuterLoopPreHeader, InnerLoopPreHeader);
1481 updateIncomingBlock(InnerLoopHeader, OuterLoopLatch, InnerLoopLatch);
1486 void LoopInterchangeTransform::adjustLoopPreheaders() {
1505 bool LoopInterchangeTransform::adjustLoopLinks() {
1507 bool Changed = adjustLoopBranches();
1509 adjustLoopPreheaders();
1516 "Interchanges loops for cache reuse",
false,
false)
Pass interface - Implemented by all 'passes'.
void push_back(const T &Elt)
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
DiagnosticInfoOptimizationBase::Argument NV
Compute iterated dominance frontiers using a linear time algorithm.
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...
static bool isInductionPHI(PHINode *Phi, const Loop *L, ScalarEvolution *SE, InductionDescriptor &D, const SCEV *Expr=nullptr, SmallVectorImpl< Instruction *> *CastsToIgnore=nullptr)
Returns true if Phi is an induction in the loop L.
Legacy pass manager pass to access dependence information.
static bool isProfitableForVectorization(unsigned InnerLoopId, unsigned OuterLoopId, CharMatrix &DepMatrix)
LoopT * removeChildLoop(iterator I)
This removes the specified child from being a subloop of this loop.
The main scalar evolution driver.
This class represents a function call, abstracting a target machine's calling convention.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
static bool containsNoDependence(CharMatrix &DepMatrix, unsigned Row, unsigned Column)
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...
auto count_if(R &&Range, UnaryPredicate P) -> typename std::iterator_traits< decltype(adl_begin(Range))>::difference_type
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
BasicBlock * getSuccessor(unsigned i) const
STATISTIC(NumFunctions, "Total number of functions")
An instruction for reading from memory.
DependenceInfo - This class is the main dependence-analysis driver.
iterator begin()
Instruction iterator methods.
static bool populateDependencyMatrix(CharMatrix &DepMatrix, unsigned Level, Loop *L, DependenceInfo *DI)
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
const Loop * getLoop() const
unsigned getNumSuccessors() const
void addBlockEntry(BlockT *BB)
This adds a basic block directly to the basic block list.
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly...
BlockT * getHeader() const
ConstantInt * getValue() 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 bool isLegalToInterChangeLoops(CharMatrix &DepMatrix, unsigned InnerLoopId, unsigned OuterLoopId)
Type * getType() const
All values are typed, get the type of this value.
This node represents a polynomial recurrence on the trip count of the specified loop.
const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
static bool validDepInterchange(CharMatrix &DepMatrix, unsigned Row, unsigned OuterLoopId, char InnerDep, char OuterDep)
static const unsigned MaxLoopNestDepth
An instruction for storing to memory.
static void updateSuccessor(BranchInst *BI, BasicBlock *OldBB, BasicBlock *NewBB, std::vector< DominatorTree::UpdateType > &DTUpdates)
Update BI to jump to NewBB instead of OldBB.
const SCEV * getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Value * getOperand(unsigned i) const
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
const SCEV * getCouldNotCompute()
static bool runOnFunction(Function &F, bool PostInlining)
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.
const Instruction * getFirstNonPHI() const
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
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.
iterator_range< filter_iterator< BasicBlock::const_iterator, std::function< bool(const Instruction &)> > > instructionsWithoutDebug() const
Return a const iterator range over the instructions in the block, skipping any debug instructions...
This file contains the declarations for the subclasses of Constant, which represent the different fla...
const Instruction & front() const
loop Interchanges loops for cache reuse
Represent the analysis usage information of a pass.
void splice(iterator where, iplist_impl &L2)
FunctionPass class - This class is used to implement most global optimizations.
bool isAffine() const
Return true if this represents an expression A + B*x where A and B are loop invariant values...
self_iterator getIterator()
static bool isReductionPHI(PHINode *Phi, Loop *TheLoop, RecurrenceDescriptor &RedDes, DemandedBits *DB=nullptr, AssumptionCache *AC=nullptr, DominatorTree *DT=nullptr)
Returns true if Phi is a reduction in TheLoop.
BlockT * getExitBlock() const
If getExitBlocks would return exactly one block, return that block.
Used in the streaming interface as the general argument type.
BlockT * getUniqueExitBlock() const
If getUniqueExitBlocks would return exactly one block, return that block.
DebugLoc getStartLoc() const
Return the debug location of the start of this loop.
iterator_range< decltype(adl_begin(std::declval< T >)))> drop_begin(T &&t, int n)
static unsigned getIncomingValueNumForOperand(unsigned i)
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
void initializeLoopInterchangePass(PassRegistry &)
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
void setSuccessor(unsigned idx, BasicBlock *NewSucc)
The RecurrenceDescriptor is used to identify recurrences variables in a loop.
BlockT * getLoopPredecessor() const
If the given loop's header has exactly one unique predecessor outside the loop, return it...
const InstListType & getInstList() const
Return the underlying instruction list container.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
Iterator for intrusive lists based on ilist_node.
unsigned getNumOperands() const
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.
Pass * createLoopInterchangePass()
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...
LLVM_NODISCARD T pop_back_val()
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static const unsigned MaxMemInstrCount
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.
PHINode * getCanonicalInductionVariable() const
Check to see if the loop has a canonical induction variable: an integer recurrence that starts at 0 a...
iterator_range< user_iterator > users()
INITIALIZE_PASS_BEGIN(LoopInterchange, "loop-interchange", "Interchanges loops for cache reuse", false, false) INITIALIZE_PASS_END(LoopInterchange
LoopT * getParentLoop() const
const std::vector< LoopT * > & getSubLoops() const
Return the loops contained entirely within this loop.
This class represents an analyzed expression in the program.
void addChildLoop(LoopT *NewChild)
Add the specified loop to be a child of this loop.
LLVM_NODISCARD bool empty() const
Represents a single loop in the control flow graph.
StringRef getName() const
Return a constant reference to the value's name.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
const Function * getParent() const
Return the enclosing method, or null if none.
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
static bool isOuterMostDepPositive(CharMatrix &DepMatrix, unsigned Row, unsigned Column)
void removeBlockFromLoop(BlockT *BB)
This removes the specified basic block from the current loop, updating the Blocks as appropriate...
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...
static void populateWorklist(Loop &L, SmallVector< LoopVector, 8 > &V)
const SCEV * getBackedgeTakenCount(const Loop *L)
If the specified loop has a predictable backedge-taken count, return it, otherwise return a SCEVCould...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static void interChangeDependencies(CharMatrix &DepMatrix, unsigned FromIndx, unsigned ToIndx)
LLVM Value Representation.
const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
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.
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...
for(unsigned i=Desc.getNumOperands(), e=OldMI.getNumOperands();i !=e;++i)
iterator_range< block_iterator > blocks() const
BlockT * getExitingBlock() const
If getExitingBlocks would return exactly one block, return that block.
static bool areLoopExitPHIsSupported(Loop *OuterLoop, Loop *InnerLoop)
const BasicBlock * getParent() const
This class represents a constant integer value.
static PHINode * getInductionVariable(Loop *L, ScalarEvolution *SE)
const BasicBlock * getUniqueSuccessor() const
Return the successor of this block if it has a unique successor.