55#define DEBUG_TYPE "loop-interchange"
57STATISTIC(LoopsInterchanged,
"Number of loops interchanged");
61 cl::desc(
"Interchange if you gain more than this number"));
67 "Maximum number of load-store instructions that should be handled "
68 "in the dependency matrix. Higher value may lead to more interchanges "
69 "at the cost of compile-time"));
83using CharMatrix = std::vector<std::vector<char>>;
98 cl::desc(
"Minimum depth of loop nest considered for the transform"));
103 cl::desc(
"Maximum depth of loop nest considered for the transform"));
109 cl::desc(
"List of profitability heuristics to be used. They are applied in "
112 RuleTy::PerInstrOrderCost,
113 RuleTy::ForVectorization}),
115 "Prioritize loop cache cost"),
116 clEnumValN(RuleTy::PerInstrOrderCost,
"instorder",
117 "Prioritize the IVs order of each instruction"),
118 clEnumValN(RuleTy::ForVectorization,
"vectorize",
119 "Prioritize vectorization"),
121 "Ignore profitability, force interchange (does not "
122 "work with other options)")));
127 cl::desc(
"Support for the inner-loop reduction pattern."));
132 for (RuleTy Rule : Rules) {
133 if (!Set.insert(Rule).second)
135 if (Rule == RuleTy::Ignore)
142 for (
auto &Row : DepMatrix) {
155 assert(Src->getParent() == Dst->getParent() && Src != Dst &&
156 "Expected Src and Dst to be different instructions in the same BB");
158 bool FoundSrc =
false;
199 <<
" Loads and Stores to analyze\n");
205 L->getStartLoc(), L->getHeader())
206 <<
"Number of loads/stores exceeded, the supported maximum "
207 "can be increased with option "
208 "-loop-interchange-maxmeminstr-count.";
218 for (
I = MemInstr.
begin(), IE = MemInstr.
end();
I != IE; ++
I) {
219 for (J =
I, JE = MemInstr.
end(); J != JE; ++J) {
220 std::vector<char> Dep;
227 if (
auto D = DI->
depends(Src, Dst)) {
228 assert(
D->isOrdered() &&
"Expected an output, flow or anti dep.");
231 if (
D->normalize(SE))
234 D->isFlow() ?
"flow" :
D->isAnti() ?
"anti" :
"output";
235 dbgs() <<
"Found " << DepType
236 <<
" dependency between Src and Dst\n"
237 <<
" Src:" << *Src <<
"\n Dst:" << *Dst <<
'\n');
238 unsigned Levels =
D->getLevels();
240 for (
unsigned II = 1;
II <= Levels; ++
II) {
247 unsigned Dir =
D->getDirection(
II);
261 if (
D->isConfused()) {
262 assert(Dep.empty() &&
"Expected empty dependency vector");
263 Dep.assign(Level,
'*');
266 while (Dep.size() != Level) {
275 L->getStartLoc(), L->getHeader())
276 <<
"All loops have dependencies in all directions.";
282 bool IsKnownForward =
true;
283 if (Src->getParent() != Dst->getParent()) {
287 IsKnownForward =
false;
293 "Unexpected instructions");
298 bool IsReversed =
D->getSrc() != Src;
300 IsKnownForward =
false;
316 DepMatrix.push_back(Dep);
323 DepMatrix[Ite->second].back() =
'*';
335 for (
auto &Row : DepMatrix)
344static std::optional<bool>
357 unsigned InnerLoopId,
358 unsigned OuterLoopId) {
359 unsigned NumRows = DepMatrix.size();
360 std::vector<char> Cur;
362 for (
unsigned Row = 0; Row < NumRows; ++Row) {
365 Cur = DepMatrix[Row];
378 std::swap(Cur[InnerLoopId], Cur[OuterLoopId]);
387 << L.getHeader()->getParent()->getName() <<
" Loop: %"
388 << L.getHeader()->getName() <<
'\n');
389 assert(LoopList.
empty() &&
"LoopList should initially be empty!");
390 Loop *CurrentLoop = &L;
391 const std::vector<Loop *> *Vec = &CurrentLoop->
getSubLoops();
392 while (!Vec->empty()) {
396 if (Vec->size() != 1) {
402 CurrentLoop = Vec->front();
410 unsigned LoopNestDepth = LoopList.
size();
412 LLVM_DEBUG(
dbgs() <<
"Unsupported depth of loop nest " << LoopNestDepth
420 <<
"Unsupported depth of loop nest, the supported range is ["
431 for (
Loop *L : LoopList) {
437 if (L->getNumBackEdges() != 1) {
441 if (!L->getExitingBlock()) {
452class LoopInterchangeLegality {
454 LoopInterchangeLegality(Loop *Outer, Loop *Inner, ScalarEvolution *SE,
455 OptimizationRemarkEmitter *ORE, DominatorTree *DT)
456 : OuterLoop(
Outer), InnerLoop(Inner), SE(SE), DT(DT), ORE(ORE) {}
459 bool canInterchangeLoops(
unsigned InnerLoopId,
unsigned OuterLoopId,
460 CharMatrix &DepMatrix);
464 bool findInductions(Loop *L, SmallVectorImpl<PHINode *> &Inductions);
468 bool isLoopStructureUnderstood();
470 bool currentLimitations();
472 const SmallPtrSetImpl<PHINode *> &getOuterInnerReductions()
const {
473 return OuterInnerReductions;
477 return InnerLoopInductions;
481 return HasNoWrapReductions;
488 struct InnerReduction {
496 StoreInst *LcssaStore;
503 return InnerReductions;
507 bool tightlyNested(Loop *Outer, Loop *Inner);
508 bool containsUnsafeInstructions(BasicBlock *BB, Instruction *Skip);
514 bool findInductionAndReductions(Loop *L,
528 bool isInnerReduction(Loop *L, PHINode *Phi,
529 SmallVectorImpl<Instruction *> &HasNoWrapInsts);
538 OptimizationRemarkEmitter *ORE;
542 SmallPtrSet<PHINode *, 4> OuterInnerReductions;
550 SmallVector<Instruction *, 4> HasNoWrapReductions;
559class CacheCostManager {
561 LoopStandardAnalysisResults *AR;
566 std::optional<std::unique_ptr<CacheCost>> CC;
570 DenseMap<const Loop *, unsigned> CostMap;
572 void computeIfUnitinialized();
575 CacheCostManager(Loop *OutermostLoop, LoopStandardAnalysisResults *AR,
577 : OutermostLoop(OutermostLoop), AR(AR), DI(DI) {}
578 CacheCost *getCacheCost();
579 const DenseMap<const Loop *, unsigned> &getCostMap();
584class LoopInterchangeProfitability {
586 LoopInterchangeProfitability(Loop *Outer, Loop *Inner, ScalarEvolution *SE,
587 OptimizationRemarkEmitter *ORE)
588 : OuterLoop(
Outer), InnerLoop(Inner), SE(SE), ORE(ORE) {}
591 bool isProfitable(
const Loop *InnerLoop,
const Loop *OuterLoop,
592 unsigned InnerLoopId,
unsigned OuterLoopId,
593 CharMatrix &DepMatrix, CacheCostManager &CCM);
596 int getInstrOrderCost();
597 std::optional<bool> isProfitablePerLoopCacheAnalysis(
598 const DenseMap<const Loop *, unsigned> &CostMap, CacheCost *CC);
599 std::optional<bool> isProfitablePerInstrOrderCost();
600 std::optional<bool> isProfitableForVectorization(
unsigned InnerLoopId,
601 unsigned OuterLoopId,
602 CharMatrix &DepMatrix);
610 OptimizationRemarkEmitter *ORE;
614class LoopInterchangeTransform {
616 LoopInterchangeTransform(Loop *Outer, Loop *Inner, ScalarEvolution *SE,
617 LoopInfo *LI, DominatorTree *DT,
618 const LoopInterchangeLegality &LIL)
619 : OuterLoop(
Outer), InnerLoop(Inner), SE(SE), LI(LI), DT(DT), LIL(LIL) {}
623 void reduction2Memory();
624 void restructureLoops(Loop *NewInner, Loop *NewOuter,
625 BasicBlock *OrigInnerPreHeader,
626 BasicBlock *OrigOuterPreHeader);
627 void removeChildLoop(Loop *OuterLoop, Loop *InnerLoop);
630 bool adjustLoopLinks();
631 bool adjustLoopBranches();
642 const LoopInterchangeLegality &LIL;
645struct LoopInterchange {
646 ScalarEvolution *SE =
nullptr;
647 LoopInfo *LI =
nullptr;
648 DependenceInfo *DI =
nullptr;
649 DominatorTree *DT =
nullptr;
650 LoopStandardAnalysisResults *AR =
nullptr;
653 OptimizationRemarkEmitter *ORE;
655 LoopInterchange(ScalarEvolution *SE, LoopInfo *LI, DependenceInfo *DI,
656 DominatorTree *DT, LoopStandardAnalysisResults *AR,
657 OptimizationRemarkEmitter *ORE)
658 : SE(SE), LI(LI), DI(DI), DT(DT), AR(AR), ORE(ORE) {}
661 if (
L->getParentLoop())
663 SmallVector<Loop *, 8> LoopList;
665 return processLoopList(LoopList);
668 bool run(LoopNest &LN) {
669 SmallVector<Loop *, 8> LoopList(LN.
getLoops());
670 for (
unsigned I = 1;
I < LoopList.size(); ++
I)
671 if (LoopList[
I]->getParentLoop() != LoopList[
I - 1])
673 return processLoopList(LoopList);
679 return LoopList.
size() - 1;
682 bool processLoopList(SmallVectorImpl<Loop *> &LoopList) {
687 "Unsupported depth of loop nest.");
689 unsigned LoopNestDepth = LoopList.
size();
692 dbgs() <<
"Processing LoopList of size = " << LoopNestDepth
693 <<
" containing the following loops:\n";
694 for (
auto *L : LoopList) {
700 CharMatrix DependencyMatrix;
701 Loop *OuterMostLoop = *(LoopList.begin());
703 OuterMostLoop, DI, SE, ORE)) {
715 <<
"' needs an unique exit block");
719 unsigned SelecLoopId = selectLoopForInterchange(LoopList);
720 CacheCostManager CCM(LoopList[0], AR, DI);
725 for (
unsigned j = SelecLoopId;
j > 0;
j--) {
726 bool ChangedPerIter =
false;
727 for (
unsigned i = SelecLoopId; i > SelecLoopId -
j; i--) {
729 processLoop(LoopList, i, i - 1, DependencyMatrix, CCM);
730 ChangedPerIter |= Interchanged;
741 bool processLoop(SmallVectorImpl<Loop *> &LoopList,
unsigned InnerLoopId,
742 unsigned OuterLoopId,
743 std::vector<std::vector<char>> &DependencyMatrix,
744 CacheCostManager &CCM) {
745 Loop *OuterLoop = LoopList[OuterLoopId];
746 Loop *InnerLoop = LoopList[InnerLoopId];
748 <<
" and OuterLoopId = " << OuterLoopId <<
"\n");
749 LoopInterchangeLegality LIL(OuterLoop, InnerLoop, SE, ORE, DT);
750 if (!LIL.canInterchangeLoops(InnerLoopId, OuterLoopId, DependencyMatrix)) {
751 LLVM_DEBUG(
dbgs() <<
"Cannot prove legality, not interchanging loops '"
752 << OuterLoop->
getName() <<
"' and '"
753 << InnerLoop->
getName() <<
"'\n");
758 <<
"' are legal to interchange\n");
759 LoopInterchangeProfitability LIP(OuterLoop, InnerLoop, SE, ORE);
760 if (!LIP.isProfitable(InnerLoop, OuterLoop, InnerLoopId, OuterLoopId,
761 DependencyMatrix, CCM)) {
763 <<
"' and '" << InnerLoop->
getName()
764 <<
"' not profitable.\n");
769 return OptimizationRemark(
DEBUG_TYPE,
"Interchanged",
772 <<
"Loop interchanged with enclosing loop.";
775 LoopInterchangeTransform LIT(OuterLoop, InnerLoop, SE, LI, DT, LIL);
776 LIT.transform(LIL.getHasNoWrapReductions());
778 << OuterLoop->
getName() <<
"' and inner loop '"
779 << InnerLoop->
getName() <<
"'\n");
785 std::swap(LoopList[OuterLoopId], LoopList[InnerLoopId]);
798bool LoopInterchangeLegality::containsUnsafeInstructions(
BasicBlock *BB,
800 return any_of(*BB, [Skip](
const Instruction &
I) {
803 return I.mayHaveSideEffects() ||
I.mayReadFromMemory();
807bool LoopInterchangeLegality::tightlyNested(Loop *OuterLoop, Loop *InnerLoop) {
813 <<
"' and '" << InnerLoop->
getName()
814 <<
"' are tightly nested\n");
819 for (BasicBlock *Succ :
successors(OuterLoopHeader))
820 if (Succ != InnerLoopPreHeader && Succ != InnerLoop->
getHeader() &&
821 Succ != OuterLoopLatch)
824 LLVM_DEBUG(
dbgs() <<
"Checking instructions in Loop header and Loop latch\n");
830 assert(InnerReductions.size() <= 1 &&
831 "So far we only support at most one reduction.");
832 if (InnerReductions.size() == 1)
833 Skip = InnerReductions[0].LcssaStore;
837 if (containsUnsafeInstructions(OuterLoopHeader, Skip) ||
838 containsUnsafeInstructions(OuterLoopLatch, Skip))
844 if (InnerLoopPreHeader != OuterLoopHeader &&
845 containsUnsafeInstructions(InnerLoopPreHeader, Skip))
853 if (&SuccInner != OuterLoopLatch) {
855 <<
" does not lead to the outer loop latch.\n";);
861 if (containsUnsafeInstructions(InnerLoopExit, Skip))
869bool LoopInterchangeLegality::isLoopStructureUnderstood() {
871 for (PHINode *InnerInduction : InnerLoopInductions) {
872 unsigned Num = InnerInduction->getNumOperands();
873 for (
unsigned i = 0; i < Num; ++i) {
874 Value *Val = InnerInduction->getOperand(i);
884 if (InnerInduction->getIncomingBlock(IncomBlockIndx) ==
885 InnerLoopPreheader &&
899 CondBrInst *InnerLoopLatchBI =
901 if (!InnerLoopLatchBI)
903 if (CmpInst *InnerLoopCmp =
905 Value *Op0 = InnerLoopCmp->getOperand(0);
906 Value *Op1 = InnerLoopCmp->getOperand(1);
917 std::function<bool(
Value *)> IsPathToInnerIndVar;
918 IsPathToInnerIndVar = [
this, &IsPathToInnerIndVar](
const Value *
V) ->
bool {
927 return IsPathToInnerIndVar(
I->getOperand(0));
929 return IsPathToInnerIndVar(
I->getOperand(0)) &&
930 IsPathToInnerIndVar(
I->getOperand(1));
936 if (IsPathToInnerIndVar(Op0) && IsPathToInnerIndVar(Op1))
944 }
else if (IsPathToInnerIndVar(Op1) && !
isa<Constant>(Op1)) {
967 if (
PHI->getNumIncomingValues() != 1)
1024 assert(
I->getOpcode() == OpCode &&
1025 "Expected the instruction to be the reduction operation");
1030 if (
I->hasNoSignedWrap() ||
I->hasNoUnsignedWrap())
1053 if (
PHI->getNumIncomingValues() == 1)
1066bool LoopInterchangeLegality::isInnerReduction(
1067 Loop *L, PHINode *Phi, SmallVectorImpl<Instruction *> &HasNoWrapInsts) {
1071 if (!
L->isInnermost()) {
1072 LLVM_DEBUG(
dbgs() <<
"Only supported when the loop is the innermost.\n");
1074 return OptimizationRemarkMissed(
DEBUG_TYPE,
"UnsupportedInnerReduction",
1075 L->getStartLoc(),
L->getHeader())
1076 <<
"Only supported when the loop is the innermost.";
1081 if (
Phi->getNumIncomingValues() != 2)
1084 Value *Init =
Phi->getIncomingValueForBlock(
L->getLoopPreheader());
1085 Value *
Next =
Phi->getIncomingValueForBlock(
L->getLoopLatch());
1091 <<
"Only supported for the reduction with a constant initial value.\n");
1093 return OptimizationRemarkMissed(
DEBUG_TYPE,
"UnsupportedInnerReduction",
1094 L->getStartLoc(),
L->getHeader())
1095 <<
"Only supported for the reduction with a constant initial "
1104 if (!
L->contains(BB))
1109 if (!
Phi->hasOneUser())
1121 PHINode *Lcssa = NULL;
1122 for (
auto *U :
Next->users()) {
1127 if (Lcssa == NULL &&
P->getParent() == ExitBlock &&
1128 P->getIncomingValueForBlock(
L->getLoopLatch()) ==
Next)
1139 LLVM_DEBUG(
dbgs() <<
"Only supported when the reduction is used once in "
1140 "the outer loop.\n");
1142 return OptimizationRemarkMissed(
DEBUG_TYPE,
"UnsupportedInnerReduction",
1143 L->getStartLoc(),
L->getHeader())
1144 <<
"Only supported when the reduction is used once in the outer "
1150 StoreInst *LcssaStore =
1152 if (!LcssaStore || LcssaStore->
getParent() != ExitBlock)
1165 LLVM_DEBUG(
dbgs() <<
"Only supported when memory reference dominate "
1166 "the inner loop.\n");
1168 return OptimizationRemarkMissed(
DEBUG_TYPE,
"UnsupportedInnerReduction",
1169 L->getStartLoc(),
L->getHeader())
1170 <<
"Only supported when memory reference dominate the inner "
1181 SR.LcssaPhi = Lcssa;
1182 SR.LcssaStore = LcssaStore;
1186 InnerReductions.push_back(SR);
1190bool LoopInterchangeLegality::findInductionAndReductions(
1192 if (!
L->getLoopLatch() || !
L->getLoopPredecessor())
1194 for (PHINode &
PHI :
L->getHeader()->phis()) {
1195 InductionDescriptor
ID;
1202 if (OuterInnerReductions.count(&
PHI)) {
1203 LLVM_DEBUG(
dbgs() <<
"Found a reduction across the outer loop.\n");
1205 isInnerReduction(L, &
PHI, HasNoWrapReductions)) {
1211 assert(
PHI.getNumIncomingValues() == 2 &&
1212 "Phis in loop header should have exactly 2 incoming values");
1216 PHINode *InnerRedPhi =
1222 <<
"Failed to recognize PHI as an induction or reduction.\n");
1225 OuterInnerReductions.insert(&
PHI);
1226 OuterInnerReductions.insert(InnerRedPhi);
1232 if (InnerReductions.size() > 1) {
1235 return OptimizationRemarkMissed(
DEBUG_TYPE,
"UnsupportedInnerReduction",
1236 L->getStartLoc(),
L->getHeader())
1237 <<
"Only supports at most one reduction.";
1247bool LoopInterchangeLegality::currentLimitations() {
1257 dbgs() <<
"Loops where the latch is not the exiting block are not"
1258 <<
" supported currently.\n");
1260 return OptimizationRemarkMissed(
DEBUG_TYPE,
"ExitingNotLatch",
1263 <<
"Loops where the latch is not the exiting block cannot be"
1264 " interchange currently.";
1270 if (!findInductionAndReductions(OuterLoop, Inductions, InnerLoop)) {
1272 dbgs() <<
"Only outer loops with induction or reduction PHI nodes "
1273 <<
"are supported currently.\n");
1275 return OptimizationRemarkMissed(
DEBUG_TYPE,
"UnsupportedPHIOuter",
1278 <<
"Only outer loops with induction or reduction PHI nodes can be"
1279 " interchanged currently.";
1288 Loop *CurLevelLoop = OuterLoop;
1291 CurLevelLoop = CurLevelLoop->
getSubLoops().front();
1292 if (!findInductionAndReductions(CurLevelLoop, Inductions,
nullptr)) {
1294 dbgs() <<
"Only inner loops with induction or reduction PHI nodes "
1295 <<
"are supported currently.\n");
1297 return OptimizationRemarkMissed(
DEBUG_TYPE,
"UnsupportedPHIInner",
1300 <<
"Only inner loops with induction or reduction PHI nodes can be"
1301 " interchange currently.";
1308 if (!isLoopStructureUnderstood()) {
1311 return OptimizationRemarkMissed(
DEBUG_TYPE,
"UnsupportedStructureInner",
1314 <<
"Inner loop structure not understood currently.";
1322bool LoopInterchangeLegality::findInductions(
1323 Loop *L, SmallVectorImpl<PHINode *> &Inductions) {
1324 for (PHINode &
PHI :
L->getHeader()->phis()) {
1325 InductionDescriptor
ID;
1329 return !Inductions.
empty();
1343 if (
PHI.getNumIncomingValues() > 1)
1345 if (&
PHI == LcssaReduction)
1348 PHINode *PN = dyn_cast<PHINode>(U);
1350 (!Reductions.count(PN) && OuterL->contains(PN->getParent()));
1415 for (
auto *U :
PHI.users()) {
1424bool LoopInterchangeLegality::canInterchangeLoops(
unsigned InnerLoopId,
1425 unsigned OuterLoopId,
1426 CharMatrix &DepMatrix) {
1428 LLVM_DEBUG(
dbgs() <<
"Failed interchange InnerLoopId = " << InnerLoopId
1429 <<
" and OuterLoopId = " << OuterLoopId
1430 <<
" due to dependence\n");
1432 return OptimizationRemarkMissed(
DEBUG_TYPE,
"Dependence",
1435 <<
"Cannot interchange loops due to dependences.";
1440 for (
auto *BB : OuterLoop->
blocks())
1444 if (CI->onlyWritesMemory())
1447 dbgs() <<
"Loops with call instructions cannot be interchanged "
1450 return OptimizationRemarkMissed(
DEBUG_TYPE,
"CallInst",
1453 <<
"Cannot interchange loops due to call instruction.";
1459 if (!findInductions(InnerLoop, InnerLoopInductions)) {
1460 LLVM_DEBUG(
dbgs() <<
"Could not find inner loop induction variables.\n");
1465 LLVM_DEBUG(
dbgs() <<
"Found unsupported PHI nodes in inner loop latch.\n");
1467 return OptimizationRemarkMissed(
DEBUG_TYPE,
"UnsupportedInnerLatchPHI",
1470 <<
"Cannot interchange loops because unsupported PHI nodes found "
1471 "in inner loop latch.";
1478 if (currentLimitations()) {
1479 LLVM_DEBUG(
dbgs() <<
"Not legal because of current transform limitation\n");
1484 if (!tightlyNested(OuterLoop, InnerLoop)) {
1487 return OptimizationRemarkMissed(
DEBUG_TYPE,
"NotTightlyNested",
1490 <<
"Cannot interchange loops because they are not tightly "
1498 PHINode *LcssaReduction =
nullptr;
1499 assert(InnerReductions.size() <= 1 &&
1500 "So far we only support at most one reduction.");
1501 if (InnerReductions.size() == 1)
1502 LcssaReduction = InnerReductions[0].LcssaPhi;
1506 LLVM_DEBUG(
dbgs() <<
"Found unsupported PHI nodes in inner loop exit.\n");
1508 return OptimizationRemarkMissed(
DEBUG_TYPE,
"UnsupportedExitPHI",
1511 <<
"Found unsupported PHI node in loop exit.";
1517 LLVM_DEBUG(
dbgs() <<
"Found unsupported PHI nodes in outer loop exit.\n");
1519 return OptimizationRemarkMissed(
DEBUG_TYPE,
"UnsupportedExitPHI",
1522 <<
"Found unsupported PHI node in loop exit.";
1530void CacheCostManager::computeIfUnitinialized() {
1545 for (
const auto &[Idx,
Cost] :
enumerate((*CC)->getLoopCosts()))
1546 CostMap[
Cost.first] = Idx;
1549CacheCost *CacheCostManager::getCacheCost() {
1550 computeIfUnitinialized();
1554const DenseMap<const Loop *, unsigned> &CacheCostManager::getCostMap() {
1555 computeIfUnitinialized();
1559int LoopInterchangeProfitability::getInstrOrderCost() {
1560 unsigned GoodOrder, BadOrder;
1561 BadOrder = GoodOrder = 0;
1562 for (BasicBlock *BB : InnerLoop->
blocks()) {
1563 for (Instruction &Ins : *BB) {
1565 bool FoundInnerInduction =
false;
1566 bool FoundOuterInduction =
false;
1572 const SCEV *OperandVal = SE->
getSCEV(
Op);
1582 if (AR->
getLoop() == InnerLoop) {
1585 FoundInnerInduction =
true;
1586 if (FoundOuterInduction) {
1596 if (AR->
getLoop() == OuterLoop) {
1599 FoundOuterInduction =
true;
1600 if (FoundInnerInduction) {
1609 return GoodOrder - BadOrder;
1613LoopInterchangeProfitability::isProfitablePerLoopCacheAnalysis(
1614 const DenseMap<const Loop *, unsigned> &CostMap, CacheCost *CC) {
1618 auto InnerLoopIt = CostMap.
find(InnerLoop);
1619 if (InnerLoopIt == CostMap.
end())
1620 return std::nullopt;
1621 auto OuterLoopIt = CostMap.
find(OuterLoop);
1622 if (OuterLoopIt == CostMap.
end())
1623 return std::nullopt;
1626 return std::nullopt;
1627 unsigned InnerIndex = InnerLoopIt->second;
1628 unsigned OuterIndex = OuterLoopIt->second;
1630 <<
", OuterIndex = " << OuterIndex <<
"\n");
1631 assert(InnerIndex != OuterIndex &&
"CostMap should assign unique "
1632 "numbers to each loop");
1633 return std::optional<bool>(InnerIndex < OuterIndex);
1637LoopInterchangeProfitability::isProfitablePerInstrOrderCost() {
1641 int Cost = getInstrOrderCost();
1644 return std::optional<bool>(
true);
1646 return std::nullopt;
1651 for (
const auto &Dep : DepMatrix) {
1652 char Dir = Dep[LoopId];
1653 char DepType = Dep.back();
1654 assert((DepType ==
'<' || DepType ==
'*') &&
1655 "Unexpected element in dependency vector");
1658 if (Dir ==
'=' || Dir ==
'I')
1664 if (Dir ==
'<' && DepType ==
'<')
1673std::optional<bool> LoopInterchangeProfitability::isProfitableForVectorization(
1674 unsigned InnerLoopId,
unsigned OuterLoopId, CharMatrix &DepMatrix) {
1690 return std::nullopt;
1693bool LoopInterchangeProfitability::isProfitable(
1694 const Loop *InnerLoop,
const Loop *OuterLoop,
unsigned InnerLoopId,
1695 unsigned OuterLoopId, CharMatrix &DepMatrix, CacheCostManager &CCM) {
1704 if (InnerBTC && InnerBTC->
isZero()) {
1705 LLVM_DEBUG(
dbgs() <<
"Inner loop back-edge isn't taken, rejecting "
1706 "single iteration loop\n");
1709 if (OuterBTC && OuterBTC->
isZero()) {
1710 LLVM_DEBUG(
dbgs() <<
"Outer loop back-edge isn't taken, rejecting "
1711 "single iteration loop\n");
1719 "Duplicate rules and option 'ignore' are not allowed");
1729 std::optional<bool> shouldInterchange;
1732 case RuleTy::PerLoopCacheAnalysis: {
1733 CacheCost *CC = CCM.getCacheCost();
1734 const DenseMap<const Loop *, unsigned> &CostMap = CCM.getCostMap();
1735 shouldInterchange = isProfitablePerLoopCacheAnalysis(CostMap, CC);
1738 case RuleTy::PerInstrOrderCost:
1739 shouldInterchange = isProfitablePerInstrOrderCost();
1741 case RuleTy::ForVectorization:
1743 isProfitableForVectorization(InnerLoopId, OuterLoopId, DepMatrix);
1745 case RuleTy::Ignore:
1752 if (shouldInterchange.has_value())
1756 if (!shouldInterchange.has_value()) {
1758 return OptimizationRemarkMissed(
DEBUG_TYPE,
"InterchangeNotProfitable",
1761 <<
"Insufficient information to calculate the cost of loop for "
1765 }
else if (!shouldInterchange.value()) {
1767 return OptimizationRemarkMissed(
DEBUG_TYPE,
"InterchangeNotProfitable",
1770 <<
"Interchanging loops is not considered to improve cache "
1771 "locality nor vectorization.";
1778void LoopInterchangeTransform::removeChildLoop(Loop *OuterLoop,
1780 for (Loop *L : *OuterLoop)
1781 if (L == InnerLoop) {
1782 OuterLoop->removeChildLoop(L);
1811void LoopInterchangeTransform::restructureLoops(
1812 Loop *NewInner, Loop *NewOuter, BasicBlock *OrigInnerPreHeader,
1813 BasicBlock *OrigOuterPreHeader) {
1814 Loop *OuterLoopParent = OuterLoop->getParentLoop();
1821 if (OuterLoopParent) {
1823 removeChildLoop(OuterLoopParent, NewInner);
1824 removeChildLoop(NewInner, NewOuter);
1827 removeChildLoop(NewInner, NewOuter);
1835 SmallVector<BasicBlock *, 8> OrigInnerBBs(NewOuter->
blocks());
1839 for (BasicBlock *BB : NewInner->
blocks())
1847 for (BasicBlock *BB : OrigInnerBBs) {
1852 if (BB == OuterHeader || BB == OuterLatch)
1890void LoopInterchangeTransform::reduction2Memory() {
1892 LIL.getInnerReductions();
1895 "So far we only support at most one reduction.");
1897 LoopInterchangeLegality::InnerReduction SR = InnerReductions[0];
1903 PHINode *FirstIter =
1904 Builder.CreatePHI(Type::getInt1Ty(
Context), 2,
"first.iter");
1909 assert(FirstIter->
isComplete() &&
"The FirstIter PHI node is not complete.");
1914 Instruction *LoadMem = Builder.CreateLoad(SR.ElemTy, SR.MemRef);
1917 Value *NewVar = Builder.CreateSelect(FirstIter, SR.Init, LoadMem,
"new.var");
1928bool LoopInterchangeTransform::transform(
1930 bool Transformed =
false;
1933 LIL.getInnerReductions();
1934 if (InnerReductions.
size() == 1)
1940 auto &InductionPHIs = LIL.getInnerLoopInductions();
1941 if (InductionPHIs.empty()) {
1942 LLVM_DEBUG(
dbgs() <<
"Failed to find the point to split loop latch \n");
1946 SmallVector<Instruction *, 8> InnerIndexVarList;
1947 for (PHINode *CurInductionPHI : InductionPHIs) {
1948 if (CurInductionPHI->getIncomingBlock(0) == InnerLoopPreHeader)
1964 SmallSetVector<Instruction *, 4> WorkList;
1966 auto MoveInstructions = [&i, &WorkList,
this, &InductionPHIs, NewLatch]() {
1967 for (; i < WorkList.
size(); i++) {
1973 "Moving instructions with side-effects may change behavior of "
1984 for (
Value *
Op : WorkList[i]->operands()) {
2002 for (Instruction *InnerIndexVar : InnerIndexVarList)
2021 BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
2022 if (InnerLoopPreHeader != OuterLoopHeader) {
2023 for (Instruction &
I :
2025 std::prev(InnerLoopPreHeader->
end()))))
2029 Transformed |= adjustLoopLinks();
2037 for (Instruction *
Reduction : DropNoWrapInsts) {
2061 I->removeFromParent();
2076 std::vector<DominatorTree::UpdateType> &DTUpdates,
2077 bool MustUpdateOnce =
true) {
2079 "BI must jump to OldBB exactly once.");
2081 for (
Use &
Op : Term->operands())
2088 DTUpdates.push_back(
2089 {DominatorTree::UpdateKind::Insert, Term->getParent(), NewBB});
2090 DTUpdates.push_back(
2091 {DominatorTree::UpdateKind::Delete, Term->getParent(), OldBB});
2110 assert(
P.getNumIncomingValues() == 1 &&
2111 "Only loops with a single exit are supported!");
2120 if (IncIInnerMost->getParent() != InnerLatch &&
2121 IncIInnerMost->
getParent() != InnerHeader)
2125 [OuterHeader, OuterExit, IncI, InnerHeader](
User *U) {
2126 return (cast<PHINode>(U)->getParent() == OuterHeader &&
2127 IncI->getParent() == InnerHeader) ||
2128 cast<PHINode>(U)->getParent() == OuterExit;
2130 "Can only replace phis iff the uses are in the loop nest exit or "
2131 "the incoming value is defined in the inner header (it will "
2132 "dominate all loop blocks after interchanging)");
2133 P.replaceAllUsesWith(IncI);
2134 P.eraseFromParent();
2162 if (
P.getNumIncomingValues() != 1)
2176 if (Pred == OuterLatch)
2181 P.setIncomingValue(0, NewPhi);
2221 if (OuterLoopLatch == InnerLoopExit)
2228 assert(Phi->getNumIncomingValues() == 1 &&
"Single input phi expected");
2229 LLVM_DEBUG(
dbgs() <<
"Removing 1-input phi in non-exit block: " << *Phi
2231 Phi->replaceAllUsesWith(Phi->getIncomingValue(0));
2232 Phi->eraseFromParent();
2236bool LoopInterchangeTransform::adjustLoopBranches() {
2238 std::vector<DominatorTree::UpdateType> DTUpdates;
2240 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader();
2243 assert(OuterLoopPreHeader != OuterLoop->getHeader() &&
2244 InnerLoopPreHeader != InnerLoop->
getHeader() && OuterLoopPreHeader &&
2245 InnerLoopPreHeader &&
"Guaranteed by loop-simplify form");
2255 OuterLoopPreHeader =
2257 if (InnerLoopPreHeader == OuterLoop->getHeader())
2258 InnerLoopPreHeader =
2263 BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
2265 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch();
2272 CondBrInst *OuterLoopLatchBI =
2274 CondBrInst *InnerLoopLatchBI =
2279 if (!OuterLoopPredecessor || !InnerLoopLatchPredecessor ||
2280 !OuterLoopLatchBI || !InnerLoopLatchBI || !OuterLoopHeaderBI ||
2288 if (!OuterLoopPredecessorBI || !InnerLoopLatchPredecessorBI)
2291 if (!InnerLoopHeaderSuccessor)
2299 InnerLoopPreHeader, DTUpdates,
false);
2309 InnerLoopHeaderSuccessor, DTUpdates,
2317 OuterLoopPreHeader, DTUpdates);
2320 if (InnerLoopLatchBI->
getSuccessor(0) == InnerLoopHeader)
2321 InnerLoopLatchSuccessor = InnerLoopLatchBI->
getSuccessor(1);
2323 InnerLoopLatchSuccessor = InnerLoopLatchBI->
getSuccessor(0);
2326 InnerLoopLatchSuccessor, DTUpdates);
2328 if (OuterLoopLatchBI->
getSuccessor(0) == OuterLoopHeader)
2329 OuterLoopLatchSuccessor = OuterLoopLatchBI->
getSuccessor(1);
2331 OuterLoopLatchSuccessor = OuterLoopLatchBI->
getSuccessor(0);
2334 OuterLoopLatchSuccessor, DTUpdates);
2335 updateSuccessor(OuterLoopLatchBI, OuterLoopLatchSuccessor, InnerLoopLatch,
2339 restructureLoops(OuterLoop, InnerLoop, InnerLoopPreHeader,
2340 OuterLoopPreHeader);
2342 moveLCSSAPhis(InnerLoopLatchSuccessor, InnerLoopHeader, InnerLoopLatch,
2343 OuterLoopHeader, OuterLoopLatch, InnerLoop->
getExitBlock(),
2349 auto &OuterInnerReductions = LIL.getOuterInnerReductions();
2352 for (PHINode &
PHI : InnerLoopHeader->
phis())
2353 if (OuterInnerReductions.contains(&
PHI))
2356 for (PHINode &
PHI : OuterLoopHeader->
phis())
2357 if (OuterInnerReductions.contains(&
PHI))
2363 for (PHINode *
PHI : OuterLoopPHIs) {
2366 assert(OuterInnerReductions.count(
PHI) &&
"Expected a reduction PHI node");
2368 for (PHINode *
PHI : InnerLoopPHIs) {
2371 assert(OuterInnerReductions.count(
PHI) &&
"Expected a reduction PHI node");
2384 SmallVector<Instruction *, 4> MayNeedLCSSAPhis;
2385 for (Instruction &
I :
2393bool LoopInterchangeTransform::adjustLoopLinks() {
2395 bool Changed = adjustLoopBranches();
2400 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader();
2425 LLVM_DEBUG(
dbgs() <<
"Not valid loop candidate for interchange\n");
2433 <<
"Computed dependence info, invoking the transform.";
2437 if (!LoopInterchange(&AR.
SE, &AR.
LI, &DI, &AR.
DT, &AR, &ORE).run(LN))
2439 U.markLoopNestChanged(
true);
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the StringMap class.
ReachingDefInfo InstSet InstSet & Ignore
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
static void moveBBContents(BasicBlock &SourceBB, BasicBlock &TargetBB)
Move the contents of SourceBB to before the last instruction of TargetBB.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
This file defines the interface for the loop cache analysis.
SmallVector< Loop *, 4 > LoopVector
Loop::LoopBounds::Direction Direction
static cl::opt< unsigned int > MaxMemInstrCount("loop-interchange-max-meminstr-count", cl::init(64), cl::Hidden, cl::desc("Maximum number of load-store instructions that should be handled " "in the dependency matrix. Higher value may lead to more interchanges " "at the cost of compile-time"))
static cl::opt< int > LoopInterchangeCostThreshold("loop-interchange-threshold", cl::init(0), cl::Hidden, cl::desc("Interchange if you gain more than this number"))
static PHINode * findInnerReductionPhi(Loop *L, Value *V, SmallVectorImpl< Instruction * > &HasNoWrapInsts)
static cl::opt< unsigned int > MinLoopNestDepth("loop-interchange-min-loop-nest-depth", cl::init(2), cl::Hidden, cl::desc("Minimum depth of loop nest considered for the transform"))
static void updateSuccessor(Instruction *Term, BasicBlock *OldBB, BasicBlock *NewBB, std::vector< DominatorTree::UpdateType > &DTUpdates, bool MustUpdateOnce=true)
static cl::opt< bool > EnableReduction2Memory("loop-interchange-reduction-to-mem", cl::init(false), cl::Hidden, cl::desc("Support for the inner-loop reduction pattern."))
static bool isComputableLoopNest(ScalarEvolution *SE, ArrayRef< Loop * > LoopList)
static bool areOuterLoopExitPHIsSupported(Loop *OuterLoop, Loop *InnerLoop)
static void simplifyLCSSAPhis(Loop *OuterLoop, Loop *InnerLoop)
This deals with a corner case when a LCSSA phi node appears in a non-exit block: the outer loop latch...
static void interChangeDependencies(CharMatrix &DepMatrix, unsigned FromIndx, unsigned ToIndx)
static void moveLCSSAPhis(BasicBlock *InnerExit, BasicBlock *InnerHeader, BasicBlock *InnerLatch, BasicBlock *OuterHeader, BasicBlock *OuterLatch, BasicBlock *OuterExit, Loop *InnerLoop, LoopInfo *LI)
static void printDepMatrix(CharMatrix &DepMatrix)
static void swapBBContents(BasicBlock *BB1, BasicBlock *BB2)
Swap instructions between BB1 and BB2 but keep terminators intact.
static bool areInnerLoopExitPHIsSupported(Loop *InnerL, Loop *OuterL, SmallPtrSetImpl< PHINode * > &Reductions, PHINode *LcssaReduction)
static cl::opt< unsigned int > MaxLoopNestDepth("loop-interchange-max-loop-nest-depth", cl::init(10), cl::Hidden, cl::desc("Maximum depth of loop nest considered for the transform"))
static bool hasSupportedLoopDepth(ArrayRef< Loop * > LoopList, OptimizationRemarkEmitter &ORE)
static bool inThisOrder(const Instruction *Src, const Instruction *Dst)
Return true if Src appears before Dst in the same basic block.
static bool areInnerLoopLatchPHIsSupported(Loop *OuterLoop, Loop *InnerLoop)
static bool canVectorize(const CharMatrix &DepMatrix, unsigned LoopId)
Return true if we can vectorize the loop specified by LoopId.
static bool isLegalToInterChangeLoops(CharMatrix &DepMatrix, unsigned InnerLoopId, unsigned OuterLoopId)
static Value * followLCSSA(Value *SV)
static void populateWorklist(Loop &L, LoopVector &LoopList)
static bool checkReductionKind(Loop *L, PHINode *PHI, SmallVectorImpl< Instruction * > &HasNoWrapInsts)
static bool populateDependencyMatrix(CharMatrix &DepMatrix, unsigned Level, Loop *L, DependenceInfo *DI, ScalarEvolution *SE, OptimizationRemarkEmitter *ORE)
static cl::list< RuleTy > Profitabilities("loop-interchange-profitabilities", cl::MiscFlags::CommaSeparated, cl::Hidden, cl::desc("List of profitability heuristics to be used. They are applied in " "the given order"), cl::list_init< RuleTy >({RuleTy::PerLoopCacheAnalysis, RuleTy::PerInstrOrderCost, RuleTy::ForVectorization}), cl::values(clEnumValN(RuleTy::PerLoopCacheAnalysis, "cache", "Prioritize loop cache cost"), clEnumValN(RuleTy::PerInstrOrderCost, "instorder", "Prioritize the IVs order of each instruction"), clEnumValN(RuleTy::ForVectorization, "vectorize", "Prioritize vectorization"), clEnumValN(RuleTy::Ignore, "ignore", "Ignore profitability, force interchange (does not " "work with other options)")))
static std::optional< bool > isLexicographicallyPositive(ArrayRef< char > DV, unsigned Begin, unsigned End)
static bool noDuplicateRulesAndIgnore(ArrayRef< RuleTy > Rules)
This file defines the interface for the loop nest analysis.
This header provides classes for managing a pipeline of passes over loops in LLVM IR.
loop Loop Strength Reduction
uint64_t IntrinsicInst * II
SmallVector< Value *, 8 > ValueVector
This file defines the SmallSet class.
This file defines the SmallVector class.
static bool isProfitable(const StableFunctionMap::StableFunctionEntries &SFS)
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
const T & front() const
front - Get the first element.
size_t size() const
size - Get the array size.
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array.
LLVM Basic Block Representation.
iterator begin()
Instruction iterator methods.
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
const Function * getParent() const
Return the enclosing method, or null if none.
LLVM_ABI iterator_range< filter_iterator< BasicBlock::const_iterator, std::function< bool(const Instruction &)> > > instructionsWithoutDebug(bool SkipPseudoOp=true) const
Return a const iterator range over the instructions in the block, skipping any debug instructions.
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
LLVM_ABI const BasicBlock * getUniqueSuccessor() const
Return the successor of this block if it has a unique successor.
LLVM_ABI 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.
LLVM_ABI const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
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...
void splice(BasicBlock::iterator ToIt, BasicBlock *FromBB)
Transfer all instructions from FromBB to this basic block at ToIt.
static std::unique_ptr< CacheCost > getCacheCost(Loop &Root, LoopStandardAnalysisResults &AR, DependenceInfo &DI, std::optional< unsigned > TRT=std::nullopt)
Create a CacheCost for the loop nest rooted by Root.
CacheCostTy getLoopCost(const Loop &L) const
Return the estimated cost of loop L if the given loop is part of the loop nest associated with this o...
Value * getCondition() const
BasicBlock * getSuccessor(unsigned i) const
iterator find(const_arg_type_t< KeyT > Val)
DependenceInfo - This class is the main dependence-analysis driver.
LLVM_ABI std::unique_ptr< Dependence > depends(Instruction *Src, Instruction *Dst, bool UnderRuntimeAssumptions=false)
depends - Tests for a dependence between the Src and Dst instructions.
void applyUpdates(ArrayRef< UpdateType > Updates)
Inform the dominator tree about a sequence of CFG edge insertions and deletions and perform a batch u...
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
static LLVM_ABI 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.
LLVM_ABI void moveAfter(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
LLVM_ABI bool mayHaveSideEffects() const LLVM_READONLY
Return true if the instruction may have side effects.
This class provides an interface for updating the loop pass manager based on mutations to the loop ne...
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
bool isInnermost() const
Return true if the loop does not contain any (natural) loops.
void removeBlockFromLoop(BlockT *BB)
This removes the specified basic block from the current loop, updating the Blocks as appropriate.
const std::vector< LoopT * > & getSubLoops() const
Return the loops contained entirely within this loop.
BlockT * getHeader() const
iterator_range< block_iterator > blocks() const
void addChildLoop(LoopT *NewChild)
Add the specified loop to be a child of this loop.
void addBlockEntry(BlockT *BB)
This adds a basic block directly to the basic block list.
BlockT * getExitBlock() const
If getExitBlocks would return exactly one block, return that block.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
BlockT * getExitingBlock() const
If getExitingBlocks would return exactly one block, return that block.
BlockT * getUniqueExitBlock() const
If getUniqueExitBlocks would return exactly one block, return that block.
LoopT * removeChildLoop(iterator I)
This removes the specified child from being a subloop of this loop.
void changeTopLevelLoop(LoopT *OldLoop, LoopT *NewLoop)
Replace the specified loop in the top-level loops list with the indicated loop.
void changeLoopFor(BlockT *BB, LoopT *L)
Change the top-level loop that contains BB to the specified loop.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
This class represents a loop nest and can be used to query its properties.
static const BasicBlock & skipEmptyBlockUntil(const BasicBlock *From, const BasicBlock *End, bool CheckUniquePred=false)
Recursivelly traverse all empty 'single successor' basic blocks of From (if there are any).
ArrayRef< Loop * > getLoops() const
Get the loops in the nest.
Function * getParent() const
Return the function to which the loop-nest belongs.
Loop & getOutermostLoop() const
Return the outermost loop in the loop nest.
Represents a single loop in the control flow graph.
DebugLoc getStartLoc() const
Return the debug location of the start of this loop.
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
StringRef getName() const
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
bool isComplete() const
If the PHI node is complete which means all of its parent's predecessors have incoming value in this ...
op_range incoming_values()
void setIncomingBlock(unsigned i, BasicBlock *BB)
void setIncomingValue(unsigned i, Value *V)
static unsigned getIncomingValueNumForOperand(unsigned i)
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
The RecurrenceDescriptor is used to identify recurrences variables in a loop.
Instruction * getExactFPMathInst() const
Returns 1st non-reassociative FP instruction in the PHI node's use-chain.
unsigned getOpcode() const
static LLVM_ABI bool isReductionPHI(PHINode *Phi, Loop *TheLoop, RecurrenceDescriptor &RedDes, DemandedBits *DB=nullptr, AssumptionCache *AC=nullptr, DominatorTree *DT=nullptr, ScalarEvolution *SE=nullptr)
Returns true if Phi is a reduction in TheLoop.
LLVM_ABI SmallVector< Instruction *, 4 > getReductionOpChain(PHINode *Phi, Loop *L) const
Attempts to find a chain of operations from Phi to LoopExitInst that can be treated as a set of reduc...
RecurKind getRecurrenceKind() const
const Loop * getLoop() const
This class represents an analyzed expression in the program.
LLVM_ABI bool isZero() const
Return true if the expression is a constant zero.
The main scalar evolution driver.
LLVM_ABI 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...
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
LLVM_ABI void forgetLoop(const Loop *L)
This method should be called by the client when it has changed a loop in a way that may effect Scalar...
LLVM_ABI bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
LLVM_ABI bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
size_type size() const
Determine the number of elements in the SetVector.
bool insert(const value_type &X)
Insert a new element into the SetVector.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
std::pair< iterator, bool > try_emplace(StringRef Key, ArgsTy &&...Args)
Emplace a new element for the specified key into the map if the key isn't already in the map.
StringRef - Represent a constant reference to a string, i.e.
constexpr size_t size() const
size - Get the string size.
A Use represents the edge between a Value definition and its users.
void setOperand(unsigned i, Value *Val)
Value * getOperand(unsigned i) const
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI bool hasOneUser() const
Return true if there is exactly one user of this value.
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
iterator_range< user_iterator > users()
LLVM_ABI User * getUniqueUndroppableUser()
Return true if there is exactly one unique user of this value that cannot be dropped (that user can h...
const ParentTy * getParent() const
self_iterator getIterator()
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
@ BasicBlock
Various leaf nodes.
list_initializer< Ty > list_init(ArrayRef< Ty > Vals)
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
initializer< Ty > init(const Ty &Val)
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
NodeAddr< PhiNode * > Phi
friend class Instruction
Iterator for Instructions in a `BasicBlock.
This is an optimization pass for GlobalISel generic memory operations.
FunctionAddr VTableAddr Value
LLVM_ABI 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...
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
auto successors(const MachineBasicBlock *BB)
LLVM_ABI bool formLCSSARecursively(Loop &L, const DominatorTree &DT, const LoopInfo *LI, ScalarEvolution *SE)
Put a loop nest into LCSSA form.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
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...
constexpr auto equal_to(T &&Arg)
Functor variant of std::equal_to that can be used as a UnaryPredicate in functional algorithms like a...
auto map_range(ContainerTy &&C, FuncTy F)
Return a range that applies F to the elements of C.
AnalysisManager< Loop, LoopStandardAnalysisResults & > LoopAnalysisManager
The loop analysis manager.
OutputIt transform(R &&Range, OutputIt d_first, UnaryFunction F)
Wrapper function around std::transform to apply a function to a range and store the result elsewhere.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
auto drop_end(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the last N elements excluded.
IRBuilder(LLVMContext &, FolderTy, InserterTy, MDNode *, ArrayRef< OperandBundleDef >) -> IRBuilder< FolderTy, InserterTy >
RecurKind
These are the kinds of recurrences that we support.
@ UMin
Unsigned integer min implemented in terms of select(cmp()).
@ FMinimumNum
FP min with llvm.minimumnum semantics.
@ Or
Bitwise or logical OR of integers.
@ FMinimum
FP min with llvm.minimum semantics.
@ Mul
Product of integers.
@ AnyOf
AnyOf reduction with select(cmp(),x,y) where one of (x,y) is loop invariant, and both x and y are int...
@ Xor
Bitwise or logical XOR of integers.
@ FMax
FP max implemented in terms of select(cmp()).
@ FMaximum
FP max with llvm.maximum semantics.
@ FMulAdd
Sum of float products with llvm.fmuladd(a * b + sum).
@ SMax
Signed integer max implemented in terms of select(cmp()).
@ And
Bitwise or logical AND of integers.
@ SMin
Signed integer min implemented in terms of select(cmp()).
@ FMin
FP min implemented in terms of select(cmp()).
@ FMaximumNum
FP max with llvm.maximumnum semantics.
@ UMax
Unsigned integer max implemented in terms of select(cmp()).
LLVM_ABI BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction.
FunctionAddr VTableAddr Next
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI bool formLCSSAForInstructions(SmallVectorImpl< Instruction * > &Worklist, const DominatorTree &DT, const LoopInfo &LI, ScalarEvolution *SE, SmallVectorImpl< PHINode * > *PHIsToRemove=nullptr, SmallVectorImpl< PHINode * > *InsertedPHIs=nullptr)
Ensures LCSSA form for every instruction from the Worklist in the scope of innermost containing loop.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI PreservedAnalyses getLoopPassPreservedAnalyses()
Returns the minimum set of Analyses that all loop passes must preserve.
auto predecessors(const MachineBasicBlock *BB)
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Incoming for lane maks phi as machine instruction, incoming register Reg and incoming block Block are...
PreservedAnalyses run(LoopNest &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &U)
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...