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)
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))
326 class LoopInterchangeLegality {
330 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), ORE(ORE) {}
333 bool canInterchangeLoops(
unsigned InnerLoopId,
unsigned OuterLoopId,
334 CharMatrix &DepMatrix);
338 bool isLoopStructureUnderstood(
PHINode *InnerInductionVar);
340 bool currentLimitations();
343 return OuterInnerReductions;
347 bool tightlyNested(
Loop *Outer,
Loop *Inner);
348 bool containsUnsafeInstructions(
BasicBlock *BB);
354 bool findInductionAndReductions(
Loop *L,
373 class LoopInterchangeProfitability {
377 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), ORE(ORE) {}
380 bool isProfitable(
unsigned InnerLoopId,
unsigned OuterLoopId,
381 CharMatrix &DepMatrix);
384 int getInstrOrderCost();
397 class LoopInterchangeTransform {
402 const LoopInterchangeLegality &LIL)
403 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), LI(LI), DT(DT),
404 LoopExit(LoopNestExit), LIL(LIL) {}
408 void restructureLoops(
Loop *NewInner,
Loop *NewOuter,
411 void removeChildLoop(
Loop *OuterLoop,
Loop *InnerLoop);
414 bool adjustLoopLinks();
415 void adjustLoopPreheaders();
416 bool adjustLoopBranches();
428 const LoopInterchangeLegality &LIL;
432 struct LoopInterchange :
public LoopPass {
457 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
458 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
459 DI = &getAnalysis<DependenceAnalysisWrapperPass>().getDI();
460 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
461 ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
466 bool isComputableLoopNest(LoopVector LoopList) {
467 for (
Loop *L : LoopList) {
485 unsigned selectLoopForInterchange(
const LoopVector &LoopList) {
488 return LoopList.size() - 1;
491 bool processLoopList(LoopVector LoopList) {
492 bool Changed =
false;
493 unsigned LoopNestDepth = LoopList.size();
494 if (LoopNestDepth < 2) {
495 LLVM_DEBUG(
dbgs() <<
"Loop doesn't contain minimum nesting level.\n");
498 if (LoopNestDepth > MaxLoopNestDepth) {
500 << MaxLoopNestDepth <<
"\n");
503 if (!isComputableLoopNest(LoopList)) {
504 LLVM_DEBUG(
dbgs() <<
"Not valid loop candidate for interchange\n");
508 LLVM_DEBUG(
dbgs() <<
"Processing LoopList of size = " << LoopNestDepth
511 CharMatrix DependencyMatrix;
512 Loop *OuterMostLoop = *(LoopList.begin());
514 OuterMostLoop, DI)) {
518 #ifdef DUMP_DEP_MATRICIES 520 printDepMatrix(DependencyMatrix);
530 unsigned SelecLoopId = selectLoopForInterchange(LoopList);
532 for (
unsigned i = SelecLoopId; i > 0; i--) {
534 processLoop(LoopList, i, i - 1, LoopNestExit, DependencyMatrix);
542 #ifdef DUMP_DEP_MATRICIES 544 printDepMatrix(DependencyMatrix);
546 Changed |= Interchanged;
551 bool processLoop(LoopVector LoopList,
unsigned InnerLoopId,
552 unsigned OuterLoopId,
BasicBlock *LoopNestExit,
553 std::vector<std::vector<char>> &DependencyMatrix) {
555 <<
" and OuterLoopId = " << OuterLoopId <<
"\n");
556 Loop *InnerLoop = LoopList[InnerLoopId];
557 Loop *OuterLoop = LoopList[OuterLoopId];
559 LoopInterchangeLegality LIL(OuterLoop, InnerLoop, SE, ORE);
560 if (!LIL.canInterchangeLoops(InnerLoopId, OuterLoopId, DependencyMatrix)) {
561 LLVM_DEBUG(
dbgs() <<
"Not interchanging loops. Cannot prove legality.\n");
565 LoopInterchangeProfitability LIP(OuterLoop, InnerLoop, SE, ORE);
566 if (!LIP.isProfitable(InnerLoopId, OuterLoopId, DependencyMatrix)) {
575 <<
"Loop interchanged with enclosing loop.";
578 LoopInterchangeTransform LIT(OuterLoop, InnerLoop, SE, LI, DT, LoopNestExit,
589 bool LoopInterchangeLegality::containsUnsafeInstructions(
BasicBlock *BB) {
595 bool LoopInterchangeLegality::tightlyNested(
Loop *OuterLoop,
Loop *InnerLoop) {
607 if (!OuterLoopHeaderBI)
611 if (Succ != InnerLoopPreHeader && Succ != InnerLoop->
getHeader() &&
612 Succ != OuterLoopLatch)
615 LLVM_DEBUG(
dbgs() <<
"Checking instructions in Loop header and Loop latch\n");
618 if (containsUnsafeInstructions(OuterLoopHeader) ||
619 containsUnsafeInstructions(OuterLoopLatch))
627 bool LoopInterchangeLegality::isLoopStructureUnderstood(
631 for (
unsigned i = 0; i < Num; ++i) {
633 if (isa<Constant>(Val))
643 InnerLoopPreheader &&
667 if (PHI->getNumIncomingValues() == 1)
679 bool LoopInterchangeLegality::findInductionAndReductions(
692 if (OuterInnerReductions.find(&PHI) == OuterInnerReductions.end()) {
694 "across the outer loop.\n");
698 assert(PHI.getNumIncomingValues() == 2 &&
699 "Phis in loop header should have exactly 2 incoming values");
706 [&PHI](
Value *V) {
return V == &PHI; })) {
709 <<
"Failed to recognize PHI as an induction or reduction.\n");
712 OuterInnerReductions.insert(&PHI);
713 OuterInnerReductions.insert(InnerRedPhi);
722 bool LoopInterchangeLegality::currentLimitations() {
733 dbgs() <<
"Loops where the latch is not the exiting block are not" 734 <<
" supported currently.\n");
739 <<
"Loops where the latch is not the exiting block cannot be" 740 " interchange currently.";
747 if (!findInductionAndReductions(OuterLoop, Inductions, InnerLoop)) {
749 dbgs() <<
"Only outer loops with induction or reduction PHI nodes " 750 <<
"are supported currently.\n");
755 <<
"Only outer loops with induction or reduction PHI nodes can be" 756 " interchanged currently.";
762 if (Inductions.
size() != 1) {
763 LLVM_DEBUG(
dbgs() <<
"Loops with more than 1 induction variables are not " 764 <<
"supported currently.\n");
769 <<
"Only outer loops with 1 induction variable can be " 770 "interchanged currently.";
776 if (!findInductionAndReductions(InnerLoop, Inductions,
nullptr)) {
778 dbgs() <<
"Only inner loops with induction or reduction PHI nodes " 779 <<
"are supported currently.\n");
784 <<
"Only inner loops with induction or reduction PHI nodes can be" 785 " interchange currently.";
791 if (Inductions.
size() != 1) {
793 dbgs() <<
"We currently only support loops with 1 induction variable." 794 <<
"Failed to interchange due to current limitation\n");
799 <<
"Only inner loops with 1 induction variable can be " 800 "interchanged currently.";
807 if (!isLoopStructureUnderstood(InnerInductionVar)) {
813 <<
"Inner loop structure not understood currently.";
836 if (!InnerIndexVarInc) {
838 dbgs() <<
"Did not find an instruction to increment the induction " 844 <<
"The inner loop does not increment the induction variable.";
853 bool FoundInduction =
false;
856 if (isa<BranchInst>(
I) || isa<CmpInst>(
I) || isa<TruncInst>(
I) ||
862 if (!
I.isIdenticalTo(InnerIndexVarInc)) {
863 LLVM_DEBUG(
dbgs() <<
"Found unsupported instructions between induction " 864 <<
"variable increment and branch.\n");
869 <<
"Found unsupported instruction between induction variable " 870 "increment and branch.";
875 FoundInduction =
true;
880 if (!FoundInduction) {
886 <<
"Did not find the induction variable.";
902 if (PHI.getNumIncomingValues() > 1)
904 if (
any_of(PHI.users(), [&Reductions, OuterL](
User *U) {
906 return !PN || (Reductions.
find(PN) == Reductions.
end() &&
928 if (PHI.getType()->isFloatingPointTy())
930 for (
unsigned i = 0; i < PHI.getNumIncomingValues(); i++) {
952 bool LoopInterchangeLegality::canInterchangeLoops(
unsigned InnerLoopId,
953 unsigned OuterLoopId,
954 CharMatrix &DepMatrix) {
956 LLVM_DEBUG(
dbgs() <<
"Failed interchange InnerLoopId = " << InnerLoopId
957 <<
" and OuterLoopId = " << OuterLoopId
958 <<
" due to dependence\n");
963 <<
"Cannot interchange loops due to dependences.";
968 for (
auto *BB : OuterLoop->
blocks())
970 if (
CallInst *CI = dyn_cast<CallInst>(&
I)) {
972 if (CI->doesNotReadMemory())
975 dbgs() <<
"Loops with call instructions cannot be interchanged " 981 <<
"Cannot interchange loops due to call instruction.";
989 if (currentLimitations()) {
990 LLVM_DEBUG(
dbgs() <<
"Not legal because of current transform limitation\n");
995 if (!tightlyNested(OuterLoop, InnerLoop)) {
1001 <<
"Cannot interchange loops because they are not tightly " 1008 OuterInnerReductions)) {
1009 LLVM_DEBUG(
dbgs() <<
"Found unsupported PHI nodes in inner loop exit.\n");
1014 <<
"Found unsupported PHI node in loop exit.";
1020 LLVM_DEBUG(
dbgs() <<
"Found unsupported PHI nodes in outer loop exit.\n");
1025 <<
"Found unsupported PHI node in loop exit.";
1033 int LoopInterchangeProfitability::getInstrOrderCost() {
1034 unsigned GoodOrder, BadOrder;
1035 BadOrder = GoodOrder = 0;
1039 unsigned NumOp =
GEP->getNumOperands();
1040 bool FoundInnerInduction =
false;
1041 bool FoundOuterInduction =
false;
1042 for (
unsigned i = 0; i < NumOp; ++i) {
1043 const SCEV *OperandVal = SE->getSCEV(
GEP->getOperand(i));
1053 if (AR->
getLoop() == InnerLoop) {
1056 FoundInnerInduction =
true;
1057 if (FoundOuterInduction) {
1067 if (AR->
getLoop() == OuterLoop) {
1070 FoundOuterInduction =
true;
1071 if (FoundInnerInduction) {
1080 return GoodOrder - BadOrder;
1084 unsigned OuterLoopId,
1085 CharMatrix &DepMatrix) {
1089 for (
auto &Row : DepMatrix) {
1090 if (Row[InnerLoopId] !=
'S' && Row[InnerLoopId] !=
'I')
1093 if (Row[OuterLoopId] !=
'=')
1099 return !DepMatrix.empty();
1102 bool LoopInterchangeProfitability::isProfitable(
unsigned InnerLoopId,
1103 unsigned OuterLoopId,
1104 CharMatrix &DepMatrix) {
1113 int Cost = getInstrOrderCost();
1127 <<
"Interchanging loops is too costly (cost=" 1128 <<
ore::NV(
"Cost", Cost) <<
", threshold=" 1130 <<
") and it does not improve parallelism.";
1135 void LoopInterchangeTransform::removeChildLoop(
Loop *OuterLoop,
1137 for (
Loop *L : *OuterLoop)
1138 if (L == InnerLoop) {
1139 OuterLoop->removeChildLoop(L);
1168 void LoopInterchangeTransform::restructureLoops(
1175 LI->changeLoopFor(OrigInnerPreHeader, OuterLoopParent);
1178 if (OuterLoopParent) {
1180 removeChildLoop(OuterLoopParent, NewInner);
1181 removeChildLoop(NewInner, NewOuter);
1184 removeChildLoop(NewInner, NewOuter);
1185 LI->changeTopLevelLoop(NewInner, NewOuter);
1187 while (!NewOuter->
empty())
1197 if (LI->getLoopFor(BB) == NewInner)
1206 if (LI->getLoopFor(BB) != NewOuter)
1209 if (BB == OuterHeader || BB == OuterLatch)
1212 LI->changeLoopFor(BB, NewInner);
1218 LI->changeLoopFor(OrigOuterPreHeader, NewOuter);
1221 SE->forgetLoop(NewOuter);
1222 SE->forgetLoop(NewInner);
1226 bool Transformed =
false;
1233 if (!InductionPHI) {
1234 LLVM_DEBUG(
dbgs() <<
"Failed to find the point to split loop latch \n");
1257 auto MoveInstructions = [&i, &WorkList,
this, InductionPHI, NewLatch]() {
1258 for (; i < WorkList.size(); i++) {
1264 "Moving instructions with side-effects may change behavior of " 1266 for (
auto UI = WorkList[i]->use_begin(), UE = WorkList[i]->use_end();
1271 UserI->
getParent() == NewLatch || UserI == InductionPHI)
1276 for (
Value *
Op : WorkList[i]->operands()) {
1279 this->LI->getLoopFor(OpI->
getParent()) != this->InnerLoop ||
1280 OpI == InductionPHI)
1282 WorkList.insert(OpI);
1292 WorkList.insert(CondI);
1294 WorkList.insert(cast<Instruction>(InnerIndexVar));
1303 Transformed |= adjustLoopLinks();
1327 std::vector<DominatorTree::UpdateType> &DTUpdates,
1328 bool MustUpdateOnce =
true) {
1329 assert((!MustUpdateOnce ||
1333 }) == 1) &&
"BI must jump to OldBB exactly once.");
1334 bool Changed =
false;
1342 DTUpdates.push_back(
1344 DTUpdates.push_back(
1347 assert(Changed &&
"Expected a successor to be updated");
1364 assert(
P.getNumIncomingValues() == 1 &&
1365 "Only loops with a single exit are supported!");
1368 auto IncI = cast<Instruction>(
P.getIncomingValueForBlock(InnerLatch));
1371 if (IncI->getParent() != InnerLatch && IncI->
getParent() != InnerHeader)
1375 [OuterHeader, OuterExit, IncI, InnerHeader](
User *U) {
1376 return (cast<PHINode>(U)->getParent() == OuterHeader &&
1378 cast<PHINode>(U)->getParent() == OuterExit;
1380 "Can only replace phis iff the uses are in the loop nest exit or " 1381 "the incoming value is defined in the inner header (it will " 1382 "dominate all loop blocks after interchanging)");
1383 P.replaceAllUsesWith(IncI);
1384 P.eraseFromParent();
1414 if (
P.getNumIncomingValues() != 1)
1426 P.setIncomingValue(0, NewPhi);
1436 bool LoopInterchangeTransform::adjustLoopBranches() {
1438 std::vector<DominatorTree::UpdateType> DTUpdates;
1444 InnerLoopPreHeader != InnerLoop->
getHeader() && OuterLoopPreHeader &&
1445 InnerLoopPreHeader &&
"Guaranteed by loop-simplify form");
1450 if (isa<PHINode>(OuterLoopPreHeader->
begin()) ||
1452 OuterLoopPreHeader =
1454 if (InnerLoopPreHeader == OuterLoop->
getHeader())
1455 InnerLoopPreHeader =
1478 if (!OuterLoopPredecessor || !InnerLoopLatchPredecessor ||
1479 !OuterLoopLatchBI || !InnerLoopLatchBI || !OuterLoopHeaderBI ||
1488 if (!OuterLoopPredecessorBI || !InnerLoopLatchPredecessorBI)
1491 if (!InnerLoopHeaderSuccessor)
1499 InnerLoopPreHeader, DTUpdates,
false);
1503 OuterLoopLatch) !=
succ_end(OuterLoopHeaderBI))
1504 updateSuccessor(OuterLoopHeaderBI, OuterLoopLatch, LoopExit, DTUpdates,
1507 InnerLoopHeaderSuccessor, DTUpdates,
1515 OuterLoopPreHeader, DTUpdates);
1518 if (InnerLoopLatchBI->getSuccessor(0) == InnerLoopHeader)
1519 InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(1);
1521 InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(0);
1524 InnerLoopLatchSuccessor, DTUpdates);
1527 if (OuterLoopLatchBI->
getSuccessor(0) == OuterLoopHeader)
1528 OuterLoopLatchSuccessor = OuterLoopLatchBI->
getSuccessor(1);
1530 OuterLoopLatchSuccessor = OuterLoopLatchBI->
getSuccessor(0);
1533 OuterLoopLatchSuccessor, DTUpdates);
1534 updateSuccessor(OuterLoopLatchBI, OuterLoopLatchSuccessor, InnerLoopLatch,
1537 DT->applyUpdates(DTUpdates);
1538 restructureLoops(OuterLoop, InnerLoop, InnerLoopPreHeader,
1539 OuterLoopPreHeader);
1541 moveLCSSAPhis(InnerLoopLatchSuccessor, InnerLoopHeader, InnerLoopLatch,
1542 OuterLoopHeader, OuterLoopLatch, InnerLoop->
getExitBlock(),
1551 InnerLoopPHIs.
push_back(cast<PHINode>(&PHI));
1553 OuterLoopPHIs.
push_back(cast<PHINode>(&PHI));
1555 auto &OuterInnerReductions = LIL.getOuterInnerReductions();
1556 (void)OuterInnerReductions;
1561 for (
PHINode *PHI : OuterLoopPHIs) {
1563 assert(OuterInnerReductions.find(PHI) != OuterInnerReductions.end() &&
1564 "Expected a reduction PHI node");
1566 for (
PHINode *PHI : InnerLoopPHIs) {
1568 assert(OuterInnerReductions.find(PHI) != OuterInnerReductions.end() &&
1569 "Expected a reduction PHI node");
1581 void LoopInterchangeTransform::adjustLoopPreheaders() {
1600 bool LoopInterchangeTransform::adjustLoopLinks() {
1602 bool Changed = adjustLoopBranches();
1604 adjustLoopPreheaders();
1611 "Interchanges loops for cache reuse",
false,
false)
Pass interface - Implemented by all 'passes'.
auto drop_begin(T &&RangeOrContainer, size_t N) -> iterator_range< decltype(adl_begin(RangeOrContainer))>
Return a range covering RangeOrContainer with the first N elements excluded.
static void moveLCSSAPhis(BasicBlock *InnerExit, BasicBlock *InnerHeader, BasicBlock *InnerLatch, BasicBlock *OuterHeader, BasicBlock *OuterLatch, BasicBlock *OuterExit, Loop *InnerLoop, LoopInfo *LI)
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
This class represents lattice values for constants.
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.
static LoopVector populateWorklist(Loop &L)
Legacy pass manager pass to access dependence information.
static bool isProfitableForVectorization(unsigned InnerLoopId, unsigned OuterLoopId, CharMatrix &DepMatrix)
void push_back(const T &Elt)
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)
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
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...
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
BasicBlock * getSuccessor(unsigned i) const
STATISTIC(NumFunctions, "Total number of functions")
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
DependenceInfo - This class is the main dependence-analysis driver.
BasicBlock * SplitBlock(BasicBlock *Old, Instruction *SplitPt, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction - everything before SplitPt stays in Old and e...
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
iterator begin()
Instruction iterator methods.
static bool populateDependencyMatrix(CharMatrix &DepMatrix, unsigned Level, Loop *L, DependenceInfo *DI)
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
unsigned getNumBackEdges() const
Calculate the number of back edges to the loop header.
const Loop * getLoop() const
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
void replacePhiUsesWith(BasicBlock *Old, BasicBlock *New)
Update all phi nodes in this basic block to refer to basic block New instead of basic block Old...
A Use represents the edge between a Value definition and its users.
void addBlockEntry(BlockT *BB)
This adds a basic block directly to the basic block list.
iterator find(ConstPtrType Ptr) const
BlockT * getHeader() const
Interval::succ_iterator succ_begin(Interval *I)
succ_begin/succ_end - define methods so that Intervals may be used just like BasicBlocks can with the...
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 void updateSuccessor(BranchInst *BI, BasicBlock *OldBB, BasicBlock *NewBB, std::vector< DominatorTree::UpdateType > &DTUpdates, bool MustUpdateOnce=true)
Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following: ...
User * getUser() const LLVM_READONLY
Returns the User that contains this Use.
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
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
Interval::succ_iterator succ_end(Interval *I)
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.
const Instruction * getFirstNonPHI() const
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified 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
bool mayHaveSideEffects() const
Return true if the instruction may have side effects.
loop Interchanges loops for cache reuse
Represent the analysis usage information of a pass.
void splice(iterator where, iplist_impl &L2)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
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.
static unsigned getIncomingValueNumForOperand(unsigned i)
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
void initializeLoopInterchangePass(PassRegistry &)
auto find(R &&Range, const T &Val) -> decltype(adl_begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
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.
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.
A SetVector that performs no allocations if smaller than a certain size.
Iterator for intrusive lists based on ilist_node.
unsigned getNumOperands() const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
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()
static void moveBBContents(BasicBlock *FromBB, Instruction *InsertBefore)
Move all instructions except the terminator from FromBB right before InsertBefore.
static bool areOuterLoopExitPHIsSupported(Loop *OuterLoop, Loop *InnerLoop)
LLVM_NODISCARD T pop_back_val()
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
unsigned getNumIncomingValues() const
Return the number of incoming edges.
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
const SCEV * getBackedgeTakenCount(const Loop *L, ExitCountKind Kind=Exact)
If the specified loop has a predictable backedge-taken count, return it, otherwise return a SCEVCould...
LoopT * getParentLoop() const
static PHINode * findInnerReductionPhi(Loop *L, Value *V)
const std::vector< LoopT * > & getSubLoops() const
Return the loops contained entirely within this loop.
static bool areInnerLoopExitPHIsSupported(Loop *InnerL, Loop *OuterL, SmallPtrSetImpl< PHINode *> &Reductions)
This class represents an analyzed expression in the program.
void addChildLoop(LoopT *NewChild)
Add the specified loop to be a child of this loop.
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 mayReadFromMemory() const
Return true if this instruction may read memory.
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
void getLoopAnalysisUsage(AnalysisUsage &AU)
Helper to consistently add the set of standard passes to a loop pass's AnalysisUsage.
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...
Loop::LoopBounds::Direction Direction
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.
static Value * followLCSSA(Value *SV)
succ_range successors(Instruction *I)
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
BasicBlock * InsertPreheaderForLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, MemorySSAUpdater *MSSAU, bool PreserveLCSSA)
InsertPreheaderForLoop - Once we discover that a loop doesn't have a preheader, this method is called...
StringRef - Represent a constant reference to a string, i.e.
void setIncomingValue(unsigned i, Value *V)
op_range incoming_values()
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.
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.